diff --git a/sandbox/src/main/java/org/springframework/ws/client/object/WebServiceInvocation.java b/sandbox/src/main/java/org/springframework/ws/client/object/WebServiceInvocation.java index ade9a146..2a05a97c 100644 --- a/sandbox/src/main/java/org/springframework/ws/client/object/WebServiceInvocation.java +++ b/sandbox/src/main/java/org/springframework/ws/client/object/WebServiceInvocation.java @@ -23,18 +23,18 @@ import org.springframework.ws.client.core.WebServiceTemplate; /** @author Arjen Poutsma */ public abstract class WebServiceInvocation { - /** Logger available to subclasses. */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); - /** Lower-level class used to invoke Web service. */ - private WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); + /** Lower-level class used to invoke Web service. */ + private WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); - /** Returns the {@link WebServiceTemplate} used by this object. */ - public WebServiceTemplate getWebServiceTemplate() { - return webServiceTemplate; - } + /** Returns the {@link WebServiceTemplate} used by this object. */ + public WebServiceTemplate getWebServiceTemplate() { + return webServiceTemplate; + } - public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) { - this.webServiceTemplate = webServiceTemplate; - } + public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) { + this.webServiceTemplate = webServiceTemplate; + } } diff --git a/sandbox/src/main/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapter.java b/sandbox/src/main/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapter.java index 00547d71..7de7350e 100644 --- a/sandbox/src/main/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapter.java +++ b/sandbox/src/main/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapter.java @@ -39,43 +39,43 @@ import org.springframework.xml.transform.TransformerObjectSupport; */ public class JaxWsProviderEndpointAdapter extends TransformerObjectSupport implements EndpointAdapter { - public boolean supports(Object endpoint) { - return endpoint.getClass().getAnnotation(WebServiceProvider.class) != null && endpoint instanceof Provider; - } + public boolean supports(Object endpoint) { + return endpoint.getClass().getAnnotation(WebServiceProvider.class) != null && endpoint instanceof Provider; + } - public void invoke(MessageContext messageContext, Object endpoint) throws Exception { - ServiceMode serviceMode = endpoint.getClass().getAnnotation(ServiceMode.class); - if (serviceMode == null || Service.Mode.PAYLOAD.equals(serviceMode.value())) { - invokeSourceProvider(messageContext, (Provider) endpoint); - } - else if (Service.Mode.MESSAGE.equals(serviceMode.value())) { - Provider provider = (Provider) endpoint; - invokeMessageProvider(messageContext, provider); - } - } + public void invoke(MessageContext messageContext, Object endpoint) throws Exception { + ServiceMode serviceMode = endpoint.getClass().getAnnotation(ServiceMode.class); + if (serviceMode == null || Service.Mode.PAYLOAD.equals(serviceMode.value())) { + invokeSourceProvider(messageContext, (Provider) endpoint); + } + else if (Service.Mode.MESSAGE.equals(serviceMode.value())) { + Provider provider = (Provider) endpoint; + invokeMessageProvider(messageContext, provider); + } + } - private void invokeSourceProvider(MessageContext messageContext, Provider provider) - throws TransformerException { - Source requestSource = messageContext.getRequest().getPayloadSource(); - Source responseSource = provider.invoke(requestSource); - if (responseSource != null) { - WebServiceMessage response = messageContext.getResponse(); - Transformer transformer = createTransformer(); - transformer.transform(responseSource, response.getPayloadResult()); - } - } + private void invokeSourceProvider(MessageContext messageContext, Provider provider) + throws TransformerException { + Source requestSource = messageContext.getRequest().getPayloadSource(); + Source responseSource = provider.invoke(requestSource); + if (responseSource != null) { + WebServiceMessage response = messageContext.getResponse(); + Transformer transformer = createTransformer(); + transformer.transform(responseSource, response.getPayloadResult()); + } + } - private void invokeMessageProvider(MessageContext messageContext, Provider provider) { - if (!(messageContext.getRequest() instanceof SaajSoapMessage)) { - throw new IllegalArgumentException("JaxWsProviderEndpointAdapter requires a SaajSoapMessage. " + - "Use a SaajSoapMessageFactory to create the SOAP messages."); - } - SaajSoapMessage request = (SaajSoapMessage) messageContext.getRequest(); - SOAPMessage saajRequest = request.getSaajMessage(); - SOAPMessage saajResponse = provider.invoke(saajRequest); - if (saajResponse != null) { - SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse(); - response.setSaajMessage(saajResponse); - } - } + private void invokeMessageProvider(MessageContext messageContext, Provider provider) { + if (!(messageContext.getRequest() instanceof SaajSoapMessage)) { + throw new IllegalArgumentException("JaxWsProviderEndpointAdapter requires a SaajSoapMessage. " + + "Use a SaajSoapMessageFactory to create the SOAP messages."); + } + SaajSoapMessage request = (SaajSoapMessage) messageContext.getRequest(); + SOAPMessage saajRequest = request.getSaajMessage(); + SOAPMessage saajResponse = provider.invoke(saajRequest); + if (saajResponse != null) { + SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse(); + response.setSaajMessage(saajResponse); + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/PerformanceTest.java b/sandbox/src/main/java/org/springframework/ws/soap/PerformanceTest.java index 0770831c..d97c41d4 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/PerformanceTest.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/PerformanceTest.java @@ -45,184 +45,184 @@ import org.apache.commons.logging.LogFactory; public class PerformanceTest { - private static final Log logger = LogFactory.getLog(PerformanceTest.class); + private static final Log logger = LogFactory.getLog(PerformanceTest.class); - private static final int ITERATIONS = 1000; + private static final int ITERATIONS = 1000; - private static final int ELEMENTS = 500; + private static final int ELEMENTS = 500; - private SoapMessageFactory messageFactory; + private SoapMessageFactory messageFactory; - private Marshaller marshaller; + private Marshaller marshaller; - private StopWatch stopWatch; + private StopWatch stopWatch; - private MyRootElement jaxbElement; + private MyRootElement jaxbElement; - private OutputStream os; + private OutputStream os; - private boolean streaming = false; + private boolean streaming = false; - private static final QName NAME = new QName("http://springframework.org", "root"); + private static final QName NAME = new QName("http://springframework.org", "root"); - private Transformer transformer; + private Transformer transformer; - public PerformanceTest(SoapMessageFactory messageFactory, StopWatch stopWatch) throws Exception { - if (messageFactory instanceof InitializingBean) { - ((InitializingBean) messageFactory).afterPropertiesSet(); - } - this.messageFactory = messageFactory; - JAXBContext jaxbContext = JAXBContext.newInstance(MyRootElement.class); - marshaller = jaxbContext.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); + public PerformanceTest(SoapMessageFactory messageFactory, StopWatch stopWatch) throws Exception { + if (messageFactory instanceof InitializingBean) { + ((InitializingBean) messageFactory).afterPropertiesSet(); + } + this.messageFactory = messageFactory; + JAXBContext jaxbContext = JAXBContext.newInstance(MyRootElement.class); + marshaller = jaxbContext.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); - jaxbElement = new MyRootElement(); - for (int i = 0; i < ELEMENTS; i++) { - jaxbElement.getStrings().add(String.valueOf(i)); - } + jaxbElement = new MyRootElement(); + for (int i = 0; i < ELEMENTS; i++) { + jaxbElement.getStrings().add(String.valueOf(i)); + } - os = new NullOutputSteam(); + os = new NullOutputSteam(); - this.stopWatch = stopWatch; + this.stopWatch = stopWatch; - this.transformer = TransformerFactory.newInstance().newTransformer(); - } + this.transformer = TransformerFactory.newInstance().newTransformer(); + } - public void test(boolean streaming) throws Exception { - String s = messageFactory.toString() + " streaming " + (streaming ? "enabled" : "disabled"); - stopWatch.start(s); - logger.info(s); - for (int i = 0; i < ITERATIONS; i++) { - SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(); + public void test(boolean streaming) throws Exception { + String s = messageFactory.toString() + " streaming " + (streaming ? "enabled" : "disabled"); + stopWatch.start(s); + logger.info(s); + for (int i = 0; i < ITERATIONS; i++) { + SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(); - marshal(message, streaming); + marshal(message, streaming); - transformer.transform(message.getPayloadSource(), new StreamResult(os)); + transformer.transform(message.getPayloadSource(), new StreamResult(os)); - message.writeTo(os); + message.writeTo(os); - } - stopWatch.stop(); - } + } + stopWatch.stop(); + } - private void marshal(SoapMessage message, boolean streaming) throws JAXBException { - if (streaming && message instanceof StreamingWebServiceMessage) { - StreamingWebServiceMessage streamingMessage = (StreamingWebServiceMessage) message; - StreamingPayload payload = new JaxbStreamingPayload(jaxbElement, NAME, marshaller); + private void marshal(SoapMessage message, boolean streaming) throws JAXBException { + if (streaming && message instanceof StreamingWebServiceMessage) { + StreamingWebServiceMessage streamingMessage = (StreamingWebServiceMessage) message; + StreamingPayload payload = new JaxbStreamingPayload(jaxbElement, NAME, marshaller); - streamingMessage.setStreamingPayload(payload); - } - else { - marshaller.marshal(jaxbElement, message.getPayloadResult()); - } - } + streamingMessage.setStreamingPayload(payload); + } + else { + marshaller.marshal(jaxbElement, message.getPayloadResult()); + } + } - public static void main(String[] args) throws Exception { - StopWatch stopWatch = new StopWatch(); + public static void main(String[] args) throws Exception { + StopWatch stopWatch = new StopWatch(); - try { - saaj(stopWatch); - axiom(stopWatch, false, false); - axiom(stopWatch, true, false); - axiom(stopWatch, false, true); - axiom(stopWatch, true, true); - stroap(stopWatch, false, false); - stroap(stopWatch, true, false); - stroap(stopWatch, false, true); - stroap(stopWatch, true, true); + try { + saaj(stopWatch); + axiom(stopWatch, false, false); + axiom(stopWatch, true, false); + axiom(stopWatch, false, true); + axiom(stopWatch, true, true); + stroap(stopWatch, false, false); + stroap(stopWatch, true, false); + stroap(stopWatch, false, true); + stroap(stopWatch, true, true); - } - finally { - System.out.println(stopWatch.prettyPrint()); - } - } + } + finally { + System.out.println(stopWatch.prettyPrint()); + } + } - private static void saaj(StopWatch stopWatch) throws Exception { - SaajSoapMessageFactory ssmf = new SaajSoapMessageFactory(); - PerformanceTest performanceTest = new PerformanceTest(ssmf, stopWatch); - performanceTest.test(false); - } + private static void saaj(StopWatch stopWatch) throws Exception { + SaajSoapMessageFactory ssmf = new SaajSoapMessageFactory(); + PerformanceTest performanceTest = new PerformanceTest(ssmf, stopWatch); + performanceTest.test(false); + } - private static void axiom(StopWatch stopWatch, boolean caching, boolean streaming) throws Exception { - AxiomSoapMessageFactory axmf = new AxiomSoapMessageFactory(); - axmf.setPayloadCaching(caching); - PerformanceTest performanceTest = new PerformanceTest(axmf, stopWatch); - performanceTest.test(streaming); - } + private static void axiom(StopWatch stopWatch, boolean caching, boolean streaming) throws Exception { + AxiomSoapMessageFactory axmf = new AxiomSoapMessageFactory(); + axmf.setPayloadCaching(caching); + PerformanceTest performanceTest = new PerformanceTest(axmf, stopWatch); + performanceTest.test(streaming); + } - private static void stroap(StopWatch stopWatch, boolean caching, boolean streaming) throws Exception { - StroapMessageFactory smf = new StroapMessageFactory(); - smf.setPayloadCaching(caching); - PerformanceTest performanceTest = new PerformanceTest(smf, stopWatch); - performanceTest.test(streaming); - } + private static void stroap(StopWatch stopWatch, boolean caching, boolean streaming) throws Exception { + StroapMessageFactory smf = new StroapMessageFactory(); + smf.setPayloadCaching(caching); + PerformanceTest performanceTest = new PerformanceTest(smf, stopWatch); + performanceTest.test(streaming); + } - @XmlRootElement(name = "root", namespace = "http://springframework.org") - public static class MyRootElement { + @XmlRootElement(name = "root", namespace = "http://springframework.org") + public static class MyRootElement { - private List strings; + private List strings; - @XmlElement(name = "string", namespace = "http://springframework.org") - public List getStrings() { - if (strings == null) { - strings = new ArrayList(); - } - return strings; - } + @XmlElement(name = "string", namespace = "http://springframework.org") + public List getStrings() { + if (strings == null) { + strings = new ArrayList(); + } + return strings; + } - } + } - private static class NullOutputSteam extends OutputStream { + private static class NullOutputSteam extends OutputStream { - @Override - public void write(int b) throws IOException { - } + @Override + public void write(int b) throws IOException { + } - @Override - public void write(byte[] b) throws IOException { - } + @Override + public void write(byte[] b) throws IOException { + } - @Override - public void write(byte[] b, int off, int len) throws IOException { - } + @Override + public void write(byte[] b, int off, int len) throws IOException { + } - @Override - public void flush() throws IOException { - } + @Override + public void flush() throws IOException { + } - @Override - public void close() throws IOException { - } - } + @Override + public void close() throws IOException { + } + } - private static class JaxbStreamingPayload implements StreamingPayload { + private static class JaxbStreamingPayload implements StreamingPayload { - private final Object jaxbElement; + private final Object jaxbElement; - private final QName name; + private final QName name; - private final Marshaller marshaller; + private final Marshaller marshaller; - private JaxbStreamingPayload(Object jaxbElement, QName name, Marshaller marshaller) { - this.jaxbElement = jaxbElement; - this.name = name; - this.marshaller = marshaller; - } + private JaxbStreamingPayload(Object jaxbElement, QName name, Marshaller marshaller) { + this.jaxbElement = jaxbElement; + this.name = name; + this.marshaller = marshaller; + } - public QName getName() { - return name; - } + public QName getName() { + return name; + } - public void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException { - try { - marshaller.marshal(jaxbElement, streamWriter); - } - catch (JAXBException ex) { - throw new XMLStreamException(ex); - } - } - } + public void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException { + try { + marshaller.marshal(jaxbElement, streamWriter); + } + catch (JAXBException ex) { + throw new XMLStreamException(ex); + } + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingStroapPayload.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingStroapPayload.java index 04a85a1a..51d3f441 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingStroapPayload.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingStroapPayload.java @@ -32,36 +32,36 @@ import org.springframework.xml.stream.ListBasedXMLEventReader; */ class CachingStroapPayload extends StroapPayload { - private final List events = new LinkedList(); + private final List events = new LinkedList(); - CachingStroapPayload() { - } + CachingStroapPayload() { + } - CachingStroapPayload(XMLEventReader eventReader) throws XMLStreamException { - Assert.notNull(eventReader, "'eventReader' must not be null"); - XMLEventWriter eventWriter = getEventWriter(); - eventWriter.add(eventReader); - } + CachingStroapPayload(XMLEventReader eventReader) throws XMLStreamException { + Assert.notNull(eventReader, "'eventReader' must not be null"); + XMLEventWriter eventWriter = getEventWriter(); + eventWriter.add(eventReader); + } - @Override - public QName getName() { - if (!events.isEmpty()) { - XMLEvent event = events.get(0); - if (event.isStartElement()) { - return event.asStartElement().getName(); - } - } - return null; - } + @Override + public QName getName() { + if (!events.isEmpty()) { + XMLEvent event = events.get(0); + if (event.isStartElement()) { + return event.asStartElement().getName(); + } + } + return null; + } - @Override - public XMLEventReader getEventReader() { - return new ListBasedXMLEventReader(events); - } + @Override + public XMLEventReader getEventReader() { + return new ListBasedXMLEventReader(events); + } - public XMLEventWriter getEventWriter() { - events.clear(); - return new CachingXMLEventWriter(events); - } + public XMLEventWriter getEventWriter() { + events.clear(); + return new CachingXMLEventWriter(events); + } } \ No newline at end of file diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingXMLEventWriter.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingXMLEventWriter.java index 850044a6..75e3191f 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingXMLEventWriter.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/CachingXMLEventWriter.java @@ -28,30 +28,30 @@ import org.springframework.xml.stream.AbstractXMLEventWriter; */ class CachingXMLEventWriter extends AbstractXMLEventWriter { - private int elementDepth = 0; + private int elementDepth = 0; - boolean startElementSeen = false; + boolean startElementSeen = false; - private final List events; + private final List events; - CachingXMLEventWriter(List events) { - Assert.notNull(events, "'events' must not be null"); - this.events = events; - } + CachingXMLEventWriter(List events) { + Assert.notNull(events, "'events' must not be null"); + this.events = events; + } - public void add(XMLEvent event) throws XMLStreamException { - if (event.isStartElement()) { - startElementSeen = true; - elementDepth++; - } - else if (event.isEndElement()) { - elementDepth--; - } - else if (event.isStartDocument() || event.isEndDocument()) { - return; - } - if (elementDepth >= 0 && startElementSeen) { - events.add(event); - } - } + public void add(XMLEvent event) throws XMLStreamException { + if (event.isStartElement()) { + startElementSeen = true; + elementDepth++; + } + else if (event.isEndElement()) { + elementDepth--; + } + else if (event.isStartDocument() || event.isEndDocument()) { + return; + } + if (elementDepth >= 0 && startElementSeen) { + events.add(event); + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/FaultStroapPayload.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/FaultStroapPayload.java index 03b61975..1121cbf6 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/FaultStroapPayload.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/FaultStroapPayload.java @@ -27,25 +27,25 @@ import org.springframework.ws.soap.SoapFault; */ class FaultStroapPayload extends StroapPayload { - private final StroapFault fault; + private final StroapFault fault; - FaultStroapPayload(StroapFault fault) { - Assert.notNull(fault, "'fault' must not be null"); - this.fault = fault; - } + FaultStroapPayload(StroapFault fault) { + Assert.notNull(fault, "'fault' must not be null"); + this.fault = fault; + } - SoapFault getFault() { - return fault; - } + SoapFault getFault() { + return fault; + } - @Override - public QName getName() { - return fault.getName(); - } + @Override + public QName getName() { + return fault.getName(); + } - @Override - public XMLEventReader getEventReader() { - return fault.getEventReader(false); - } + @Override + public XMLEventReader getEventReader() { + return fault.getEventReader(false); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/NonCachingStroapPayload.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/NonCachingStroapPayload.java index a95704e8..6bba3d2b 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/NonCachingStroapPayload.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/NonCachingStroapPayload.java @@ -30,62 +30,62 @@ import org.springframework.xml.stream.AbstractXMLEventReader; */ class NonCachingStroapPayload extends StroapPayload { - private final XMLEventReader eventReader; + private final XMLEventReader eventReader; - private int elementDepth = 0; + private int elementDepth = 0; - NonCachingStroapPayload(XMLEventReader eventReader) throws XMLStreamException { - Assert.notNull(eventReader, "'eventReader' must not be null"); - this.eventReader = eventReader; - } + NonCachingStroapPayload(XMLEventReader eventReader) throws XMLStreamException { + Assert.notNull(eventReader, "'eventReader' must not be null"); + this.eventReader = eventReader; + } - @Override - public QName getName() { - try { - XMLEvent event = eventReader.peek(); - if (event != null && event.isStartElement()) { - return event.asStartElement().getName(); - } + @Override + public QName getName() { + try { + XMLEvent event = eventReader.peek(); + if (event != null && event.isStartElement()) { + return event.asStartElement().getName(); + } - } - catch (XMLStreamException ex) { - // ignore - } - return null; - } + } + catch (XMLStreamException ex) { + // ignore + } + return null; + } - @Override - public XMLEventReader getEventReader() { - return new NonCachingXMLEventReader(); - } + @Override + public XMLEventReader getEventReader() { + return new NonCachingXMLEventReader(); + } - private class NonCachingXMLEventReader extends AbstractXMLEventReader { + private class NonCachingXMLEventReader extends AbstractXMLEventReader { - public boolean hasNext() { - return elementDepth >= 0 && eventReader.hasNext(); - } + public boolean hasNext() { + return elementDepth >= 0 && eventReader.hasNext(); + } - public XMLEvent nextEvent() throws XMLStreamException { - if (elementDepth < 0) { - throw new NoSuchElementException(); - } - XMLEvent event = eventReader.nextEvent(); - if (event.isStartElement()) { - elementDepth++; - } - else if (event.isEndElement()) { - elementDepth--; - } - return event; - } + public XMLEvent nextEvent() throws XMLStreamException { + if (elementDepth < 0) { + throw new NoSuchElementException(); + } + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) { + elementDepth++; + } + else if (event.isEndElement()) { + elementDepth--; + } + return event; + } - public XMLEvent peek() throws XMLStreamException { - if (elementDepth < 0) { - return null; - } - else { - return eventReader.peek(); - } - } - } + public XMLEvent peek() throws XMLStreamException { + if (elementDepth < 0) { + return null; + } + else { + return eventReader.peek(); + } + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StreamingStroapPayload.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StreamingStroapPayload.java index fb3036cf..2e86c79f 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StreamingStroapPayload.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StreamingStroapPayload.java @@ -33,42 +33,42 @@ import org.springframework.ws.stream.StreamingPayload; */ class StreamingStroapPayload extends StroapPayload { - private final StreamingPayload payload; + private final StreamingPayload payload; - private final StroapMessageFactory messageFactory; + private final StroapMessageFactory messageFactory; - StreamingStroapPayload(StreamingPayload payload, StroapMessageFactory messageFactory) { - Assert.notNull(payload, "'payload' must not be null"); - Assert.notNull(messageFactory, "'messageFactory' must not be null"); + StreamingStroapPayload(StreamingPayload payload, StroapMessageFactory messageFactory) { + Assert.notNull(payload, "'payload' must not be null"); + Assert.notNull(messageFactory, "'messageFactory' must not be null"); - this.payload = payload; - this.messageFactory = messageFactory; - } + this.payload = payload; + this.messageFactory = messageFactory; + } - @Override - public QName getName() { - return payload.getName(); - } + @Override + public QName getName() { + return payload.getName(); + } - @Override - public XMLEventReader getEventReader() { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - XMLStreamWriter streamWriter = messageFactory.getOutputFactory().createXMLStreamWriter(bos); - payload.writeTo(streamWriter); - streamWriter.flush(); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - return messageFactory.getInputFactory().createXMLEventReader(bis); - } - catch (XMLStreamException ex) { - throw new StroapBodyException(ex); - } - } + @Override + public XMLEventReader getEventReader() { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + XMLStreamWriter streamWriter = messageFactory.getOutputFactory().createXMLStreamWriter(bos); + payload.writeTo(streamWriter); + streamWriter.flush(); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + return messageFactory.getInputFactory().createXMLEventReader(bis); + } + catch (XMLStreamException ex) { + throw new StroapBodyException(ex); + } + } - @Override - public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { - XMLStreamWriter streamWriter = StaxUtils.createEventStreamWriter(eventWriter, messageFactory.getEventFactory()); - payload.writeTo(streamWriter); - } + @Override + public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { + XMLStreamWriter streamWriter = StaxUtils.createEventStreamWriter(eventWriter, messageFactory.getEventFactory()); + payload.writeTo(streamWriter); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Body.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Body.java index dc70d557..c5016ec3 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Body.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Body.java @@ -30,67 +30,67 @@ import org.springframework.ws.soap.soap11.Soap11Fault; */ class Stroap11Body extends StroapBody implements Soap11Body { - private static final String ENVELOPE_NAMESPACE_URI = "http://schemas.xmlsoap.org/soap/envelope/"; + private static final String ENVELOPE_NAMESPACE_URI = "http://schemas.xmlsoap.org/soap/envelope/"; - private QName CLIENT_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Client", DEFAULT_PREFIX); + private QName CLIENT_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Client", DEFAULT_PREFIX); - private QName SERVER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Server", DEFAULT_PREFIX); + private QName SERVER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Server", DEFAULT_PREFIX); - private QName MUST_UNDERSTAND_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "MustUnderstand", DEFAULT_PREFIX); + private QName MUST_UNDERSTAND_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "MustUnderstand", DEFAULT_PREFIX); - private QName VERSION_MISMATCH_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "VersionMismatch", DEFAULT_PREFIX); + private QName VERSION_MISMATCH_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "VersionMismatch", DEFAULT_PREFIX); - Stroap11Body(StroapMessageFactory messageFactory) { - super(messageFactory); - } + Stroap11Body(StroapMessageFactory messageFactory) { + super(messageFactory); + } - Stroap11Body(StartElement startElement, StroapPayload payload, StroapMessageFactory messageFactory) { - super(startElement, payload, messageFactory); - } + Stroap11Body(StartElement startElement, StroapPayload payload, StroapMessageFactory messageFactory) { + super(startElement, payload, messageFactory); + } - @Override - public Soap11Fault getFault() { - return (Soap11Fault) super.getFault(); - } + @Override + public Soap11Fault getFault() { + return (Soap11Fault) super.getFault(); + } - public Soap11Fault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException { - Stroap11Fault fault = - new Stroap11Fault(MUST_UNDERSTAND_FAULT_NAME, "SOAP Must Understand Error", null, getMessageFactory()); - setFault(fault); - return fault; - } + public Soap11Fault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException { + Stroap11Fault fault = + new Stroap11Fault(MUST_UNDERSTAND_FAULT_NAME, "SOAP Must Understand Error", null, getMessageFactory()); + setFault(fault); + return fault; + } - public Soap11Fault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - Stroap11Fault fault = new Stroap11Fault(CLIENT_FAULT_NAME, faultStringOrReason, null, getMessageFactory()); - setFault(fault); - return fault; - } + public Soap11Fault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + Stroap11Fault fault = new Stroap11Fault(CLIENT_FAULT_NAME, faultStringOrReason, null, getMessageFactory()); + setFault(fault); + return fault; + } - public Soap11Fault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - Stroap11Fault fault = new Stroap11Fault(SERVER_FAULT_NAME, faultStringOrReason, null, getMessageFactory()); - setFault(fault); - return fault; - } + public Soap11Fault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + Stroap11Fault fault = new Stroap11Fault(SERVER_FAULT_NAME, faultStringOrReason, null, getMessageFactory()); + setFault(fault); + return fault; + } - public Soap11Fault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - Stroap11Fault fault = - new Stroap11Fault(VERSION_MISMATCH_FAULT_NAME, faultStringOrReason, null, getMessageFactory()); - setFault(fault); - return fault; - } + public Soap11Fault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + Stroap11Fault fault = + new Stroap11Fault(VERSION_MISMATCH_FAULT_NAME, faultStringOrReason, null, getMessageFactory()); + setFault(fault); + return fault; + } - public Soap11Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) - throws SoapFaultException { - Assert.notNull(faultCode, "'faultCode' must not be null"); - Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); - Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); - Assert.hasLength(faultString, "'faultString' must not be empty"); + public Soap11Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) + throws SoapFaultException { + Assert.notNull(faultCode, "'faultCode' must not be null"); + Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); + Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); + Assert.hasLength(faultString, "'faultString' must not be empty"); - Stroap11Fault fault = new Stroap11Fault(faultCode, faultString, faultStringLocale, getMessageFactory()); - setFault(fault); - return fault; - } + Stroap11Fault fault = new Stroap11Fault(faultCode, faultString, faultStringLocale, getMessageFactory()); + setFault(fault); + return fault; + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Fault.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Fault.java index 0a788331..2230b5d3 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Fault.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Fault.java @@ -34,124 +34,124 @@ import org.springframework.xml.stream.ListBasedXMLEventReader; */ class Stroap11Fault extends StroapFault implements Soap11Fault { - private static final QName XML_LANG_NAME = new QName(XMLConstants.XML_NS_URI, "lang", XMLConstants.XML_NS_PREFIX); + private static final QName XML_LANG_NAME = new QName(XMLConstants.XML_NS_URI, "lang", XMLConstants.XML_NS_PREFIX); - private final FaultElement faultCode; + private final FaultElement faultCode; - private final FaultElement faultString; + private final FaultElement faultString; - private FaultElement faultActor; + private FaultElement faultActor; - Stroap11Fault(QName faultCode, String faultString, Locale faultStringLocale, StroapMessageFactory messageFactory) { - super(messageFactory); + Stroap11Fault(QName faultCode, String faultString, Locale faultStringLocale, StroapMessageFactory messageFactory) { + super(messageFactory); - this.faultCode = FaultElement.createFaultCode(faultCode, messageFactory); - this.faultString = FaultElement.createFaultString(faultString, faultStringLocale, messageFactory); - addNamespaceDeclaration(faultCode.getPrefix(), faultCode.getNamespaceURI()); - } + this.faultCode = FaultElement.createFaultCode(faultCode, messageFactory); + this.faultString = FaultElement.createFaultString(faultString, faultStringLocale, messageFactory); + addNamespaceDeclaration(faultCode.getPrefix(), faultCode.getNamespaceURI()); + } - public QName getFaultCode() { - return parseFaultCodeString(faultCode.getCharacterData()); - } + public QName getFaultCode() { + return parseFaultCodeString(faultCode.getCharacterData()); + } - private QName parseFaultCodeString(String faultCodeString) { - if (faultCodeString == null) { - return null; - } - int idx = faultCodeString.indexOf(':'); - if (idx == -1) { - return new QName(faultCodeString); - } - else { - String prefix = faultCodeString.substring(0, idx); - String localPart = faultCodeString.substring(idx + 1, faultCodeString.length()); - String namespaceUri = getStartElement().getNamespaceURI(prefix); - return new QName(namespaceUri, localPart, prefix); - } - } + private QName parseFaultCodeString(String faultCodeString) { + if (faultCodeString == null) { + return null; + } + int idx = faultCodeString.indexOf(':'); + if (idx == -1) { + return new QName(faultCodeString); + } + else { + String prefix = faultCodeString.substring(0, idx); + String localPart = faultCodeString.substring(idx + 1, faultCodeString.length()); + String namespaceUri = getStartElement().getNamespaceURI(prefix); + return new QName(namespaceUri, localPart, prefix); + } + } - public String getFaultStringOrReason() { - return faultString.getCharacterData(); - } + public String getFaultStringOrReason() { + return faultString.getCharacterData(); + } - public Locale getFaultStringLocale() { - String xmlLangString = faultString.getAttributeValue(XML_LANG_NAME); - if (xmlLangString != null) { - String localeString = xmlLangString.replace('-', '_'); - return StringUtils.parseLocaleString(localeString); - } - return null; - } + public Locale getFaultStringLocale() { + String xmlLangString = faultString.getAttributeValue(XML_LANG_NAME); + if (xmlLangString != null) { + String localeString = xmlLangString.replace('-', '_'); + return StringUtils.parseLocaleString(localeString); + } + return null; + } - public String getFaultActorOrRole() { - return faultActor != null ? faultActor.getCharacterData() : null; - } + public String getFaultActorOrRole() { + return faultActor != null ? faultActor.getCharacterData() : null; + } - public void setFaultActorOrRole(String faultActor) { - this.faultActor = FaultElement.createFaultActor(faultActor, getMessageFactory()); - } + public void setFaultActorOrRole(String faultActor) { + this.faultActor = FaultElement.createFaultActor(faultActor, getMessageFactory()); + } - public SoapFaultDetail getFaultDetail() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public SoapFaultDetail getFaultDetail() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } - public SoapFaultDetail addFaultDetail() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public SoapFaultDetail addFaultDetail() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } - @Override - protected XMLEventReader getChildEventReader() { - XMLEventReader[] eventReaders = (faultActor == null) ? new XMLEventReader[2] : new XMLEventReader[3]; - eventReaders[0] = faultCode.getEventReader(false); - eventReaders[1] = faultString.getEventReader(false); - if (faultActor != null) { - eventReaders[2] = faultActor.getEventReader(false); - } - return new CompositeXMLEventReader(eventReaders); - } + @Override + protected XMLEventReader getChildEventReader() { + XMLEventReader[] eventReaders = (faultActor == null) ? new XMLEventReader[2] : new XMLEventReader[3]; + eventReaders[0] = faultCode.getEventReader(false); + eventReaders[1] = faultString.getEventReader(false); + if (faultActor != null) { + eventReaders[2] = faultActor.getEventReader(false); + } + return new CompositeXMLEventReader(eventReaders); + } - private static class FaultElement extends StroapElement { + private static class FaultElement extends StroapElement { - private final Characters characters; + private final Characters characters; - private FaultElement(String localName, String value, StroapMessageFactory messageFactory) { - super(messageFactory.getEventFactory().createStartElement(new QName(localName), null, null), - messageFactory); - this.characters = getEventFactory().createCharacters(value); - } + private FaultElement(String localName, String value, StroapMessageFactory messageFactory) { + super(messageFactory.getEventFactory().createStartElement(new QName(localName), null, null), + messageFactory); + this.characters = getEventFactory().createCharacters(value); + } - public static FaultElement createFaultCode(QName faultCode, StroapMessageFactory messageFactory) { - Assert.notNull(faultCode, "'faultCode' must not be null"); - Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); - Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); - String value = faultCode.getPrefix() + ":" + faultCode.getLocalPart(); - return new FaultElement("faultcode", value, messageFactory); - } + public static FaultElement createFaultCode(QName faultCode, StroapMessageFactory messageFactory) { + Assert.notNull(faultCode, "'faultCode' must not be null"); + Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); + Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); + String value = faultCode.getPrefix() + ":" + faultCode.getLocalPart(); + return new FaultElement("faultcode", value, messageFactory); + } - public static FaultElement createFaultString(String faultString, - Locale faultStringLocale, - StroapMessageFactory messageFactory) { - Assert.hasLength(faultString, "'faultString' must not be empty"); - FaultElement element = new FaultElement("faultstring", faultString, messageFactory); - if (faultStringLocale != null) { - String xmlLangString = faultStringLocale.toString().replace('_', '-'); - element.addAttribute(XML_LANG_NAME, xmlLangString); - } - return element; - } + public static FaultElement createFaultString(String faultString, + Locale faultStringLocale, + StroapMessageFactory messageFactory) { + Assert.hasLength(faultString, "'faultString' must not be empty"); + FaultElement element = new FaultElement("faultstring", faultString, messageFactory); + if (faultStringLocale != null) { + String xmlLangString = faultStringLocale.toString().replace('_', '-'); + element.addAttribute(XML_LANG_NAME, xmlLangString); + } + return element; + } - public static FaultElement createFaultActor(String actor, StroapMessageFactory messageFactory) { - Assert.hasLength(actor, "'actor' must not be empty"); - return new FaultElement("faultactor", actor, messageFactory); - } + public static FaultElement createFaultActor(String actor, StroapMessageFactory messageFactory) { + Assert.hasLength(actor, "'actor' must not be empty"); + return new FaultElement("faultactor", actor, messageFactory); + } - public String getCharacterData() { - return characters.getData(); - } + public String getCharacterData() { + return characters.getData(); + } - @Override - protected XMLEventReader getChildEventReader() { - return new ListBasedXMLEventReader(characters); - } - } + @Override + protected XMLEventReader getChildEventReader() { + return new ListBasedXMLEventReader(characters); + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Header.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Header.java index 472970b1..63fc88b1 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Header.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/Stroap11Header.java @@ -32,42 +32,42 @@ import org.springframework.ws.soap.soap11.Soap11Header; */ class Stroap11Header extends StroapHeader implements Soap11Header { - Stroap11Header(StroapMessageFactory messageFactory) { - super(messageFactory); - } + Stroap11Header(StroapMessageFactory messageFactory) { + super(messageFactory); + } - Stroap11Header(StartElement startElement, StroapMessageFactory messageFactory) { - super(startElement, messageFactory); - } + Stroap11Header(StartElement startElement, StroapMessageFactory messageFactory) { + super(startElement, messageFactory); + } - public Iterator examineHeaderElementsToProcess(String[] actors) { - List result = new LinkedList(); - Iterator iterator = examineAllHeaderElements(); - while (iterator.hasNext()) { - SoapHeaderElement headerElement = iterator.next(); - String actor = headerElement.getActorOrRole(); - if (shouldProcess(actor, actors)) { - result.add(headerElement); - } - } - return result.iterator(); - } + public Iterator examineHeaderElementsToProcess(String[] actors) { + List result = new LinkedList(); + Iterator iterator = examineAllHeaderElements(); + while (iterator.hasNext()) { + SoapHeaderElement headerElement = iterator.next(); + String actor = headerElement.getActorOrRole(); + if (shouldProcess(actor, actors)) { + result.add(headerElement); + } + } + return result.iterator(); + } - private boolean shouldProcess(String headerActor, String[] actors) { - if (!StringUtils.hasLength(headerActor)) { - return true; - } - if (SOAPConstants.URI_SOAP_ACTOR_NEXT.equals(headerActor)) { - return true; - } - if (!ObjectUtils.isEmpty(actors)) { - for (String actor : actors) { - if (actor.equals(headerActor)) { - return true; - } - } - } - return false; - } + private boolean shouldProcess(String headerActor, String[] actors) { + if (!StringUtils.hasLength(headerActor)) { + return true; + } + if (SOAPConstants.URI_SOAP_ACTOR_NEXT.equals(headerActor)) { + return true; + } + if (!ObjectUtils.isEmpty(actors)) { + for (String actor : actors) { + if (actor.equals(headerActor)) { + return true; + } + } + } + return false; + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBody.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBody.java index c83072f0..3cde853b 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBody.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBody.java @@ -36,92 +36,92 @@ import org.springframework.ws.stream.StreamingPayload; */ abstract class StroapBody extends StroapElement implements SoapBody { - private StroapPayload payload; + private StroapPayload payload; - protected StroapBody(StroapMessageFactory messageFactory) { - super(messageFactory.getSoapVersion().getBodyName(), messageFactory); - this.payload = new CachingStroapPayload(); - } + protected StroapBody(StroapMessageFactory messageFactory) { + super(messageFactory.getSoapVersion().getBodyName(), messageFactory); + this.payload = new CachingStroapPayload(); + } - protected StroapBody(StartElement startElement, StroapPayload payload, StroapMessageFactory messageFactory) { - super(startElement, messageFactory); - this.payload = payload; - } + protected StroapBody(StartElement startElement, StroapPayload payload, StroapMessageFactory messageFactory) { + super(startElement, messageFactory); + this.payload = payload; + } - static StroapBody build(XMLEventReader eventReader, StroapMessageFactory messageFactory) throws XMLStreamException { - XMLEvent event = eventReader.nextTag(); - if (!event.isStartElement()) { - throw new StroapMessageCreationException("Unexpected event: " + event + ", expected StartElement"); - } - StartElement startElement = event.asStartElement(); - SoapVersion soapVersion = messageFactory.getSoapVersion(); - if (!soapVersion.getBodyName().equals(startElement.getName())) { - throw new StroapMessageCreationException( - "Unexpected name: " + startElement.getName() + ", expected " + soapVersion.getBodyName()); - } - StroapPayload payload; - if (messageFactory.isPayloadCaching()) { - payload = new CachingStroapPayload(eventReader); - } - else { - payload = new NonCachingStroapPayload(eventReader); - } + static StroapBody build(XMLEventReader eventReader, StroapMessageFactory messageFactory) throws XMLStreamException { + XMLEvent event = eventReader.nextTag(); + if (!event.isStartElement()) { + throw new StroapMessageCreationException("Unexpected event: " + event + ", expected StartElement"); + } + StartElement startElement = event.asStartElement(); + SoapVersion soapVersion = messageFactory.getSoapVersion(); + if (!soapVersion.getBodyName().equals(startElement.getName())) { + throw new StroapMessageCreationException( + "Unexpected name: " + startElement.getName() + ", expected " + soapVersion.getBodyName()); + } + StroapPayload payload; + if (messageFactory.isPayloadCaching()) { + payload = new CachingStroapPayload(eventReader); + } + else { + payload = new NonCachingStroapPayload(eventReader); + } - if (SoapVersion.SOAP_11.equals(soapVersion)) { - return new Stroap11Body(startElement, payload, messageFactory); - } - else { - return null; - } - } + if (SoapVersion.SOAP_11.equals(soapVersion)) { + return new Stroap11Body(startElement, payload, messageFactory); + } + else { + return null; + } + } - public Source getPayloadSource() { - XMLEventReader eventReader = payload.getEventReader(); - return StaxUtils.createCustomStaxSource(eventReader); - } + public Source getPayloadSource() { + XMLEventReader eventReader = payload.getEventReader(); + return StaxUtils.createCustomStaxSource(eventReader); + } - public Result getPayloadResult() { - CachingStroapPayload cachingPayload; - if (payload instanceof CachingStroapPayload) { - cachingPayload = (CachingStroapPayload) payload; - } - else { - cachingPayload = new CachingStroapPayload(); - this.payload = cachingPayload; - } - XMLEventWriter eventWriter = cachingPayload.getEventWriter(); - return StaxUtils.createCustomStaxResult(eventWriter); - } + public Result getPayloadResult() { + CachingStroapPayload cachingPayload; + if (payload instanceof CachingStroapPayload) { + cachingPayload = (CachingStroapPayload) payload; + } + else { + cachingPayload = new CachingStroapPayload(); + this.payload = cachingPayload; + } + XMLEventWriter eventWriter = cachingPayload.getEventWriter(); + return StaxUtils.createCustomStaxResult(eventWriter); + } - public boolean hasFault() { - return payload instanceof FaultStroapPayload; - } + public boolean hasFault() { + return payload instanceof FaultStroapPayload; + } - public SoapFault getFault() { - return payload instanceof FaultStroapPayload ? ((FaultStroapPayload) payload).getFault() : null; - } + public SoapFault getFault() { + return payload instanceof FaultStroapPayload ? ((FaultStroapPayload) payload).getFault() : null; + } - protected void setFault(StroapFault fault) { - this.payload = new FaultStroapPayload(fault); - } + protected void setFault(StroapFault fault) { + this.payload = new FaultStroapPayload(fault); + } - @Override - protected final XMLEventReader getChildEventReader() { - return payload.getEventReader(); - } + @Override + protected final XMLEventReader getChildEventReader() { + return payload.getEventReader(); + } - @Override - public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { - eventWriter.add(getStartElement()); - payload.writeTo(eventWriter); - eventWriter.add(getEndElement()); - } + @Override + public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { + eventWriter.add(getStartElement()); + payload.writeTo(eventWriter); + eventWriter.add(getEndElement()); + } - public void setStreamingPayload(StreamingPayload payload) { - this.payload = new StreamingStroapPayload(payload, getMessageFactory()); - } + public void setStreamingPayload(StreamingPayload payload) { + this.payload = new StreamingStroapPayload(payload, getMessageFactory()); + } - public QName getPayloadName() { - return payload.getName(); - } + public QName getPayloadName() { + return payload.getName(); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBodyException.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBodyException.java index 500d3134..d017262d 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBodyException.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapBodyException.java @@ -23,15 +23,15 @@ import org.springframework.ws.soap.SoapBodyException; */ public class StroapBodyException extends SoapBodyException { - public StroapBodyException(String msg) { - super(msg); - } + public StroapBodyException(String msg) { + super(msg); + } - public StroapBodyException(String msg, Throwable ex) { - super(msg, ex); - } + public StroapBodyException(String msg, Throwable ex) { + super(msg, ex); + } - public StroapBodyException(Throwable ex) { - super(ex); - } + public StroapBodyException(Throwable ex) { + super(ex); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapElement.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapElement.java index 62b1e724..19a00a41 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapElement.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapElement.java @@ -44,217 +44,217 @@ import org.springframework.xml.stream.AbstractXMLEventReader; */ abstract class StroapElement implements SoapElement { - protected static final String DEFAULT_PREFIX = "SOAP-ENV"; + protected static final String DEFAULT_PREFIX = "SOAP-ENV"; - private final StroapMessageFactory messageFactory; + private final StroapMessageFactory messageFactory; - private StartElement startElement; + private StartElement startElement; - private EndElement endElement; + private EndElement endElement; - protected StroapElement(QName name, StroapMessageFactory messageFactory) { - this(createStartElement(name, messageFactory), messageFactory); - } + protected StroapElement(QName name, StroapMessageFactory messageFactory) { + this(createStartElement(name, messageFactory), messageFactory); + } - private static StartElement createStartElement(QName name, StroapMessageFactory messageFactory) { - if (!StringUtils.hasLength(name.getPrefix())) { - name = new QName(name.getNamespaceURI(), name.getLocalPart(), DEFAULT_PREFIX); - } - return messageFactory.getEventFactory().createStartElement(name, null, null); - } + private static StartElement createStartElement(QName name, StroapMessageFactory messageFactory) { + if (!StringUtils.hasLength(name.getPrefix())) { + name = new QName(name.getNamespaceURI(), name.getLocalPart(), DEFAULT_PREFIX); + } + return messageFactory.getEventFactory().createStartElement(name, null, null); + } - protected StroapElement(StartElement startElement, StroapMessageFactory messageFactory) { - Assert.notNull(startElement, "'startElement' must not be null"); - Assert.notNull(messageFactory, "'messageFactory' must not be null"); - this.messageFactory = messageFactory; - this.startElement = startElement; - this.endElement = getEventFactory().createEndElement(startElement.getName(), startElement.getNamespaces()); - } + protected StroapElement(StartElement startElement, StroapMessageFactory messageFactory) { + Assert.notNull(startElement, "'startElement' must not be null"); + Assert.notNull(messageFactory, "'messageFactory' must not be null"); + this.messageFactory = messageFactory; + this.startElement = startElement; + this.endElement = getEventFactory().createEndElement(startElement.getName(), startElement.getNamespaces()); + } - public final Source getSource() { - return StaxUtils.createCustomStaxSource(getEventReader(true)); - } + public final Source getSource() { + return StaxUtils.createCustomStaxSource(getEventReader(true)); + } - protected XMLEventReader getEventReader(boolean documentEvents) { - return new StroapElementEventReader(documentEvents); - } + protected XMLEventReader getEventReader(boolean documentEvents) { + return new StroapElementEventReader(documentEvents); + } - public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { - eventWriter.add(getEventReader(false)); - } + public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { + eventWriter.add(getEventReader(false)); + } - protected StroapMessageFactory getMessageFactory() { - return messageFactory; - } + protected StroapMessageFactory getMessageFactory() { + return messageFactory; + } - protected final XMLEventFactory getEventFactory() { - return getMessageFactory().getEventFactory(); - } + protected final XMLEventFactory getEventFactory() { + return getMessageFactory().getEventFactory(); + } - protected SoapVersion getSoapVersion() { - return getMessageFactory().getSoapVersion(); - } + protected SoapVersion getSoapVersion() { + return getMessageFactory().getSoapVersion(); + } - public final QName getName() { - return getStartElement().getName(); - } + public final QName getName() { + return getStartElement().getName(); + } - protected abstract XMLEventReader getChildEventReader(); + protected abstract XMLEventReader getChildEventReader(); - public final Iterator getAllAttributes() { - List result = new LinkedList(); - for (Iterator iterator = getStartElement().getAttributes(); iterator.hasNext();) { - Attribute attribute = (Attribute) iterator.next(); - result.add(attribute.getName()); - } - return result.iterator(); - } + public final Iterator getAllAttributes() { + List result = new LinkedList(); + for (Iterator iterator = getStartElement().getAttributes(); iterator.hasNext();) { + Attribute attribute = (Attribute) iterator.next(); + result.add(attribute.getName()); + } + return result.iterator(); + } - public final String getAttributeValue(QName name) { - Attribute attribute = getStartElement().getAttributeByName(name); - return attribute != null ? attribute.getValue() : null; - } + public final String getAttributeValue(QName name) { + Attribute attribute = getStartElement().getAttributeByName(name); + return attribute != null ? attribute.getValue() : null; + } - public final void removeAttribute(QName name) { - List newAttributes = new LinkedList(); - for (Iterator iterator = getStartElement().getAttributes(); iterator.hasNext();) { - Attribute attribute = (Attribute) iterator.next(); - if (!name.equals(attribute.getName())) { - newAttributes.add(attribute); - } - } - StartElement oldStartElement = getStartElement(); - this.startElement = getEventFactory().createStartElement(oldStartElement.getName(), newAttributes.iterator(), - oldStartElement.getNamespaces()); - } + public final void removeAttribute(QName name) { + List newAttributes = new LinkedList(); + for (Iterator iterator = getStartElement().getAttributes(); iterator.hasNext();) { + Attribute attribute = (Attribute) iterator.next(); + if (!name.equals(attribute.getName())) { + newAttributes.add(attribute); + } + } + StartElement oldStartElement = getStartElement(); + this.startElement = getEventFactory().createStartElement(oldStartElement.getName(), newAttributes.iterator(), + oldStartElement.getNamespaces()); + } - public final void addAttribute(QName name, String value) { - List newAttributes = new LinkedList(); - for (Iterator iterator = getStartElement().getAttributes(); iterator.hasNext();) { - Attribute attribute = (Attribute) iterator.next(); - newAttributes.add(attribute); - } - Attribute newAttribute = getEventFactory().createAttribute(name, value); - newAttributes.add(newAttribute); - StartElement oldStartElement = getStartElement(); - this.startElement = getEventFactory().createStartElement(oldStartElement.getName(), newAttributes.iterator(), - oldStartElement.getNamespaces()); - } + public final void addAttribute(QName name, String value) { + List newAttributes = new LinkedList(); + for (Iterator iterator = getStartElement().getAttributes(); iterator.hasNext();) { + Attribute attribute = (Attribute) iterator.next(); + newAttributes.add(attribute); + } + Attribute newAttribute = getEventFactory().createAttribute(name, value); + newAttributes.add(newAttribute); + StartElement oldStartElement = getStartElement(); + this.startElement = getEventFactory().createStartElement(oldStartElement.getName(), newAttributes.iterator(), + oldStartElement.getNamespaces()); + } - public final void addNamespaceDeclaration(String prefix, String namespaceUri) { - List newNamespaces = new LinkedList(); - for (Iterator iterator = getStartElement().getNamespaces(); iterator.hasNext();) { - Namespace namespace = (Namespace) iterator.next(); - newNamespaces.add(namespace); - } - Namespace newNamespace; - if (StringUtils.hasLength(prefix)) { - newNamespace = getEventFactory().createNamespace(prefix, namespaceUri); - } - else { - newNamespace = getEventFactory().createNamespace(namespaceUri); - } - newNamespaces.add(newNamespace); - StartElement oldStartElement = getStartElement(); - this.startElement = getEventFactory() - .createStartElement(oldStartElement.getName(), oldStartElement.getAttributes(), - newNamespaces.iterator()); - } + public final void addNamespaceDeclaration(String prefix, String namespaceUri) { + List newNamespaces = new LinkedList(); + for (Iterator iterator = getStartElement().getNamespaces(); iterator.hasNext();) { + Namespace namespace = (Namespace) iterator.next(); + newNamespaces.add(namespace); + } + Namespace newNamespace; + if (StringUtils.hasLength(prefix)) { + newNamespace = getEventFactory().createNamespace(prefix, namespaceUri); + } + else { + newNamespace = getEventFactory().createNamespace(namespaceUri); + } + newNamespaces.add(newNamespace); + StartElement oldStartElement = getStartElement(); + this.startElement = getEventFactory() + .createStartElement(oldStartElement.getName(), oldStartElement.getAttributes(), + newNamespaces.iterator()); + } - protected final StartElement getStartElement() { - return startElement; - } + protected final StartElement getStartElement() { + return startElement; + } - protected final EndElement getEndElement() { - return endElement; - } + protected final EndElement getEndElement() { + return endElement; + } - private enum EVENT_READER_STATE { + private enum EVENT_READER_STATE { - START_DOCUMENT, - START_ELEMENT, - CHILDREN, - END_ELEMENT, - END_DOCUMENT, - DONE - } + START_DOCUMENT, + START_ELEMENT, + CHILDREN, + END_ELEMENT, + END_DOCUMENT, + DONE + } - private class StroapElementEventReader extends AbstractXMLEventReader { + private class StroapElementEventReader extends AbstractXMLEventReader { - private EVENT_READER_STATE state; + private EVENT_READER_STATE state; - private boolean documentEvents; + private boolean documentEvents; - private final XMLEventReader childEventReader; + private final XMLEventReader childEventReader; - private StroapElementEventReader(boolean documentEvents) { - this.documentEvents = documentEvents; - state = documentEvents ? EVENT_READER_STATE.START_DOCUMENT : EVENT_READER_STATE.START_ELEMENT; - this.childEventReader = getChildEventReader(); - } + private StroapElementEventReader(boolean documentEvents) { + this.documentEvents = documentEvents; + state = documentEvents ? EVENT_READER_STATE.START_DOCUMENT : EVENT_READER_STATE.START_ELEMENT; + this.childEventReader = getChildEventReader(); + } - public boolean hasNext() { - if (documentEvents && state == EVENT_READER_STATE.DONE) { - return false; - } - else if (!documentEvents && state == EVENT_READER_STATE.END_DOCUMENT) { - return false; - } - else { - return true; - } - } + public boolean hasNext() { + if (documentEvents && state == EVENT_READER_STATE.DONE) { + return false; + } + else if (!documentEvents && state == EVENT_READER_STATE.END_DOCUMENT) { + return false; + } + else { + return true; + } + } - public XMLEvent nextEvent() throws XMLStreamException { - switch (state) { - case START_DOCUMENT: - state = EVENT_READER_STATE.START_ELEMENT; - return getEventFactory().createStartDocument(); - case START_ELEMENT: - state = EVENT_READER_STATE.CHILDREN; - return getStartElement(); - case CHILDREN: - if (!childEventReader.hasNext()) { - state = EVENT_READER_STATE.END_ELEMENT; - return nextEvent(); - } - return childEventReader.nextEvent(); - case END_ELEMENT: - state = EVENT_READER_STATE.END_DOCUMENT; - return getEndElement(); - case END_DOCUMENT: - state = EVENT_READER_STATE.DONE; - return getEventFactory().createEndDocument(); - case DONE: - throw new NoSuchElementException(); - default: - throw new IllegalStateException(); - } - } + public XMLEvent nextEvent() throws XMLStreamException { + switch (state) { + case START_DOCUMENT: + state = EVENT_READER_STATE.START_ELEMENT; + return getEventFactory().createStartDocument(); + case START_ELEMENT: + state = EVENT_READER_STATE.CHILDREN; + return getStartElement(); + case CHILDREN: + if (!childEventReader.hasNext()) { + state = EVENT_READER_STATE.END_ELEMENT; + return nextEvent(); + } + return childEventReader.nextEvent(); + case END_ELEMENT: + state = EVENT_READER_STATE.END_DOCUMENT; + return getEndElement(); + case END_DOCUMENT: + state = EVENT_READER_STATE.DONE; + return getEventFactory().createEndDocument(); + case DONE: + throw new NoSuchElementException(); + default: + throw new IllegalStateException(); + } + } - public XMLEvent peek() throws XMLStreamException { - switch (state) { - case START_DOCUMENT: - return getEventFactory().createStartDocument(); - case START_ELEMENT: - return getStartElement(); - case CHILDREN: - XMLEvent event = childEventReader.peek(); - if (event == null) { - state = EVENT_READER_STATE.END_ELEMENT; - event = getEndElement(); - } - return event; - case END_ELEMENT: - return getEndElement(); - case END_DOCUMENT: - return getEventFactory().createEndDocument(); - case DONE: - return null; - default: - throw new IllegalStateException(); - } + public XMLEvent peek() throws XMLStreamException { + switch (state) { + case START_DOCUMENT: + return getEventFactory().createStartDocument(); + case START_ELEMENT: + return getStartElement(); + case CHILDREN: + XMLEvent event = childEventReader.peek(); + if (event == null) { + state = EVENT_READER_STATE.END_ELEMENT; + event = getEndElement(); + } + return event; + case END_ELEMENT: + return getEndElement(); + case END_DOCUMENT: + return getEventFactory().createEndDocument(); + case DONE: + return null; + default: + throw new IllegalStateException(); + } - } - } + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapEnvelope.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapEnvelope.java index 184e9b84..66d0471a 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapEnvelope.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapEnvelope.java @@ -35,91 +35,91 @@ import org.springframework.xml.stream.CompositeXMLEventReader; */ class StroapEnvelope extends StroapElement implements SoapEnvelope { - private static final String LOCAL_NAME = "Envelope"; + private static final String LOCAL_NAME = "Envelope"; - private StroapHeader header; + private StroapHeader header; - private StroapBody body; + private StroapBody body; - StroapEnvelope(StroapMessageFactory messageFactory) { - super(messageFactory.getSoapVersion().getEnvelopeName(), messageFactory); - this.header = null; - this.body = new Stroap11Body(messageFactory); - } + StroapEnvelope(StroapMessageFactory messageFactory) { + super(messageFactory.getSoapVersion().getEnvelopeName(), messageFactory); + this.header = null; + this.body = new Stroap11Body(messageFactory); + } - private StroapEnvelope(StartElement startElement, - StroapHeader header, - StroapBody body, - StroapMessageFactory messageFactory) { - super(startElement, messageFactory); - this.header = header; - this.body = body; - } + private StroapEnvelope(StartElement startElement, + StroapHeader header, + StroapBody body, + StroapMessageFactory messageFactory) { + super(startElement, messageFactory); + this.header = header; + this.body = body; + } - static StroapEnvelope build(XMLEventReader eventReader, StroapMessageFactory messageFactory) - throws XMLStreamException { - XMLEvent event = eventReader.nextTag(); - if (!event.isStartElement()) { - throw new StroapMessageCreationException("Unexpected event: " + event + ", expected StartElement"); - } - StartElement startElement = event.asStartElement(); - SoapVersion soapVersion = messageFactory.getSoapVersion(); - if (!soapVersion.getEnvelopeName().equals(startElement.getName())) { - throw new StroapMessageCreationException( - "Unexpected name: " + startElement.getName() + ", expected " + soapVersion.getEnvelopeName()); - } - StroapHeader header = null; - StroapBody body = null; - XMLEvent peekedEvent = eventReader.peek(); - while (peekedEvent != null) { - if (peekedEvent.isStartElement()) { - QName headerOrBodyName = peekedEvent.asStartElement().getName(); - if (soapVersion.getHeaderName().equals(headerOrBodyName)) { - header = StroapHeader.build(eventReader, messageFactory); - } - else if (soapVersion.getBodyName().equals(headerOrBodyName)) { - body = StroapBody.build(eventReader, messageFactory); - break; - } - else { - throw new StroapMessageCreationException( - "Unexpected start element name [" + headerOrBodyName + "]"); - } - } - else { - eventReader.nextEvent(); - } - peekedEvent = eventReader.peek(); - } - if (body == null) { - throw new StroapMessageCreationException("No SOAP body found"); - } + static StroapEnvelope build(XMLEventReader eventReader, StroapMessageFactory messageFactory) + throws XMLStreamException { + XMLEvent event = eventReader.nextTag(); + if (!event.isStartElement()) { + throw new StroapMessageCreationException("Unexpected event: " + event + ", expected StartElement"); + } + StartElement startElement = event.asStartElement(); + SoapVersion soapVersion = messageFactory.getSoapVersion(); + if (!soapVersion.getEnvelopeName().equals(startElement.getName())) { + throw new StroapMessageCreationException( + "Unexpected name: " + startElement.getName() + ", expected " + soapVersion.getEnvelopeName()); + } + StroapHeader header = null; + StroapBody body = null; + XMLEvent peekedEvent = eventReader.peek(); + while (peekedEvent != null) { + if (peekedEvent.isStartElement()) { + QName headerOrBodyName = peekedEvent.asStartElement().getName(); + if (soapVersion.getHeaderName().equals(headerOrBodyName)) { + header = StroapHeader.build(eventReader, messageFactory); + } + else if (soapVersion.getBodyName().equals(headerOrBodyName)) { + body = StroapBody.build(eventReader, messageFactory); + break; + } + else { + throw new StroapMessageCreationException( + "Unexpected start element name [" + headerOrBodyName + "]"); + } + } + else { + eventReader.nextEvent(); + } + peekedEvent = eventReader.peek(); + } + if (body == null) { + throw new StroapMessageCreationException("No SOAP body found"); + } - return new StroapEnvelope(startElement, header, body, messageFactory); - } + return new StroapEnvelope(startElement, header, body, messageFactory); + } - public SoapHeader getHeader() throws SoapHeaderException { - if (header == null) { - header = new Stroap11Header(getMessageFactory()); - } - return header; - } + public SoapHeader getHeader() throws SoapHeaderException { + if (header == null) { + header = new Stroap11Header(getMessageFactory()); + } + return header; + } - public SoapBody getBody() throws SoapBodyException { - if (body == null) { - body = new Stroap11Body(getMessageFactory()); - } - return body; - } + public SoapBody getBody() throws SoapBodyException { + if (body == null) { + body = new Stroap11Body(getMessageFactory()); + } + return body; + } - @Override - protected XMLEventReader getChildEventReader() { - if (header != null) { - return new CompositeXMLEventReader(header.getEventReader(false), body.getEventReader(false)); - } - else { - return body.getEventReader(false); - } - } + @Override + protected XMLEventReader getChildEventReader() { + if (header != null) { + return new CompositeXMLEventReader(header.getEventReader(false), body.getEventReader(false)); + } + else { + return body.getEventReader(false); + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapFault.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapFault.java index aad4cc87..a74737ab 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapFault.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapFault.java @@ -23,7 +23,7 @@ import org.springframework.ws.soap.SoapFault; */ abstract class StroapFault extends StroapElement implements SoapFault { - protected StroapFault(StroapMessageFactory messageFactory) { - super(messageFactory.getSoapVersion().getFaultName(), messageFactory); - } + protected StroapFault(StroapMessageFactory messageFactory) { + super(messageFactory.getSoapVersion().getFaultName(), messageFactory); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeader.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeader.java index dbd82791..04daf8f3 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeader.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeader.java @@ -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, @@ -41,125 +41,125 @@ import org.springframework.xml.stream.CompositeXMLEventReader; */ abstract class StroapHeader extends StroapElement implements SoapHeader { - private List headerElements = new LinkedList(); + private List headerElements = new LinkedList(); - protected StroapHeader(StroapMessageFactory messageFactory) { - super(messageFactory.getSoapVersion().getHeaderName(), messageFactory); - } + protected StroapHeader(StroapMessageFactory messageFactory) { + super(messageFactory.getSoapVersion().getHeaderName(), messageFactory); + } - protected StroapHeader(StartElement startElement, StroapMessageFactory messageFactory) { - super(startElement, messageFactory); - } + protected StroapHeader(StartElement startElement, StroapMessageFactory messageFactory) { + super(startElement, messageFactory); + } - static StroapHeader build(XMLEventReader eventReader, StroapMessageFactory messageFactory) - throws XMLStreamException { - XMLEvent event = eventReader.nextTag(); - if (!event.isStartElement()) { - throw new StroapMessageCreationException("Unexpected event: " + event + ", expected StartElement"); - } - StartElement startElement = event.asStartElement(); - SoapVersion soapVersion = messageFactory.getSoapVersion(); - if (!soapVersion.getHeaderName().equals(startElement.getName())) { - throw new StroapMessageCreationException( - "Unexpected name: " + startElement.getName() + ", expected " + soapVersion.getHeaderName()); - } + static StroapHeader build(XMLEventReader eventReader, StroapMessageFactory messageFactory) + throws XMLStreamException { + XMLEvent event = eventReader.nextTag(); + if (!event.isStartElement()) { + throw new StroapMessageCreationException("Unexpected event: " + event + ", expected StartElement"); + } + StartElement startElement = event.asStartElement(); + SoapVersion soapVersion = messageFactory.getSoapVersion(); + if (!soapVersion.getHeaderName().equals(startElement.getName())) { + throw new StroapMessageCreationException( + "Unexpected name: " + startElement.getName() + ", expected " + soapVersion.getHeaderName()); + } - if (SoapVersion.SOAP_11.equals(soapVersion)) { - return new Stroap11Header(startElement, messageFactory); - } - else { - return null; - } + if (SoapVersion.SOAP_11.equals(soapVersion)) { + return new Stroap11Header(startElement, messageFactory); + } + else { + return null; + } - } + } - public SoapHeaderElement addHeaderElement(QName name) throws SoapHeaderException { - StroapHeaderElement headerElement = new StroapHeaderElement(name, getMessageFactory()); - headerElements.add(headerElement); - return headerElement; - } + public SoapHeaderElement addHeaderElement(QName name) throws SoapHeaderException { + StroapHeaderElement headerElement = new StroapHeaderElement(name, getMessageFactory()); + headerElements.add(headerElement); + return headerElement; + } - public Iterator examineAllHeaderElements() throws SoapHeaderException { - List headerElements = Collections.unmodifiableList(this.headerElements); - return headerElements.iterator(); - } + public Iterator examineAllHeaderElements() throws SoapHeaderException { + List headerElements = Collections.unmodifiableList(this.headerElements); + return headerElements.iterator(); + } - public Iterator examineHeaderElements(QName name) throws SoapHeaderException { - List result = new LinkedList(); - for (StroapHeaderElement headerElement : this.headerElements) { - if (headerElement.getName().equals(name)) { - result.add(headerElement); - } - } - return result.iterator(); - } + public Iterator examineHeaderElements(QName name) throws SoapHeaderException { + List result = new LinkedList(); + for (StroapHeaderElement headerElement : this.headerElements) { + if (headerElement.getName().equals(name)) { + result.add(headerElement); + } + } + return result.iterator(); + } - public Iterator examineMustUnderstandHeaderElements(String actorOrRole) - throws SoapHeaderException { - List result = new LinkedList(); - for (StroapHeaderElement headerElement : this.headerElements) { - if (headerElement.getMustUnderstand() && headerElement.getActorOrRole().equals(actorOrRole)) { - result.add(headerElement); - } - } - return result.iterator(); - } + public Iterator examineMustUnderstandHeaderElements(String actorOrRole) + throws SoapHeaderException { + List result = new LinkedList(); + for (StroapHeaderElement headerElement : this.headerElements) { + if (headerElement.getMustUnderstand() && headerElement.getActorOrRole().equals(actorOrRole)) { + result.add(headerElement); + } + } + return result.iterator(); + } - public void removeHeaderElement(QName name) throws SoapHeaderException { - Assert.notNull(name, "'name' must not be null"); + public void removeHeaderElement(QName name) throws SoapHeaderException { + Assert.notNull(name, "'name' must not be null"); - for (Iterator iterator = headerElements.iterator(); iterator.hasNext();) { - StroapHeaderElement headerElement = iterator.next(); - if (name.equals(headerElement.getName())) { - iterator.remove(); - break; - } - } - } + for (Iterator iterator = headerElements.iterator(); iterator.hasNext();) { + StroapHeaderElement headerElement = iterator.next(); + if (name.equals(headerElement.getName())) { + iterator.remove(); + break; + } + } + } - @Override - protected XMLEventReader getChildEventReader() { - XMLEventReader[] eventReaders = new XMLEventReader[headerElements.size()]; - for (int i = 0; i < headerElements.size(); i++) { - StroapHeaderElement headerElement = headerElements.get(i); - eventReaders[i] = headerElement.getEventReader(false); - } - return new CompositeXMLEventReader(eventReaders); - } + @Override + protected XMLEventReader getChildEventReader() { + XMLEventReader[] eventReaders = new XMLEventReader[headerElements.size()]; + for (int i = 0; i < headerElements.size(); i++) { + StroapHeaderElement headerElement = headerElements.get(i); + eventReaders[i] = headerElement.getEventReader(false); + } + return new CompositeXMLEventReader(eventReaders); + } - public Result getResult() { - headerElements.clear(); - return StaxUtils.createCustomStaxResult(new StroapHeaderXMLEventWriter()); - } + public Result getResult() { + headerElements.clear(); + return StaxUtils.createCustomStaxResult(new StroapHeaderXMLEventWriter()); + } - class StroapHeaderXMLEventWriter extends AbstractXMLEventWriter { + class StroapHeaderXMLEventWriter extends AbstractXMLEventWriter { - private int elementDepth = 0; + private int elementDepth = 0; - boolean startElementSeen = false; + boolean startElementSeen = false; - private final List events = new LinkedList(); + private final List events = new LinkedList(); - public void add(XMLEvent event) throws XMLStreamException { - if (event.isStartElement()) { - startElementSeen = true; - elementDepth++; - } - else if (event.isEndElement()) { - elementDepth--; - } - else if (event.isStartDocument() || event.isEndDocument()) { - return; - } - if (elementDepth >= 0 && startElementSeen) { - events.add(event); - } - if (elementDepth == 0 && (event.isEndElement() || event.isEndDocument())) { - StroapHeaderElement headerElement = StroapHeaderElement.build(events, getMessageFactory()); - headerElements.add(headerElement); - events.clear(); - } - } - } + public void add(XMLEvent event) throws XMLStreamException { + if (event.isStartElement()) { + startElementSeen = true; + elementDepth++; + } + else if (event.isEndElement()) { + elementDepth--; + } + else if (event.isStartDocument() || event.isEndDocument()) { + return; + } + if (elementDepth >= 0 && startElementSeen) { + events.add(event); + } + if (elementDepth == 0 && (event.isEndElement() || event.isEndDocument())) { + StroapHeaderElement headerElement = StroapHeaderElement.build(events, getMessageFactory()); + headerElements.add(headerElement); + events.clear(); + } + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderElement.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderElement.java index 1c305f73..cc6b86ee 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderElement.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderElement.java @@ -36,77 +36,77 @@ import org.springframework.xml.stream.ListBasedXMLEventReader; */ class StroapHeaderElement extends StroapElement implements SoapHeaderElement { - private final List events = new LinkedList(); + private final List events = new LinkedList(); - StroapHeaderElement(QName name, StroapMessageFactory messageFactory) { - super(name, messageFactory); - } + StroapHeaderElement(QName name, StroapMessageFactory messageFactory) { + super(name, messageFactory); + } - private StroapHeaderElement(StartElement startElement, List events, StroapMessageFactory messageFactory) { - super(startElement, messageFactory); - Assert.notNull(events, "'events' must not be null"); - this.events.addAll(events); - } + private StroapHeaderElement(StartElement startElement, List events, StroapMessageFactory messageFactory) { + super(startElement, messageFactory); + Assert.notNull(events, "'events' must not be null"); + this.events.addAll(events); + } - static StroapHeaderElement build(List events, StroapMessageFactory messageFactory) - throws XMLStreamException { - Assert.notNull(events, "'events' must not be null"); - Assert.isTrue(events.size() >= 2, "not enough events"); - XMLEvent event = events.get(0); - if (!event.isStartElement()) { - throw new StroapHeaderException("Unexpected event: " + event + ", expected StartElement"); - } - StartElement startElement = event.asStartElement(); - event = events.get(events.size() - 1); - if (!event.isEndElement()) { - throw new StroapHeaderException("Unexpected event: " + event + ", expected EndElement"); - } - List childEvents = events.subList(1, events.size() - 1); - return new StroapHeaderElement(startElement, childEvents, messageFactory); - } + static StroapHeaderElement build(List events, StroapMessageFactory messageFactory) + throws XMLStreamException { + Assert.notNull(events, "'events' must not be null"); + Assert.isTrue(events.size() >= 2, "not enough events"); + XMLEvent event = events.get(0); + if (!event.isStartElement()) { + throw new StroapHeaderException("Unexpected event: " + event + ", expected StartElement"); + } + StartElement startElement = event.asStartElement(); + event = events.get(events.size() - 1); + if (!event.isEndElement()) { + throw new StroapHeaderException("Unexpected event: " + event + ", expected EndElement"); + } + List childEvents = events.subList(1, events.size() - 1); + return new StroapHeaderElement(startElement, childEvents, messageFactory); + } - public final String getActorOrRole() throws SoapHeaderException { - return getAttributeValue(getSoapVersion().getActorOrRoleName()); - } + public final String getActorOrRole() throws SoapHeaderException { + return getAttributeValue(getSoapVersion().getActorOrRoleName()); + } - public final void setActorOrRole(String actorOrRole) throws SoapHeaderException { - addAttribute(getSoapVersion().getActorOrRoleName(), actorOrRole); - } + public final void setActorOrRole(String actorOrRole) throws SoapHeaderException { + addAttribute(getSoapVersion().getActorOrRoleName(), actorOrRole); + } - public final boolean getMustUnderstand() throws SoapHeaderException { - String mustUnderstandAttribute = getAttributeValue(getSoapVersion().getMustUnderstandAttributeName()); - return "1".equals(mustUnderstandAttribute); - } + public final boolean getMustUnderstand() throws SoapHeaderException { + String mustUnderstandAttribute = getAttributeValue(getSoapVersion().getMustUnderstandAttributeName()); + return "1".equals(mustUnderstandAttribute); + } - public void setMustUnderstand(boolean mustUnderstand) throws SoapHeaderException { - String mustUnderstandAttribute = mustUnderstand ? "1" : "0"; - addAttribute(getSoapVersion().getMustUnderstandAttributeName(), mustUnderstandAttribute); - } + public void setMustUnderstand(boolean mustUnderstand) throws SoapHeaderException { + String mustUnderstandAttribute = mustUnderstand ? "1" : "0"; + addAttribute(getSoapVersion().getMustUnderstandAttributeName(), mustUnderstandAttribute); + } - public Result getResult() throws SoapHeaderException { - events.clear(); - return StaxUtils.createCustomStaxResult(new CachingXMLEventWriter(events)); - } + public Result getResult() throws SoapHeaderException { + events.clear(); + return StaxUtils.createCustomStaxResult(new CachingXMLEventWriter(events)); + } - public String getText() { - StringBuilder builder = new StringBuilder(); - for (XMLEvent event : events) { - if (event.isCharacters()) { - builder.append(event.asCharacters().getData()); - } - } - return builder.toString(); - } + public String getText() { + StringBuilder builder = new StringBuilder(); + for (XMLEvent event : events) { + if (event.isCharacters()) { + builder.append(event.asCharacters().getData()); + } + } + return builder.toString(); + } - public void setText(String content) { - events.clear(); - events.add(getEventFactory().createCharacters(content)); - } + public void setText(String content) { + events.clear(); + events.add(getEventFactory().createCharacters(content)); + } - @Override - protected XMLEventReader getChildEventReader() { - return new ListBasedXMLEventReader(events); - } + @Override + protected XMLEventReader getChildEventReader() { + return new ListBasedXMLEventReader(events); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderException.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderException.java index ecd73acc..362a681e 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderException.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapHeaderException.java @@ -24,15 +24,15 @@ import org.springframework.ws.soap.SoapHeaderException; */ public class StroapHeaderException extends SoapHeaderException { - public StroapHeaderException(String msg) { - super(msg); - } + public StroapHeaderException(String msg) { + super(msg); + } - public StroapHeaderException(String msg, Throwable ex) { - super(msg, ex); - } + public StroapHeaderException(String msg, Throwable ex) { + super(msg, ex); + } - public StroapHeaderException(Throwable ex) { - super(ex); - } + public StroapHeaderException(Throwable ex) { + super(ex); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessage.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessage.java index 6abbc1a7..ccd13ade 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessage.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessage.java @@ -68,230 +68,230 @@ import org.xml.sax.SAXException; */ public class StroapMessage extends AbstractSoapMessage implements StreamingWebServiceMessage { - private final MultiValueMap mimeHeaders = new LinkedMultiValueMap(); + private final MultiValueMap mimeHeaders = new LinkedMultiValueMap(); - private StroapEnvelope envelope; + private StroapEnvelope envelope; - private final StroapMessageFactory messageFactory; + private final StroapMessageFactory messageFactory; - private final StartDocument startDocument; + private final StartDocument startDocument; - private final EndDocument endDocument; + private final EndDocument endDocument; - public StroapMessage(StroapMessageFactory messageFactory) { - this(null, null, messageFactory); - } + public StroapMessage(StroapMessageFactory messageFactory) { + this(null, null, messageFactory); + } - public StroapMessage(MultiValueMap mimeHeaders, - StroapEnvelope envelope, - StroapMessageFactory messageFactory) { - Assert.notNull(messageFactory, "'messageFactory' must not be null"); - this.messageFactory = messageFactory; - if (mimeHeaders != null) { - this.mimeHeaders.putAll(mimeHeaders); - } - this.envelope = envelope != null ? envelope : new StroapEnvelope(messageFactory); - if (!this.mimeHeaders.containsKey(TransportConstants.HEADER_CONTENT_TYPE)) { - this.mimeHeaders - .set(TransportConstants.HEADER_CONTENT_TYPE, messageFactory.getSoapVersion().getContentType()); - } - if (!this.mimeHeaders.containsKey(TransportConstants.HEADER_ACCEPT)) { - this.mimeHeaders.set(TransportConstants.HEADER_ACCEPT, messageFactory.getSoapVersion().getContentType()); - } - this.startDocument = messageFactory.getEventFactory().createStartDocument(); - this.endDocument = messageFactory.getEventFactory().createEndDocument(); - } + public StroapMessage(MultiValueMap mimeHeaders, + StroapEnvelope envelope, + StroapMessageFactory messageFactory) { + Assert.notNull(messageFactory, "'messageFactory' must not be null"); + this.messageFactory = messageFactory; + if (mimeHeaders != null) { + this.mimeHeaders.putAll(mimeHeaders); + } + this.envelope = envelope != null ? envelope : new StroapEnvelope(messageFactory); + if (!this.mimeHeaders.containsKey(TransportConstants.HEADER_CONTENT_TYPE)) { + this.mimeHeaders + .set(TransportConstants.HEADER_CONTENT_TYPE, messageFactory.getSoapVersion().getContentType()); + } + if (!this.mimeHeaders.containsKey(TransportConstants.HEADER_ACCEPT)) { + this.mimeHeaders.set(TransportConstants.HEADER_ACCEPT, messageFactory.getSoapVersion().getContentType()); + } + this.startDocument = messageFactory.getEventFactory().createStartDocument(); + this.endDocument = messageFactory.getEventFactory().createEndDocument(); + } - static StroapMessage build(InputStream inputStream, StroapMessageFactory messageFactory) - throws XMLStreamException, IOException { - MultiValueMap mimeHeaders = parseMimeHeaders(inputStream); - XMLEventReader eventReader = messageFactory.getInputFactory().createXMLEventReader(inputStream); - StroapEnvelope envelope = StroapEnvelope.build(eventReader, messageFactory); - return new StroapMessage(mimeHeaders, envelope, messageFactory); - } + static StroapMessage build(InputStream inputStream, StroapMessageFactory messageFactory) + throws XMLStreamException, IOException { + MultiValueMap mimeHeaders = parseMimeHeaders(inputStream); + XMLEventReader eventReader = messageFactory.getInputFactory().createXMLEventReader(inputStream); + StroapEnvelope envelope = StroapEnvelope.build(eventReader, messageFactory); + return new StroapMessage(mimeHeaders, envelope, messageFactory); + } - private static MultiValueMap parseMimeHeaders(InputStream inputStream) throws IOException { - MultiValueMap mimeHeaders = new LinkedMultiValueMap(); - if (inputStream instanceof TransportInputStream) { - TransportInputStream transportInputStream = (TransportInputStream) inputStream; - for (Iterator headerNames = transportInputStream.getHeaderNames(); headerNames.hasNext();) { - String headerName = headerNames.next(); - for (Iterator headerValues = transportInputStream.getHeaders(headerName); - headerValues.hasNext();) { - String headerValue = headerValues.next(); - StringTokenizer tokenizer = new StringTokenizer(headerValue, ","); - while (tokenizer.hasMoreTokens()) { - mimeHeaders.add(headerName, tokenizer.nextToken().trim()); - } - } - } - } - return mimeHeaders; - } + private static MultiValueMap parseMimeHeaders(InputStream inputStream) throws IOException { + MultiValueMap mimeHeaders = new LinkedMultiValueMap(); + if (inputStream instanceof TransportInputStream) { + TransportInputStream transportInputStream = (TransportInputStream) inputStream; + for (Iterator headerNames = transportInputStream.getHeaderNames(); headerNames.hasNext();) { + String headerName = headerNames.next(); + for (Iterator headerValues = transportInputStream.getHeaders(headerName); + headerValues.hasNext();) { + String headerValue = headerValues.next(); + StringTokenizer tokenizer = new StringTokenizer(headerValue, ","); + while (tokenizer.hasMoreTokens()) { + mimeHeaders.add(headerName, tokenizer.nextToken().trim()); + } + } + } + } + return mimeHeaders; + } - public SoapEnvelope getEnvelope() throws SoapEnvelopeException { - return envelope; - } + public SoapEnvelope getEnvelope() throws SoapEnvelopeException { + return envelope; + } - public void setStreamingPayload(StreamingPayload payload) { - StroapBody soapBody = (StroapBody) getSoapBody(); - soapBody.setStreamingPayload(payload); - } + public void setStreamingPayload(StreamingPayload payload) { + StroapBody soapBody = (StroapBody) getSoapBody(); + soapBody.setStreamingPayload(payload); + } - public String getSoapAction() { - String soapAction = mimeHeaders.getFirst(TransportConstants.HEADER_SOAP_ACTION); - return StringUtils.hasLength(soapAction) ? soapAction : TransportConstants.EMPTY_SOAP_ACTION; - } + public String getSoapAction() { + String soapAction = mimeHeaders.getFirst(TransportConstants.HEADER_SOAP_ACTION); + return StringUtils.hasLength(soapAction) ? soapAction : TransportConstants.EMPTY_SOAP_ACTION; + } - public void setSoapAction(String soapAction) { - soapAction = SoapUtils.escapeAction(soapAction); - mimeHeaders.set(TransportConstants.HEADER_SOAP_ACTION, soapAction); - } + public void setSoapAction(String soapAction) { + soapAction = SoapUtils.escapeAction(soapAction); + mimeHeaders.set(TransportConstants.HEADER_SOAP_ACTION, soapAction); + } - @Override - public SoapVersion getVersion() { - return messageFactory.getSoapVersion(); - } + @Override + public SoapVersion getVersion() { + return messageFactory.getSoapVersion(); + } - public Document getDocument() { - try { - DocumentBuilder documentBuilder = messageFactory.getDocumentBuilderFactory().newDocumentBuilder(); - try { - Document result = documentBuilder.newDocument(); - DOMResult domResult = new DOMResult(result); - XMLEventWriter eventWriter = messageFactory.getOutputFactory().createXMLEventWriter(domResult); - eventWriter.add(startDocument); - envelope.writeTo(new NoStartEndDocumentWriter(eventWriter)); - eventWriter.add(endDocument); - eventWriter.flush(); - return result; - } - catch (XMLStreamException ignored) { - // ignored - } - catch (UnsupportedOperationException ignored) { - // ignored - } + public Document getDocument() { + try { + DocumentBuilder documentBuilder = messageFactory.getDocumentBuilderFactory().newDocumentBuilder(); + try { + Document result = documentBuilder.newDocument(); + DOMResult domResult = new DOMResult(result); + XMLEventWriter eventWriter = messageFactory.getOutputFactory().createXMLEventWriter(domResult); + eventWriter.add(startDocument); + envelope.writeTo(new NoStartEndDocumentWriter(eventWriter)); + eventWriter.add(endDocument); + eventWriter.flush(); + return result; + } + catch (XMLStreamException ignored) { + // ignored + } + catch (UnsupportedOperationException ignored) { + // ignored + } - // XMLOutputFactory does not support DOMResults, so let's do it the hard way - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - writeTo(bos); + // XMLOutputFactory does not support DOMResults, so let's do it the hard way + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + writeTo(bos); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - return documentBuilder.parse(bis); - } - catch (ParserConfigurationException ex) { - throw new StroapMessageException("Could not create DocumentBuilderFactory", ex); - } - catch (SAXException ex) { - throw new StroapMessageException("Could not save message as Document", ex); - } - catch (IOException ex) { - throw new StroapMessageException("Could not save message as Document", ex); - } - } + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + return documentBuilder.parse(bis); + } + catch (ParserConfigurationException ex) { + throw new StroapMessageException("Could not create DocumentBuilderFactory", ex); + } + catch (SAXException ex) { + throw new StroapMessageException("Could not save message as Document", ex); + } + catch (IOException ex) { + throw new StroapMessageException("Could not save message as Document", ex); + } + } - public void setDocument(Document document) { - try { - try { - DOMSource domSource = new DOMSource(document); - XMLEventReader eventReader = messageFactory.getInputFactory().createXMLEventReader(domSource); - this.envelope = StroapEnvelope.build(eventReader, messageFactory); - return; - } - catch (XMLStreamException ignored) { - // ignored - } - catch (UnsupportedOperationException ignored) { - // ignored - } - // XMLInputFactory does not support DOMSources, so let's do it the hard way - DOMImplementation implementation = document.getImplementation(); - Assert.isInstanceOf(DOMImplementationLS.class, implementation); + public void setDocument(Document document) { + try { + try { + DOMSource domSource = new DOMSource(document); + XMLEventReader eventReader = messageFactory.getInputFactory().createXMLEventReader(domSource); + this.envelope = StroapEnvelope.build(eventReader, messageFactory); + return; + } + catch (XMLStreamException ignored) { + // ignored + } + catch (UnsupportedOperationException ignored) { + // ignored + } + // XMLInputFactory does not support DOMSources, so let's do it the hard way + DOMImplementation implementation = document.getImplementation(); + Assert.isInstanceOf(DOMImplementationLS.class, implementation); - DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation; - LSOutput output = loadSaveImplementation.createLSOutput(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - output.setByteStream(bos); + DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation; + LSOutput output = loadSaveImplementation.createLSOutput(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + output.setByteStream(bos); - LSSerializer serializer = loadSaveImplementation.createLSSerializer(); - serializer.write(document, output); + LSSerializer serializer = loadSaveImplementation.createLSSerializer(); + serializer.write(document, output); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - XMLEventReader eventReader = messageFactory.getInputFactory().createXMLEventReader(bis); - this.envelope = StroapEnvelope.build(eventReader, messageFactory); - } - catch (XMLStreamException ex) { - throw new StroapMessageException("Could not read Document", ex); - } - } + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + XMLEventReader eventReader = messageFactory.getInputFactory().createXMLEventReader(bis); + this.envelope = StroapEnvelope.build(eventReader, messageFactory); + } + catch (XMLStreamException ex) { + throw new StroapMessageException("Could not read Document", ex); + } + } - public void writeTo(OutputStream outputStream) throws IOException { - if (outputStream instanceof TransportOutputStream) { - TransportOutputStream tos = (TransportOutputStream) outputStream; - for (Map.Entry> entry : mimeHeaders.entrySet()) { - String name = entry.getKey(); - for (String value : entry.getValue()) { - tos.addHeader(name, value); - } - } - } - try { - XMLEventWriter eventWriter = messageFactory.getOutputFactory().createXMLEventWriter(outputStream); - eventWriter.add(startDocument); - envelope.writeTo(new NoStartEndDocumentWriter(eventWriter)); - eventWriter.add(endDocument); - eventWriter.flush(); - } - catch (XMLStreamException ex) { - throw new StroapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); - } - } + public void writeTo(OutputStream outputStream) throws IOException { + if (outputStream instanceof TransportOutputStream) { + TransportOutputStream tos = (TransportOutputStream) outputStream; + for (Map.Entry> entry : mimeHeaders.entrySet()) { + String name = entry.getKey(); + for (String value : entry.getValue()) { + tos.addHeader(name, value); + } + } + } + try { + XMLEventWriter eventWriter = messageFactory.getOutputFactory().createXMLEventWriter(outputStream); + eventWriter.add(startDocument); + envelope.writeTo(new NoStartEndDocumentWriter(eventWriter)); + eventWriter.add(endDocument); + eventWriter.flush(); + } + catch (XMLStreamException ex) { + throw new StroapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); + } + } - public boolean isXopPackage() { - return false; - } + public boolean isXopPackage() { + return false; + } - public boolean convertToXopPackage() { - return false; - } + public boolean convertToXopPackage() { + return false; + } - public Attachment getAttachment(String contentId) throws AttachmentException { - throw new UnsupportedOperationException(); - } + public Attachment getAttachment(String contentId) throws AttachmentException { + throw new UnsupportedOperationException(); + } - public Iterator getAttachments() throws AttachmentException { - return Collections.emptyList().iterator(); - } + public Iterator getAttachments() throws AttachmentException { + return Collections.emptyList().iterator(); + } - public Attachment addAttachment(String contentId, DataHandler dataHandler) { - throw new UnsupportedOperationException(); - } + public Attachment addAttachment(String contentId, DataHandler dataHandler) { + throw new UnsupportedOperationException(); + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder("StroapMessage"); - StroapBody body = (StroapBody) envelope.getBody(); - if (body != null) { - builder.append(' '); - builder.append(body.getPayloadName()); - } - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder("StroapMessage"); + StroapBody body = (StroapBody) envelope.getBody(); + if (body != null) { + builder.append(' '); + builder.append(body.getPayloadName()); + } + return builder.toString(); + } - private static class NoStartEndDocumentWriter extends AbstractXMLEventWriter { + private static class NoStartEndDocumentWriter extends AbstractXMLEventWriter { - private final XMLEventWriter delegate; + private final XMLEventWriter delegate; - private NoStartEndDocumentWriter(XMLEventWriter delegate) { - this.delegate = delegate; - } + private NoStartEndDocumentWriter(XMLEventWriter delegate) { + this.delegate = delegate; + } - public void add(XMLEvent event) throws XMLStreamException { - if (!event.isStartDocument() && !event.isEndDocument()) { - delegate.add(event); - } - } - } + public void add(XMLEvent event) throws XMLStreamException { + if (!event.isStartDocument() && !event.isEndDocument()) { + delegate.add(event); + } + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageCreationException.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageCreationException.java index b2c24db9..3f696ecd 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageCreationException.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageCreationException.java @@ -23,11 +23,11 @@ import org.springframework.ws.soap.SoapMessageCreationException; */ public class StroapMessageCreationException extends SoapMessageCreationException { - public StroapMessageCreationException(String msg) { - super(msg); - } + public StroapMessageCreationException(String msg) { + super(msg); + } - public StroapMessageCreationException(String msg, Throwable ex) { - super(msg, ex); - } + public StroapMessageCreationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageException.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageException.java index a60f666e..e8cc4d68 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageException.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageException.java @@ -23,13 +23,13 @@ import org.springframework.ws.soap.SoapMessageException; */ public class StroapMessageException extends SoapMessageException { - public StroapMessageException(String msg) { - super(msg); - } + public StroapMessageException(String msg) { + super(msg); + } - public StroapMessageException(String msg, Throwable ex) { - super(msg, ex); - } + public StroapMessageException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageFactory.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageFactory.java index 398d3dd2..05e4d4c4 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageFactory.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapMessageFactory.java @@ -32,137 +32,137 @@ import org.springframework.ws.soap.SoapVersion; */ public class StroapMessageFactory implements SoapMessageFactory { - private final XMLInputFactory inputFactory = createXmlInputFactory(); + private final XMLInputFactory inputFactory = createXmlInputFactory(); - private final XMLOutputFactory outputFactory = createXmlOutputFactory(); + private final XMLOutputFactory outputFactory = createXmlOutputFactory(); - private final XMLEventFactory eventFactory = createXmlEventFactory(); + private final XMLEventFactory eventFactory = createXmlEventFactory(); - private final DocumentBuilderFactory documentBuilderFactory = createDocumentBuilderFactory(); + private final DocumentBuilderFactory documentBuilderFactory = createDocumentBuilderFactory(); - private boolean payloadCaching = true; + private boolean payloadCaching = true; - public boolean isPayloadCaching() { - return payloadCaching; - } + public boolean isPayloadCaching() { + return payloadCaching; + } - public void setPayloadCaching(boolean payloadCaching) { - this.payloadCaching = payloadCaching; - } + public void setPayloadCaching(boolean payloadCaching) { + this.payloadCaching = payloadCaching; + } - public SoapVersion getSoapVersion() { - return SoapVersion.SOAP_11; - } + public SoapVersion getSoapVersion() { + return SoapVersion.SOAP_11; + } - public void setSoapVersion(SoapVersion version) { - if (version != SoapVersion.SOAP_11) { - throw new UnsupportedOperationException(); - } - } + public void setSoapVersion(SoapVersion version) { + if (version != SoapVersion.SOAP_11) { + throw new UnsupportedOperationException(); + } + } - public StroapMessage createWebServiceMessage() { - return new StroapMessage(this); - } + public StroapMessage createWebServiceMessage() { + return new StroapMessage(this); + } - public StroapMessage createWebServiceMessage(InputStream inputStream) throws IOException { - try { - return StroapMessage.build(inputStream, this); - } - catch (XMLStreamException ex) { - throw new StroapMessageCreationException("Could not create message from InputStream: " + ex.getMessage(), - ex); - } - } + public StroapMessage createWebServiceMessage(InputStream inputStream) throws IOException { + try { + return StroapMessage.build(inputStream, this); + } + catch (XMLStreamException ex) { + throw new StroapMessageCreationException("Could not create message from InputStream: " + ex.getMessage(), + ex); + } + } - XMLInputFactory getInputFactory() { - return inputFactory; - } + XMLInputFactory getInputFactory() { + return inputFactory; + } - XMLOutputFactory getOutputFactory() { - return outputFactory; - } + XMLOutputFactory getOutputFactory() { + return outputFactory; + } - XMLEventFactory getEventFactory() { - return eventFactory; - } + XMLEventFactory getEventFactory() { + return eventFactory; + } - DocumentBuilderFactory getDocumentBuilderFactory() { - return documentBuilderFactory; - } + DocumentBuilderFactory getDocumentBuilderFactory() { + return documentBuilderFactory; + } - /** - * Create a {@code XMLInputFactory} that this message factory will use to create {@link - * javax.xml.stream.XMLEventReader} objects. - * - *

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 message factory will use to create {@link + * javax.xml.stream.XMLEventReader} objects. + * + *

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 XMLOutputFactory} that this message factory will use to create {@link - * javax.xml.stream.XMLEventWriter} objects. - * - *

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 XMLOutputFactory createXmlOutputFactory() { - XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); - outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", true); - return outputFactory; - } + /** + * Create a {@code XMLOutputFactory} that this message factory will use to create {@link + * javax.xml.stream.XMLEventWriter} objects. + * + *

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 XMLOutputFactory createXmlOutputFactory() { + XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); + outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", true); + return outputFactory; + } - /** - * Create a {@code XMLEventFactory} that this message factory will use to create {@link - * javax.xml.stream.events.XMLEvent} objects. - * - *

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 XMLEventFactory createXmlEventFactory() { - return XMLEventFactory.newFactory(); - } + /** + * Create a {@code XMLEventFactory} that this message factory will use to create {@link + * javax.xml.stream.events.XMLEvent} objects. + * + *

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 XMLEventFactory createXmlEventFactory() { + return XMLEventFactory.newFactory(); + } - /** - * Create a {@code DocumentBuilderFactory} that this message factory will use to create {@link org.w3c.dom.Document} objects. - * - *

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() { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - return documentBuilderFactory; - } + /** + * Create a {@code DocumentBuilderFactory} that this message factory will use to create {@link org.w3c.dom.Document} objects. + * + *

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() { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + return documentBuilderFactory; + } - public String toString() { - StringBuilder builder = new StringBuilder("StroapMessageFactory["); - if (getSoapVersion() == SoapVersion.SOAP_11) { - builder.append("SOAP 1.1"); - } - else if (getSoapVersion() == SoapVersion.SOAP_12) { - builder.append("SOAP 1.2"); - } - builder.append(','); - if (payloadCaching) { - builder.append("PayloadCaching enabled"); - } - else { - builder.append("PayloadCaching disabled"); - } - builder.append(']'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("StroapMessageFactory["); + if (getSoapVersion() == SoapVersion.SOAP_11) { + builder.append("SOAP 1.1"); + } + else if (getSoapVersion() == SoapVersion.SOAP_12) { + builder.append("SOAP 1.2"); + } + builder.append(','); + if (payloadCaching) { + builder.append("PayloadCaching enabled"); + } + else { + builder.append("PayloadCaching disabled"); + } + builder.append(']'); + return builder.toString(); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapPayload.java b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapPayload.java index 765ddaf4..89c1a0ed 100644 --- a/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapPayload.java +++ b/sandbox/src/main/java/org/springframework/ws/soap/stroap/StroapPayload.java @@ -26,12 +26,12 @@ import javax.xml.stream.XMLStreamException; */ abstract class StroapPayload { - public abstract QName getName(); + public abstract QName getName(); - public abstract XMLEventReader getEventReader(); + public abstract XMLEventReader getEventReader(); - public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { - eventWriter.add(getEventReader()); - } + public void writeTo(XMLEventWriter eventWriter) throws XMLStreamException { + eventWriter.add(getEventReader()); + } } \ No newline at end of file diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageReceiver.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageReceiver.java index d5302fd8..506c1771 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageReceiver.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageReceiver.java @@ -30,123 +30,123 @@ import org.springframework.ws.transport.support.AbstractAsyncStandaloneMessageRe /** @author Arjen Poutsma */ public class TcpMessageReceiver extends AbstractAsyncStandaloneMessageReceiver { - public static final int DEFAULT_PORT = 8081; + public static final int DEFAULT_PORT = 8081; - private ServerSocket serverSocket; + private ServerSocket serverSocket; - private InetAddress bindAddress; + private InetAddress bindAddress; - private int backlog = -1; + private int backlog = -1; - private int port = DEFAULT_PORT; + private int port = DEFAULT_PORT; - /** Sets the port the server will bind to. */ - public void setPort(int port) { - this.port = port; - } + /** Sets the port the server will bind to. */ + public void setPort(int port) { + this.port = port; + } - /** Sets the server back log. */ - public void setBacklog(int backlog) { - this.backlog = backlog; - } + /** Sets the server back log. */ + public void setBacklog(int backlog) { + this.backlog = backlog; + } - /** - * Sets the local internet address the server will bind to. By default, it will accept connections on any/all local - * addresses. - * - * @throws UnknownHostException when the given address is not known - * @see ServerSocket#ServerSocket(int,int,java.net.InetAddress) - */ - public void setBindAddress(String bindAddress) throws UnknownHostException { - this.bindAddress = InetAddress.getByName(bindAddress); - } + /** + * Sets the local internet address the server will bind to. By default, it will accept connections on any/all local + * addresses. + * + * @throws UnknownHostException when the given address is not known + * @see ServerSocket#ServerSocket(int,int,java.net.InetAddress) + */ + public void setBindAddress(String bindAddress) throws UnknownHostException { + this.bindAddress = InetAddress.getByName(bindAddress); + } - protected void onActivate() throws IOException { - openServerSocket(); - } + protected void onActivate() throws IOException { + openServerSocket(); + } - protected void onStart() { - if (logger.isInfoEnabled()) { - logger.info("Starting tcp receiver [" + serverSocket.getLocalSocketAddress() + "]"); - } - execute(new SocketAcceptingRunnable()); - } + protected void onStart() { + if (logger.isInfoEnabled()) { + logger.info("Starting tcp receiver [" + serverSocket.getLocalSocketAddress() + "]"); + } + execute(new SocketAcceptingRunnable()); + } - protected void onStop() { - if (logger.isInfoEnabled()) { - logger.info("Stopping tcp receiver [" + serverSocket.getLocalSocketAddress() + "]"); - } - } + protected void onStop() { + if (logger.isInfoEnabled()) { + logger.info("Stopping tcp receiver [" + serverSocket.getLocalSocketAddress() + "]"); + } + } - protected void onShutdown() { - if (logger.isInfoEnabled()) { - logger.info("Shutting down tcp receiver [" + serverSocket.getLocalSocketAddress() + "]"); - } - closeServerSocket(); - } + protected void onShutdown() { + if (logger.isInfoEnabled()) { + logger.info("Shutting down tcp receiver [" + serverSocket.getLocalSocketAddress() + "]"); + } + closeServerSocket(); + } - /** Establish a ServerSocket for this receiver. */ - protected void openServerSocket() throws IOException { - closeServerSocket(); - serverSocket = new ServerSocket(port, backlog, bindAddress); - } + /** Establish a ServerSocket for this receiver. */ + protected void openServerSocket() throws IOException { + closeServerSocket(); + serverSocket = new ServerSocket(port, backlog, bindAddress); + } - protected void closeServerSocket() { - if (serverSocket == null) { - return; - } - try { - serverSocket.close(); - } - catch (IOException ex) { - logger.debug("Could not close ServerSocket", ex); - } - } + protected void closeServerSocket() { + if (serverSocket == null) { + return; + } + try { + serverSocket.close(); + } + catch (IOException ex) { + logger.debug("Could not close ServerSocket", ex); + } + } - private class SocketAcceptingRunnable implements SchedulingAwareRunnable { + private class SocketAcceptingRunnable implements SchedulingAwareRunnable { - public void run() { - while (isRunning()) { - try { - Socket socket = serverSocket.accept(); - TcpRequestHandler handler = new TcpRequestHandler(socket); - execute(handler); - } - catch (InterruptedIOException ex) { - logger.warn(ex); - } - catch (IOException ex) { - logger.warn("Could not accept incoming connection: " + ex.getMessage()); - } - } - } + public void run() { + while (isRunning()) { + try { + Socket socket = serverSocket.accept(); + TcpRequestHandler handler = new TcpRequestHandler(socket); + execute(handler); + } + catch (InterruptedIOException ex) { + logger.warn(ex); + } + catch (IOException ex) { + logger.warn("Could not accept incoming connection: " + ex.getMessage()); + } + } + } - public boolean isLongLived() { - return true; - } - } + public boolean isLongLived() { + return true; + } + } - private class TcpRequestHandler implements SchedulingAwareRunnable { + private class TcpRequestHandler implements SchedulingAwareRunnable { - private final Socket socket; + private final Socket socket; - public TcpRequestHandler(Socket socket) { - this.socket = socket; - } + public TcpRequestHandler(Socket socket) { + this.socket = socket; + } - public void run() { - WebServiceConnection connection = new TcpReceiverConnection(socket); - try { - handleConnection(connection); - } - catch (Exception ex) { - logger.warn("Could not handle request", ex); - } - } + public void run() { + WebServiceConnection connection = new TcpReceiverConnection(socket); + try { + handleConnection(connection); + } + catch (Exception ex) { + logger.warn("Could not handle request", ex); + } + } - public boolean isLongLived() { - return false; - } - } + public boolean isLongLived() { + return false; + } + } } diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageSender.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageSender.java index 4d72066f..a423ca44 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageSender.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpMessageSender.java @@ -30,27 +30,27 @@ import org.springframework.ws.transport.WebServiceMessageSender; /** @author Arjen Poutsma */ public class TcpMessageSender implements WebServiceMessageSender { - public static final int DEFAULT_PORT = 8081; + public static final int DEFAULT_PORT = 8081; - private int timeOut = 1000; + private int timeOut = 1000; - /** Sets the amount of milliseconds before the tcp connection will timeout. */ - public void setTimeOut(int timeOut) { - this.timeOut = timeOut; - } + /** Sets the amount of milliseconds before the tcp connection will timeout. */ + public void setTimeOut(int timeOut) { + this.timeOut = timeOut; + } - public WebServiceConnection createConnection(URI theUri) throws IOException { - int port = theUri.getPort(); - if (port == -1) { - port = DEFAULT_PORT; - } - Socket socket = new Socket(); - SocketAddress socketAddress = new InetSocketAddress(theUri.getHost(), port); - socket.connect(socketAddress, timeOut); - return new TcpSenderConnection(socket); - } + public WebServiceConnection createConnection(URI theUri) throws IOException { + int port = theUri.getPort(); + if (port == -1) { + port = DEFAULT_PORT; + } + Socket socket = new Socket(); + SocketAddress socketAddress = new InetSocketAddress(theUri.getHost(), port); + socket.connect(socketAddress, timeOut); + return new TcpSenderConnection(socket); + } - public boolean supports(URI uri) { - return uri.getScheme().equals(TcpTransportConstants.TCP_URI_SCHEME); - } + public boolean supports(URI uri) { + return uri.getScheme().equals(TcpTransportConstants.TCP_URI_SCHEME); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpReceiverConnection.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpReceiverConnection.java index 020ea9cb..de1d55b5 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpReceiverConnection.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpReceiverConnection.java @@ -34,63 +34,63 @@ import org.springframework.ws.transport.tcp.support.TcpTransportUtils; /** @author Arjen Poutsma */ public class TcpReceiverConnection extends AbstractReceiverConnection { - private final Socket socket; + private final Socket socket; - protected TcpReceiverConnection(Socket socket) { - Assert.notNull(socket, "socket must not be null"); - this.socket = socket; - } + protected TcpReceiverConnection(Socket socket) { + Assert.notNull(socket, "socket must not be null"); + this.socket = socket; + } - public URI getUri() throws URISyntaxException { - return TcpTransportUtils.toUri(socket); - } + public URI getUri() throws URISyntaxException { + return TcpTransportUtils.toUri(socket); + } - public boolean hasError() throws IOException { - return false; - } + public boolean hasError() throws IOException { + return false; + } - public String getErrorMessage() throws IOException { - return null; - } + public String getErrorMessage() throws IOException { + return null; + } - public void onClose() throws IOException { - socket.close(); - } + public void onClose() throws IOException { + socket.close(); + } - protected Iterator getRequestHeaderNames() throws IOException { - return Collections.EMPTY_LIST.iterator(); - } + protected Iterator getRequestHeaderNames() throws IOException { + return Collections.EMPTY_LIST.iterator(); + } - protected Iterator getRequestHeaders(String name) throws IOException { - return Collections.EMPTY_LIST.iterator(); - } + protected Iterator getRequestHeaders(String name) throws IOException { + return Collections.EMPTY_LIST.iterator(); + } - protected InputStream getRequestInputStream() throws IOException { - return new FilterInputStream(socket.getInputStream()) { + protected InputStream getRequestInputStream() throws IOException { + return new FilterInputStream(socket.getInputStream()) { - @Override - public void close() throws IOException { - // don't close the socket - socket.shutdownInput(); - } - }; - } + @Override + public void close() throws IOException { + // don't close the socket + socket.shutdownInput(); + } + }; + } - protected void addResponseHeader(String name, String value) throws IOException { - } + protected void addResponseHeader(String name, String value) throws IOException { + } - protected OutputStream getResponseOutputStream() throws IOException { - return new FilterOutputStream(socket.getOutputStream()) { + protected OutputStream getResponseOutputStream() throws IOException { + return new FilterOutputStream(socket.getOutputStream()) { - @Override - public void close() throws IOException { - // don't close the socket - socket.shutdownOutput(); - } - }; - } + @Override + public void close() throws IOException { + // don't close the socket + socket.shutdownOutput(); + } + }; + } - protected void sendResponse(boolean sentFault) throws IOException { - } + protected void sendResponse(boolean sentFault) throws IOException { + } } diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpSenderConnection.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpSenderConnection.java index 32b1f375..a702dec9 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpSenderConnection.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpSenderConnection.java @@ -39,76 +39,76 @@ import org.springframework.ws.transport.tcp.support.TcpTransportUtils; */ public class TcpSenderConnection extends AbstractSenderConnection { - private final Socket socket; + private final Socket socket; - /** Constructs a new TCP/IP connection with the given socket. */ - protected TcpSenderConnection(Socket socket) { - Assert.notNull(socket, "socket must not be null"); - this.socket = socket; - } + /** Constructs a new TCP/IP connection with the given socket. */ + protected TcpSenderConnection(Socket socket) { + Assert.notNull(socket, "socket must not be null"); + this.socket = socket; + } - /** Returns the socket for this connection. */ - public Socket getSocket() { - return socket; - } + /** Returns the socket for this connection. */ + public Socket getSocket() { + return socket; + } - public URI getUri() throws URISyntaxException { - return TcpTransportUtils.toUri(socket); - } + public URI getUri() throws URISyntaxException { + return TcpTransportUtils.toUri(socket); + } - public void onClose() throws IOException { - socket.close(); - } + public void onClose() throws IOException { + socket.close(); + } - /* - * Errors - */ + /* + * Errors + */ - public boolean hasError() throws IOException { - return false; - } + public boolean hasError() throws IOException { + return false; + } - public String getErrorMessage() throws IOException { - return null; - } + public String getErrorMessage() throws IOException { + return null; + } - protected void addRequestHeader(String name, String value) throws IOException { - } + protected void addRequestHeader(String name, String value) throws IOException { + } - protected OutputStream getRequestOutputStream() throws IOException { - return new FilterOutputStream(socket.getOutputStream()) { + protected OutputStream getRequestOutputStream() throws IOException { + return new FilterOutputStream(socket.getOutputStream()) { - @Override - public void close() throws IOException { - // don't close the socket - socket.shutdownOutput(); - } - }; - } + @Override + public void close() throws IOException { + // don't close the socket + socket.shutdownOutput(); + } + }; + } - protected void sendRequest() throws IOException { - } + protected void sendRequest() throws IOException { + } - protected boolean hasResponse() throws IOException { - return true; - } + protected boolean hasResponse() throws IOException { + return true; + } - protected Iterator getResponseHeaderNames() throws IOException { - return Collections.EMPTY_LIST.iterator(); - } + protected Iterator getResponseHeaderNames() throws IOException { + return Collections.EMPTY_LIST.iterator(); + } - protected Iterator getResponseHeaders(String name) throws IOException { - return Collections.EMPTY_LIST.iterator(); - } + protected Iterator getResponseHeaders(String name) throws IOException { + return Collections.EMPTY_LIST.iterator(); + } - protected InputStream getResponseInputStream() throws IOException { - return new FilterInputStream(socket.getInputStream()) { + protected InputStream getResponseInputStream() throws IOException { + return new FilterInputStream(socket.getInputStream()) { - @Override - public void close() throws IOException { - // don't close the socket - socket.shutdownInput(); - } - }; - } + @Override + public void close() throws IOException { + // don't close the socket + socket.shutdownInput(); + } + }; + } } diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportConstants.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportConstants.java index c726cebe..31f85087 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportConstants.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportConstants.java @@ -23,7 +23,7 @@ package org.springframework.ws.transport.tcp; */ public interface TcpTransportConstants { - /** The "tcp" URI scheme. */ - String TCP_URI_SCHEME = "tcp"; + /** The "tcp" URI scheme. */ + String TCP_URI_SCHEME = "tcp"; } diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportException.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportException.java index a1797367..a2e5480b 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportException.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/TcpTransportException.java @@ -23,15 +23,15 @@ import org.springframework.ws.transport.TransportException; /** @author Arjen Poutsma */ public class TcpTransportException extends TransportException { - public TcpTransportException(String msg) { - super(msg); - } + public TcpTransportException(String msg) { + super(msg); + } - public TcpTransportException(String msg, IOException ex) { - super(msg + ": " + ex.getMessage()); - } + public TcpTransportException(String msg, IOException ex) { + super(msg + ": " + ex.getMessage()); + } - public TcpTransportException(IOException ex) { - super(ex.getMessage()); - } + public TcpTransportException(IOException ex) { + super(ex.getMessage()); + } } diff --git a/sandbox/src/main/java/org/springframework/ws/transport/tcp/support/TcpTransportUtils.java b/sandbox/src/main/java/org/springframework/ws/transport/tcp/support/TcpTransportUtils.java index 9aef177a..40193071 100644 --- a/sandbox/src/main/java/org/springframework/ws/transport/tcp/support/TcpTransportUtils.java +++ b/sandbox/src/main/java/org/springframework/ws/transport/tcp/support/TcpTransportUtils.java @@ -29,16 +29,16 @@ import org.springframework.ws.transport.tcp.TcpTransportConstants; */ public abstract class TcpTransportUtils { - /** - * Converts the given Socket into a tcp URI. - * - * @param socket the socket - * @return a tcp URI - */ - public static URI toUri(Socket socket) throws URISyntaxException { - String host = socket.getInetAddress().getHostName(); - return new URI(TcpTransportConstants.TCP_URI_SCHEME, null, host, socket.getPort(), null, null, null); + /** + * Converts the given Socket into a tcp URI. + * + * @param socket the socket + * @return a tcp URI + */ + public static URI toUri(Socket socket) throws URISyntaxException { + String host = socket.getInetAddress().getHostName(); + return new URI(TcpTransportConstants.TCP_URI_SCHEME, null, host, socket.getPort(), null, null, null); - } + } } diff --git a/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventReader.java b/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventReader.java index 4790fb2d..223e08bf 100644 --- a/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventReader.java +++ b/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventReader.java @@ -32,108 +32,108 @@ import org.springframework.util.ClassUtils; */ public abstract class AbstractXMLEventReader implements XMLEventReader { - private boolean closed; + private boolean closed; - public Object next() { - try { - return nextEvent(); - } - catch (XMLStreamException ex) { - throw new NoSuchElementException(); - } - } + public Object next() { + try { + return nextEvent(); + } + catch (XMLStreamException ex) { + throw new NoSuchElementException(); + } + } - /** - * Throws an UnsupportedOperationException when called. - * - * @throws UnsupportedOperationException when called - */ - public void remove() { - throw new UnsupportedOperationException("remove not supported on " + ClassUtils.getShortName(getClass())); - } + /** + * Throws an UnsupportedOperationException when called. + * + * @throws UnsupportedOperationException when called + */ + public void remove() { + throw new UnsupportedOperationException("remove not supported on " + ClassUtils.getShortName(getClass())); + } - public String getElementText() throws XMLStreamException { - checkIfClosed(); - if (!peek().isStartElement()) { - throw new XMLStreamException("Not at START_ELEMENT"); - } + public String getElementText() throws XMLStreamException { + checkIfClosed(); + if (!peek().isStartElement()) { + throw new XMLStreamException("Not at START_ELEMENT"); + } - StringBuilder builder = new StringBuilder(); - while (true) { - XMLEvent event = nextEvent(); - if (event.isEndElement()) { - break; - } - else if (!event.isCharacters()) { - throw new XMLStreamException("Unexpected event [" + event + "] in getElementText()"); - } - Characters characters = event.asCharacters(); - if (!characters.isIgnorableWhiteSpace()) { - builder.append(event.asCharacters().getData()); - } - } - return builder.toString(); - } + StringBuilder builder = new StringBuilder(); + while (true) { + XMLEvent event = nextEvent(); + if (event.isEndElement()) { + break; + } + else if (!event.isCharacters()) { + throw new XMLStreamException("Unexpected event [" + event + "] in getElementText()"); + } + Characters characters = event.asCharacters(); + if (!characters.isIgnorableWhiteSpace()) { + builder.append(event.asCharacters().getData()); + } + } + return builder.toString(); + } - public XMLEvent nextTag() throws XMLStreamException { - checkIfClosed(); - while (true) { - XMLEvent event = nextEvent(); - switch (event.getEventType()) { - case XMLStreamConstants.START_ELEMENT: - case XMLStreamConstants.END_ELEMENT: - return event; - case XMLStreamConstants.END_DOCUMENT: - return null; - case XMLStreamConstants.SPACE: - case XMLStreamConstants.COMMENT: - case XMLStreamConstants.PROCESSING_INSTRUCTION: - continue; - case XMLStreamConstants.CDATA: - case XMLStreamConstants.CHARACTERS: - if (!event.asCharacters().isWhiteSpace()) { - throw new XMLStreamException("Non-ignorable whitespace CDATA or CHARACTERS event in nextTag()"); - } - break; - default: - throw new XMLStreamException( - "Received event [" + event + "], instead of START_ELEMENT or END_ELEMENT."); - } - } - } + public XMLEvent nextTag() throws XMLStreamException { + checkIfClosed(); + while (true) { + XMLEvent event = nextEvent(); + switch (event.getEventType()) { + case XMLStreamConstants.START_ELEMENT: + case XMLStreamConstants.END_ELEMENT: + return event; + case XMLStreamConstants.END_DOCUMENT: + return null; + case XMLStreamConstants.SPACE: + case XMLStreamConstants.COMMENT: + case XMLStreamConstants.PROCESSING_INSTRUCTION: + continue; + case XMLStreamConstants.CDATA: + case XMLStreamConstants.CHARACTERS: + if (!event.asCharacters().isWhiteSpace()) { + throw new XMLStreamException("Non-ignorable whitespace CDATA or CHARACTERS event in nextTag()"); + } + break; + default: + throw new XMLStreamException( + "Received event [" + event + "], instead of START_ELEMENT or END_ELEMENT."); + } + } + } - /** - * Throws an IllegalArgumentException when called. - * - * @throws IllegalArgumentException when called. - */ - public Object getProperty(String name) throws IllegalArgumentException { - throw new IllegalArgumentException("Property not supported: [" + name + "]"); - } + /** + * Throws an IllegalArgumentException when called. + * + * @throws IllegalArgumentException when called. + */ + public Object getProperty(String name) throws IllegalArgumentException { + throw new IllegalArgumentException("Property not supported: [" + name + "]"); + } - /** - * Returns true if closed; false otherwise. - * - * @see #close() - */ - protected boolean isClosed() { - return closed; - } + /** + * Returns true if closed; false otherwise. + * + * @see #close() + */ + protected boolean isClosed() { + return closed; + } - /** - * Checks if the reader is closed, and throws a XMLStreamException if so. - * - * @throws XMLStreamException if the reader is closed - * @see #close() - * @see #isClosed() - */ - protected void checkIfClosed() throws XMLStreamException { - if (closed) { - throw new XMLStreamException("XMLEventReader has been closed"); - } - } + /** + * Checks if the reader is closed, and throws a XMLStreamException if so. + * + * @throws XMLStreamException if the reader is closed + * @see #close() + * @see #isClosed() + */ + protected void checkIfClosed() throws XMLStreamException { + if (closed) { + throw new XMLStreamException("XMLEventReader has been closed"); + } + } - public void close() { - closed = true; - } + public void close() { + closed = true; + } } diff --git a/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventWriter.java b/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventWriter.java index 0125e2ce..0c1344c8 100644 --- a/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventWriter.java +++ b/sandbox/src/main/java/org/springframework/xml/stream/AbstractXMLEventWriter.java @@ -31,66 +31,66 @@ import org.springframework.xml.namespace.SimpleNamespaceContext; */ public abstract class AbstractXMLEventWriter implements XMLEventWriter { - private boolean closed; + private boolean closed; - private SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); + private SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); - public void flush() throws XMLStreamException { - } + public void flush() throws XMLStreamException { + } - public void add(XMLEventReader eventReader) throws XMLStreamException { - checkIfClosed(); - while (eventReader.hasNext()) { - XMLEvent event = eventReader.nextEvent(); - add(event); - } - } + public void add(XMLEventReader eventReader) throws XMLStreamException { + checkIfClosed(); + while (eventReader.hasNext()) { + XMLEvent event = eventReader.nextEvent(); + add(event); + } + } - public String getPrefix(String uri) throws XMLStreamException { - return namespaceContext.getPrefix(uri); - } + public String getPrefix(String uri) throws XMLStreamException { + return namespaceContext.getPrefix(uri); + } - public void setPrefix(String prefix, String uri) throws XMLStreamException { - namespaceContext.bindNamespaceUri(prefix, uri); - } + public void setPrefix(String prefix, String uri) throws XMLStreamException { + namespaceContext.bindNamespaceUri(prefix, uri); + } - public void setDefaultNamespace(String uri) throws XMLStreamException { - namespaceContext.bindDefaultNamespaceUri(uri); - } + public void setDefaultNamespace(String uri) throws XMLStreamException { + namespaceContext.bindDefaultNamespaceUri(uri); + } - public void setNamespaceContext(NamespaceContext namespaceContext) throws XMLStreamException { - Assert.notNull(namespaceContext, "'namespaceContext' must not be null"); - this.namespaceContext = (SimpleNamespaceContext) namespaceContext; - } + public void setNamespaceContext(NamespaceContext namespaceContext) throws XMLStreamException { + Assert.notNull(namespaceContext, "'namespaceContext' must not be null"); + this.namespaceContext = (SimpleNamespaceContext) namespaceContext; + } - public NamespaceContext getNamespaceContext() { - return namespaceContext; - } + public NamespaceContext getNamespaceContext() { + return namespaceContext; + } - /** - * Returns true if closed; false otherwise. - * - * @see #close() - */ - protected boolean isClosed() { - return closed; - } + /** + * Returns true if closed; false otherwise. + * + * @see #close() + */ + protected boolean isClosed() { + return closed; + } - /** - * Checks if the reader is closed, and throws a XMLStreamException if so. - * - * @throws XMLStreamException if the reader is closed - * @see #close() - * @see #isClosed() - */ - protected void checkIfClosed() throws XMLStreamException { - if (closed) { - throw new XMLStreamException(ClassUtils.getShortName(getClass()) + " has been closed"); - } - } + /** + * Checks if the reader is closed, and throws a XMLStreamException if so. + * + * @throws XMLStreamException if the reader is closed + * @see #close() + * @see #isClosed() + */ + protected void checkIfClosed() throws XMLStreamException { + if (closed) { + throw new XMLStreamException(ClassUtils.getShortName(getClass()) + " has been closed"); + } + } - public void close() { - closed = true; - } + public void close() { + closed = true; + } } diff --git a/sandbox/src/main/java/org/springframework/xml/stream/CompositeXMLEventReader.java b/sandbox/src/main/java/org/springframework/xml/stream/CompositeXMLEventReader.java index d2d2849d..edb3b3f7 100644 --- a/sandbox/src/main/java/org/springframework/xml/stream/CompositeXMLEventReader.java +++ b/sandbox/src/main/java/org/springframework/xml/stream/CompositeXMLEventReader.java @@ -30,72 +30,72 @@ import org.springframework.util.Assert; */ public class CompositeXMLEventReader extends AbstractXMLEventReader { - private final XMLEventReader[] eventReaders; + private final XMLEventReader[] eventReaders; - private int cursor = 0; + private int cursor = 0; - public CompositeXMLEventReader(XMLEventReader eventReader) { - Assert.notNull(eventReader, "'eventReader' must not be null"); - this.eventReaders = new XMLEventReader[]{eventReader}; - } + public CompositeXMLEventReader(XMLEventReader eventReader) { + Assert.notNull(eventReader, "'eventReader' must not be null"); + this.eventReaders = new XMLEventReader[]{eventReader}; + } - public CompositeXMLEventReader(XMLEventReader... eventReaders) { - Assert.notNull(eventReaders, "'eventReaders' must not be null"); - this.eventReaders = eventReaders; - } + public CompositeXMLEventReader(XMLEventReader... eventReaders) { + Assert.notNull(eventReaders, "'eventReaders' must not be null"); + this.eventReaders = eventReaders; + } - public CompositeXMLEventReader(List eventReaders) { - Assert.notNull(eventReaders, "'eventReaders' must not be null"); - this.eventReaders = eventReaders.toArray(new XMLEventReader[eventReaders.size()]); - } + public CompositeXMLEventReader(List eventReaders) { + Assert.notNull(eventReaders, "'eventReaders' must not be null"); + this.eventReaders = eventReaders.toArray(new XMLEventReader[eventReaders.size()]); + } - public boolean hasNext() { - while (cursor < eventReaders.length) { - if (!atLastEventReader()) { - if (!currentEventReader().hasNext()) { - cursor++; - continue; - } - } - return currentEventReader().hasNext(); - } - return false; - } + public boolean hasNext() { + while (cursor < eventReaders.length) { + if (!atLastEventReader()) { + if (!currentEventReader().hasNext()) { + cursor++; + continue; + } + } + return currentEventReader().hasNext(); + } + return false; + } - public XMLEvent nextEvent() throws XMLStreamException { - XMLEvent event = null; - while (cursor < eventReaders.length) { - event = currentEventReader().nextEvent(); - if (!atLastEventReader() && event.isEndDocument()) { - cursor++; - } - else { - break; - } - } - return event; - } + public XMLEvent nextEvent() throws XMLStreamException { + XMLEvent event = null; + while (cursor < eventReaders.length) { + event = currentEventReader().nextEvent(); + if (!atLastEventReader() && event.isEndDocument()) { + cursor++; + } + else { + break; + } + } + return event; + } - public XMLEvent peek() throws XMLStreamException { - XMLEvent event = null; - while (cursor < eventReaders.length) { - event = currentEventReader().peek(); - if (!atLastEventReader() && (event == null || event.isEndDocument())) { - cursor++; - } - else { - break; - } - } - return event; - } + public XMLEvent peek() throws XMLStreamException { + XMLEvent event = null; + while (cursor < eventReaders.length) { + event = currentEventReader().peek(); + if (!atLastEventReader() && (event == null || event.isEndDocument())) { + cursor++; + } + else { + break; + } + } + return event; + } - private XMLEventReader currentEventReader() { - return eventReaders[cursor]; - } + private XMLEventReader currentEventReader() { + return eventReaders[cursor]; + } - private boolean atLastEventReader() { - return cursor == eventReaders.length - 1; - } + private boolean atLastEventReader() { + return cursor == eventReaders.length - 1; + } } diff --git a/sandbox/src/main/java/org/springframework/xml/stream/ListBasedXMLEventReader.java b/sandbox/src/main/java/org/springframework/xml/stream/ListBasedXMLEventReader.java index 77fc0a45..d56814b6 100644 --- a/sandbox/src/main/java/org/springframework/xml/stream/ListBasedXMLEventReader.java +++ b/sandbox/src/main/java/org/springframework/xml/stream/ListBasedXMLEventReader.java @@ -27,53 +27,53 @@ import org.springframework.util.Assert; */ public class ListBasedXMLEventReader extends AbstractXMLEventReader { - private final XMLEvent[] events; + private final XMLEvent[] events; - private int cursor = 0; + private int cursor = 0; - public ListBasedXMLEventReader() { - this.events = new XMLEvent[0]; - } + public ListBasedXMLEventReader() { + this.events = new XMLEvent[0]; + } - public ListBasedXMLEventReader(XMLEvent event) { - if (event != null) { - this.events = new XMLEvent[]{event}; - } - else { - this.events = new XMLEvent[0]; - } - } + public ListBasedXMLEventReader(XMLEvent event) { + if (event != null) { + this.events = new XMLEvent[]{event}; + } + else { + this.events = new XMLEvent[0]; + } + } - public ListBasedXMLEventReader(XMLEvent... events) { - Assert.notNull(events, "'events' must not be null"); - this.events = events; - } + public ListBasedXMLEventReader(XMLEvent... events) { + Assert.notNull(events, "'events' must not be null"); + this.events = events; + } - public ListBasedXMLEventReader(List events) { - Assert.notNull(events, "'events' must not be null"); - this.events = events.toArray(new XMLEvent[events.size()]); - } + public ListBasedXMLEventReader(List events) { + Assert.notNull(events, "'events' must not be null"); + this.events = events.toArray(new XMLEvent[events.size()]); + } - public boolean hasNext() { - Assert.notNull(events, "'events' must not be null"); - return cursor != events.length; - } + public boolean hasNext() { + Assert.notNull(events, "'events' must not be null"); + return cursor != events.length; + } - public XMLEvent nextEvent() { - if (cursor < events.length) { - return events[cursor++]; - } - else { - throw new NoSuchElementException(); - } - } + public XMLEvent nextEvent() { + if (cursor < events.length) { + return events[cursor++]; + } + else { + throw new NoSuchElementException(); + } + } - public XMLEvent peek() { - if (cursor < events.length) { - return events[cursor]; - } - else { - return null; - } - } + public XMLEvent peek() { + if (cursor < events.length) { + return events[cursor]; + } + else { + return null; + } + } } diff --git a/sandbox/src/test/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapterTest.java b/sandbox/src/test/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapterTest.java index 11fdd399..3ca263a9 100644 --- a/sandbox/src/test/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapterTest.java +++ b/sandbox/src/test/java/org/springframework/ws/jaxws/JaxWsProviderEndpointAdapterTest.java @@ -33,75 +33,75 @@ import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; public class JaxWsProviderEndpointAdapterTest extends TestCase { - private JaxWsProviderEndpointAdapter adapter; + private JaxWsProviderEndpointAdapter adapter; - private MessageContext messageContext; + private MessageContext messageContext; - @Override - protected void setUp() throws Exception { - adapter = new JaxWsProviderEndpointAdapter(); - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage request = messageFactory.createMessage(); - request.getSOAPBody().addBodyElement(new QName("http://springframework.org/spring-ws", "content")); - messageContext = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - } + @Override + protected void setUp() throws Exception { + adapter = new JaxWsProviderEndpointAdapter(); + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage request = messageFactory.createMessage(); + request.getSOAPBody().addBodyElement(new QName("http://springframework.org/spring-ws", "content")); + messageContext = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + } - public void testSupports() throws Exception { - MyMessageProvider messageProvider = new MyMessageProvider(); - assertTrue("Does not support message provider", adapter.supports(messageProvider)); - MySourceProvider sourceProvider = new MySourceProvider(); - assertTrue("Does not support source provider", adapter.supports(sourceProvider)); - MyDefaultProvider defaultProvider = new MyDefaultProvider(); - assertTrue("Does not support source provider", adapter.supports(defaultProvider)); - } + public void testSupports() throws Exception { + MyMessageProvider messageProvider = new MyMessageProvider(); + assertTrue("Does not support message provider", adapter.supports(messageProvider)); + MySourceProvider sourceProvider = new MySourceProvider(); + assertTrue("Does not support source provider", adapter.supports(sourceProvider)); + MyDefaultProvider defaultProvider = new MyDefaultProvider(); + assertTrue("Does not support source provider", adapter.supports(defaultProvider)); + } - public void testInvokeMessageProvider() throws Exception { - MyMessageProvider provider = new MyMessageProvider(); - adapter.invoke(messageContext, provider); - assertTrue("No response", messageContext.hasResponse()); - SaajSoapMessage request = (SaajSoapMessage) messageContext.getRequest(); - SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse(); - assertEquals("Invalid response", request.getSaajMessage(), response.getSaajMessage()); - } + public void testInvokeMessageProvider() throws Exception { + MyMessageProvider provider = new MyMessageProvider(); + adapter.invoke(messageContext, provider); + assertTrue("No response", messageContext.hasResponse()); + SaajSoapMessage request = (SaajSoapMessage) messageContext.getRequest(); + SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse(); + assertEquals("Invalid response", request.getSaajMessage(), response.getSaajMessage()); + } - public void testInvokeSourceProvider() throws Exception { - MySourceProvider provider = new MySourceProvider(); - adapter.invoke(messageContext, provider); - assertTrue("No response", messageContext.hasResponse()); - } + public void testInvokeSourceProvider() throws Exception { + MySourceProvider provider = new MySourceProvider(); + adapter.invoke(messageContext, provider); + assertTrue("No response", messageContext.hasResponse()); + } - public void testInvokeDefaultProvider() throws Exception { - MyDefaultProvider provider = new MyDefaultProvider(); - adapter.invoke(messageContext, provider); - assertTrue("No response", messageContext.hasResponse()); - } + public void testInvokeDefaultProvider() throws Exception { + MyDefaultProvider provider = new MyDefaultProvider(); + adapter.invoke(messageContext, provider); + assertTrue("No response", messageContext.hasResponse()); + } - @WebServiceProvider - @ServiceMode(Service.Mode.MESSAGE) - private static class MyMessageProvider implements Provider { + @WebServiceProvider + @ServiceMode(Service.Mode.MESSAGE) + private static class MyMessageProvider implements Provider { - public SOAPMessage invoke(SOAPMessage request) { - return request; - } - } + public SOAPMessage invoke(SOAPMessage request) { + return request; + } + } - @WebServiceProvider - @ServiceMode(value = Service.Mode.PAYLOAD) - private static class MySourceProvider implements Provider { + @WebServiceProvider + @ServiceMode(value = Service.Mode.PAYLOAD) + private static class MySourceProvider implements Provider { - public Source invoke(Source request) { - return request; - } - } + public Source invoke(Source request) { + return request; + } + } - @WebServiceProvider - private static class MyDefaultProvider implements Provider { + @WebServiceProvider + private static class MyDefaultProvider implements Provider { - public Source invoke(Source request) { - return request; - } - } + public Source invoke(Source request) { + return request; + } + } } diff --git a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11BodyTest.java b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11BodyTest.java index 3567a9f2..d977c381 100644 --- a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11BodyTest.java +++ b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11BodyTest.java @@ -21,17 +21,17 @@ import org.springframework.ws.soap.soap11.AbstractSoap11BodyTestCase; public class Stroap11BodyTest extends AbstractSoap11BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - StroapMessageFactory messageFactory = new StroapMessageFactory(); - return new Stroap11Body(messageFactory); - } + @Override + protected SoapBody createSoapBody() throws Exception { + StroapMessageFactory messageFactory = new StroapMessageFactory(); + return new Stroap11Body(messageFactory); + } - @Override - public void testAddFaultWithDetail() throws Exception { - } + @Override + public void testAddFaultWithDetail() throws Exception { + } - @Override - public void testAddFaultWithDetailResult() throws Exception { - } + @Override + public void testAddFaultWithDetailResult() throws Exception { + } } diff --git a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11EnvelopeTest.java b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11EnvelopeTest.java index d695b229..6bcf2773 100644 --- a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11EnvelopeTest.java +++ b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11EnvelopeTest.java @@ -21,11 +21,11 @@ import org.springframework.ws.soap.soap11.AbstractSoap11EnvelopeTestCase; public class Stroap11EnvelopeTest extends AbstractSoap11EnvelopeTestCase { - @Override - protected SoapEnvelope createSoapEnvelope() throws Exception { - StroapMessageFactory messageFactory = new StroapMessageFactory(); - StroapEnvelope envelope = new StroapEnvelope(messageFactory); - envelope.getHeader(); - return envelope; - } + @Override + protected SoapEnvelope createSoapEnvelope() throws Exception { + StroapMessageFactory messageFactory = new StroapMessageFactory(); + StroapEnvelope envelope = new StroapEnvelope(messageFactory); + envelope.getHeader(); + return envelope; + } } diff --git a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11HeaderTest.java b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11HeaderTest.java index 891a5d2f..21f9530d 100644 --- a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11HeaderTest.java +++ b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11HeaderTest.java @@ -21,9 +21,9 @@ import org.springframework.ws.soap.soap11.AbstractSoap11HeaderTestCase; public class Stroap11HeaderTest extends AbstractSoap11HeaderTestCase { - @Override - protected SoapHeader createSoapHeader() throws Exception { - StroapMessageFactory messageFactory = new StroapMessageFactory(); - return new Stroap11Header(messageFactory); - } + @Override + protected SoapHeader createSoapHeader() throws Exception { + StroapMessageFactory messageFactory = new StroapMessageFactory(); + return new Stroap11Header(messageFactory); + } } diff --git a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageFactoryTest.java b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageFactoryTest.java index c766aca0..9e525a1f 100644 --- a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageFactoryTest.java +++ b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageFactoryTest.java @@ -21,20 +21,20 @@ import org.springframework.ws.soap.soap11.AbstractSoap11MessageFactoryTestCase; public class Stroap11MessageFactoryTest extends AbstractSoap11MessageFactoryTestCase { - @Override - protected WebServiceMessageFactory createMessageFactory() throws Exception { - return new StroapMessageFactory(); - } + @Override + protected WebServiceMessageFactory createMessageFactory() throws Exception { + return new StroapMessageFactory(); + } - @Override - public void testCreateSoapMessageMtom() throws Exception { - } + @Override + public void testCreateSoapMessageMtom() throws Exception { + } - @Override - public void testCreateSoapMessageSwA() throws Exception { - } + @Override + public void testCreateSoapMessageSwA() throws Exception { + } - @Override - public void testCreateSoapMessageMtomWeirdStartInfo() throws Exception { - } + @Override + public void testCreateSoapMessageMtomWeirdStartInfo() throws Exception { + } } \ No newline at end of file diff --git a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageTest.java b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageTest.java index ad8908ec..ce1dce70 100644 --- a/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageTest.java +++ b/sandbox/src/test/java/org/springframework/ws/soap/stroap/Stroap11MessageTest.java @@ -21,26 +21,26 @@ import org.springframework.ws.soap.soap11.AbstractSoap11MessageTestCase; public class Stroap11MessageTest extends AbstractSoap11MessageTestCase { - @Override - protected final SoapMessage createSoapMessage() throws Exception { - StroapMessageFactory messageFactory = new StroapMessageFactory(); - return new StroapMessage(messageFactory); - } + @Override + protected final SoapMessage createSoapMessage() throws Exception { + StroapMessageFactory messageFactory = new StroapMessageFactory(); + return new StroapMessage(messageFactory); + } - @Override - public void testWriteToTransportResponseAttachment() throws Exception { - } + @Override + public void testWriteToTransportResponseAttachment() throws Exception { + } - @Override - public void testAddAttachment() throws Exception { - } + @Override + public void testAddAttachment() throws Exception { + } - @Override - public void testGetAttachment() throws Exception { - } + @Override + public void testGetAttachment() throws Exception { + } - @Override - public void testGetAttachments() throws Exception { - } + @Override + public void testGetAttachments() throws Exception { + } } diff --git a/sandbox/src/test/java/org/springframework/ws/transport/tcp/Driver.java b/sandbox/src/test/java/org/springframework/ws/transport/tcp/Driver.java index 7d55643a..90de5f07 100644 --- a/sandbox/src/test/java/org/springframework/ws/transport/tcp/Driver.java +++ b/sandbox/src/test/java/org/springframework/ws/transport/tcp/Driver.java @@ -24,10 +24,10 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; /** @author Arjen Poutsma */ public class Driver { - public static void main(String[] args) throws IOException { - new ClassPathXmlApplicationContext("applicationContext.xml", Driver.class); - System.out.println("Started...."); - System.in.read(); - } + public static void main(String[] args) throws IOException { + new ClassPathXmlApplicationContext("applicationContext.xml", Driver.class); + System.out.println("Started...."); + System.in.read(); + } } diff --git a/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpIntegrationTest.java b/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpIntegrationTest.java index 754b81f8..4db39b69 100644 --- a/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpIntegrationTest.java +++ b/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpIntegrationTest.java @@ -27,21 +27,21 @@ import org.junit.Ignore; @Ignore public class TcpIntegrationTest extends AbstractDependencyInjectionSpringContextTests { - private WebServiceTemplate webServiceTemplate; + private WebServiceTemplate webServiceTemplate; - protected String[] getConfigLocations() { - return new String[]{"classpath:org/springframework/ws/transport/tcp/tcp-applicationContext.xml"}; - } + protected String[] getConfigLocations() { + return new String[]{"classpath:org/springframework/ws/transport/tcp/tcp-applicationContext.xml"}; + } - public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) { - this.webServiceTemplate = webServiceTemplate; - } + public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) { + this.webServiceTemplate = webServiceTemplate; + } - public void testJmsTransport() throws Exception { - String content = ""; - StringResult result = new StringResult(); - webServiceTemplate.sendSourceAndReceiveToResult(new StringSource(content), result); - XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); - applicationContext.close(); - } + public void testJmsTransport() throws Exception { + String content = ""; + StringResult result = new StringResult(); + webServiceTemplate.sendSourceAndReceiveToResult(new StringSource(content), result); + XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); + applicationContext.close(); + } } \ No newline at end of file diff --git a/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpMessageReceiverIntegrationTest.java b/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpMessageReceiverIntegrationTest.java index e6efac72..eae28ae0 100644 --- a/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpMessageReceiverIntegrationTest.java +++ b/sandbox/src/test/java/org/springframework/ws/transport/tcp/TcpMessageReceiverIntegrationTest.java @@ -36,55 +36,55 @@ import org.junit.Ignore; @Ignore public class TcpMessageReceiverIntegrationTest extends AbstractDependencyInjectionSpringContextTests { - private WebServiceMessageFactory messageFactory; + private WebServiceMessageFactory messageFactory; - private WebServiceMessageSender messageSender; + private WebServiceMessageSender messageSender; - public void setMessageFactory(WebServiceMessageFactory messageFactory) { - this.messageFactory = messageFactory; - } + public void setMessageFactory(WebServiceMessageFactory messageFactory) { + this.messageFactory = messageFactory; + } - public void setMessageSender(WebServiceMessageSender messageSender) { - this.messageSender = messageSender; - } + public void setMessageSender(WebServiceMessageSender messageSender) { + this.messageSender = messageSender; + } - public static final String REQUEST = - "\n" + - " \n" + - " \n" + - " DIS\n" + " \n" + - " \n" + ""; + public static final String REQUEST = + "\n" + + " \n" + + " \n" + + " DIS\n" + " \n" + + " \n" + ""; - public void testServer() throws IOException, InterruptedException { - Socket socket = new Socket("localhost", TcpMessageReceiver.DEFAULT_PORT); - Writer writer; - BufferedReader reader; - try { - writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); - writer.write(REQUEST); - writer.flush(); - socket.shutdownOutput(); - reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); - String line; - while ((line = reader.readLine()) != null) { - System.out.println(line); - } - } - finally { - socket.close(); - } - } + public void testServer() throws IOException, InterruptedException { + Socket socket = new Socket("localhost", TcpMessageReceiver.DEFAULT_PORT); + Writer writer; + BufferedReader reader; + try { + writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); + writer.write(REQUEST); + writer.flush(); + socket.shutdownOutput(); + reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + } + finally { + socket.close(); + } + } - public void testTemplate() throws Exception { - WebServiceTemplate template = new WebServiceTemplate(messageFactory); - template.setMessageSender(messageSender); - template.sendSourceAndReceiveToResult("tcp://localhost", new StringSource(REQUEST), - new StreamResult(System.out)); - } + public void testTemplate() throws Exception { + WebServiceTemplate template = new WebServiceTemplate(messageFactory); + template.setMessageSender(messageSender); + template.sendSourceAndReceiveToResult("tcp://localhost", new StringSource(REQUEST), + new StreamResult(System.out)); + } - protected String[] getConfigLocations() { - return new String[]{"classpath:/org/springframework/ws/transport/tcp/applicationContext.xml"}; - } + protected String[] getConfigLocations() { + return new String[]{"classpath:/org/springframework/ws/transport/tcp/applicationContext.xml"}; + } } \ No newline at end of file diff --git a/sandbox/src/test/java/org/springframework/xml/stream/CompositeXMLEventReaderTest.java b/sandbox/src/test/java/org/springframework/xml/stream/CompositeXMLEventReaderTest.java index e25bdede..df79a7e2 100644 --- a/sandbox/src/test/java/org/springframework/xml/stream/CompositeXMLEventReaderTest.java +++ b/sandbox/src/test/java/org/springframework/xml/stream/CompositeXMLEventReaderTest.java @@ -36,60 +36,60 @@ import static org.junit.Assert.*; */ public class CompositeXMLEventReaderTest { - private CompositeXMLEventReader chain; + private CompositeXMLEventReader chain; - private XMLInputFactory inputFactory; + private XMLInputFactory inputFactory; - private List expectedEvents = new ArrayList(); + private List expectedEvents = new ArrayList(); - @Before - public void createChainUp() throws Exception { - inputFactory = XMLInputFactory.newFactory(); - List events = getEvents("text1"); - expectedEvents.addAll(events); - XMLEventReader reader1 = new ListBasedXMLEventReader(events); - XMLEventReader reader2 = new ListBasedXMLEventReader(); - events = getEvents(""); - expectedEvents.addAll(events); - XMLEventReader reader3 = new ListBasedXMLEventReader(events); - XMLEventReader reader4 = new ListBasedXMLEventReader(); - chain = new CompositeXMLEventReader(reader1, reader2, reader3, reader4); - } + @Before + public void createChainUp() throws Exception { + inputFactory = XMLInputFactory.newFactory(); + List events = getEvents("text1"); + expectedEvents.addAll(events); + XMLEventReader reader1 = new ListBasedXMLEventReader(events); + XMLEventReader reader2 = new ListBasedXMLEventReader(); + events = getEvents(""); + expectedEvents.addAll(events); + XMLEventReader reader3 = new ListBasedXMLEventReader(events); + XMLEventReader reader4 = new ListBasedXMLEventReader(); + chain = new CompositeXMLEventReader(reader1, reader2, reader3, reader4); + } - private List getEvents(String xml) throws XMLStreamException { - XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(xml)); - List events = new LinkedList(); - while (eventReader.hasNext()) { - XMLEvent event = eventReader.nextEvent(); - if (!(event.isStartDocument() || event.isEndDocument())) { - events.add(event); - } + private List getEvents(String xml) throws XMLStreamException { + XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(xml)); + List events = new LinkedList(); + while (eventReader.hasNext()) { + XMLEvent event = eventReader.nextEvent(); + if (!(event.isStartDocument() || event.isEndDocument())) { + events.add(event); + } - } - return events; - } + } + return events; + } - @Test - public void testChain() throws Exception { - for (XMLEvent expectedEvent : expectedEvents) { - testEvent(expectedEvent); - } - assertFalse("hasNext returns true", chain.hasNext()); - assertNull("peek returns element", chain.peek()); - try { - chain.nextEvent(); - fail("NoSuchElementElementException expected"); - } - catch (NoSuchElementException e) { - // expected - } - } + @Test + public void testChain() throws Exception { + for (XMLEvent expectedEvent : expectedEvents) { + testEvent(expectedEvent); + } + assertFalse("hasNext returns true", chain.hasNext()); + assertNull("peek returns element", chain.peek()); + try { + chain.nextEvent(); + fail("NoSuchElementElementException expected"); + } + catch (NoSuchElementException e) { + // expected + } + } - private void testEvent(XMLEvent expected) throws XMLStreamException { - assertEquals("1st peek returns invalid result", expected, chain.peek()); - assertEquals("2nd peek returns invalid result", expected, chain.peek()); - assertTrue("hasNext returns false", chain.hasNext()); - assertEquals("nextEvent returns invalid result", expected, chain.nextEvent()); - } + private void testEvent(XMLEvent expected) throws XMLStreamException { + assertEquals("1st peek returns invalid result", expected, chain.peek()); + assertEquals("2nd peek returns invalid result", expected, chain.peek()); + assertTrue("hasNext returns false", chain.hasNext()); + assertEquals("nextEvent returns invalid result", expected, chain.nextEvent()); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/FaultAwareWebServiceMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/FaultAwareWebServiceMessage.java index 77911b90..2a1dbecd 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/FaultAwareWebServiceMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/FaultAwareWebServiceMessage.java @@ -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(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/InvalidXmlException.java b/spring-ws-core/src/main/java/org/springframework/ws/InvalidXmlException.java index 7af8a365..16e4626b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/InvalidXmlException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/InvalidXmlException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/NoEndpointFoundException.java b/spring-ws-core/src/main/java/org/springframework/ws/NoEndpointFoundException.java index 5b0d3624..3fa39054 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/NoEndpointFoundException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/NoEndpointFoundException.java @@ -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 + "]"); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceException.java b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceException.java index c66a2ac2..9cea0c08 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessage.java index 93bb09e6..e5207232 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessage.java @@ -33,35 +33,35 @@ import javax.xml.transform.Source; */ public interface WebServiceMessage { - /** - * Returns the contents of the message as a {@link Source}. - * - *

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}. + * + *

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}. - * - *

Calling this method removes the current payload. - * - *

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}. + * + *

Calling this method removes the current payload. + * + *

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.

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.

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageException.java b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageException.java index 9e28207c..5217e947 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageFactory.java b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageFactory.java index 218da113..5fae1bf5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageFactory.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/WebServiceMessageFactory.java @@ -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. - * - *

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. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceClientException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceClientException.java index 19100e6d..5236482d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceClientException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceClientException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceFaultException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceFaultException.java index bebd8757..ecc64aa1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceFaultException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceFaultException.java @@ -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; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceIOException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceIOException.java index ca81420a..167fb484 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceIOException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceIOException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransformerException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransformerException.java index e69c803a..39e57702 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransformerException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransformerException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransportException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransportException.java index eee5992e..b5103d18 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransportException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/WebServiceTransportException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/FaultMessageResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/FaultMessageResolver.java index b6f2e6b0..a5571cbe 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/FaultMessageResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/FaultMessageResolver.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/SimpleFaultMessageResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/SimpleFaultMessageResolver.java index 63f931cc..df35218d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/SimpleFaultMessageResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/SimpleFaultMessageResolver.java @@ -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); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/SourceExtractor.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/SourceExtractor.java index 7a6db967..8809d336 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/SourceExtractor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/SourceExtractor.java @@ -37,14 +37,14 @@ import javax.xml.transform.TransformerException; */ public interface SourceExtractor { - /** - * 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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageCallback.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageCallback.java index a8142898..338cc65d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageCallback.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageCallback.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageExtractor.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageExtractor.java index bd168b6d..8d5a8c9a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageExtractor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceMessageExtractor.java @@ -37,15 +37,15 @@ import org.springframework.ws.WebServiceMessage; */ public interface WebServiceMessageExtractor { - /** - * 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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceOperations.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceOperations.java index 9b06b08f..311f6ff1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceOperations.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceOperations.java @@ -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}. - * - *

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 sendAndReceive(WebServiceMessageCallback requestCallback, WebServiceMessageExtractor responseExtractor) - throws WebServiceClientException; + /** + * Sends a web service message that can be manipulated with the given callback, reading the result with a + * {@code WebServiceMessageExtractor}. + * + *

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 sendAndReceive(WebServiceMessageCallback requestCallback, WebServiceMessageExtractor 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 sendAndReceive(String uri, - WebServiceMessageCallback requestCallback, - WebServiceMessageExtractor 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 sendAndReceive(String uri, + WebServiceMessageCallback requestCallback, + WebServiceMessageExtractor responseExtractor) throws WebServiceClientException; - /** - * Sends a web service message that can be manipulated with the given request callback, handling the response with a - * response callback. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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}. - * - *

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 sendSourceAndReceive(Source requestPayload, SourceExtractor responseExtractor) - throws WebServiceClientException; + /** + * Sends a web service message that contains the given payload, reading the result with a + * {@code SourceExtractor}. + * + *

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 sendSourceAndReceive(Source requestPayload, SourceExtractor 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 sendSourceAndReceive(String uri, Source requestPayload, SourceExtractor 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 sendSourceAndReceive(String uri, Source requestPayload, SourceExtractor responseExtractor) + throws WebServiceClientException; - /** - * Sends a web service message that contains the given payload, reading the result with a - * {@code SourceExtractor}. - * - *

The given callback allows changing of the request message after the payload has been written to it. - * - *

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 sendSourceAndReceive(Source requestPayload, - WebServiceMessageCallback requestCallback, - SourceExtractor responseExtractor) throws WebServiceClientException; + /** + * Sends a web service message that contains the given payload, reading the result with a + * {@code SourceExtractor}. + * + *

The given callback allows changing of the request message after the payload has been written to it. + * + *

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 sendSourceAndReceive(Source requestPayload, + WebServiceMessageCallback requestCallback, + SourceExtractor responseExtractor) throws WebServiceClientException; - /** - * Sends a web service message that contains the given payload, reading the result with a - * {@code SourceExtractor}. - * - *

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 sendSourceAndReceive(String uri, - Source requestPayload, - WebServiceMessageCallback requestCallback, - SourceExtractor responseExtractor) throws WebServiceClientException; + /** + * Sends a web service message that contains the given payload, reading the result with a + * {@code SourceExtractor}. + * + *

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 sendSourceAndReceive(String uri, + Source requestPayload, + WebServiceMessageCallback requestCallback, + SourceExtractor 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}. - * - *

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}. + * + *

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}. - * - *

The given callback allows changing of the request message after the payload has been written to it. - * - *

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}. + * + *

The given callback allows changing of the request message after the payload has been written to it. + * + *

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}. - * - *

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}. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceTemplate.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceTemplate.java index 501214d0..028dbb8a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceTemplate.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/WebServiceTemplate.java @@ -100,697 +100,697 @@ import org.springframework.ws.transport.support.TransportUtils; */ public class WebServiceTemplate extends WebServiceAccessor implements WebServiceOperations { - /** Log category to use for message tracing. */ - public static final String MESSAGE_TRACING_LOG_CATEGORY = "org.springframework.ws.client.MessageTracing"; - - /** Additional logger to use for sent message tracing. */ - protected static final Log sentMessageTracingLogger = - LogFactory.getLog(WebServiceTemplate.MESSAGE_TRACING_LOG_CATEGORY + ".sent"); - - /** Additional logger to use for received message tracing. */ - protected static final Log receivedMessageTracingLogger = - LogFactory.getLog(WebServiceTemplate.MESSAGE_TRACING_LOG_CATEGORY + ".received"); - - private Marshaller marshaller; - - private Unmarshaller unmarshaller; - - private FaultMessageResolver faultMessageResolver; - - private boolean checkConnectionForError = true; - - private boolean checkConnectionForFault = true; - - private ClientInterceptor[] interceptors; - - private DestinationProvider destinationProvider; - - /** Creates a new {@code WebServiceTemplate} using default settings. */ - public WebServiceTemplate() { - initDefaultStrategies(); - } - - /** - * Creates a new {@code WebServiceTemplate} based on the given message factory. - * - * @param messageFactory the message factory to use - */ - public WebServiceTemplate(WebServiceMessageFactory messageFactory) { - setMessageFactory(messageFactory); - initDefaultStrategies(); - } - - /** - * Creates a new {@code WebServiceTemplate} 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. - * - *

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 - * @since 2.0.3 - */ - public WebServiceTemplate(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 " + - "WebServiceTemplate(Marshaller, Unmarshaller) constructor."); - } - else { - this.setMarshaller(marshaller); - this.setUnmarshaller((Unmarshaller) marshaller); - } - initDefaultStrategies(); - } - - /** - * Creates a new {@code MarshallingMethodEndpointAdapter} with the given marshaller and unmarshaller. - * - * @param marshaller the marshaller to use - * @param unmarshaller the unmarshaller to use - * @since 2.0.3 - */ - public WebServiceTemplate(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); - initDefaultStrategies(); - } - - /** Returns the default URI to be used on operations that do not have a URI parameter. */ - public String getDefaultUri() { - if (destinationProvider != null) { - URI uri = destinationProvider.getDestination(); - return uri != null ? uri.toString() : null; - } - else { - return null; - } - } - - /** - * Set the default URI to be used on operations that do not have a URI parameter. - * - *

Typically, either this property is set, or {@link #setDestinationProvider(DestinationProvider)}, but not both. - * - * @see #marshalSendAndReceive(Object) - * @see #marshalSendAndReceive(Object,WebServiceMessageCallback) - * @see #sendSourceAndReceiveToResult(Source,Result) - * @see #sendSourceAndReceiveToResult(Source,WebServiceMessageCallback,Result) - * @see #sendSourceAndReceive(Source,SourceExtractor) - * @see #sendSourceAndReceive(Source,WebServiceMessageCallback,SourceExtractor) - * @see #sendAndReceive(WebServiceMessageCallback,WebServiceMessageCallback) - */ - public void setDefaultUri(final String uri) { - destinationProvider = new DestinationProvider() { - - public URI getDestination() { - return URI.create(uri); - } - }; - } - - /** Returns the destination provider used on operations that do not have a URI parameter. */ - public DestinationProvider getDestinationProvider() { - return destinationProvider; - } - - /** - * Set the destination provider URI to be used on operations that do not have a URI parameter. - * - *

Typically, either this property is set, or {@link #setDefaultUri(String)}, but not both. - * - * @see #marshalSendAndReceive(Object) - * @see #marshalSendAndReceive(Object,WebServiceMessageCallback) - * @see #sendSourceAndReceiveToResult(Source,Result) - * @see #sendSourceAndReceiveToResult(Source,WebServiceMessageCallback,Result) - * @see #sendSourceAndReceive(Source,SourceExtractor) - * @see #sendSourceAndReceive(Source,WebServiceMessageCallback,SourceExtractor) - * @see #sendAndReceive(WebServiceMessageCallback,WebServiceMessageCallback) - */ - public void setDestinationProvider(DestinationProvider destinationProvider) { - this.destinationProvider = destinationProvider; - } - - /** Returns the marshaller for this template. */ - public Marshaller getMarshaller() { - return marshaller; - } - - /** Sets the marshaller for this template. */ - public void setMarshaller(Marshaller marshaller) { - this.marshaller = marshaller; - } - - /** Returns the unmarshaller for this template. */ - public Unmarshaller getUnmarshaller() { - return unmarshaller; - } - - /** Sets the unmarshaller for this template. */ - public void setUnmarshaller(Unmarshaller unmarshaller) { - this.unmarshaller = unmarshaller; - } - - /** Returns the fault message resolver for this template. */ - public FaultMessageResolver getFaultMessageResolver() { - return faultMessageResolver; - } - - /** - * Sets the fault resolver for this template. Default is the - * {@link org.springframework.ws.soap.client.core.SoapFaultMessageResolver SoapFaultMessageResolver}, but may be - * set to {@code null} to disable fault handling. - */ - public void setFaultMessageResolver(FaultMessageResolver faultMessageResolver) { - this.faultMessageResolver = faultMessageResolver; - } - - /** - * Indicates whether the {@linkplain WebServiceConnection#hasError() connection} should be checked for error - * indicators ({@code true}), or whether these should be ignored ({@code false}). The default is - * {@code true}. - * - *

When using an HTTP transport, this property defines whether to check the HTTP response status code is in the 2xx - * Successful range. Both the SOAP specification and the WS-I Basic Profile define that a Web service must return a - * "200 OK" or "202 Accepted" HTTP status code for a normal response. Setting this property to {@code false} - * allows this template to deal with non-conforming services. - * - * @see #hasError(WebServiceConnection, WebServiceMessage) - * @see SOAP 1.1 specification - * @see WS-I Basic - * Profile - */ - public void setCheckConnectionForError(boolean checkConnectionForError) { - this.checkConnectionForError = checkConnectionForError; - } - - /** - * Indicates whether the {@linkplain FaultAwareWebServiceConnection#hasFault() connection} should be checked for - * fault indicators ({@code true}), or whether we should rely on the {@link - * FaultAwareWebServiceMessage#hasFault() message} only ({@code false}). The default is {@code true}. - * - *

When using an HTTP transport, this property defines whether to check the HTTP response status code for fault - * indicators. Both the SOAP specification and the WS-I Basic Profile define that a Web service must return a "500 - * Internal Server Error" HTTP status code if the response envelope is a Fault. Setting this property to - * {@code false} allows this template to deal with non-conforming services. - * - * @see #hasFault(WebServiceConnection,WebServiceMessage) - * @see SOAP 1.1 specification - * @see WS-I Basic - * Profile - */ - public void setCheckConnectionForFault(boolean checkConnectionForFault) { - this.checkConnectionForFault = checkConnectionForFault; - } - - /** - * Returns the client interceptors to apply to all web service invocations made by this template. - * - * @return array of endpoint interceptors, or {@code null} if none - */ - public ClientInterceptor[] getInterceptors() { - return interceptors; - } - - /** - * Sets the client interceptors to apply to all web service invocations made by this template. - * - * @param interceptors array of endpoint interceptors, or {@code null} if none - */ - public final void setInterceptors(ClientInterceptor[] interceptors) { - this.interceptors = interceptors; - } - - /** - * Initialize the default implementations for the template's strategies: {@link SoapFaultMessageResolver}, {@link - * org.springframework.ws.soap.saaj.SaajSoapMessageFactory}, and {@link HttpUrlConnectionMessageSender}. - * - * @throws BeanInitializationException in case of initalization errors - * @see #setFaultMessageResolver(FaultMessageResolver) - * @see #setMessageFactory(WebServiceMessageFactory) - * @see #setMessageSender(WebServiceMessageSender) - */ - protected void initDefaultStrategies() { - DefaultStrategiesHelper strategiesHelper = new DefaultStrategiesHelper(WebServiceTemplate.class); - if (getMessageFactory() == null) { - initMessageFactory(strategiesHelper); - } - if (ObjectUtils.isEmpty(getMessageSenders())) { - initMessageSenders(strategiesHelper); - } - if (getFaultMessageResolver() == null) { - initFaultMessageResolver(strategiesHelper); - } - } - - private void initMessageFactory(DefaultStrategiesHelper helper) throws BeanInitializationException { - WebServiceMessageFactory messageFactory = helper.getDefaultStrategy(WebServiceMessageFactory.class); - setMessageFactory(messageFactory); - } - - private void initMessageSenders(DefaultStrategiesHelper helper) { - List messageSenders = helper.getDefaultStrategies(WebServiceMessageSender.class); - setMessageSenders(messageSenders.toArray(new WebServiceMessageSender[messageSenders.size()])); - } - - private void initFaultMessageResolver(DefaultStrategiesHelper helper) throws BeanInitializationException { - FaultMessageResolver faultMessageResolver = helper.getDefaultStrategy(FaultMessageResolver.class); - setFaultMessageResolver(faultMessageResolver); - } - - // - // Marshalling methods - // - - @Override - public Object marshalSendAndReceive(final Object requestPayload) { - return marshalSendAndReceive(requestPayload, null); - } - - @Override - public Object marshalSendAndReceive(String uri, final Object requestPayload) { - return marshalSendAndReceive(uri, requestPayload, null); - } - - @Override - public Object marshalSendAndReceive(final Object requestPayload, final WebServiceMessageCallback requestCallback) { - return marshalSendAndReceive(getDefaultUri(), requestPayload, requestCallback); - } - - @Override - public Object marshalSendAndReceive(String uri, - final Object requestPayload, - final WebServiceMessageCallback requestCallback) { - return sendAndReceive(uri, new WebServiceMessageCallback() { - - public void doWithMessage(WebServiceMessage request) throws IOException, TransformerException { - if (requestPayload != null) { - Marshaller marshaller = getMarshaller(); - if (marshaller == null) { - throw new IllegalStateException( - "No marshaller registered. Check configuration of WebServiceTemplate."); - } - MarshallingUtils.marshal(marshaller, requestPayload, request); - if (requestCallback != null) { - requestCallback.doWithMessage(request); - } - } - } - }, new WebServiceMessageExtractor() { - - public Object extractData(WebServiceMessage response) throws IOException { - Unmarshaller unmarshaller = getUnmarshaller(); - if (unmarshaller == null) { - throw new IllegalStateException( - "No unmarshaller registered. Check configuration of WebServiceTemplate."); - } - return MarshallingUtils.unmarshal(unmarshaller, response); - } - }); - } - - // - // Result-handling methods - // - - @Override - public boolean sendSourceAndReceiveToResult(Source requestPayload, Result responseResult) { - return sendSourceAndReceiveToResult(requestPayload, null, responseResult); - } - - @Override - public boolean sendSourceAndReceiveToResult(String uri, Source requestPayload, Result responseResult) { - return sendSourceAndReceiveToResult(uri, requestPayload, null, responseResult); - } - - @Override - public boolean sendSourceAndReceiveToResult(Source requestPayload, - WebServiceMessageCallback requestCallback, - final Result responseResult) { - return sendSourceAndReceiveToResult(getDefaultUri(), requestPayload, requestCallback, responseResult); - } - - @Override - public boolean sendSourceAndReceiveToResult(String uri, - Source requestPayload, - WebServiceMessageCallback requestCallback, - final Result responseResult) { - try { - final Transformer transformer = createTransformer(); - Boolean retVal = doSendAndReceive(uri, transformer, requestPayload, requestCallback, - new SourceExtractor() { - - public Boolean extractData(Source source) throws IOException, TransformerException { - if (source != null) { - transformer.transform(source, responseResult); - } - return Boolean.TRUE; - } - }); - return retVal != null && retVal; - } - catch (TransformerConfigurationException ex) { - throw new WebServiceTransformerException("Could not create transformer", ex); - } - } - - // - // Source-handling methods - // - - @Override - public T sendSourceAndReceive(final Source requestPayload, final SourceExtractor responseExtractor) { - return sendSourceAndReceive(requestPayload, null, responseExtractor); - } - - @Override - public T sendSourceAndReceive(String uri, - final Source requestPayload, - final SourceExtractor responseExtractor) { - return sendSourceAndReceive(uri, requestPayload, null, responseExtractor); - } - - @Override - public T sendSourceAndReceive(final Source requestPayload, - final WebServiceMessageCallback requestCallback, - final SourceExtractor responseExtractor) { - return sendSourceAndReceive(getDefaultUri(), requestPayload, requestCallback, responseExtractor); - } - - @Override - public T sendSourceAndReceive(String uri, - final Source requestPayload, - final WebServiceMessageCallback requestCallback, - final SourceExtractor responseExtractor) { - - try { - return doSendAndReceive(uri, createTransformer(), requestPayload, requestCallback, responseExtractor); - } - catch (TransformerConfigurationException ex) { - throw new WebServiceTransformerException("Could not create transformer", ex); - } - } - - private T doSendAndReceive(String uri, - final Transformer transformer, - final Source requestPayload, - final WebServiceMessageCallback requestCallback, - final SourceExtractor responseExtractor) { - Assert.notNull(responseExtractor, "responseExtractor must not be null"); - return sendAndReceive(uri, new WebServiceMessageCallback() { - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - transformer.transform(requestPayload, message.getPayloadResult()); - if (requestCallback != null) { - requestCallback.doWithMessage(message); - } - } - }, new SourceExtractorMessageExtractor(responseExtractor)); - } - - // - // WebServiceMessage-handling methods - // - - @Override - public boolean sendAndReceive(WebServiceMessageCallback requestCallback, - WebServiceMessageCallback responseCallback) { - return sendAndReceive(getDefaultUri(), requestCallback, responseCallback); - } - - @Override - public boolean sendAndReceive(String uri, - WebServiceMessageCallback requestCallback, - WebServiceMessageCallback responseCallback) { - Assert.notNull(responseCallback, "responseCallback must not be null"); - Boolean result = sendAndReceive(uri, requestCallback, - new WebServiceMessageCallbackMessageExtractor(responseCallback)); - return result != null && result; - } - - @Override - public T sendAndReceive(WebServiceMessageCallback requestCallback, - WebServiceMessageExtractor responseExtractor) { - return sendAndReceive(getDefaultUri(), requestCallback, responseExtractor); - } - - @Override - public T sendAndReceive(String uriString, - WebServiceMessageCallback requestCallback, - WebServiceMessageExtractor responseExtractor) { - Assert.notNull(responseExtractor, "'responseExtractor' must not be null"); - Assert.hasLength(uriString, "'uri' must not be empty"); - TransportContext previousTransportContext = TransportContextHolder.getTransportContext(); - WebServiceConnection connection = null; - try { - connection = createConnection(URI.create(uriString)); - TransportContextHolder.setTransportContext(new DefaultTransportContext(connection)); - MessageContext messageContext = new DefaultMessageContext(getMessageFactory()); - - return doSendAndReceive(messageContext, connection, requestCallback, responseExtractor); - } - catch (TransportException ex) { - throw new WebServiceTransportException("Could not use transport: " + ex.getMessage(), ex); - } - catch (IOException ex) { - throw new WebServiceIOException("I/O error: " + ex.getMessage(), ex); - } - finally { - TransportUtils.closeConnection(connection); - TransportContextHolder.setTransportContext(previousTransportContext); - } - } - - /** - * Sends and receives a {@link MessageContext}. Sends the {@link MessageContext#getRequest() request message}, and - * received to the {@link MessageContext#getResponse() repsonse message}. Invocates the defined {@link - * #setInterceptors(ClientInterceptor[]) interceptors} as part of the process. - * - * @param messageContext the message context - * @param connection the connection to use - * @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 - * @throws IOException in case of I/O errors - */ - @SuppressWarnings("unchecked") - protected T doSendAndReceive(MessageContext messageContext, - WebServiceConnection connection, - WebServiceMessageCallback requestCallback, - WebServiceMessageExtractor responseExtractor) throws IOException { - int interceptorIndex = -1; - try { - if (requestCallback != null) { - requestCallback.doWithMessage(messageContext.getRequest()); - } - // Apply handleRequest of registered interceptors - boolean intercepted = false; - if (interceptors != null) { - for (int i = 0; i < interceptors.length; i++) { - interceptorIndex = i; - if (!interceptors[i].handleRequest(messageContext)) { - intercepted = true; - break; - } - } - } - // no send/receive if an interceptor has set a response or if the chain - // has been interrupted - if (!messageContext.hasResponse() && !intercepted) { - sendRequest(connection, messageContext.getRequest()); - if (hasError(connection, messageContext.getRequest())) { - triggerAfterCompletion(interceptorIndex, messageContext, null); - return (T) handleError(connection, messageContext.getRequest()); - } - WebServiceMessage response = connection.receive(getMessageFactory()); - messageContext.setResponse(response); - } - logResponse(messageContext); - if (messageContext.hasResponse()) { - if (!hasFault(connection, messageContext.getResponse())) { - triggerHandleResponse(interceptorIndex, messageContext); - triggerAfterCompletion(interceptorIndex, messageContext, null); - return responseExtractor.extractData(messageContext.getResponse()); - } - else { - triggerHandleFault(interceptorIndex, messageContext); - triggerAfterCompletion(interceptorIndex, messageContext, null); - return (T)handleFault(connection, messageContext); - } - } - else { - triggerAfterCompletion(interceptorIndex, messageContext, null); - return null; - } - } - catch (TransformerException ex) { - triggerAfterCompletion(interceptorIndex, messageContext, ex); - throw new WebServiceTransformerException("Transformation error: " + ex.getMessage(), ex); - } - catch (RuntimeException ex) { - // Trigger after-completion for thrown exception. - triggerAfterCompletion(interceptorIndex, messageContext, ex); - throw ex; - } - catch (IOException ex) { - // Trigger after-completion for thrown exception. - triggerAfterCompletion(interceptorIndex, messageContext, ex); - throw ex; - } - } - - /** Sends the request in the given message context over the connection. */ - private void sendRequest(WebServiceConnection connection, WebServiceMessage request) throws IOException { - if (sentMessageTracingLogger.isTraceEnabled()) { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - request.writeTo(os); - sentMessageTracingLogger.trace("Sent request [" + os.toString("UTF-8") + "]"); - } - else if (sentMessageTracingLogger.isDebugEnabled()) { - sentMessageTracingLogger.debug("Sent request [" + request + "]"); - } - connection.send(request); - } - - /** - * Determines whether the given connection or message context has an error. - * - *

This implementation checks the {@link WebServiceConnection#hasError() connection} first. If it indicates an - * error, it makes sure that it is not a {@link FaultAwareWebServiceConnection#hasFault() fault}. - * - * @param connection the connection (possibly a {@link FaultAwareWebServiceConnection} - * @param request the response message (possibly a {@link FaultAwareWebServiceMessage} - * @return {@code true} if the connection has an error; {@code false} otherwise - * @throws IOException in case of I/O errors - */ - protected boolean hasError(WebServiceConnection connection, WebServiceMessage request) throws IOException { - if (checkConnectionForError && connection.hasError()) { - // could be a fault - if (checkConnectionForFault && connection instanceof FaultAwareWebServiceConnection) { - FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection; - return !(faultConnection.hasFault() && request instanceof FaultAwareWebServiceMessage); - } - else { - return true; - } - } - return false; - } - - /** - * Handles an error on the given connection. The default implementation throws a {@link - * WebServiceTransportException}. - * - * @param connection the erroneous connection - * @param request the corresponding request message - * @return the object to be returned from {@link #sendAndReceive(String,WebServiceMessageCallback, - * WebServiceMessageExtractor)}, if any - */ - protected Object handleError(WebServiceConnection connection, WebServiceMessage request) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("Received error for request [" + request + "]"); - } - throw new WebServiceTransportException(connection.getErrorMessage()); - } - - private void logResponse(MessageContext messageContext) throws IOException { - if (messageContext.hasResponse()) { - if (receivedMessageTracingLogger.isTraceEnabled()) { - ByteArrayOutputStream requestStream = new ByteArrayOutputStream(); - messageContext.getRequest().writeTo(requestStream); - ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); - messageContext.getResponse().writeTo(responseStream); - receivedMessageTracingLogger - .trace("Received response [" + responseStream.toString("UTF-8") + "] for request [" + - requestStream.toString("UTF-8") + "]"); - } - else if (receivedMessageTracingLogger.isDebugEnabled()) { - receivedMessageTracingLogger - .debug("Received response [" + messageContext.getResponse() + "] for request [" + - messageContext.getRequest() + "]"); - } - } - else { - if (receivedMessageTracingLogger.isDebugEnabled()) { - receivedMessageTracingLogger - .debug("Received no response for request [" + messageContext.getRequest() + "]"); - } - } - } - - /** - * Determines whether the given connection or message has a fault. - * - *

This implementation checks the {@link FaultAwareWebServiceConnection#hasFault() connection} if the {@link - * #setCheckConnectionForFault(boolean) checkConnectionForFault} property is true, and defaults to the {@link - * FaultAwareWebServiceMessage#hasFault() message} otherwise. - * - * @param connection the connection (possibly a {@link FaultAwareWebServiceConnection} - * @param response the response message (possibly a {@link FaultAwareWebServiceMessage} - * @return {@code true} if either the connection or the message has a fault; {@code false} otherwise - * @throws IOException in case of I/O errors - */ - protected boolean hasFault(WebServiceConnection connection, WebServiceMessage response) throws IOException { - if (checkConnectionForFault && connection instanceof FaultAwareWebServiceConnection) { - // check whether the connection has a fault (i.e. status code 500 in HTTP) - FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection; - if (!faultConnection.hasFault()) { - return false; - } - } - if (response instanceof FaultAwareWebServiceMessage) { - // either the connection has a fault, or checkConnectionForFault is false: let's verify the fault - FaultAwareWebServiceMessage faultMessage = (FaultAwareWebServiceMessage) response; - return faultMessage.hasFault(); - } - return false; - } - - /** - * Trigger handleResponse on the defined ClientInterceptors. 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 interceptorIndex index of last interceptor that was called - * @param messageContext the message context, whose request and response are filled - * @see ClientInterceptor#handleResponse(MessageContext) - * @see ClientInterceptor#handleFault(MessageContext) - */ - private void triggerHandleResponse(int interceptorIndex, MessageContext messageContext) { - if (messageContext.hasResponse() && interceptors != null) { - for (int i = interceptorIndex; i >= 0; i--) { - if (!interceptors[i].handleResponse(messageContext)) { - break; - } - } - } - } - - /** - * Trigger handleFault on the defined ClientInterceptors. 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 interceptorIndex index of last interceptor that was called - * @param messageContext the message context, whose request and response are filled - * @see ClientInterceptor#handleResponse(MessageContext) - * @see ClientInterceptor#handleFault(MessageContext) - */ - private void triggerHandleFault(int interceptorIndex, MessageContext messageContext) { - if (messageContext.hasResponse() && interceptors != null) { - for (int i = interceptorIndex; i >= 0; i--) { - if (!interceptors[i].handleFault(messageContext)) { - break; - } - } - } - } + /** Log category to use for message tracing. */ + public static final String MESSAGE_TRACING_LOG_CATEGORY = "org.springframework.ws.client.MessageTracing"; + + /** Additional logger to use for sent message tracing. */ + protected static final Log sentMessageTracingLogger = + LogFactory.getLog(WebServiceTemplate.MESSAGE_TRACING_LOG_CATEGORY + ".sent"); + + /** Additional logger to use for received message tracing. */ + protected static final Log receivedMessageTracingLogger = + LogFactory.getLog(WebServiceTemplate.MESSAGE_TRACING_LOG_CATEGORY + ".received"); + + private Marshaller marshaller; + + private Unmarshaller unmarshaller; + + private FaultMessageResolver faultMessageResolver; + + private boolean checkConnectionForError = true; + + private boolean checkConnectionForFault = true; + + private ClientInterceptor[] interceptors; + + private DestinationProvider destinationProvider; + + /** Creates a new {@code WebServiceTemplate} using default settings. */ + public WebServiceTemplate() { + initDefaultStrategies(); + } + + /** + * Creates a new {@code WebServiceTemplate} based on the given message factory. + * + * @param messageFactory the message factory to use + */ + public WebServiceTemplate(WebServiceMessageFactory messageFactory) { + setMessageFactory(messageFactory); + initDefaultStrategies(); + } + + /** + * Creates a new {@code WebServiceTemplate} 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. + * + *

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 + * @since 2.0.3 + */ + public WebServiceTemplate(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 " + + "WebServiceTemplate(Marshaller, Unmarshaller) constructor."); + } + else { + this.setMarshaller(marshaller); + this.setUnmarshaller((Unmarshaller) marshaller); + } + initDefaultStrategies(); + } + + /** + * Creates a new {@code MarshallingMethodEndpointAdapter} with the given marshaller and unmarshaller. + * + * @param marshaller the marshaller to use + * @param unmarshaller the unmarshaller to use + * @since 2.0.3 + */ + public WebServiceTemplate(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); + initDefaultStrategies(); + } + + /** Returns the default URI to be used on operations that do not have a URI parameter. */ + public String getDefaultUri() { + if (destinationProvider != null) { + URI uri = destinationProvider.getDestination(); + return uri != null ? uri.toString() : null; + } + else { + return null; + } + } + + /** + * Set the default URI to be used on operations that do not have a URI parameter. + * + *

Typically, either this property is set, or {@link #setDestinationProvider(DestinationProvider)}, but not both. + * + * @see #marshalSendAndReceive(Object) + * @see #marshalSendAndReceive(Object,WebServiceMessageCallback) + * @see #sendSourceAndReceiveToResult(Source,Result) + * @see #sendSourceAndReceiveToResult(Source,WebServiceMessageCallback,Result) + * @see #sendSourceAndReceive(Source,SourceExtractor) + * @see #sendSourceAndReceive(Source,WebServiceMessageCallback,SourceExtractor) + * @see #sendAndReceive(WebServiceMessageCallback,WebServiceMessageCallback) + */ + public void setDefaultUri(final String uri) { + destinationProvider = new DestinationProvider() { + + public URI getDestination() { + return URI.create(uri); + } + }; + } + + /** Returns the destination provider used on operations that do not have a URI parameter. */ + public DestinationProvider getDestinationProvider() { + return destinationProvider; + } + + /** + * Set the destination provider URI to be used on operations that do not have a URI parameter. + * + *

Typically, either this property is set, or {@link #setDefaultUri(String)}, but not both. + * + * @see #marshalSendAndReceive(Object) + * @see #marshalSendAndReceive(Object,WebServiceMessageCallback) + * @see #sendSourceAndReceiveToResult(Source,Result) + * @see #sendSourceAndReceiveToResult(Source,WebServiceMessageCallback,Result) + * @see #sendSourceAndReceive(Source,SourceExtractor) + * @see #sendSourceAndReceive(Source,WebServiceMessageCallback,SourceExtractor) + * @see #sendAndReceive(WebServiceMessageCallback,WebServiceMessageCallback) + */ + public void setDestinationProvider(DestinationProvider destinationProvider) { + this.destinationProvider = destinationProvider; + } + + /** Returns the marshaller for this template. */ + public Marshaller getMarshaller() { + return marshaller; + } + + /** Sets the marshaller for this template. */ + public void setMarshaller(Marshaller marshaller) { + this.marshaller = marshaller; + } + + /** Returns the unmarshaller for this template. */ + public Unmarshaller getUnmarshaller() { + return unmarshaller; + } + + /** Sets the unmarshaller for this template. */ + public void setUnmarshaller(Unmarshaller unmarshaller) { + this.unmarshaller = unmarshaller; + } + + /** Returns the fault message resolver for this template. */ + public FaultMessageResolver getFaultMessageResolver() { + return faultMessageResolver; + } + + /** + * Sets the fault resolver for this template. Default is the + * {@link org.springframework.ws.soap.client.core.SoapFaultMessageResolver SoapFaultMessageResolver}, but may be + * set to {@code null} to disable fault handling. + */ + public void setFaultMessageResolver(FaultMessageResolver faultMessageResolver) { + this.faultMessageResolver = faultMessageResolver; + } + + /** + * Indicates whether the {@linkplain WebServiceConnection#hasError() connection} should be checked for error + * indicators ({@code true}), or whether these should be ignored ({@code false}). The default is + * {@code true}. + * + *

When using an HTTP transport, this property defines whether to check the HTTP response status code is in the 2xx + * Successful range. Both the SOAP specification and the WS-I Basic Profile define that a Web service must return a + * "200 OK" or "202 Accepted" HTTP status code for a normal response. Setting this property to {@code false} + * allows this template to deal with non-conforming services. + * + * @see #hasError(WebServiceConnection, WebServiceMessage) + * @see SOAP 1.1 specification + * @see WS-I Basic + * Profile + */ + public void setCheckConnectionForError(boolean checkConnectionForError) { + this.checkConnectionForError = checkConnectionForError; + } + + /** + * Indicates whether the {@linkplain FaultAwareWebServiceConnection#hasFault() connection} should be checked for + * fault indicators ({@code true}), or whether we should rely on the {@link + * FaultAwareWebServiceMessage#hasFault() message} only ({@code false}). The default is {@code true}. + * + *

When using an HTTP transport, this property defines whether to check the HTTP response status code for fault + * indicators. Both the SOAP specification and the WS-I Basic Profile define that a Web service must return a "500 + * Internal Server Error" HTTP status code if the response envelope is a Fault. Setting this property to + * {@code false} allows this template to deal with non-conforming services. + * + * @see #hasFault(WebServiceConnection,WebServiceMessage) + * @see SOAP 1.1 specification + * @see WS-I Basic + * Profile + */ + public void setCheckConnectionForFault(boolean checkConnectionForFault) { + this.checkConnectionForFault = checkConnectionForFault; + } + + /** + * Returns the client interceptors to apply to all web service invocations made by this template. + * + * @return array of endpoint interceptors, or {@code null} if none + */ + public ClientInterceptor[] getInterceptors() { + return interceptors; + } + + /** + * Sets the client interceptors to apply to all web service invocations made by this template. + * + * @param interceptors array of endpoint interceptors, or {@code null} if none + */ + public final void setInterceptors(ClientInterceptor[] interceptors) { + this.interceptors = interceptors; + } + + /** + * Initialize the default implementations for the template's strategies: {@link SoapFaultMessageResolver}, {@link + * org.springframework.ws.soap.saaj.SaajSoapMessageFactory}, and {@link HttpUrlConnectionMessageSender}. + * + * @throws BeanInitializationException in case of initalization errors + * @see #setFaultMessageResolver(FaultMessageResolver) + * @see #setMessageFactory(WebServiceMessageFactory) + * @see #setMessageSender(WebServiceMessageSender) + */ + protected void initDefaultStrategies() { + DefaultStrategiesHelper strategiesHelper = new DefaultStrategiesHelper(WebServiceTemplate.class); + if (getMessageFactory() == null) { + initMessageFactory(strategiesHelper); + } + if (ObjectUtils.isEmpty(getMessageSenders())) { + initMessageSenders(strategiesHelper); + } + if (getFaultMessageResolver() == null) { + initFaultMessageResolver(strategiesHelper); + } + } + + private void initMessageFactory(DefaultStrategiesHelper helper) throws BeanInitializationException { + WebServiceMessageFactory messageFactory = helper.getDefaultStrategy(WebServiceMessageFactory.class); + setMessageFactory(messageFactory); + } + + private void initMessageSenders(DefaultStrategiesHelper helper) { + List messageSenders = helper.getDefaultStrategies(WebServiceMessageSender.class); + setMessageSenders(messageSenders.toArray(new WebServiceMessageSender[messageSenders.size()])); + } + + private void initFaultMessageResolver(DefaultStrategiesHelper helper) throws BeanInitializationException { + FaultMessageResolver faultMessageResolver = helper.getDefaultStrategy(FaultMessageResolver.class); + setFaultMessageResolver(faultMessageResolver); + } + + // + // Marshalling methods + // + + @Override + public Object marshalSendAndReceive(final Object requestPayload) { + return marshalSendAndReceive(requestPayload, null); + } + + @Override + public Object marshalSendAndReceive(String uri, final Object requestPayload) { + return marshalSendAndReceive(uri, requestPayload, null); + } + + @Override + public Object marshalSendAndReceive(final Object requestPayload, final WebServiceMessageCallback requestCallback) { + return marshalSendAndReceive(getDefaultUri(), requestPayload, requestCallback); + } + + @Override + public Object marshalSendAndReceive(String uri, + final Object requestPayload, + final WebServiceMessageCallback requestCallback) { + return sendAndReceive(uri, new WebServiceMessageCallback() { + + public void doWithMessage(WebServiceMessage request) throws IOException, TransformerException { + if (requestPayload != null) { + Marshaller marshaller = getMarshaller(); + if (marshaller == null) { + throw new IllegalStateException( + "No marshaller registered. Check configuration of WebServiceTemplate."); + } + MarshallingUtils.marshal(marshaller, requestPayload, request); + if (requestCallback != null) { + requestCallback.doWithMessage(request); + } + } + } + }, new WebServiceMessageExtractor() { + + public Object extractData(WebServiceMessage response) throws IOException { + Unmarshaller unmarshaller = getUnmarshaller(); + if (unmarshaller == null) { + throw new IllegalStateException( + "No unmarshaller registered. Check configuration of WebServiceTemplate."); + } + return MarshallingUtils.unmarshal(unmarshaller, response); + } + }); + } + + // + // Result-handling methods + // + + @Override + public boolean sendSourceAndReceiveToResult(Source requestPayload, Result responseResult) { + return sendSourceAndReceiveToResult(requestPayload, null, responseResult); + } + + @Override + public boolean sendSourceAndReceiveToResult(String uri, Source requestPayload, Result responseResult) { + return sendSourceAndReceiveToResult(uri, requestPayload, null, responseResult); + } + + @Override + public boolean sendSourceAndReceiveToResult(Source requestPayload, + WebServiceMessageCallback requestCallback, + final Result responseResult) { + return sendSourceAndReceiveToResult(getDefaultUri(), requestPayload, requestCallback, responseResult); + } + + @Override + public boolean sendSourceAndReceiveToResult(String uri, + Source requestPayload, + WebServiceMessageCallback requestCallback, + final Result responseResult) { + try { + final Transformer transformer = createTransformer(); + Boolean retVal = doSendAndReceive(uri, transformer, requestPayload, requestCallback, + new SourceExtractor() { + + public Boolean extractData(Source source) throws IOException, TransformerException { + if (source != null) { + transformer.transform(source, responseResult); + } + return Boolean.TRUE; + } + }); + return retVal != null && retVal; + } + catch (TransformerConfigurationException ex) { + throw new WebServiceTransformerException("Could not create transformer", ex); + } + } + + // + // Source-handling methods + // + + @Override + public T sendSourceAndReceive(final Source requestPayload, final SourceExtractor responseExtractor) { + return sendSourceAndReceive(requestPayload, null, responseExtractor); + } + + @Override + public T sendSourceAndReceive(String uri, + final Source requestPayload, + final SourceExtractor responseExtractor) { + return sendSourceAndReceive(uri, requestPayload, null, responseExtractor); + } + + @Override + public T sendSourceAndReceive(final Source requestPayload, + final WebServiceMessageCallback requestCallback, + final SourceExtractor responseExtractor) { + return sendSourceAndReceive(getDefaultUri(), requestPayload, requestCallback, responseExtractor); + } + + @Override + public T sendSourceAndReceive(String uri, + final Source requestPayload, + final WebServiceMessageCallback requestCallback, + final SourceExtractor responseExtractor) { + + try { + return doSendAndReceive(uri, createTransformer(), requestPayload, requestCallback, responseExtractor); + } + catch (TransformerConfigurationException ex) { + throw new WebServiceTransformerException("Could not create transformer", ex); + } + } + + private T doSendAndReceive(String uri, + final Transformer transformer, + final Source requestPayload, + final WebServiceMessageCallback requestCallback, + final SourceExtractor responseExtractor) { + Assert.notNull(responseExtractor, "responseExtractor must not be null"); + return sendAndReceive(uri, new WebServiceMessageCallback() { + public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { + transformer.transform(requestPayload, message.getPayloadResult()); + if (requestCallback != null) { + requestCallback.doWithMessage(message); + } + } + }, new SourceExtractorMessageExtractor(responseExtractor)); + } + + // + // WebServiceMessage-handling methods + // + + @Override + public boolean sendAndReceive(WebServiceMessageCallback requestCallback, + WebServiceMessageCallback responseCallback) { + return sendAndReceive(getDefaultUri(), requestCallback, responseCallback); + } + + @Override + public boolean sendAndReceive(String uri, + WebServiceMessageCallback requestCallback, + WebServiceMessageCallback responseCallback) { + Assert.notNull(responseCallback, "responseCallback must not be null"); + Boolean result = sendAndReceive(uri, requestCallback, + new WebServiceMessageCallbackMessageExtractor(responseCallback)); + return result != null && result; + } + + @Override + public T sendAndReceive(WebServiceMessageCallback requestCallback, + WebServiceMessageExtractor responseExtractor) { + return sendAndReceive(getDefaultUri(), requestCallback, responseExtractor); + } + + @Override + public T sendAndReceive(String uriString, + WebServiceMessageCallback requestCallback, + WebServiceMessageExtractor responseExtractor) { + Assert.notNull(responseExtractor, "'responseExtractor' must not be null"); + Assert.hasLength(uriString, "'uri' must not be empty"); + TransportContext previousTransportContext = TransportContextHolder.getTransportContext(); + WebServiceConnection connection = null; + try { + connection = createConnection(URI.create(uriString)); + TransportContextHolder.setTransportContext(new DefaultTransportContext(connection)); + MessageContext messageContext = new DefaultMessageContext(getMessageFactory()); + + return doSendAndReceive(messageContext, connection, requestCallback, responseExtractor); + } + catch (TransportException ex) { + throw new WebServiceTransportException("Could not use transport: " + ex.getMessage(), ex); + } + catch (IOException ex) { + throw new WebServiceIOException("I/O error: " + ex.getMessage(), ex); + } + finally { + TransportUtils.closeConnection(connection); + TransportContextHolder.setTransportContext(previousTransportContext); + } + } + + /** + * Sends and receives a {@link MessageContext}. Sends the {@link MessageContext#getRequest() request message}, and + * received to the {@link MessageContext#getResponse() repsonse message}. Invocates the defined {@link + * #setInterceptors(ClientInterceptor[]) interceptors} as part of the process. + * + * @param messageContext the message context + * @param connection the connection to use + * @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 + * @throws IOException in case of I/O errors + */ + @SuppressWarnings("unchecked") + protected T doSendAndReceive(MessageContext messageContext, + WebServiceConnection connection, + WebServiceMessageCallback requestCallback, + WebServiceMessageExtractor responseExtractor) throws IOException { + int interceptorIndex = -1; + try { + if (requestCallback != null) { + requestCallback.doWithMessage(messageContext.getRequest()); + } + // Apply handleRequest of registered interceptors + boolean intercepted = false; + if (interceptors != null) { + for (int i = 0; i < interceptors.length; i++) { + interceptorIndex = i; + if (!interceptors[i].handleRequest(messageContext)) { + intercepted = true; + break; + } + } + } + // no send/receive if an interceptor has set a response or if the chain + // has been interrupted + if (!messageContext.hasResponse() && !intercepted) { + sendRequest(connection, messageContext.getRequest()); + if (hasError(connection, messageContext.getRequest())) { + triggerAfterCompletion(interceptorIndex, messageContext, null); + return (T) handleError(connection, messageContext.getRequest()); + } + WebServiceMessage response = connection.receive(getMessageFactory()); + messageContext.setResponse(response); + } + logResponse(messageContext); + if (messageContext.hasResponse()) { + if (!hasFault(connection, messageContext.getResponse())) { + triggerHandleResponse(interceptorIndex, messageContext); + triggerAfterCompletion(interceptorIndex, messageContext, null); + return responseExtractor.extractData(messageContext.getResponse()); + } + else { + triggerHandleFault(interceptorIndex, messageContext); + triggerAfterCompletion(interceptorIndex, messageContext, null); + return (T)handleFault(connection, messageContext); + } + } + else { + triggerAfterCompletion(interceptorIndex, messageContext, null); + return null; + } + } + catch (TransformerException ex) { + triggerAfterCompletion(interceptorIndex, messageContext, ex); + throw new WebServiceTransformerException("Transformation error: " + ex.getMessage(), ex); + } + catch (RuntimeException ex) { + // Trigger after-completion for thrown exception. + triggerAfterCompletion(interceptorIndex, messageContext, ex); + throw ex; + } + catch (IOException ex) { + // Trigger after-completion for thrown exception. + triggerAfterCompletion(interceptorIndex, messageContext, ex); + throw ex; + } + } + + /** Sends the request in the given message context over the connection. */ + private void sendRequest(WebServiceConnection connection, WebServiceMessage request) throws IOException { + if (sentMessageTracingLogger.isTraceEnabled()) { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + request.writeTo(os); + sentMessageTracingLogger.trace("Sent request [" + os.toString("UTF-8") + "]"); + } + else if (sentMessageTracingLogger.isDebugEnabled()) { + sentMessageTracingLogger.debug("Sent request [" + request + "]"); + } + connection.send(request); + } + + /** + * Determines whether the given connection or message context has an error. + * + *

This implementation checks the {@link WebServiceConnection#hasError() connection} first. If it indicates an + * error, it makes sure that it is not a {@link FaultAwareWebServiceConnection#hasFault() fault}. + * + * @param connection the connection (possibly a {@link FaultAwareWebServiceConnection} + * @param request the response message (possibly a {@link FaultAwareWebServiceMessage} + * @return {@code true} if the connection has an error; {@code false} otherwise + * @throws IOException in case of I/O errors + */ + protected boolean hasError(WebServiceConnection connection, WebServiceMessage request) throws IOException { + if (checkConnectionForError && connection.hasError()) { + // could be a fault + if (checkConnectionForFault && connection instanceof FaultAwareWebServiceConnection) { + FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection; + return !(faultConnection.hasFault() && request instanceof FaultAwareWebServiceMessage); + } + else { + return true; + } + } + return false; + } + + /** + * Handles an error on the given connection. The default implementation throws a {@link + * WebServiceTransportException}. + * + * @param connection the erroneous connection + * @param request the corresponding request message + * @return the object to be returned from {@link #sendAndReceive(String,WebServiceMessageCallback, + * WebServiceMessageExtractor)}, if any + */ + protected Object handleError(WebServiceConnection connection, WebServiceMessage request) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("Received error for request [" + request + "]"); + } + throw new WebServiceTransportException(connection.getErrorMessage()); + } + + private void logResponse(MessageContext messageContext) throws IOException { + if (messageContext.hasResponse()) { + if (receivedMessageTracingLogger.isTraceEnabled()) { + ByteArrayOutputStream requestStream = new ByteArrayOutputStream(); + messageContext.getRequest().writeTo(requestStream); + ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + messageContext.getResponse().writeTo(responseStream); + receivedMessageTracingLogger + .trace("Received response [" + responseStream.toString("UTF-8") + "] for request [" + + requestStream.toString("UTF-8") + "]"); + } + else if (receivedMessageTracingLogger.isDebugEnabled()) { + receivedMessageTracingLogger + .debug("Received response [" + messageContext.getResponse() + "] for request [" + + messageContext.getRequest() + "]"); + } + } + else { + if (receivedMessageTracingLogger.isDebugEnabled()) { + receivedMessageTracingLogger + .debug("Received no response for request [" + messageContext.getRequest() + "]"); + } + } + } + + /** + * Determines whether the given connection or message has a fault. + * + *

This implementation checks the {@link FaultAwareWebServiceConnection#hasFault() connection} if the {@link + * #setCheckConnectionForFault(boolean) checkConnectionForFault} property is true, and defaults to the {@link + * FaultAwareWebServiceMessage#hasFault() message} otherwise. + * + * @param connection the connection (possibly a {@link FaultAwareWebServiceConnection} + * @param response the response message (possibly a {@link FaultAwareWebServiceMessage} + * @return {@code true} if either the connection or the message has a fault; {@code false} otherwise + * @throws IOException in case of I/O errors + */ + protected boolean hasFault(WebServiceConnection connection, WebServiceMessage response) throws IOException { + if (checkConnectionForFault && connection instanceof FaultAwareWebServiceConnection) { + // check whether the connection has a fault (i.e. status code 500 in HTTP) + FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection; + if (!faultConnection.hasFault()) { + return false; + } + } + if (response instanceof FaultAwareWebServiceMessage) { + // either the connection has a fault, or checkConnectionForFault is false: let's verify the fault + FaultAwareWebServiceMessage faultMessage = (FaultAwareWebServiceMessage) response; + return faultMessage.hasFault(); + } + return false; + } + + /** + * Trigger handleResponse on the defined ClientInterceptors. 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 interceptorIndex index of last interceptor that was called + * @param messageContext the message context, whose request and response are filled + * @see ClientInterceptor#handleResponse(MessageContext) + * @see ClientInterceptor#handleFault(MessageContext) + */ + private void triggerHandleResponse(int interceptorIndex, MessageContext messageContext) { + if (messageContext.hasResponse() && interceptors != null) { + for (int i = interceptorIndex; i >= 0; i--) { + if (!interceptors[i].handleResponse(messageContext)) { + break; + } + } + } + } + + /** + * Trigger handleFault on the defined ClientInterceptors. 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 interceptorIndex index of last interceptor that was called + * @param messageContext the message context, whose request and response are filled + * @see ClientInterceptor#handleResponse(MessageContext) + * @see ClientInterceptor#handleFault(MessageContext) + */ + private void triggerHandleFault(int interceptorIndex, MessageContext messageContext) { + if (messageContext.hasResponse() && interceptors != null) { + for (int i = interceptorIndex; i >= 0; i--) { + if (!interceptors[i].handleFault(messageContext)) { + break; + } + } + } + } /** * Trigger afterCompletion callbacks on the mapped ClientInterceptors. Will just @@ -812,58 +812,58 @@ public class WebServiceTemplate extends WebServiceAccessor implements WebService } } - /** - * Handles an fault in the given response message. The default implementation invokes the {@link - * FaultMessageResolver fault resolver} if registered, or invokes {@link #handleError(WebServiceConnection, - * WebServiceMessage)} otherwise. - * - * @param connection the faulty connection - * @param messageContext the message context - * @return the object to be returned from {@link #sendAndReceive(String,WebServiceMessageCallback, - * WebServiceMessageExtractor)}, if any - */ - protected Object handleFault(WebServiceConnection connection, MessageContext messageContext) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("Received Fault message for request [" + messageContext.getRequest() + "]"); - } - if (getFaultMessageResolver() != null) { - getFaultMessageResolver().resolveFault(messageContext.getResponse()); - return null; - } - else { - return handleError(connection, messageContext.getRequest()); - } - } + /** + * Handles an fault in the given response message. The default implementation invokes the {@link + * FaultMessageResolver fault resolver} if registered, or invokes {@link #handleError(WebServiceConnection, + * WebServiceMessage)} otherwise. + * + * @param connection the faulty connection + * @param messageContext the message context + * @return the object to be returned from {@link #sendAndReceive(String,WebServiceMessageCallback, + * WebServiceMessageExtractor)}, if any + */ + protected Object handleFault(WebServiceConnection connection, MessageContext messageContext) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("Received Fault message for request [" + messageContext.getRequest() + "]"); + } + if (getFaultMessageResolver() != null) { + getFaultMessageResolver().resolveFault(messageContext.getResponse()); + return null; + } + else { + return handleError(connection, messageContext.getRequest()); + } + } - /** Adapter to enable use of a WebServiceMessageCallback inside a WebServiceMessageExtractor. */ - private static class WebServiceMessageCallbackMessageExtractor implements WebServiceMessageExtractor { + /** Adapter to enable use of a WebServiceMessageCallback inside a WebServiceMessageExtractor. */ + private static class WebServiceMessageCallbackMessageExtractor implements WebServiceMessageExtractor { - private final WebServiceMessageCallback callback; + private final WebServiceMessageCallback callback; - private WebServiceMessageCallbackMessageExtractor(WebServiceMessageCallback callback) { - this.callback = callback; - } + private WebServiceMessageCallbackMessageExtractor(WebServiceMessageCallback callback) { + this.callback = callback; + } - @Override - public Boolean extractData(WebServiceMessage message) throws IOException, TransformerException { - callback.doWithMessage(message); - return Boolean.TRUE; - } - } + @Override + public Boolean extractData(WebServiceMessage message) throws IOException, TransformerException { + callback.doWithMessage(message); + return Boolean.TRUE; + } + } - /** Adapter to enable use of a SourceExtractor inside a WebServiceMessageExtractor. */ - private static class SourceExtractorMessageExtractor implements WebServiceMessageExtractor { + /** Adapter to enable use of a SourceExtractor inside a WebServiceMessageExtractor. */ + private static class SourceExtractorMessageExtractor implements WebServiceMessageExtractor { - private final SourceExtractor sourceExtractor; + private final SourceExtractor sourceExtractor; - private SourceExtractorMessageExtractor(SourceExtractor sourceExtractor) { - this.sourceExtractor = sourceExtractor; - } + private SourceExtractorMessageExtractor(SourceExtractor sourceExtractor) { + this.sourceExtractor = sourceExtractor; + } - @Override - public T extractData(WebServiceMessage message) throws IOException, TransformerException { - return sourceExtractor.extractData(message.getPayloadSource()); - } - } + @Override + public T extractData(WebServiceMessage message) throws IOException, TransformerException { + return sourceExtractor.extractData(message.getPayloadSource()); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/core/support/WebServiceGatewaySupport.java b/spring-ws-core/src/main/java/org/springframework/ws/client/core/support/WebServiceGatewaySupport.java index 01ca6b5b..85d0ea55 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/core/support/WebServiceGatewaySupport.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/core/support/WebServiceGatewaySupport.java @@ -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. - * - *

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. + * + *

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 { + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/WebServiceAccessor.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/WebServiceAccessor.java index 15fba65d..2917dba2 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/WebServiceAccessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/WebServiceAccessor.java @@ -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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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"); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/AbstractCachingDestinationProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/AbstractCachingDestinationProvider.java index b92f9577..2a348861 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/AbstractCachingDestinationProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/AbstractCachingDestinationProvider.java @@ -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. - * - *

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. + * + *

If {@linkplain #setCache(boolean) caching} is enabled, this method will only be called once. + * + * @return the destination URI + */ + protected abstract URI lookupDestination(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvider.java index 4939dd4c..9ac1c728 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvider.java @@ -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(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvisionException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvisionException.java index f8474259..6f469d42 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvisionException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/DestinationProvisionException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProvider.java index 967ecd10..dda294a0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProvider.java @@ -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 expressionNamespaces = new HashMap(); + private Map expressionNamespaces = new HashMap(); - 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. - * - *

The expression can use the following bound prefixes:

- * - * - * - *
PrefixNamespace
{@code wsdl}{@code http://schemas.xmlsoap.org/wsdl/}
{@code soap}{@code http://schemas.xmlsoap.org/wsdl/soap/}
{@code soap12}{@code http://schemas.xmlsoap.org/wsdl/soap12/}
- * - *

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. + * + *

The expression can use the following bound prefixes:

+ * + * + * + *
PrefixNamespace
{@code wsdl}{@code http://schemas.xmlsoap.org/wsdl/}
{@code soap}{@code http://schemas.xmlsoap.org/wsdl/soap/}
{@code soap12}{@code http://schemas.xmlsoap.org/wsdl/soap12/}
+ * + *

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); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/AbstractValidatingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/AbstractValidatingInterceptor.java index cc9a4a67..1b41a83e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/AbstractValidatingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/AbstractValidatingInterceptor.java @@ -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. - * - *

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. + * + *

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. - * - *

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. + * + *

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 not the - * default. - * - *

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 not the + * default. + * + *

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. - * - *

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. + * + *

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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/ClientInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/ClientInterceptor.java index 5074b40d..a12a7e73 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/ClientInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/ClientInterceptor.java @@ -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}. - * - *

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}. - * - *

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}. + * + *

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}. + * + *

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. - * - *

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; + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptor.java index b33309c0..28760e1f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptor.java @@ -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(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/WebServiceValidationException.java b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/WebServiceValidationException.java index 47ef87bb..c16fa352 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/WebServiceValidationException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/client/support/interceptor/WebServiceValidationException.java @@ -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; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParser.java b/spring-ws-core/src/main/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParser.java index 225ef391..27fd62b6 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParser.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParser.java @@ -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 argumentResolvers = new ManagedList(); - argumentResolvers.setSource(source); + ManagedList argumentResolvers = new ManagedList(); + argumentResolvers.setSource(source); - ManagedList returnValueHandlers = new ManagedList(); - returnValueHandlers.setSource(source); + ManagedList returnValueHandlers = new ManagedList(); + 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; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/DynamicWsdlBeanDefinitionParser.java b/spring-ws-core/src/main/java/org/springframework/ws/config/DynamicWsdlBeanDefinitionParser.java index 83ac2c7b..0cdfc4be 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/DynamicWsdlBeanDefinitionParser.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/DynamicWsdlBeanDefinitionParser.java @@ -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 schemas = DomUtils.getChildElementsByTagName(element, "xsd"); - if (commonsSchemaPresent) { - RootBeanDefinition collectionDef = createBeanDefinition(CommonsXsdSchemaCollection.class, source); - collectionDef.getPropertyValues().addPropertyValue("inline", "true"); - ManagedList xsds = new ManagedList(); - 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 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 schemas = DomUtils.getChildElementsByTagName(element, "xsd"); + if (commonsSchemaPresent) { + RootBeanDefinition collectionDef = createBeanDefinition(CommonsXsdSchemaCollection.class, source); + collectionDef.getPropertyValues().addPropertyValue("inline", "true"); + ManagedList xsds = new ManagedList(); + 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 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; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/InterceptorsBeanDefinitionParser.java b/spring-ws-core/src/main/java/org/springframework/ws/config/InterceptorsBeanDefinitionParser.java index 5fa7df63..63973329 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/InterceptorsBeanDefinitionParser.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/InterceptorsBeanDefinitionParser.java @@ -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 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 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 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 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 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 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 element", element); - return null; - } - } - if (!StringUtils.hasText(refName)) { - error(parserContext, " 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 element", element); + return null; + } + } + if (!StringUtils.hasText(refName)) { + error(parserContext, " element contains empty target attribute", element); + return null; + } + RuntimeBeanReference ref = new RuntimeBeanReference(refName); + ref.setSource(parserContext.extractSource(element)); + return ref; + } - private RootBeanDefinition createSmartInterceptorDefinition(Class 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 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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/MarshallingEndpointsBeanDefinitionParser.java b/spring-ws-core/src/main/java/org/springframework/ws/config/MarshallingEndpointsBeanDefinitionParser.java index 36c07aba..0693af46 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/MarshallingEndpointsBeanDefinitionParser.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/MarshallingEndpointsBeanDefinitionParser.java @@ -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); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/StaticWsdlBeanDefinitionParser.java b/spring-ws-core/src/main/java/org/springframework/ws/config/StaticWsdlBeanDefinitionParser.java index 5758061b..66d21c50 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/StaticWsdlBeanDefinitionParser.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/StaticWsdlBeanDefinitionParser.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/WebServicesNamespaceHandler.java b/spring-ws-core/src/main/java/org/springframework/ws/config/WebServicesNamespaceHandler.java index 180f1850..c3a61d85 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/WebServicesNamespaceHandler.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/WebServicesNamespaceHandler.java @@ -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()); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/XPathEndpointsBeanDefinitionParser.java b/spring-ws-core/src/main/java/org/springframework/ws/config/XPathEndpointsBeanDefinitionParser.java index 24641e02..bbb4820c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/XPathEndpointsBeanDefinitionParser.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/XPathEndpointsBeanDefinitionParser.java @@ -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 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 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); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/EnableWs.java b/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/EnableWs.java index e57810f2..ff3d6e4d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/EnableWs.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/EnableWs.java @@ -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; * @ComponentScan(basePackageClasses = { MyConfiguration.class }) * public class MyConfiguration extends WsConfigurerAdapter { * - * @Override - * public void addInterceptors(List<EndpointInterceptor> interceptors) { - * interceptors.add(new MyInterceptor()); - * } + * @Override + * public void addInterceptors(List<EndpointInterceptor> interceptors) { + * interceptors.add(new MyInterceptor()); + * } * - * @Override - * public void addArgumentResolvers(List<MethodArgumentResolver> argumentResolvers) { - * argumentResolvers.add(new MyArgumentResolver()); - * } + * @Override + * public void addArgumentResolvers(List<MethodArgumentResolver> argumentResolvers) { + * argumentResolvers.add(new MyArgumentResolver()); + * } * - * // More overridden methods ... + * // More overridden methods ... * } * * @@ -72,17 +72,17 @@ import org.springframework.context.annotation.Import; * @ComponentScan(basePackageClasses = { MyConfiguration.class }) * public class MyConfiguration extends WsConfigurationSupport { * - * @Override - * public void addInterceptors(List<EndpointInterceptor> interceptors) { - * interceptors.add(new MyInterceptor()); - * } + * @Override + * public void addInterceptors(List<EndpointInterceptor> interceptors) { + * interceptors.add(new MyInterceptor()); + * } * - * @Bean - * @Override - * public DefaultMethodEndpointAdapter defaultMethodEndpointAdapter() { + * @Bean + * @Override + * public DefaultMethodEndpointAdapter defaultMethodEndpointAdapter() { * // Create or delegate to "super" to create and * // customize properties of DefaultMethodEndpointAdapter - * } + * } * } * * diff --git a/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/WsConfigurationSupport.java b/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/WsConfigurationSupport.java index 69522d6b..93befe39 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/WsConfigurationSupport.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/config/annotation/WsConfigurationSupport.java @@ -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 * *

This class registers the following {@link EndpointMapping}s: *

    - *
  • {@link PayloadRootAnnotationMethodEndpointMapping} - * ordered at 0 for mapping requests to {@link PayloadRoot @PayloadRoot} annotated - * controller methods. - *
  • {@link SoapActionAnnotationMethodEndpointMapping} - * ordered at 1 for mapping requests to {@link SoapAction @SoapAction} annotated - * controller methods. - *
  • {@link AnnotationActionEndpointMapping} - * ordered at 2 for mapping requests to {@link Action @Action} annotated - * controller methods. + *
  • {@link PayloadRootAnnotationMethodEndpointMapping} + * ordered at 0 for mapping requests to {@link PayloadRoot @PayloadRoot} annotated + * controller methods. + *
  • {@link SoapActionAnnotationMethodEndpointMapping} + * ordered at 1 for mapping requests to {@link SoapAction @SoapAction} annotated + * controller methods. + *
  • {@link AnnotationActionEndpointMapping} + * ordered at 2 for mapping requests to {@link Action @Action} annotated + * controller methods. *
* *

Registers one {@link EndpointAdapter}: *

    - *
  • {@link DefaultMethodEndpointAdapter} - * for processing requests with annotated endpoint methods. + *
  • {@link DefaultMethodEndpointAdapter} + * for processing requests with annotated endpoint methods. *
* *

Registers the following {@link EndpointExceptionResolver}s: *

    - *
  • {@link SoapFaultAnnotationExceptionResolver} for handling exceptions - * annotated with {@link SoapFault @SoapFault}. - *
  • {@link SimpleSoapExceptionResolver} for creating default exceptions. + *
  • {@link SoapFaultAnnotationExceptionResolver} for handling exceptions + * annotated with {@link SoapFault @SoapFault}. + *
  • {@link SimpleSoapExceptionResolver} for creating default exceptions. *
* * @see EnableWs @@ -149,8 +149,8 @@ public class WsConfigurationSupport { * through annotated endpoint methods. Consider overriding one of these * other more fine-grained methods: *
    - *
  • {@link #addArgumentResolvers(List)} for adding custom argument resolvers. - *
  • {@link #addReturnValueHandlers(List)} for adding custom return value handlers. + *
  • {@link #addArgumentResolvers(List)} for adding custom argument resolvers. + *
  • {@link #addReturnValueHandlers(List)} for adding custom return value handlers. *
*/ @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 argumentResolvers) { } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/context/AbstractMessageContext.java b/spring-ws-core/src/main/java/org/springframework/ws/context/AbstractMessageContext.java index f1c4596f..a08ed51e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/context/AbstractMessageContext.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/context/AbstractMessageContext.java @@ -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 properties; + /** + * Keys are {@code Strings}, values are {@code Objects}. Lazily initialized by + * {@code getProperties()}. + */ + private Map 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 getProperties() { - if (properties == null) { - properties = new HashMap(); - } - return properties; - } + private Map getProperties() { + if (properties == null) { + properties = new HashMap(); + } + return properties; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/context/DefaultMessageContext.java b/spring-ws-core/src/main/java/org/springframework/ws/context/DefaultMessageContext.java index 52536faf..6a41ca0a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/context/DefaultMessageContext.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/context/DefaultMessageContext.java @@ -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"); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/context/MessageContext.java b/spring-ws-core/src/main/java/org/springframework/ws/context/MessageContext.java index c20ff734..3d94db04 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/context/MessageContext.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/context/MessageContext.java @@ -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(); } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/mime/AbstractMimeMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/mime/AbstractMimeMessage.java index 9346bb18..a6fbac5c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/mime/AbstractMimeMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/mime/AbstractMimeMessage.java @@ -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"); + } + } - } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/mime/Attachment.java b/spring-ws-core/src/main/java/org/springframework/ws/mime/Attachment.java index 57d401f9..919ac931 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/mime/Attachment.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/mime/Attachment.java @@ -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(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/mime/AttachmentException.java b/spring-ws-core/src/main/java/org/springframework/ws/mime/AttachmentException.java index a27c37b0..b2f586c3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/mime/AttachmentException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/mime/AttachmentException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/mime/MimeMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/mime/MimeMessage.java index 7e337ad0..3310e9b8 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/mime/MimeMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/mime/MimeMessage.java @@ -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 Identifying - * XOP Documents are met. - * @see XOP Packages - */ - boolean isXopPackage(); + /** + * Indicates whether this message is a XOP package. + * + * @return {@code true} when the constraints specified in Identifying + * XOP Documents are met. + * @see XOP Packages + */ + boolean isXopPackage(); - /** - * Turns this message into a XOP package. - * - * @return {@code true} when the message is a XOP package - * @see XOP Packages - */ - boolean convertToXopPackage(); + /** + * Turns this message into a XOP package. + * + * @return {@code true} when the message is a XOP package + * @see XOP Packages + */ + 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 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 getAttachments() throws AttachmentException; - /** - * Add an attachment to the message, taking the content from a {@link File}. - * - *

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}. + * + *

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}. - * - *

Note that the stream returned by the source needs to be a fresh one on each call, 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}. + * + *

Note that the stream returned by the source needs to be a fresh one on each call, 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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/pox/PoxMessageException.java b/spring-ws-core/src/main/java/org/springframework/ws/pox/PoxMessageException.java index d273353d..9bed4024 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/pox/PoxMessageException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/pox/PoxMessageException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessage.java index 3122e220..514123e5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessage.java @@ -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); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageException.java b/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageException.java index 787fcd08..78a495fb 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageException.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageFactory.java b/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageFactory.java index 0672d194..5100d35a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageFactory.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/pox/dom/DomPoxMessageFactory.java @@ -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); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointAdapter.java index 7a1690d4..9a6a6254 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointAdapter.java @@ -32,23 +32,23 @@ import org.springframework.ws.context.MessageContext; */ public interface EndpointAdapter { - /** - * Does this {@code EndpointAdapter} support the given {@code endpoint}? - * - *

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}? + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointExceptionResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointExceptionResolver.java index 349d2f8d..66e58e32 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointExceptionResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointExceptionResolver.java @@ -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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInterceptor.java index 301fbeb3..78379d3b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInterceptor.java @@ -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. - * - *

{@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, without invoking the endpoint - * @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. + * + *

{@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, without invoking the endpoint + * @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. - * - *

{@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. - * - *

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. + * + *

{@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. + * + *

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. - * - *

{@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. - * - *

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. + * + *

{@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. + * + *

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. - * - *

Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed. - * - *

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. + * + *

Note: Will only be called if this interceptor's {@link #handleRequest} method has successfully completed. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInvocationChain.java b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInvocationChain.java index 8f926b50..4aa5f48b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInvocationChain.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointInvocationChain.java @@ -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; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointMapping.java index 42149074..ce345a8b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/EndpointMapping.java @@ -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. - * - *

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. - * - *

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. + * + *

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. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/MessageDispatcher.java b/spring-ws-core/src/main/java/org/springframework/ws/server/MessageDispatcher.java index 9573fc6e..fad490a3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/MessageDispatcher.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/MessageDispatcher.java @@ -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 endpointAdapters; + /** List of EndpointAdapters used in this dispatcher. */ + private List endpointAdapters; - /** List of EndpointExceptionResolvers used in this dispatcher. */ - private List endpointExceptionResolvers; + /** List of EndpointExceptionResolvers used in this dispatcher. */ + private List endpointExceptionResolvers; - /** List of EndpointMappings used in this dispatcher. */ - private List endpointMappings; + /** List of EndpointMappings used in this dispatcher. */ + private List 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 getEndpointAdapters() { - return endpointAdapters; - } + /** Returns the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */ + public List getEndpointAdapters() { + return endpointAdapters; + } - /** Sets the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */ - public void setEndpointAdapters(List endpointAdapters) { - this.endpointAdapters = endpointAdapters; - } + /** Sets the {@code EndpointAdapter}s to use by this {@code MessageDispatcher}. */ + public void setEndpointAdapters(List endpointAdapters) { + this.endpointAdapters = endpointAdapters; + } - /** Returns the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */ - public List getEndpointExceptionResolvers() { - return endpointExceptionResolvers; - } + /** Returns the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */ + public List getEndpointExceptionResolvers() { + return endpointExceptionResolvers; + } - /** Sets the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */ - public void setEndpointExceptionResolvers(List endpointExceptionResolvers) { - this.endpointExceptionResolvers = endpointExceptionResolvers; - } + /** Sets the {@code EndpointExceptionResolver}s to use by this {@code MessageDispatcher}. */ + public void setEndpointExceptionResolvers(List endpointExceptionResolvers) { + this.endpointExceptionResolvers = endpointExceptionResolvers; + } - /** Returns the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */ - public List getEndpointMappings() { - return endpointMappings; - } + /** Returns the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */ + public List getEndpointMappings() { + return endpointMappings; + } - /** Sets the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */ - public void setEndpointMappings(List endpointMappings) { - this.endpointMappings = endpointMappings; - } + /** Sets the {@code EndpointMapping}s to use by this {@code MessageDispatcher}. */ + public void setEndpointMappings(List 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. - * - *

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. + * + *

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 matchingBeans = BeanFactoryUtils - .beansOfTypeIncludingAncestors(applicationContext, EndpointAdapter.class, true, false); - if (!matchingBeans.isEmpty()) { - endpointAdapters = new ArrayList(matchingBeans.values()); - Collections.sort(endpointAdapters, new OrderComparator()); - } - else { - endpointAdapters = - defaultStrategiesHelper.getDefaultStrategies(EndpointAdapter.class, applicationContext); - if (logger.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 matchingBeans = BeanFactoryUtils + .beansOfTypeIncludingAncestors(applicationContext, EndpointAdapter.class, true, false); + if (!matchingBeans.isEmpty()) { + endpointAdapters = new ArrayList(matchingBeans.values()); + Collections.sort(endpointAdapters, new OrderComparator()); + } + else { + endpointAdapters = + defaultStrategiesHelper.getDefaultStrategies(EndpointAdapter.class, applicationContext); + if (logger.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 matchingBeans = BeanFactoryUtils - .beansOfTypeIncludingAncestors(applicationContext, EndpointExceptionResolver.class, true, false); - if (!matchingBeans.isEmpty()) { - endpointExceptionResolvers = new ArrayList(matchingBeans.values()); - Collections.sort(endpointExceptionResolvers, new OrderComparator()); - } - else { - endpointExceptionResolvers = defaultStrategiesHelper - .getDefaultStrategies(EndpointExceptionResolver.class, applicationContext); - if (logger.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 matchingBeans = BeanFactoryUtils + .beansOfTypeIncludingAncestors(applicationContext, EndpointExceptionResolver.class, true, false); + if (!matchingBeans.isEmpty()) { + endpointExceptionResolvers = new ArrayList(matchingBeans.values()); + Collections.sort(endpointExceptionResolvers, new OrderComparator()); + } + else { + endpointExceptionResolvers = defaultStrategiesHelper + .getDefaultStrategies(EndpointExceptionResolver.class, applicationContext); + if (logger.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 matchingBeans = BeanFactoryUtils - .beansOfTypeIncludingAncestors(applicationContext, EndpointMapping.class, true, false); - if (!matchingBeans.isEmpty()) { - endpointMappings = new ArrayList(matchingBeans.values()); - Collections.sort(endpointMappings, new OrderComparator()); - } - else { - endpointMappings = - defaultStrategiesHelper.getDefaultStrategies(EndpointMapping.class, applicationContext); - if (logger.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 matchingBeans = BeanFactoryUtils + .beansOfTypeIncludingAncestors(applicationContext, EndpointMapping.class, true, false); + if (!matchingBeans.isEmpty()) { + endpointMappings = new ArrayList(matchingBeans.values()); + Collections.sort(endpointMappings, new OrderComparator()); + } + else { + endpointMappings = + defaultStrategiesHelper.getDefaultStrategies(EndpointMapping.class, applicationContext); + if (logger.isDebugEnabled()) { + logger.debug("No EndpointMappings found, using defaults"); + } + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/SmartEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/SmartEndpointInterceptor.java index 35bf8be4..1f00aa21 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/SmartEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/SmartEndpointInterceptor.java @@ -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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDom4jPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDom4jPayloadEndpoint.java index 9780eac6..65063984 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDom4jPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDom4jPayloadEndpoint.java @@ -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}. - * - *

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}. + * + *

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. - * - *

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. + * + *

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}. - * - *

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}. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDomPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDomPayloadEndpoint.java index b938213e..b508b349 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDomPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractDomPayloadEndpoint.java @@ -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}. - * - *

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}. + * + *

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. - * - *

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. + * + *

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. - * - *

Offers the request payload as a DOM {@code Element}, and allows subclasses to return a response - * {@code Element}. - * - *

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. + * + *

Offers the request payload as a DOM {@code Element}, and allows subclasses to return a response + * {@code Element}. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractEndpointExceptionResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractEndpointExceptionResolver.java index ccdd8398..115b0fcc 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractEndpointExceptionResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractEndpointExceptionResolver.java @@ -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.

The exception mappings and the default - * fault will only apply to the specified endpoints. - * - *

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.

The exception mappings and the default + * fault will only apply to the specified endpoints. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractJDomPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractJDomPayloadEndpoint.java index 5b6514bb..ac20425f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractJDomPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractJDomPayloadEndpoint.java @@ -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}. - * - *

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}. + * + *

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. - * - *

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. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractLoggingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractLoggingInterceptor.java index 73162dc6..b8840e24 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractLoggingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractLoggingInterceptor.java @@ -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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractMarshallingPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractMarshallingPayloadEndpoint.java index e8bccdb7..e7b001f9 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractMarshallingPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractMarshallingPayloadEndpoint.java @@ -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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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. - * - *

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. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractSaxPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractSaxPayloadEndpoint.java index b097e667..4270b245 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractSaxPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractSaxPayloadEndpoint.java @@ -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. - * - *

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. + * + *

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. - * - *

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. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxEventPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxEventPayloadEndpoint.java index ef4623a1..c16fd7e1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxEventPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxEventPayloadEndpoint.java @@ -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); + } + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxPayloadEndpoint.java index 2f9e5d9a..685b0c87 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxPayloadEndpoint.java @@ -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(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxStreamPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxStreamPayloadEndpoint.java index 78be7787..8b719717 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxStreamPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractStaxStreamPayloadEndpoint.java @@ -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); + } + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractValidatingMarshallingPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractValidatingMarshallingPayloadEndpoint.java index 5370f47a..762650fe 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractValidatingMarshallingPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractValidatingMarshallingPayloadEndpoint.java @@ -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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractXomPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractXomPayloadEndpoint.java index 991620d1..c08ce77f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractXomPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/AbstractXomPayloadEndpoint.java @@ -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. - * - *

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. + * + *

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; + } + } - } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MessageEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MessageEndpoint.java index 5911fb82..3f242f78 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MessageEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MessageEndpoint.java @@ -30,13 +30,13 @@ import org.springframework.ws.context.MessageContext; */ public interface MessageEndpoint { - /** - * Invokes an operation. - * - *

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. + * + *

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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MethodEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MethodEndpoint.java index f365d58b..b85313f1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MethodEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/MethodEndpoint.java @@ -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(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/PayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/PayloadEndpoint.java index 3c7fe954..b85a7732 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/PayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/PayloadEndpoint.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/AbstractMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/AbstractMethodEndpointAdapter.java index 1a7185f2..1aa6bafd 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/AbstractMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/AbstractMethodEndpointAdapter.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapter.java index 5583128e..b6953014 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapter.java @@ -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 methodArgumentResolvers; + private List methodArgumentResolvers; private List customMethodArgumentResolvers; - private List methodReturnValueHandlers; + private List methodReturnValueHandlers; - private List customMethodReturnValueHandlers; + private List customMethodReturnValueHandlers; - private ClassLoader classLoader; + private ClassLoader classLoader; /** * Returns the list of {@code MethodArgumentResolver}s to use. */ public List getMethodArgumentResolvers() { - return methodArgumentResolvers; - } + return methodArgumentResolvers; + } /** * Sets the list of {@code MethodArgumentResolver}s to use. */ public void setMethodArgumentResolvers(List 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 getMethodReturnValueHandlers() { - return methodReturnValueHandlers; - } + return methodReturnValueHandlers; + } /** * Sets the list of {@code MethodReturnValueHandler}s to use. */ public void setMethodReturnValueHandlers(List 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 methodArgumentResolvers = new ArrayList(); - 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 methodArgumentResolvers = new ArrayList(); + 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 methodArgumentResolvers) { - try { - Class methodArgumentResolverClass = - (Class) 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 methodArgumentResolvers) { + try { + Class methodArgumentResolverClass = + (Class) 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 methodReturnValueHandlers = new ArrayList(); - 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 methodReturnValueHandlers = new ArrayList(); + 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. - * - *

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. + * + *

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. - * - *

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. + * + *

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"); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapter.java index f815eeda..a7579a82 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapter.java @@ -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. - * - *

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. + * + *

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]); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapter.java index 6f67358a..9c4f033e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapter.java @@ -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. - * - *

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. + * + *

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]); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapter.java index bf67c595..02d850e2 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapter.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapter.java index bdffe26b..41a82b8c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapter.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapter.java index 1969f772..f8dfdc02 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapter.java @@ -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()); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapter.java index c5cef60b..eb8a1d5e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapter.java @@ -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()); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapter.java index 3c4cebc8..89a182a6 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapter.java @@ -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 namespaces; + private Map namespaces; - /** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */ - public void setNamespaces(Map namespaces) { - this.namespaces = namespaces; - } + /** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */ + public void setNamespaces(Map 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(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessor.java index f90d00d4..b92cac85 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessor.java @@ -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} - * - *

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} + * + *

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} - * - *

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} + * + *

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()); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadSourceMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadSourceMethodProcessor.java index d657926a..ebbb38ce 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadSourceMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadSourceMethodProcessor.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessor.java index df90a50c..4e7ba29d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessor.java @@ -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. - * - *

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. + * + *

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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolver.java index d86618b1..895962e9 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolver.java @@ -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; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodArgumentResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodArgumentResolver.java index 54dd0a57..dd9b5b17 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodArgumentResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodArgumentResolver.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodReturnValueHandler.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodReturnValueHandler.java index 43f447d5..038e1855 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodReturnValueHandler.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/MethodReturnValueHandler.java @@ -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; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessor.java index 26ca4f25..b0ecbe9d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessor.java @@ -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. - * - *

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. + * + *

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; + } + }; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolver.java index 15f42a07..cdd370fa 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolver.java @@ -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. - * - *

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. + * + *

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()); + } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolver.java index 18231bdc..4874fce0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolver.java @@ -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. - * - *

Defaults to the {@linkplain ConversionServiceFactory#createDefaultConversionService() default conversion - * service}. - */ - public void setConversionService(ConversionService conversionService) { - this.conversionService = conversionService; - } + /** + * Sets the conversion service to use. + * + *

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. - * - *

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. + * + *

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(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessor.java index fc0c3d72..7396c6de 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessor.java @@ -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()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessor.java index ebe7f4b1..83f72661 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessor.java @@ -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()); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessor.java index a75da5ba..e63fd872 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessor.java @@ -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()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessor.java index 4185d7f8..cb94ca89 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessor.java @@ -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. - * - *

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. + * + *

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(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/AbstractJaxb2PayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/AbstractJaxb2PayloadMethodProcessor.java index b4b696a6..ab837732 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/AbstractJaxb2PayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/AbstractJaxb2PayloadMethodProcessor.java @@ -71,7 +71,7 @@ import org.springframework.xml.transform.TraxUtils; */ public abstract class AbstractJaxb2PayloadMethodProcessor extends AbstractPayloadMethodProcessor { - private final ConcurrentMap, JAXBContext> jaxbContexts = new ConcurrentHashMap, JAXBContext>(); + private final ConcurrentMap, JAXBContext> jaxbContexts = new ConcurrentHashMap, 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 JAXBElement unmarshalElementFromRequestPayload(MessageContext messageContext, Class clazz) - throws JAXBException { - Source requestPayload = getRequestPayload(messageContext); - if (requestPayload == null) { - return null; - } - try { - JaxbElementSourceCallback callback = new JaxbElementSourceCallback(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 JAXBElement unmarshalElementFromRequestPayload(MessageContext messageContext, Class clazz) + throws JAXBException { + Source requestPayload = getRequestPayload(messageContext); + if (requestPayload == null) { + return null; + } + try { + JaxbElementSourceCallback callback = new JaxbElementSourceCallback(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 implements TraxUtils.SourceCallback { + private class JaxbElementSourceCallback implements TraxUtils.SourceCallback { - private final Unmarshaller unmarshaller; + private final Unmarshaller unmarshaller; - private final Class declaredType; + private final Class declaredType; - private JAXBElement result; + private JAXBElement result; - public JaxbElementSourceCallback(Class declaredType) throws JAXBException { - this.unmarshaller = createUnmarshaller(declaredType); - this.declaredType = declaredType; - } + public JaxbElementSourceCallback(Class 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); + } + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessor.java index 10d22d90..0406f8a0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessor.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessor.java index 0d6bf6d4..f21de94a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessor.java @@ -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); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Endpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Endpoint.java index a1a6a958..4f75c92f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Endpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Endpoint.java @@ -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 ""; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespace.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespace.java index fd839a68..44335ce3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespace.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespace.java @@ -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(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespaces.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespaces.java index 9ba9d7f0..52b4d416 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespaces.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/Namespaces.java @@ -34,5 +34,5 @@ import java.lang.annotation.Target; @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.METHOD}) public @interface Namespaces { - Namespace[] value(); + Namespace[] value(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/PayloadRoot.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/PayloadRoot.java index 82ff4701..d1631537 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/PayloadRoot.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/PayloadRoot.java @@ -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 ""; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/XPathParam.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/XPathParam.java index fd268ea2..55151359 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/XPathParam.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/annotation/XPathParam.java @@ -37,5 +37,5 @@ import java.lang.annotation.Target; @Documented public @interface XPathParam { - String value(); + String value(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/AbstractValidatingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/AbstractValidatingInterceptor.java index 50d01c80..f33492d4 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/AbstractValidatingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/AbstractValidatingInterceptor.java @@ -54,231 +54,231 @@ import org.springframework.xml.xsd.XsdSchemaCollection; * @since 1.0.0 */ public abstract class AbstractValidatingInterceptor extends TransformerObjectSupport - implements EndpointInterceptor, InitializingBean { + implements EndpointInterceptor, 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; - private ValidationErrorHandler errorHandler; + private ValidationErrorHandler errorHandler; - 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 org.springframework.xml.validation.XmlValidatorFactory#SCHEMA_W3C_XML - * @see org.springframework.xml.validation.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 org.springframework.xml.validation.XmlValidatorFactory#SCHEMA_W3C_XML + * @see org.springframework.xml.validation.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 IOException in case of I/O errors - */ - public void setXsdSchema(XsdSchema schema) { - 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 IOException in case of I/O errors + */ + public void setXsdSchema(XsdSchema schema) { + 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 IOException in case of I/O errors - */ - public void setXsdSchemaCollection(XsdSchemaCollection schemaCollection) { - 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 IOException in case of I/O errors + */ + public void setXsdSchemaCollection(XsdSchemaCollection schemaCollection) { + this.validator = schemaCollection.createValidator(); + } - /** - * Sets the error handler to use for validation. If not set, a default error handler will be used. - * - * @param errorHandler the error handler. - */ - public void setErrorHandler(ValidationErrorHandler errorHandler) { - this.errorHandler = errorHandler; - } + /** + * Sets the error handler to use for validation. If not set, a default error handler will be used. + * + * @param errorHandler the error handler. + */ + public void setErrorHandler(ValidationErrorHandler errorHandler) { + this.errorHandler = errorHandler; + } - /** 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 - * {@code validateRequest} is set to {@code true}, which is the default. - * - *

Returns {@code true} if the request is valid, or {@code false} if it isn't. Additionally, when the - * request message is a {@link SoapMessage}, a {@link SoapFault} is added as response. - * - * @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, Object endpoint) - throws IOException, SAXException, TransformerException { - if (validateRequest) { - Source requestSource = getValidationRequestSource(messageContext.getRequest()); - if (requestSource != null) { - SAXParseException[] errors = validator.validate(requestSource, errorHandler); - 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 + * {@code validateRequest} is set to {@code true}, which is the default. + * + *

Returns {@code true} if the request is valid, or {@code false} if it isn't. Additionally, when the + * request message is a {@link SoapMessage}, a {@link SoapFault} is added as response. + * + * @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, Object endpoint) + throws IOException, SAXException, TransformerException { + if (validateRequest) { + Source requestSource = getValidationRequestSource(messageContext.getRequest()); + if (requestSource != null) { + SAXParseException[] errors = validator.validate(requestSource, errorHandler); + 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. Default implementation logs - * all errors, and returns {@code false}, i.e. do not process the request. - * - * @param messageContext the message context - * @param errors the validation errors - * @return {@code true} to continue processing the request, {@code false} (the default) otherwise - */ - protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) - throws TransformerException { - for (SAXParseException error : errors) { - logger.warn("XML validation error on request: " + error.getMessage()); - } - return false; - } + /** + * Template method that is called when the request message contains validation errors. Default implementation logs + * all errors, and returns {@code false}, i.e. do not process the request. + * + * @param messageContext the message context + * @param errors the validation errors + * @return {@code true} to continue processing the request, {@code false} (the default) otherwise + */ + protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) + throws TransformerException { + for (SAXParseException error : errors) { + logger.warn("XML validation error on request: " + error.getMessage()); + } + return false; + } - /** - * Validates the response message in the given message context. Validation only occurs if - * {@code validateResponse} is set to {@code true}, which is not the default. - * - *

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, Object endpoint) throws IOException, SAXException { - if (validateResponse) { - Source responseSource = getValidationResponseSource(messageContext.getResponse()); - if (responseSource != null) { - SAXParseException[] errors = validator.validate(responseSource, errorHandler); - 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 + * {@code validateResponse} is set to {@code true}, which is not the default. + * + *

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, Object endpoint) throws IOException, SAXException { + if (validateResponse) { + Source responseSource = getValidationResponseSource(messageContext.getResponse()); + if (responseSource != null) { + SAXParseException[] errors = validator.validate(responseSource, errorHandler); + 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. Default implementation logs - * all errors, and returns {@code false}, i.e. do not cot continue to process the response interceptor chain. - * - * @param messageContext the message context - * @param errors the validation errors - * @return {@code true} to continue the response interceptor chain, {@code false} (the default) otherwise - */ - protected boolean handleResponseValidationErrors(MessageContext messageContext, SAXParseException[] errors) { - for (SAXParseException error : errors) { - logger.error("XML validation error on response: " + error.getMessage()); - } - return false; - } + /** + * Template method that is called when the response message contains validation errors. Default implementation logs + * all errors, and returns {@code false}, i.e. do not cot continue to process the response interceptor chain. + * + * @param messageContext the message context + * @param errors the validation errors + * @return {@code true} to continue the response interceptor chain, {@code false} (the default) otherwise + */ + protected boolean handleResponseValidationErrors(MessageContext messageContext, SAXParseException[] errors) { + for (SAXParseException error : errors) { + logger.error("XML validation error on response: " + error.getMessage()); + } + return false; + } - /** Does nothing by default. Faults are not validated. */ - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + /** Does nothing by default. Faults are not validated. */ + @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) { + } - /** - * 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); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/DelegatingSmartEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/DelegatingSmartEndpointInterceptor.java index 7df45178..26b23f7b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/DelegatingSmartEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/DelegatingSmartEndpointInterceptor.java @@ -31,67 +31,67 @@ import org.springframework.ws.server.SmartEndpointInterceptor; */ public class DelegatingSmartEndpointInterceptor implements SmartEndpointInterceptor { - private final EndpointInterceptor delegate; + private final EndpointInterceptor delegate; - /** - * Creates a new instance of the {@code DelegatingSmartEndpointInterceptor} with the given delegate. - * - * @param delegate the endpoint interceptor to delegate to. - */ - public DelegatingSmartEndpointInterceptor(EndpointInterceptor delegate) { - Assert.notNull(delegate, "'delegate' must not be null"); - this.delegate = delegate; - } + /** + * Creates a new instance of the {@code DelegatingSmartEndpointInterceptor} with the given delegate. + * + * @param delegate the endpoint interceptor to delegate to. + */ + public DelegatingSmartEndpointInterceptor(EndpointInterceptor delegate) { + Assert.notNull(delegate, "'delegate' must not be null"); + this.delegate = delegate; + } - /** - * Returns the delegate. - * @return the delegate - */ - public EndpointInterceptor getDelegate() { - return delegate; - } + /** + * Returns the delegate. + * @return the delegate + */ + public EndpointInterceptor getDelegate() { + return delegate; + } - /** - * {@inheritDoc} - * - *

This implementation delegates to {@link #shouldIntercept(WebServiceMessage, Object)}. - */ - @Override - public boolean shouldIntercept(MessageContext messageContext, Object endpoint) { - WebServiceMessage request = messageContext.getRequest(); - return request != null && shouldIntercept(request, endpoint); - } + /** + * {@inheritDoc} + * + *

This implementation delegates to {@link #shouldIntercept(WebServiceMessage, Object)}. + */ + @Override + public boolean shouldIntercept(MessageContext messageContext, Object endpoint) { + WebServiceMessage request = messageContext.getRequest(); + return request != null && shouldIntercept(request, endpoint); + } - /** - * Indicates whether this interceptor should intercept the given request message. - * - *

This implementation always returns {@code true}. - * - * @param request the request message - * @param endpoint chosen endpoint to invoke - * @return {@code true} to indicate that this interceptor applies; {@code false} otherwise - */ - protected boolean shouldIntercept(WebServiceMessage request, Object endpoint) { - return true; - } + /** + * Indicates whether this interceptor should intercept the given request message. + * + *

This implementation always returns {@code true}. + * + * @param request the request message + * @param endpoint chosen endpoint to invoke + * @return {@code true} to indicate that this interceptor applies; {@code false} otherwise + */ + protected boolean shouldIntercept(WebServiceMessage request, Object endpoint) { + return true; + } - @Override - public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { - return getDelegate().handleRequest(messageContext, endpoint); - } + @Override + public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { + return getDelegate().handleRequest(messageContext, endpoint); + } - @Override - public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { - return getDelegate().handleResponse(messageContext, endpoint); - } + @Override + public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { + return getDelegate().handleResponse(messageContext, endpoint); + } - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return getDelegate().handleFault(messageContext, endpoint); - } + @Override + public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { + return getDelegate().handleFault(messageContext, endpoint); + } - @Override - public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception { - getDelegate().afterCompletion(messageContext, endpoint, ex); - } + @Override + public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception { + getDelegate().afterCompletion(messageContext, endpoint, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/EndpointInterceptorAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/EndpointInterceptorAdapter.java index d1ffa179..24d5beb2 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/EndpointInterceptorAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/EndpointInterceptorAdapter.java @@ -32,48 +32,48 @@ import org.springframework.ws.server.EndpointInterceptor; */ public class EndpointInterceptorAdapter implements EndpointInterceptor { - /** Logger available to subclasses */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); - /** Returns {@code false}. */ - public boolean understands(Element header) { - return false; - } + /** Returns {@code false}. */ + public boolean understands(Element header) { + return false; + } - /** - * Returns {@code true}. - * - * @return {@code true} - */ - @Override - public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + /** + * Returns {@code true}. + * + * @return {@code true} + */ + @Override + public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { + return true; + } - /** - * Returns {@code true}. - * - * @return {@code true} - */ - @Override - public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + /** + * Returns {@code true}. + * + * @return {@code true} + */ + @Override + public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { + return true; + } - /** - * Returns {@code true}. - * - * @return {@code true} - */ - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + /** + * Returns {@code true}. + * + * @return {@code true} + */ + @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) throws Exception { - } + /** + * Does nothing by default. + */ + @Override + public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception { + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptor.java index 2caeb332..d19f912e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptor.java @@ -35,9 +35,9 @@ import org.springframework.ws.server.endpoint.AbstractLoggingInterceptor; */ public class PayloadLoggingInterceptor extends AbstractLoggingInterceptor { - @Override - protected Source getSource(WebServiceMessage message) { - return message.getPayloadSource(); - } + @Override + protected Source getSource(WebServiceMessage message) { + return message.getPayloadSource(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptor.java index c02b8502..7a44979e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptor.java @@ -55,107 +55,107 @@ import org.springframework.xml.transform.TransformerObjectSupport; * @since 1.0.0 */ public class PayloadTransformingInterceptor extends TransformerObjectSupport - implements EndpointInterceptor, InitializingBean { + implements EndpointInterceptor, InitializingBean { - private static final Log logger = LogFactory.getLog(PayloadTransformingInterceptor.class); + private static final Log logger = LogFactory.getLog(PayloadTransformingInterceptor.class); - private Resource requestXslt; + private Resource requestXslt; - private Resource responseXslt; + private Resource responseXslt; - private Templates requestTemplates; + private Templates requestTemplates; - private Templates responseTemplates; + private Templates responseTemplates; - /** Sets the XSLT stylesheet to use for transforming incoming request. */ - public void setRequestXslt(Resource requestXslt) { - this.requestXslt = requestXslt; - } + /** Sets the XSLT stylesheet to use for transforming incoming request. */ + public void setRequestXslt(Resource requestXslt) { + this.requestXslt = requestXslt; + } - /** Sets the XSLT stylesheet to use for transforming outgoing responses. */ - public void setResponseXslt(Resource responseXslt) { - this.responseXslt = responseXslt; - } + /** Sets the XSLT stylesheet to use for transforming outgoing responses. */ + public void setResponseXslt(Resource responseXslt) { + this.responseXslt = responseXslt; + } - /** - * Transforms the request message in the given message context using a provided stylesheet. Transformation only - * occurs if the {@code requestXslt} has been set. - * - * @param messageContext the message context - * @return always returns {@code true} - * @see #setRequestXslt(org.springframework.core.io.Resource) - */ - @Override - public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { - if (requestTemplates != null) { - WebServiceMessage request = messageContext.getRequest(); - Transformer transformer = requestTemplates.newTransformer(); - transformMessage(request, transformer); - logger.debug("Request message transformed"); - } - return true; - } + /** + * Transforms the request message in the given message context using a provided stylesheet. Transformation only + * occurs if the {@code requestXslt} has been set. + * + * @param messageContext the message context + * @return always returns {@code true} + * @see #setRequestXslt(org.springframework.core.io.Resource) + */ + @Override + public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { + if (requestTemplates != null) { + WebServiceMessage request = messageContext.getRequest(); + Transformer transformer = requestTemplates.newTransformer(); + transformMessage(request, transformer); + logger.debug("Request message transformed"); + } + return true; + } - /** - * Transforms the response message in the given message context using a stylesheet. Transformation only occurs if - * the {@code responseXslt} has been set. - * - * @param messageContext the message context - * @return always returns {@code true} - * @see #setResponseXslt(org.springframework.core.io.Resource) - */ - @Override - public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { - if (responseTemplates != null) { - WebServiceMessage response = messageContext.getResponse(); - Transformer transformer = responseTemplates.newTransformer(); - transformMessage(response, transformer); - logger.debug("Response message transformed"); - } - return true; - } + /** + * Transforms the response message in the given message context using a stylesheet. Transformation only occurs if + * the {@code responseXslt} has been set. + * + * @param messageContext the message context + * @return always returns {@code true} + * @see #setResponseXslt(org.springframework.core.io.Resource) + */ + @Override + public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { + if (responseTemplates != null) { + WebServiceMessage response = messageContext.getResponse(); + Transformer transformer = responseTemplates.newTransformer(); + transformMessage(response, transformer); + logger.debug("Response message transformed"); + } + return true; + } - private void transformMessage(WebServiceMessage message, Transformer transformer) throws TransformerException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - transformer.transform(message.getPayloadSource(), new StreamResult(os)); - ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); - transform(new StreamSource(is), message.getPayloadResult()); - } + private void transformMessage(WebServiceMessage message, Transformer transformer) throws TransformerException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + transformer.transform(message.getPayloadSource(), new StreamResult(os)); + ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); + transform(new StreamSource(is), message.getPayloadResult()); + } - /** Does nothing by default. Faults are not transformed. */ - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + /** Does nothing by default. Faults are not transformed. */ + @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) { + } - @Override - public void afterPropertiesSet() throws Exception { - if (requestXslt == null && responseXslt == null) { - throw new IllegalArgumentException("Setting either 'requestXslt' or 'responseXslt' is required"); - } - TransformerFactory transformerFactory = getTransformerFactory(); - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); - xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); - if (requestXslt != null) { - Assert.isTrue(requestXslt.exists(), "requestXslt \"" + requestXslt + "\" does not exit"); - if (logger.isInfoEnabled()) { - logger.info("Transforming request using " + requestXslt); - } - Source requestSource = new ResourceSource(xmlReader, requestXslt); - requestTemplates = transformerFactory.newTemplates(requestSource); - } - if (responseXslt != null) { - Assert.isTrue(responseXslt.exists(), "responseXslt \"" + responseXslt + "\" does not exit"); - if (logger.isInfoEnabled()) { - logger.info("Transforming response using " + responseXslt); - } - Source responseSource = new ResourceSource(xmlReader, responseXslt); - responseTemplates = transformerFactory.newTemplates(responseSource); - } - } + @Override + public void afterPropertiesSet() throws Exception { + if (requestXslt == null && responseXslt == null) { + throw new IllegalArgumentException("Setting either 'requestXslt' or 'responseXslt' is required"); + } + TransformerFactory transformerFactory = getTransformerFactory(); + XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + if (requestXslt != null) { + Assert.isTrue(requestXslt.exists(), "requestXslt \"" + requestXslt + "\" does not exit"); + if (logger.isInfoEnabled()) { + logger.info("Transforming request using " + requestXslt); + } + Source requestSource = new ResourceSource(xmlReader, requestXslt); + requestTemplates = transformerFactory.newTemplates(requestSource); + } + if (responseXslt != null) { + Assert.isTrue(responseXslt.exists(), "responseXslt \"" + responseXslt + "\" does not exit"); + if (logger.isInfoEnabled()) { + logger.info("Transforming response using " + responseXslt); + } + Source responseSource = new ResourceSource(xmlReader, responseXslt); + responseTemplates = transformerFactory.newTemplates(responseSource); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractAnnotationMethodEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractAnnotationMethodEndpointMapping.java index e7eac3bf..2ce19c16 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractAnnotationMethodEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractAnnotationMethodEndpointMapping.java @@ -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,44 +34,44 @@ import org.springframework.ws.server.endpoint.annotation.Endpoint; */ public abstract class AbstractAnnotationMethodEndpointMapping extends AbstractMethodEndpointMapping { - private boolean detectEndpointsInAncestorContexts = false; + private boolean detectEndpointsInAncestorContexts = false; - /** - * Set whether to detect endpoint beans in ancestor ApplicationContexts. - * - *

Default is "false": Only endpoint beans in the current ApplicationContext will be detected, i.e. only in the - * context that this EndpointMapping itself is defined in (typically the current MessageDispatcherServlet's - * context). - * - *

Switch this flag on to detect endpoint beans in ancestor contexts (typically the Spring root - * WebApplicationContext) as well. - */ - public void setDetectEndpointsInAncestorContexts(boolean detectEndpointsInAncestorContexts) { - this.detectEndpointsInAncestorContexts = detectEndpointsInAncestorContexts; - } + /** + * Set whether to detect endpoint beans in ancestor ApplicationContexts. + * + *

Default is "false": Only endpoint beans in the current ApplicationContext will be detected, i.e. only in the + * context that this EndpointMapping itself is defined in (typically the current MessageDispatcherServlet's + * context). + * + *

Switch this flag on to detect endpoint beans in ancestor contexts (typically the Spring root + * WebApplicationContext) as well. + */ + public void setDetectEndpointsInAncestorContexts(boolean detectEndpointsInAncestorContexts) { + this.detectEndpointsInAncestorContexts = detectEndpointsInAncestorContexts; + } - /** Returns the 'endpoint' annotation type. Default is {@link Endpoint}. */ - protected Class getEndpointAnnotationType() { - return Endpoint.class; - } + /** Returns the 'endpoint' annotation type. Default is {@link Endpoint}. */ + protected Class getEndpointAnnotationType() { + return Endpoint.class; + } - @Override - protected void initApplicationContext() throws BeansException { - super.initApplicationContext(); - if (logger.isDebugEnabled()) { - logger.debug("Looking for endpoints in application context: " + getApplicationContext()); - } - String[] beanNames = (this.detectEndpointsInAncestorContexts ? - BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) : - getApplicationContext().getBeanNamesForType(Object.class)); + @Override + protected void initApplicationContext() throws BeansException { + super.initApplicationContext(); + if (logger.isDebugEnabled()) { + logger.debug("Looking for endpoints in application context: " + getApplicationContext()); + } + String[] beanNames = (this.detectEndpointsInAncestorContexts ? + BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) : + getApplicationContext().getBeanNamesForType(Object.class)); - for (String beanName : beanNames) { - Class endpointClass = getApplicationContext().getType(beanName); - if (endpointClass != null && - AnnotationUtils.findAnnotation(endpointClass, getEndpointAnnotationType()) != null) { - registerMethods(beanName); - } - } - } + for (String beanName : beanNames) { + Class endpointClass = getApplicationContext().getType(beanName); + if (endpointClass != null && + AnnotationUtils.findAnnotation(endpointClass, getEndpointAnnotationType()) != null) { + registerMethods(beanName); + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractEndpointMapping.java index 986d2811..9cc205c8 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractEndpointMapping.java @@ -41,176 +41,176 @@ import org.springframework.ws.server.SmartEndpointInterceptor; */ public abstract class AbstractEndpointMapping extends ApplicationObjectSupport implements EndpointMapping, Ordered { - private int order = Integer.MAX_VALUE; // default: same as non-Ordered + private int order = Integer.MAX_VALUE; // default: same as non-Ordered - private Object defaultEndpoint; + private Object defaultEndpoint; - private EndpointInterceptor[] interceptors; + private EndpointInterceptor[] interceptors; - private SmartEndpointInterceptor[] smartInterceptors; + private SmartEndpointInterceptor[] smartInterceptors; - /** - * Returns the the endpoint interceptors to apply to all endpoints mapped by this endpoint mapping. - * - * @return array of endpoint interceptors, or {@code null} if none - */ - public EndpointInterceptor[] getInterceptors() { - return interceptors; - } + /** + * Returns the the endpoint interceptors to apply to all endpoints mapped by this endpoint mapping. + * + * @return array of endpoint interceptors, or {@code null} if none + */ + public EndpointInterceptor[] getInterceptors() { + return interceptors; + } - /** - * Sets the endpoint interceptors to apply to all endpoints mapped by this endpoint mapping. - * - * @param interceptors array of endpoint interceptors, or {@code null} if none - */ - public final void setInterceptors(EndpointInterceptor[] interceptors) { - this.interceptors = interceptors; - } + /** + * Sets the endpoint interceptors to apply to all endpoints mapped by this endpoint mapping. + * + * @param interceptors array of endpoint interceptors, or {@code null} if none + */ + public final void setInterceptors(EndpointInterceptor[] interceptors) { + this.interceptors = interceptors; + } - @Override - public final int getOrder() { - return order; - } + @Override + public final int getOrder() { + return order; + } - /** - * Specify the order value for this mapping. - * - *

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. + * + *

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; + } - /** - * Initializes the interceptors. - * - * @see #initInterceptors() - */ - @Override - protected void initApplicationContext() throws BeansException { - initInterceptors(); - } + /** + * Initializes the interceptors. + * + * @see #initInterceptors() + */ + @Override + protected void initApplicationContext() throws BeansException { + initInterceptors(); + } - /** - * Initialize the specified interceptors, adapting them where necessary. - * - * @see #setInterceptors - */ - protected void initInterceptors() { - Map smartInterceptors = BeanFactoryUtils - .beansOfTypeIncludingAncestors(getApplicationContext(), SmartEndpointInterceptor.class, true, false); - if (!smartInterceptors.isEmpty()) { - this.smartInterceptors = - smartInterceptors.values().toArray(new SmartEndpointInterceptor[smartInterceptors.size()]); - } - } + /** + * Initialize the specified interceptors, adapting them where necessary. + * + * @see #setInterceptors + */ + protected void initInterceptors() { + Map smartInterceptors = BeanFactoryUtils + .beansOfTypeIncludingAncestors(getApplicationContext(), SmartEndpointInterceptor.class, true, false); + if (!smartInterceptors.isEmpty()) { + this.smartInterceptors = + smartInterceptors.values().toArray(new SmartEndpointInterceptor[smartInterceptors.size()]); + } + } - /** - * Look up an endpoint for the given message context, falling back to the default endpoint if no specific one is - * found. - * - * @return the looked up endpoint instance, or the default endpoint - * @see #getEndpointInternal(org.springframework.ws.context.MessageContext) - */ - @Override - public final EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception { - Object endpoint = getEndpointInternal(messageContext); - if (endpoint == null) { - endpoint = defaultEndpoint; - } - if (endpoint == null) { - return null; - } - if (endpoint instanceof String) { - String endpointName = (String) endpoint; - endpoint = resolveStringEndpoint(endpointName); - if (endpoint == null) { - return null; - } - } + /** + * Look up an endpoint for the given message context, falling back to the default endpoint if no specific one is + * found. + * + * @return the looked up endpoint instance, or the default endpoint + * @see #getEndpointInternal(org.springframework.ws.context.MessageContext) + */ + @Override + public final EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception { + Object endpoint = getEndpointInternal(messageContext); + if (endpoint == null) { + endpoint = defaultEndpoint; + } + if (endpoint == null) { + return null; + } + if (endpoint instanceof String) { + String endpointName = (String) endpoint; + endpoint = resolveStringEndpoint(endpointName); + if (endpoint == null) { + return null; + } + } - List interceptors = new ArrayList(); - if (this.interceptors != null) { - interceptors.addAll(Arrays.asList(this.interceptors)); - } + List interceptors = new ArrayList(); + if (this.interceptors != null) { + interceptors.addAll(Arrays.asList(this.interceptors)); + } - if (this.smartInterceptors != null) { - for (SmartEndpointInterceptor smartInterceptor : smartInterceptors) { - if (smartInterceptor.shouldIntercept(messageContext, endpoint)) { - interceptors.add(smartInterceptor); - } - } - } + if (this.smartInterceptors != null) { + for (SmartEndpointInterceptor smartInterceptor : smartInterceptors) { + if (smartInterceptor.shouldIntercept(messageContext, endpoint)) { + interceptors.add(smartInterceptor); + } + } + } - return createEndpointInvocationChain(messageContext, endpoint, - interceptors.toArray(new EndpointInterceptor[interceptors.size()])); - } + return createEndpointInvocationChain(messageContext, endpoint, + interceptors.toArray(new EndpointInterceptor[interceptors.size()])); + } - /** - * Creates a new {@code EndpointInvocationChain} based on the given message context, endpoint, and - * interceptors. Default implementation creates a simple {@code EndpointInvocationChain} based on the set - * interceptors. - * - * @param endpoint the endpoint - * @param interceptors the endpoint interceptors - * @return the created invocation chain - * @see #setInterceptors(org.springframework.ws.server.EndpointInterceptor[]) - */ - protected EndpointInvocationChain createEndpointInvocationChain(MessageContext messageContext, - Object endpoint, - EndpointInterceptor[] interceptors) { - return new EndpointInvocationChain(endpoint, interceptors); - } + /** + * Creates a new {@code EndpointInvocationChain} based on the given message context, endpoint, and + * interceptors. Default implementation creates a simple {@code EndpointInvocationChain} based on the set + * interceptors. + * + * @param endpoint the endpoint + * @param interceptors the endpoint interceptors + * @return the created invocation chain + * @see #setInterceptors(org.springframework.ws.server.EndpointInterceptor[]) + */ + protected EndpointInvocationChain createEndpointInvocationChain(MessageContext messageContext, + Object endpoint, + EndpointInterceptor[] interceptors) { + return new EndpointInvocationChain(endpoint, interceptors); + } - /** - * Returns the default endpoint for this endpoint mapping. - * - * @return the default endpoint mapping, or null if none - */ - protected final Object getDefaultEndpoint() { - return defaultEndpoint; - } + /** + * Returns the default endpoint for this endpoint mapping. + * + * @return the default endpoint mapping, or null if none + */ + protected final Object getDefaultEndpoint() { + return defaultEndpoint; + } - /** - * Sets the default endpoint for this endpoint mapping. This endpoint will be returned if no specific mapping was - * found. - * - *

Default is {@code null}, indicating no default endpoint. - * - * @param defaultEndpoint the default endpoint, or null if none - */ - public final void setDefaultEndpoint(Object defaultEndpoint) { - this.defaultEndpoint = defaultEndpoint; - } + /** + * Sets the default endpoint for this endpoint mapping. This endpoint will be returned if no specific mapping was + * found. + * + *

Default is {@code null}, indicating no default endpoint. + * + * @param defaultEndpoint the default endpoint, or null if none + */ + public final void setDefaultEndpoint(Object defaultEndpoint) { + this.defaultEndpoint = defaultEndpoint; + } - /** - * Resolves an endpoint string. If the given string can is a bean name, it is resolved using the application - * context. - * - * @param endpointName the endpoint name - * @return the resolved endpoint, or {@code null} if the name could not be resolved - */ - protected Object resolveStringEndpoint(String endpointName) { - if (getApplicationContext().containsBean(endpointName)) { - return getApplicationContext().getBean(endpointName); - } - else { - return null; - } - } + /** + * Resolves an endpoint string. If the given string can is a bean name, it is resolved using the application + * context. + * + * @param endpointName the endpoint name + * @return the resolved endpoint, or {@code null} if the name could not be resolved + */ + protected Object resolveStringEndpoint(String endpointName) { + if (getApplicationContext().containsBean(endpointName)) { + return getApplicationContext().getBean(endpointName); + } + else { + return null; + } + } - /** - * Lookup an endpoint for the given request, returning {@code null} if no specific one is found. This template - * method is called by getEndpoint, a {@code null} return value will lead to the default handler, if one is - * set. - * - *

The returned endpoint can be a string, in which case it is resolved as a bean name. Also, it can take the form - * {@code beanName#method}, in which case the method is resolved. - * - * @return the looked up endpoint instance, or null - * @throws Exception if there is an error - */ - protected abstract Object getEndpointInternal(MessageContext messageContext) throws Exception; + /** + * Lookup an endpoint for the given request, returning {@code null} if no specific one is found. This template + * method is called by getEndpoint, a {@code null} return value will lead to the default handler, if one is + * set. + * + *

The returned endpoint can be a string, in which case it is resolved as a bean name. Also, it can take the form + * {@code beanName#method}, in which case the method is resolved. + * + * @return the looked up endpoint instance, or null + * @throws Exception if there is an error + */ + protected abstract Object getEndpointInternal(MessageContext messageContext) throws Exception; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMapBasedEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMapBasedEndpointMapping.java index 05647bb5..dcd010a6 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMapBasedEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMapBasedEndpointMapping.java @@ -37,162 +37,162 @@ import org.springframework.ws.context.MessageContext; */ public abstract class AbstractMapBasedEndpointMapping extends AbstractEndpointMapping { - private boolean lazyInitEndpoints = false; + private boolean lazyInitEndpoints = false; - private boolean registerBeanNames = false; + private boolean registerBeanNames = false; - private final Map endpointMap = new HashMap(); + private final Map endpointMap = new HashMap(); - // holds mappings set via setEndpointMap and setMappings - private Map temporaryEndpointMap = new HashMap(); + // holds mappings set via setEndpointMap and setMappings + private Map temporaryEndpointMap = new HashMap(); - /** - * Set whether to lazily initialize endpoints. Only applicable to singleton endpoints, as prototypes are always - * lazily initialized. Default is {@code false}, as eager initialization allows for more efficiency through - * referencing the controller objects directly. - * - *

If you want to allow your endpoints to be lazily initialized, make them "lazy-init" and set this flag to - * {@code true}. Just making them "lazy-init" will not work, as they are initialized through the references - * from the endpoint mapping in this case. - */ - public void setLazyInitEndpoints(boolean lazyInitEndpoints) { - this.lazyInitEndpoints = lazyInitEndpoints; - } + /** + * Set whether to lazily initialize endpoints. Only applicable to singleton endpoints, as prototypes are always + * lazily initialized. Default is {@code false}, as eager initialization allows for more efficiency through + * referencing the controller objects directly. + * + *

If you want to allow your endpoints to be lazily initialized, make them "lazy-init" and set this flag to + * {@code true}. Just making them "lazy-init" will not work, as they are initialized through the references + * from the endpoint mapping in this case. + */ + public void setLazyInitEndpoints(boolean lazyInitEndpoints) { + this.lazyInitEndpoints = lazyInitEndpoints; + } - /** - * Set whether to register bean names found in the application context. Setting this to {@code true} will - * register all beans found in the application context under their name. Default is {@code false}. - */ - public final void setRegisterBeanNames(boolean registerBeanNames) { - this.registerBeanNames = registerBeanNames; - } + /** + * Set whether to register bean names found in the application context. Setting this to {@code true} will + * register all beans found in the application context under their name. Default is {@code false}. + */ + public final void setRegisterBeanNames(boolean registerBeanNames) { + this.registerBeanNames = registerBeanNames; + } - /** - * Sets a Map with keys and endpoint beans as values. The nature of the keys in the given map depends on the exact - * subclass used. They can be qualified names, for instance, or mime headers. - * - * @throws IllegalArgumentException if the endpoint is invalid - */ - public final void setEndpointMap(Map endpointMap) { - temporaryEndpointMap.putAll(endpointMap); - } + /** + * Sets a Map with keys and endpoint beans as values. The nature of the keys in the given map depends on the exact + * subclass used. They can be qualified names, for instance, or mime headers. + * + * @throws IllegalArgumentException if the endpoint is invalid + */ + public final void setEndpointMap(Map endpointMap) { + temporaryEndpointMap.putAll(endpointMap); + } - /** - * Maps keys to endpoint bean names. The nature of the property names depends on the exact subclass used. They can - * be qualified names, for instance, or mime headers. - */ - public void setMappings(Properties mappings) { - for (Map.Entry entry : mappings.entrySet()) { - if (entry.getKey() instanceof String) { - temporaryEndpointMap.put((String) entry.getKey(), entry.getValue()); - } - } - } + /** + * Maps keys to endpoint bean names. The nature of the property names depends on the exact subclass used. They can + * be qualified names, for instance, or mime headers. + */ + public void setMappings(Properties mappings) { + for (Map.Entry entry : mappings.entrySet()) { + if (entry.getKey() instanceof String) { + temporaryEndpointMap.put((String) entry.getKey(), entry.getValue()); + } + } + } - /** Validates the given endpoint key. Should return {@code true} is the given string is valid. */ - protected abstract boolean validateLookupKey(String key); + /** Validates the given endpoint key. Should return {@code true} is the given string is valid. */ + protected abstract boolean validateLookupKey(String key); - /** - * Returns the the endpoint key for the given message context. Returns {@code null} if a key cannot be found. - * - * @return the registration key; or {@code null} - */ - protected abstract String getLookupKeyForMessage(MessageContext messageContext) throws Exception; + /** + * Returns the the endpoint key for the given message context. Returns {@code null} if a key cannot be found. + * + * @return the registration key; or {@code null} + */ + protected abstract String getLookupKeyForMessage(MessageContext messageContext) throws Exception; - /** - * Lookup an endpoint for the given message. The extraction of the endpoint key is delegated to the concrete - * subclass. - * - * @return the looked up endpoint, or {@code null} - */ - @Override - protected final Object getEndpointInternal(MessageContext messageContext) throws Exception { - String key = getLookupKeyForMessage(messageContext); - if (!StringUtils.hasLength(key)) { - return null; - } - if (logger.isDebugEnabled()) { - logger.debug("Looking up endpoint for [" + key + "]"); - } - return lookupEndpoint(key); - } + /** + * Lookup an endpoint for the given message. The extraction of the endpoint key is delegated to the concrete + * subclass. + * + * @return the looked up endpoint, or {@code null} + */ + @Override + protected final Object getEndpointInternal(MessageContext messageContext) throws Exception { + String key = getLookupKeyForMessage(messageContext); + if (!StringUtils.hasLength(key)) { + return null; + } + if (logger.isDebugEnabled()) { + logger.debug("Looking up endpoint for [" + key + "]"); + } + return lookupEndpoint(key); + } - /** - * Looks up an endpoint instance for the given keys. All keys are tried in order. - * - * @param key key the beans are mapped to - * @return the associated endpoint instance, or {@code null} if not found - */ - protected Object lookupEndpoint(String key) { - return endpointMap.get(key); - } + /** + * Looks up an endpoint instance for the given keys. All keys are tried in order. + * + * @param key key the beans are mapped to + * @return the associated endpoint instance, or {@code null} if not found + */ + protected Object lookupEndpoint(String key) { + return endpointMap.get(key); + } - /** - * Register the given endpoint instance under the registration key. - * - * @param key the string representation of the registration key - * @param endpoint the endpoint instance - * @throws org.springframework.beans.BeansException - * if the endpoint could not be registered - */ - protected void registerEndpoint(String key, Object endpoint) throws BeansException { - Object mappedEndpoint = endpointMap.get(key); - if (mappedEndpoint != null) { - throw new ApplicationContextException("Cannot map endpoint [" + endpoint + "] on registration key [" + key + - "]: there's already endpoint [" + mappedEndpoint + "] mapped"); - } - if (!lazyInitEndpoints && endpoint instanceof String) { - String endpointName = (String) endpoint; - endpoint = resolveStringEndpoint(endpointName); - } - if (endpoint == null) { - throw new ApplicationContextException("Could not find endpoint for key [" + key + "]"); - } - endpointMap.put(key, endpoint); - if (logger.isDebugEnabled()) { - logger.debug("Mapped key [" + key + "] onto endpoint [" + endpoint + "]"); - } - } + /** + * Register the given endpoint instance under the registration key. + * + * @param key the string representation of the registration key + * @param endpoint the endpoint instance + * @throws org.springframework.beans.BeansException + * if the endpoint could not be registered + */ + protected void registerEndpoint(String key, Object endpoint) throws BeansException { + Object mappedEndpoint = endpointMap.get(key); + if (mappedEndpoint != null) { + throw new ApplicationContextException("Cannot map endpoint [" + endpoint + "] on registration key [" + key + + "]: there's already endpoint [" + mappedEndpoint + "] mapped"); + } + if (!lazyInitEndpoints && endpoint instanceof String) { + String endpointName = (String) endpoint; + endpoint = resolveStringEndpoint(endpointName); + } + if (endpoint == null) { + throw new ApplicationContextException("Could not find endpoint for key [" + key + "]"); + } + endpointMap.put(key, endpoint); + if (logger.isDebugEnabled()) { + logger.debug("Mapped key [" + key + "] onto endpoint [" + endpoint + "]"); + } + } - /** - * Registers annd checks the set endpoints. Checks the beans set through {@code setEndpointMap} and - * {@code setMappings}, and registers the bean names found in the application context, if - * {@code registerBeanNames} is set to {@code true}. - * - * @throws ApplicationContextException if either of the endpoints defined via {@code setEndpointMap} or - * {@code setMappings} is invalid - * @see #setEndpointMap(java.util.Map) - * @see #setMappings(java.util.Properties) - * @see #setRegisterBeanNames(boolean) - */ - @Override - protected final void initApplicationContext() throws BeansException { - super.initApplicationContext(); - for (String key : temporaryEndpointMap.keySet()) { - Object endpoint = temporaryEndpointMap.get(key); - if (!validateLookupKey(key)) { - throw new ApplicationContextException("Invalid key [" + key + "] for endpoint [" + endpoint + "]"); - } - registerEndpoint(key, endpoint); - } - temporaryEndpointMap = null; - if (registerBeanNames) { - if (logger.isDebugEnabled()) { - logger.debug("Looking for endpoint mappings in application context: [" + getApplicationContext() + "]"); - } - String[] beanNames = getApplicationContext().getBeanDefinitionNames(); - for (String beanName : beanNames) { - if (validateLookupKey(beanName)) { - registerEndpoint(beanName, beanName); - } - String[] aliases = getApplicationContext().getAliases(beanName); - for (String aliase : aliases) { - if (validateLookupKey(aliase)) { - registerEndpoint(aliase, beanName); - } - } - } - } - } + /** + * Registers annd checks the set endpoints. Checks the beans set through {@code setEndpointMap} and + * {@code setMappings}, and registers the bean names found in the application context, if + * {@code registerBeanNames} is set to {@code true}. + * + * @throws ApplicationContextException if either of the endpoints defined via {@code setEndpointMap} or + * {@code setMappings} is invalid + * @see #setEndpointMap(java.util.Map) + * @see #setMappings(java.util.Properties) + * @see #setRegisterBeanNames(boolean) + */ + @Override + protected final void initApplicationContext() throws BeansException { + super.initApplicationContext(); + for (String key : temporaryEndpointMap.keySet()) { + Object endpoint = temporaryEndpointMap.get(key); + if (!validateLookupKey(key)) { + throw new ApplicationContextException("Invalid key [" + key + "] for endpoint [" + endpoint + "]"); + } + registerEndpoint(key, endpoint); + } + temporaryEndpointMap = null; + if (registerBeanNames) { + if (logger.isDebugEnabled()) { + logger.debug("Looking for endpoint mappings in application context: [" + getApplicationContext() + "]"); + } + String[] beanNames = getApplicationContext().getBeanDefinitionNames(); + for (String beanName : beanNames) { + if (validateLookupKey(beanName)) { + registerEndpoint(beanName, beanName); + } + String[] aliases = getApplicationContext().getAliases(beanName); + for (String aliase : aliases) { + if (validateLookupKey(aliase)) { + registerEndpoint(aliase, beanName); + } + } + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMethodEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMethodEndpointMapping.java index ee744bea..ffdc8e43 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMethodEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractMethodEndpointMapping.java @@ -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,181 +48,181 @@ import org.springframework.ws.server.endpoint.MethodEndpoint; */ public abstract class AbstractMethodEndpointMapping extends AbstractEndpointMapping { - private final Map endpointMap = new HashMap(); + private final Map endpointMap = new HashMap(); - /** - * Lookup an endpoint for the given message. The extraction of the endpoint key is delegated to the concrete - * subclass. - * - * @return the looked up endpoint, or {@code null} - * @see #getLookupKeyForMessage(MessageContext) - */ - @Override - protected Object getEndpointInternal(MessageContext messageContext) throws Exception { - T key = getLookupKeyForMessage(messageContext); - if (key == null) { - return null; - } - if (logger.isDebugEnabled()) { - logger.debug("Looking up endpoint for [" + key + "]"); - } - return lookupEndpoint(key); - } + /** + * Lookup an endpoint for the given message. The extraction of the endpoint key is delegated to the concrete + * subclass. + * + * @return the looked up endpoint, or {@code null} + * @see #getLookupKeyForMessage(MessageContext) + */ + @Override + protected Object getEndpointInternal(MessageContext messageContext) throws Exception { + T key = getLookupKeyForMessage(messageContext); + if (key == null) { + return null; + } + if (logger.isDebugEnabled()) { + logger.debug("Looking up endpoint for [" + key + "]"); + } + return lookupEndpoint(key); + } - /** - * Returns the the endpoint keys for the given message context. - * - * @return the registration keys - */ - protected abstract T getLookupKeyForMessage(MessageContext messageContext) throws Exception; + /** + * Returns the the endpoint keys for the given message context. + * + * @return the registration keys + */ + protected abstract T getLookupKeyForMessage(MessageContext messageContext) throws Exception; - /** - * Looks up an endpoint instance for the given keys. All keys are tried in order. - * - * @param key key the beans are mapped to - * @return the associated endpoint instance, or {@code null} if not found - */ - protected MethodEndpoint lookupEndpoint(T key) { - return endpointMap.get(key); - } + /** + * Looks up an endpoint instance for the given keys. All keys are tried in order. + * + * @param key key the beans are mapped to + * @return the associated endpoint instance, or {@code null} if not found + */ + protected MethodEndpoint lookupEndpoint(T key) { + return endpointMap.get(key); + } - /** - * Register the given endpoint instance under the key. - * - * @param key the lookup key - * @param endpoint the method endpoint instance - * @throws BeansException if the endpoint could not be registered - */ - protected void registerEndpoint(T key, MethodEndpoint endpoint) throws BeansException { - Object mappedEndpoint = endpointMap.get(key); - if (mappedEndpoint != null) { - throw new ApplicationContextException("Cannot map endpoint [" + endpoint + "] on registration key [" + key + - "]: there's already endpoint [" + mappedEndpoint + "] mapped"); - } - if (endpoint == null) { - throw new ApplicationContextException("Could not find endpoint for key [" + key + "]"); - } - endpointMap.put(key, endpoint); - if (logger.isDebugEnabled()) { - logger.debug("Mapped [" + key + "] onto endpoint [" + endpoint + "]"); - } - } + /** + * Register the given endpoint instance under the key. + * + * @param key the lookup key + * @param endpoint the method endpoint instance + * @throws BeansException if the endpoint could not be registered + */ + protected void registerEndpoint(T key, MethodEndpoint endpoint) throws BeansException { + Object mappedEndpoint = endpointMap.get(key); + if (mappedEndpoint != null) { + throw new ApplicationContextException("Cannot map endpoint [" + endpoint + "] on registration key [" + key + + "]: there's already endpoint [" + mappedEndpoint + "] mapped"); + } + if (endpoint == null) { + throw new ApplicationContextException("Could not find endpoint for key [" + key + "]"); + } + endpointMap.put(key, endpoint); + if (logger.isDebugEnabled()) { + logger.debug("Mapped [" + key + "] onto endpoint [" + endpoint + "]"); + } + } - /** - * Helper method that registers the methods of the given bean. This method iterates over the methods of the bean, - * and calls {@link #getLookupKeyForMethod(Method)} for each. If this returns a string, the method is registered - * using {@link #registerEndpoint(Object, MethodEndpoint)}. - * - * @see #getLookupKeyForMethod(Method) - */ - protected void registerMethods(final Object endpoint) { - Assert.notNull(endpoint, "'endpoint' must not be null"); - Class endpointClass = getEndpointClass(endpoint); - ReflectionUtils.doWithMethods(endpointClass, new ReflectionUtils.MethodCallback() { + /** + * Helper method that registers the methods of the given bean. This method iterates over the methods of the bean, + * and calls {@link #getLookupKeyForMethod(Method)} for each. If this returns a string, the method is registered + * using {@link #registerEndpoint(Object, MethodEndpoint)}. + * + * @see #getLookupKeyForMethod(Method) + */ + protected void registerMethods(final Object endpoint) { + Assert.notNull(endpoint, "'endpoint' must not be null"); + Class endpointClass = getEndpointClass(endpoint); + ReflectionUtils.doWithMethods(endpointClass, new ReflectionUtils.MethodCallback() { - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - List keys = getLookupKeysForMethod(method); - for (T key : keys) { - registerEndpoint(key, new MethodEndpoint(endpoint, method)); - } - } - }); - } + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + List keys = getLookupKeysForMethod(method); + for (T key : keys) { + registerEndpoint(key, new MethodEndpoint(endpoint, method)); + } + } + }); + } - /** - * Helper method that registers the methods of the given class. This method iterates over the methods of the class, - * and calls {@link #getLookupKeyForMethod(Method)} for each. If this returns a string, the method is registered - * using {@link #registerEndpoint(Object, MethodEndpoint)}. - * - * @see #getLookupKeyForMethod(Method) - * @see #getLookupKeysForMethod(Method) - */ - protected void registerMethods(String beanName) { - Assert.hasText(beanName, "'beanName' must not be empty"); - Class endpointType = getApplicationContext().getType(beanName); - endpointType = ClassUtils.getUserClass(endpointType); - - Set methods = findEndpointMethods(endpointType, new ReflectionUtils.MethodFilter() { - public boolean matches(Method method) { - return !getLookupKeysForMethod(method).isEmpty(); - } - }); + /** + * Helper method that registers the methods of the given class. This method iterates over the methods of the class, + * and calls {@link #getLookupKeyForMethod(Method)} for each. If this returns a string, the method is registered + * using {@link #registerEndpoint(Object, MethodEndpoint)}. + * + * @see #getLookupKeyForMethod(Method) + * @see #getLookupKeysForMethod(Method) + */ + protected void registerMethods(String beanName) { + Assert.hasText(beanName, "'beanName' must not be empty"); + Class endpointType = getApplicationContext().getType(beanName); + endpointType = ClassUtils.getUserClass(endpointType); + + Set methods = findEndpointMethods(endpointType, new ReflectionUtils.MethodFilter() { + public boolean matches(Method method) { + return !getLookupKeysForMethod(method).isEmpty(); + } + }); - for (Method method : methods) { - List keys = getLookupKeysForMethod(method); - for (T key : keys) { - registerEndpoint(key, new MethodEndpoint(beanName, getApplicationContext(), method)); - } - } + for (Method method : methods) { + List keys = getLookupKeysForMethod(method); + for (T key : keys) { + registerEndpoint(key, new MethodEndpoint(beanName, getApplicationContext(), method)); + } + } - } + } - private Set findEndpointMethods(Class endpointType, - final ReflectionUtils.MethodFilter endpointMethodFilter) { - final Set endpointMethods = new LinkedHashSet(); - Set> endpointTypes = new LinkedHashSet>(); - Class specificEndpointType = null; - if (!Proxy.isProxyClass(endpointType)) { - endpointTypes.add(endpointType); - specificEndpointType = endpointType; - } - endpointTypes.addAll(Arrays.asList(endpointType.getInterfaces())); - for (Class currentEndpointType : endpointTypes) { - final Class targetClass = (specificEndpointType != null ? specificEndpointType : currentEndpointType); - ReflectionUtils.doWithMethods(currentEndpointType, new ReflectionUtils.MethodCallback() { - public void doWith(Method method) { - Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); - Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); - if (endpointMethodFilter.matches(specificMethod) && - (bridgedMethod == specificMethod || !endpointMethodFilter.matches(bridgedMethod))) { - endpointMethods.add(specificMethod); - } - } - }, ReflectionUtils.USER_DECLARED_METHODS); - } - return endpointMethods; - } + private Set findEndpointMethods(Class endpointType, + final ReflectionUtils.MethodFilter endpointMethodFilter) { + final Set endpointMethods = new LinkedHashSet(); + Set> endpointTypes = new LinkedHashSet>(); + Class specificEndpointType = null; + if (!Proxy.isProxyClass(endpointType)) { + endpointTypes.add(endpointType); + specificEndpointType = endpointType; + } + endpointTypes.addAll(Arrays.asList(endpointType.getInterfaces())); + for (Class currentEndpointType : endpointTypes) { + final Class targetClass = (specificEndpointType != null ? specificEndpointType : currentEndpointType); + ReflectionUtils.doWithMethods(currentEndpointType, new ReflectionUtils.MethodCallback() { + public void doWith(Method method) { + Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); + Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); + if (endpointMethodFilter.matches(specificMethod) && + (bridgedMethod == specificMethod || !endpointMethodFilter.matches(bridgedMethod))) { + endpointMethods.add(specificMethod); + } + } + }, ReflectionUtils.USER_DECLARED_METHODS); + } + return endpointMethods; + } - /** - * Returns the the endpoint key for the given method. Returns {@code null} if the method is not to be - * registered, which is the default. - * - * @param method the method - * @return a registration key, or {@code null} if the method is not to be registered - * @see #getLookupKeysForMethod(Method) - */ - protected T getLookupKeyForMethod(Method method) { - return null; - } + /** + * Returns the the endpoint key for the given method. Returns {@code null} if the method is not to be + * registered, which is the default. + * + * @param method the method + * @return a registration key, or {@code null} if the method is not to be registered + * @see #getLookupKeysForMethod(Method) + */ + protected T getLookupKeyForMethod(Method method) { + return null; + } - /** - * Returns the the endpoint keys for the given method. Should return an empty array if the method is not to be - * registered. The default delegates to {@link #getLookupKeysForMethod(Method)}. - * - * @param method the method - * @return a list of registration keys - * @since 2.2 - */ - protected List getLookupKeysForMethod(Method method) { - T key = getLookupKeyForMethod(method); - return key != null ? Collections.singletonList(key) : Collections.emptyList(); - } + /** + * Returns the the endpoint keys for the given method. Should return an empty array if the method is not to be + * registered. The default delegates to {@link #getLookupKeysForMethod(Method)}. + * + * @param method the method + * @return a list of registration keys + * @since 2.2 + */ + protected List getLookupKeysForMethod(Method method) { + T key = getLookupKeyForMethod(method); + return key != null ? Collections.singletonList(key) : Collections.emptyList(); + } - /** - * Return the class or interface to use for method reflection. - * - *

Default implementation delegates to {@link AopUtils#getTargetClass(Object)}. - * - * @param endpoint the bean instance (might be an AOP proxy) - * @return the bean class to expose - */ - protected Class getEndpointClass(Object endpoint) { - if (AopUtils.isJdkDynamicProxy(endpoint)) { - throw new IllegalArgumentException(ClassUtils.getShortName(getClass()) + - " does not work with JDK Dynamic Proxies. " + - "Please use CGLIB proxies, by setting proxy-target-class=\"true\" on the aop:aspectj-autoproxy " + - "or aop:config element."); - } - return AopUtils.getTargetClass(endpoint); - } + /** + * Return the class or interface to use for method reflection. + * + *

Default implementation delegates to {@link AopUtils#getTargetClass(Object)}. + * + * @param endpoint the bean instance (might be an AOP proxy) + * @return the bean class to expose + */ + protected Class getEndpointClass(Object endpoint) { + if (AopUtils.isJdkDynamicProxy(endpoint)) { + throw new IllegalArgumentException(ClassUtils.getShortName(getClass()) + + " does not work with JDK Dynamic Proxies. " + + "Please use CGLIB proxies, by setting proxy-target-class=\"true\" on the aop:aspectj-autoproxy " + + "or aop:config element."); + } + return AopUtils.getTargetClass(endpoint); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractQNameEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractQNameEndpointMapping.java index 0d7e898f..d54d6ffb 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractQNameEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/AbstractQNameEndpointMapping.java @@ -29,22 +29,22 @@ import org.springframework.xml.namespace.QNameUtils; */ public abstract class AbstractQNameEndpointMapping extends AbstractMapBasedEndpointMapping { - @Override - protected final String getLookupKeyForMessage(MessageContext messageContext) throws Exception { - QName qName = resolveQName(messageContext); - return qName != null ? qName.toString() : null; - } + @Override + protected final String getLookupKeyForMessage(MessageContext messageContext) throws Exception { + QName qName = resolveQName(messageContext); + return qName != null ? qName.toString() : null; + } - /** - * Template method that resolves the qualified names from the given SOAP message. - * - * @return an array of qualified names that serve as registration keys - */ - protected abstract QName resolveQName(MessageContext messageContext) throws Exception; + /** + * Template method that resolves the qualified names from the given SOAP message. + * + * @return an array of qualified names that serve as registration keys + */ + protected abstract QName resolveQName(MessageContext messageContext) throws Exception; - @Override - protected boolean validateLookupKey(String key) { - return QNameUtils.validateQName(key); - } + @Override + protected boolean validateLookupKey(String key) { + return QNameUtils.validateQName(key); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMapping.java index 66721978..6d4ea86f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMapping.java @@ -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, @@ -38,11 +38,11 @@ import org.springframework.ws.server.endpoint.support.PayloadRootUtils; *

  * @Endpoint
  * public class MyEndpoint{
- *    @PayloadRoot(localPart = "Request",
- *                 namespace = "http://springframework.org/spring-ws")
- *    public Source doSomethingWithRequest() {
- *       ...
- *    }
+ *	  @PayloadRoot(localPart = "Request",
+ *				   namespace = "http://springframework.org/spring-ws")
+ *	  public Source doSomethingWithRequest() {
+ *		 ...
+ *	  }
  * }
  * 
* @@ -51,44 +51,44 @@ import org.springframework.ws.server.endpoint.support.PayloadRootUtils; */ public class PayloadRootAnnotationMethodEndpointMapping extends AbstractAnnotationMethodEndpointMapping { - private static TransformerFactory transformerFactory; + private static TransformerFactory transformerFactory; - static { - transformerFactory = TransformerFactory.newInstance(); - } + static { + transformerFactory = TransformerFactory.newInstance(); + } - @Override - protected QName getLookupKeyForMessage(MessageContext messageContext) throws Exception { - return PayloadRootUtils.getPayloadRootQName(messageContext.getRequest().getPayloadSource(), transformerFactory); - } + @Override + protected QName getLookupKeyForMessage(MessageContext messageContext) throws Exception { + return PayloadRootUtils.getPayloadRootQName(messageContext.getRequest().getPayloadSource(), transformerFactory); + } - @Override - protected List getLookupKeysForMethod(Method method) { - List result = new ArrayList(); + @Override + protected List getLookupKeysForMethod(Method method) { + List result = new ArrayList(); - PayloadRoots payloadRoots = AnnotationUtils.findAnnotation(method, PayloadRoots.class); - if (payloadRoots != null) { - for (PayloadRoot payloadRoot : payloadRoots.value()) { - result.add(getQNameFromAnnotation(payloadRoot)); - } - } - else { - PayloadRoot payloadRoot = AnnotationUtils.findAnnotation(method, PayloadRoot.class); - if (payloadRoot != null) { - result.add(getQNameFromAnnotation(payloadRoot)); - } - } + PayloadRoots payloadRoots = AnnotationUtils.findAnnotation(method, PayloadRoots.class); + if (payloadRoots != null) { + for (PayloadRoot payloadRoot : payloadRoots.value()) { + result.add(getQNameFromAnnotation(payloadRoot)); + } + } + else { + PayloadRoot payloadRoot = AnnotationUtils.findAnnotation(method, PayloadRoot.class); + if (payloadRoot != null) { + result.add(getQNameFromAnnotation(payloadRoot)); + } + } - return result; - } + return result; + } private QName getQNameFromAnnotation(PayloadRoot payloadRoot) { if (StringUtils.hasLength(payloadRoot.localPart()) && StringUtils.hasLength( payloadRoot.namespace())) { - return new QName(payloadRoot.namespace(), payloadRoot.localPart()); + return new QName(payloadRoot.namespace(), payloadRoot.localPart()); } else { - return new QName(payloadRoot.localPart()); + return new QName(payloadRoot.localPart()); } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMapping.java index 264ba236..88556bd1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMapping.java @@ -48,15 +48,15 @@ import org.springframework.ws.server.endpoint.support.PayloadRootUtils; @Deprecated public class PayloadRootQNameEndpointMapping extends AbstractQNameEndpointMapping { - private static TransformerFactory transformerFactory; + private static TransformerFactory transformerFactory; - static { - transformerFactory = TransformerFactory.newInstance(); - } + static { + transformerFactory = TransformerFactory.newInstance(); + } - @Override - protected QName resolveQName(MessageContext messageContext) throws TransformerException { - return PayloadRootUtils.getPayloadRootQName(messageContext.getRequest().getPayloadSource(), transformerFactory); - } + @Override + protected QName resolveQName(MessageContext messageContext) throws TransformerException { + return PayloadRootUtils.getPayloadRootQName(messageContext.getRequest().getPayloadSource(), transformerFactory); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMapping.java index 3112bd18..bcc0cd45 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMapping.java @@ -36,9 +36,9 @@ import org.springframework.ws.server.endpoint.support.PayloadRootUtils; *
  * public class MyEndpoint{
  *
- *    public Source handleMyMessage(Source source) {
- *       ...
- *    }
+ *	  public Source handleMyMessage(Source source) {
+ *		 ...
+ *	  }
  * }
  * 
* This method will handle any message that has the {@code MyMessage} as a payload root local name. @@ -49,91 +49,91 @@ import org.springframework.ws.server.endpoint.support.PayloadRootUtils; */ public class SimpleMethodEndpointMapping extends AbstractMethodEndpointMapping implements InitializingBean { - /** Default method prefix. */ - public static final String DEFAULT_METHOD_PREFIX = "handle"; + /** Default method prefix. */ + public static final String DEFAULT_METHOD_PREFIX = "handle"; - /** Default method suffix. */ - public static final String DEFAULT_METHOD_SUFFIX = ""; + /** Default method suffix. */ + public static final String DEFAULT_METHOD_SUFFIX = ""; - private Object[] endpoints; + private Object[] endpoints; - private String methodPrefix = DEFAULT_METHOD_PREFIX; + private String methodPrefix = DEFAULT_METHOD_PREFIX; - private String methodSuffix = DEFAULT_METHOD_SUFFIX; + private String methodSuffix = DEFAULT_METHOD_SUFFIX; - private TransformerFactory transformerFactory; + private TransformerFactory transformerFactory; - public Object[] getEndpoints() { - return endpoints; - } + public Object[] getEndpoints() { + return endpoints; + } - /** - * Sets the endpoints. The endpoint methods that start with {@code methodPrefix} and end with - * {@code methodSuffix} will be registered. - */ - public void setEndpoints(Object[] endpoints) { - this.endpoints = endpoints; - } + /** + * Sets the endpoints. The endpoint methods that start with {@code methodPrefix} and end with + * {@code methodSuffix} will be registered. + */ + public void setEndpoints(Object[] endpoints) { + this.endpoints = endpoints; + } - /** Returns the method prefix. */ - public String getMethodPrefix() { - return methodPrefix; - } + /** Returns the method prefix. */ + public String getMethodPrefix() { + return methodPrefix; + } - /** - * Sets the method prefix. All methods with names starting with this string will be registered. Default is - * "{@code handle}". - * - * @see #DEFAULT_METHOD_PREFIX - */ - public void setMethodPrefix(String methodPrefix) { - this.methodPrefix = methodPrefix; - } + /** + * Sets the method prefix. All methods with names starting with this string will be registered. Default is + * "{@code handle}". + * + * @see #DEFAULT_METHOD_PREFIX + */ + public void setMethodPrefix(String methodPrefix) { + this.methodPrefix = methodPrefix; + } - /** Returns the method suffix. */ - public String getMethodSuffix() { - return methodSuffix; - } + /** Returns the method suffix. */ + public String getMethodSuffix() { + return methodSuffix; + } - /** - * Sets the method suffix. All methods with names ending with this string will be registered. Default is "" (i.e. no - * suffix). - * - * @see #DEFAULT_METHOD_SUFFIX - */ - public void setMethodSuffix(String methodSuffix) { - this.methodSuffix = methodSuffix; - } + /** + * Sets the method suffix. All methods with names ending with this string will be registered. Default is "" (i.e. no + * suffix). + * + * @see #DEFAULT_METHOD_SUFFIX + */ + public void setMethodSuffix(String methodSuffix) { + this.methodSuffix = methodSuffix; + } - @Override - public final void afterPropertiesSet() throws Exception { - Assert.notEmpty(getEndpoints(), "'endpoints' is required"); - transformerFactory = TransformerFactory.newInstance(); - for (int i = 0; i < getEndpoints().length; i++) { - registerMethods(getEndpoints()[i]); - } - } + @Override + public final void afterPropertiesSet() throws Exception { + Assert.notEmpty(getEndpoints(), "'endpoints' is required"); + transformerFactory = TransformerFactory.newInstance(); + for (int i = 0; i < getEndpoints().length; i++) { + registerMethods(getEndpoints()[i]); + } + } - /** Returns the name of the given method, with the prefix and suffix stripped off. */ - @Override - protected String getLookupKeyForMethod(Method method) { - String methodName = method.getName(); - String prefix = getMethodPrefix(); - String suffix = getMethodSuffix(); - if (methodName.startsWith(prefix) && methodName.endsWith(suffix)) { - return methodName.substring(prefix.length(), methodName.length() - suffix.length()); - } - else { - return null; - } - } + /** Returns the name of the given method, with the prefix and suffix stripped off. */ + @Override + protected String getLookupKeyForMethod(Method method) { + String methodName = method.getName(); + String prefix = getMethodPrefix(); + String suffix = getMethodSuffix(); + if (methodName.startsWith(prefix) && methodName.endsWith(suffix)) { + return methodName.substring(prefix.length(), methodName.length() - suffix.length()); + } + else { + return null; + } + } - /** Returns the local part of the payload root element of the request. */ - @Override - protected String getLookupKeyForMessage(MessageContext messageContext) - throws TransformerException { - WebServiceMessage request = messageContext.getRequest(); - QName rootQName = PayloadRootUtils.getPayloadRootQName(request.getPayloadSource(), transformerFactory); - return rootQName.getLocalPart(); - } + /** Returns the local part of the payload root element of the request. */ + @Override + protected String getLookupKeyForMessage(MessageContext messageContext) + throws TransformerException { + WebServiceMessage request = messageContext.getRequest(); + QName rootQName = PayloadRootUtils.getPayloadRootQName(request.getPayloadSource(), transformerFactory); + return rootQName.getLocalPart(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMapping.java index d015e1dd..b84a56f7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMapping.java @@ -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, @@ -57,43 +57,43 @@ import org.springframework.ws.transport.context.TransportContextHolder; */ public class UriEndpointMapping extends AbstractMapBasedEndpointMapping { - private boolean usePath = false; + private boolean usePath = false; - /** - * Indicates whether the path should be used instead of the full URI. Default is {@code false}. - * - * @since 2.1.1 - */ - public void setUsePath(boolean usePath) { - this.usePath = usePath; - } + /** + * Indicates whether the path should be used instead of the full URI. Default is {@code false}. + * + * @since 2.1.1 + */ + public void setUsePath(boolean usePath) { + this.usePath = usePath; + } - @Override - protected boolean validateLookupKey(String key) { - try { - new URI(key); - return true; - } - catch (URISyntaxException e) { - return false; - } - } + @Override + protected boolean validateLookupKey(String key) { + try { + new URI(key); + return true; + } + catch (URISyntaxException e) { + return false; + } + } - @Override - protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { - TransportContext transportContext = TransportContextHolder.getTransportContext(); - if (transportContext != null) { - WebServiceConnection connection = transportContext.getConnection(); - if (connection != null) { - URI connectionUri = connection.getUri(); - if (usePath) { - return connectionUri.getPath(); - } - else { - return connectionUri.toString(); - } - } - } - return null; - } + @Override + protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { + TransportContext transportContext = TransportContextHolder.getTransportContext(); + if (transportContext != null) { + WebServiceConnection connection = transportContext.getConnection(); + if (connection != null) { + URI connectionUri = connection.getUri(); + if (usePath) { + return connectionUri.getPath(); + } + else { + return connectionUri.toString(); + } + } + } + return null; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMapping.java index 50073716..efba2c08 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMapping.java @@ -59,51 +59,51 @@ import org.springframework.xml.xpath.XPathExpressionFactory; */ public class XPathPayloadEndpointMapping extends AbstractMapBasedEndpointMapping implements InitializingBean { - private String expressionString; + private String expressionString; - private XPathExpression expression; + private XPathExpression expression; - private Map namespaces; + private Map namespaces; - private TransformerFactory transformerFactory; + private TransformerFactory transformerFactory; - /** Sets the XPath expression to be used. */ - public void setExpression(String expression) { - expressionString = expression; - } + /** Sets the XPath expression to be used. */ + public void setExpression(String expression) { + expressionString = expression; + } - /** Sets the namespaces bindings used in the expression. Keys are prefixes, values are namespaces. */ - public void setNamespaces(Map namespaces) { - this.namespaces = namespaces; - } + /** Sets the namespaces bindings used in the expression. Keys are prefixes, values are namespaces. */ + public void setNamespaces(Map namespaces) { + this.namespaces = namespaces; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(expressionString, "expression is required"); - if (namespaces == null) { - expression = XPathExpressionFactory.createXPathExpression(expressionString); - } - else { - expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces); - } - transformerFactory = TransformerFactory.newInstance(); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(expressionString, "expression is required"); + if (namespaces == null) { + expression = XPathExpressionFactory.createXPathExpression(expressionString); + } + else { + expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces); + } + transformerFactory = TransformerFactory.newInstance(); + } - @Override - protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { - Element payloadElement = getMessagePayloadElement(messageContext.getRequest()); - return expression.evaluateAsString(payloadElement); - } + @Override + protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { + Element payloadElement = getMessagePayloadElement(messageContext.getRequest()); + return expression.evaluateAsString(payloadElement); + } - private Element getMessagePayloadElement(WebServiceMessage message) throws TransformerException { - Transformer transformer = transformerFactory.newTransformer(); - DOMResult domResult = new DOMResult(); - transformer.transform(message.getPayloadSource(), domResult); - return (Element) domResult.getNode().getFirstChild(); - } + private Element getMessagePayloadElement(WebServiceMessage message) throws TransformerException { + Transformer transformer = transformerFactory.newTransformer(); + DOMResult domResult = new DOMResult(); + transformer.transform(message.getPayloadSource(), domResult); + return (Element) domResult.getNode().getFirstChild(); + } - @Override - protected boolean validateLookupKey(String key) { - return StringUtils.hasLength(key); - } + @Override + protected boolean validateLookupKey(String key) { + return StringUtils.hasLength(key); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMapping.java index 233429c5..bd079fe5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMapping.java @@ -37,16 +37,16 @@ import org.springframework.xml.transform.TransformerHelper; *
  * @Endpoint
  * public class MyEndpoint{
- *    public void doSomethingWithRequest(@RequestBody MyRootElement rootElement) {
- *       ...
- *    }
+ *	  public void doSomethingWithRequest(@RequestBody MyRootElement rootElement) {
+ *		 ...
+ *	  }
  * }
  * 
* where MyRootElement is annotated with {@code @XmlRootElement}: *
  * @XmlRootElement(name = "myRoot", namespace = "http://springframework.org/spring-ws")
  * public class MyRootElement {
- *   ...
+ *	 ...
  * }
  * 
* @@ -55,59 +55,59 @@ import org.springframework.xml.transform.TransformerHelper; */ public class XmlRootElementEndpointMapping extends AbstractAnnotationMethodEndpointMapping { - private TransformerHelper transformerHelper = new TransformerHelper(); + private TransformerHelper transformerHelper = new TransformerHelper(); - public void setTransformerHelper(TransformerHelper transformerHelper) { - this.transformerHelper = transformerHelper; - } + public void setTransformerHelper(TransformerHelper transformerHelper) { + this.transformerHelper = transformerHelper; + } - @Override - protected QName getLookupKeyForMethod(Method method) { - Class[] parameterTypes = method.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) { - MethodParameter methodParameter = new MethodParameter(method, i); - Class parameterType = methodParameter.getParameterType(); - if (parameterType.isAnnotationPresent(XmlRootElement.class)) { - QName result = handleRootElement(parameterType); - if (result != null) { - return result; - } - } + @Override + protected QName getLookupKeyForMethod(Method method) { + Class[] parameterTypes = method.getParameterTypes(); + for (int i = 0; i < parameterTypes.length; i++) { + MethodParameter methodParameter = new MethodParameter(method, i); + Class parameterType = methodParameter.getParameterType(); + if (parameterType.isAnnotationPresent(XmlRootElement.class)) { + QName result = handleRootElement(parameterType); + if (result != null) { + return result; + } + } - } - return null; - } + } + return null; + } - private QName handleRootElement(Class parameterType) { - try { - Object param = parameterType.newInstance(); - QName result = getElementName(parameterType, param); - if (result != null) { - return result; - } - } - catch (InstantiationException e) { - // ignore - } - catch (IllegalAccessException ex) { - // ignore - } - return null; - } + private QName handleRootElement(Class parameterType) { + try { + Object param = parameterType.newInstance(); + QName result = getElementName(parameterType, param); + if (result != null) { + return result; + } + } + catch (InstantiationException e) { + // ignore + } + catch (IllegalAccessException ex) { + // ignore + } + return null; + } - private QName getElementName(Class parameterType, Object param) { - try { - JAXBContext context = JAXBContext.newInstance(parameterType); - JAXBIntrospector introspector = context.createJAXBIntrospector(); - return introspector.getElementName(param); - } - catch (JAXBException ex) { - return null; - } - } + private QName getElementName(Class parameterType, Object param) { + try { + JAXBContext context = JAXBContext.newInstance(parameterType); + JAXBIntrospector introspector = context.createJAXBIntrospector(); + return introspector.getElementName(param); + } + catch (JAXBException ex) { + return null; + } + } - @Override - protected QName getLookupKeyForMessage(MessageContext messageContext) throws Exception { - return PayloadRootUtils.getPayloadRootQName(messageContext.getRequest().getPayloadSource(), transformerHelper); - } + @Override + protected QName getLookupKeyForMessage(MessageContext messageContext) throws Exception { + return PayloadRootUtils.getPayloadRootQName(messageContext.getRequest().getPayloadSource(), transformerHelper); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/NamespaceUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/NamespaceUtils.java index 511af52c..97786fa5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/NamespaceUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/NamespaceUtils.java @@ -33,45 +33,45 @@ import org.springframework.xml.namespace.SimpleNamespaceContext; */ public abstract class NamespaceUtils { - private NamespaceUtils() { - } + private NamespaceUtils() { + } - /** - * Creates a {@code NamespaceContext} for the specified method, based on {@link Namespaces @Namespaces} and {@link - * Namespace @Namespace} annotations. - * - *

This method will search for {@link Namespaces @Namespaces} and {@link Namespace @Namespace} annotation in the - * given method, its class, and its package, in reverse order. That is: package-level annotations are overridden by - * class-level annotations, which again are overridden by method-level annotations. - * - * @param method the method to create the namespace context for - * @return the namespace context - */ - public static NamespaceContext getNamespaceContext(Method method) { - Assert.notNull(method, "'method' must not be null"); - SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); - Class endpointClass = method.getDeclaringClass(); - Package endpointPackage = endpointClass.getPackage(); - if (endpointPackage != null) { - addNamespaceAnnotations(endpointPackage, namespaceContext); - } - addNamespaceAnnotations(endpointClass, namespaceContext); - addNamespaceAnnotations(method, namespaceContext); - return namespaceContext; - } + /** + * Creates a {@code NamespaceContext} for the specified method, based on {@link Namespaces @Namespaces} and {@link + * Namespace @Namespace} annotations. + * + *

This method will search for {@link Namespaces @Namespaces} and {@link Namespace @Namespace} annotation in the + * given method, its class, and its package, in reverse order. That is: package-level annotations are overridden by + * class-level annotations, which again are overridden by method-level annotations. + * + * @param method the method to create the namespace context for + * @return the namespace context + */ + public static NamespaceContext getNamespaceContext(Method method) { + Assert.notNull(method, "'method' must not be null"); + SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); + Class endpointClass = method.getDeclaringClass(); + Package endpointPackage = endpointClass.getPackage(); + if (endpointPackage != null) { + addNamespaceAnnotations(endpointPackage, namespaceContext); + } + addNamespaceAnnotations(endpointClass, namespaceContext); + addNamespaceAnnotations(method, namespaceContext); + return namespaceContext; + } - private static void addNamespaceAnnotations(AnnotatedElement annotatedElement, - SimpleNamespaceContext namespaceContext) { - if (annotatedElement.isAnnotationPresent(Namespaces.class)) { - Namespaces namespacesAnn = annotatedElement.getAnnotation(Namespaces.class); - for (Namespace namespaceAnn : namespacesAnn.value()) { - namespaceContext.bindNamespaceUri(namespaceAnn.prefix(), namespaceAnn.uri()); - } - } - if (annotatedElement.isAnnotationPresent(Namespace.class)) { - Namespace namespaceAnn = annotatedElement.getAnnotation(Namespace.class); - namespaceContext.bindNamespaceUri(namespaceAnn.prefix(), namespaceAnn.uri()); - } - } + private static void addNamespaceAnnotations(AnnotatedElement annotatedElement, + SimpleNamespaceContext namespaceContext) { + if (annotatedElement.isAnnotationPresent(Namespaces.class)) { + Namespaces namespacesAnn = annotatedElement.getAnnotation(Namespaces.class); + for (Namespace namespaceAnn : namespacesAnn.value()) { + namespaceContext.bindNamespaceUri(namespaceAnn.prefix(), namespaceAnn.uri()); + } + } + if (annotatedElement.isAnnotationPresent(Namespace.class)) { + Namespace namespaceAnn = annotatedElement.getAnnotation(Namespace.class); + namespaceContext.bindNamespaceUri(namespaceAnn.prefix(), namespaceAnn.uri()); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/PayloadRootUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/PayloadRootUtils.java index e1195bdb..7666c1a5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/PayloadRootUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/server/endpoint/support/PayloadRootUtils.java @@ -46,115 +46,115 @@ import org.springframework.xml.transform.TraxUtils; */ public abstract class PayloadRootUtils { - private PayloadRootUtils() { - } + private PayloadRootUtils() { + } - /** - * Returns the root qualified name of the given source, transforming it if necessary. - * - * @param source the source to get the root element from - * @param transformerFactory a transformer factory, necessary if the given source is not a {@code DOMSource} - * @return the root element, or {@code null} if {@code source} is {@code null} - */ - public static QName getPayloadRootQName(Source source, TransformerFactory transformerFactory) - throws TransformerException { - return getPayloadRootQName(source, new TransformerHelper(transformerFactory)); - } + /** + * Returns the root qualified name of the given source, transforming it if necessary. + * + * @param source the source to get the root element from + * @param transformerFactory a transformer factory, necessary if the given source is not a {@code DOMSource} + * @return the root element, or {@code null} if {@code source} is {@code null} + */ + public static QName getPayloadRootQName(Source source, TransformerFactory transformerFactory) + throws TransformerException { + return getPayloadRootQName(source, new TransformerHelper(transformerFactory)); + } - public static QName getPayloadRootQName(Source source, TransformerHelper transformerHelper) - throws TransformerException { - if (source == null) { - return null; - } - try { - PayloadRootSourceCallback callback = new PayloadRootSourceCallback(); - TraxUtils.doWithSource(source, callback); - if (callback.result != null) { - return callback.result; - } - else { - // we have no other option than to transform - DOMResult domResult = new DOMResult(); - transformerHelper.transform(source, domResult); - Document document = (Document) domResult.getNode(); - return QNameUtils.getQNameForNode(document.getDocumentElement()); - } - } - catch (TransformerException ex) { - throw ex; - } - catch (Exception ex) { - return null; - } - } + public static QName getPayloadRootQName(Source source, TransformerHelper transformerHelper) + throws TransformerException { + if (source == null) { + return null; + } + try { + PayloadRootSourceCallback callback = new PayloadRootSourceCallback(); + TraxUtils.doWithSource(source, callback); + if (callback.result != null) { + return callback.result; + } + else { + // we have no other option than to transform + DOMResult domResult = new DOMResult(); + transformerHelper.transform(source, domResult); + Document document = (Document) domResult.getNode(); + return QNameUtils.getQNameForNode(document.getDocumentElement()); + } + } + catch (TransformerException ex) { + throw ex; + } + catch (Exception ex) { + return null; + } + } - private static class PayloadRootSourceCallback implements TraxUtils.SourceCallback { + private static class PayloadRootSourceCallback implements TraxUtils.SourceCallback { - private QName result; + private QName result; - @Override - public void domSource(Node node) throws Exception { - if (node.getNodeType() == Node.ELEMENT_NODE) { - result = QNameUtils.getQNameForNode(node); - } - else if (node.getNodeType() == Node.DOCUMENT_NODE) { - Document document = (Document) node; - result = QNameUtils.getQNameForNode(document.getDocumentElement()); - } - } + @Override + public void domSource(Node node) throws Exception { + if (node.getNodeType() == Node.ELEMENT_NODE) { + result = QNameUtils.getQNameForNode(node); + } + else if (node.getNodeType() == Node.DOCUMENT_NODE) { + Document document = (Document) node; + result = QNameUtils.getQNameForNode(document.getDocumentElement()); + } + } - @Override - public void staxSource(XMLEventReader eventReader) throws Exception { - XMLEvent event = eventReader.peek(); - if (event != null && event.isStartDocument()) { - event = eventReader.nextTag(); - } - if (event != null) { - if (event.isStartElement()) { - result = event.asStartElement().getName(); - } - else if (event.isEndElement()) { - result = event.asEndElement().getName(); - } - } - } + @Override + public void staxSource(XMLEventReader eventReader) throws Exception { + XMLEvent event = eventReader.peek(); + if (event != null && event.isStartDocument()) { + event = eventReader.nextTag(); + } + if (event != null) { + if (event.isStartElement()) { + result = event.asStartElement().getName(); + } + else if (event.isEndElement()) { + result = event.asEndElement().getName(); + } + } + } - @Override - public void staxSource(XMLStreamReader streamReader) throws Exception { - if (streamReader.getEventType() == XMLStreamConstants.START_DOCUMENT) { - try { - streamReader.nextTag(); - } - catch (XMLStreamException ex) { - throw new IllegalStateException("Could not read next tag: " + ex.getMessage(), ex); - } - } - if (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT || - streamReader.getEventType() == XMLStreamConstants.END_ELEMENT) { - result = streamReader.getName(); - } - } + @Override + public void staxSource(XMLStreamReader streamReader) throws Exception { + if (streamReader.getEventType() == XMLStreamConstants.START_DOCUMENT) { + try { + streamReader.nextTag(); + } + catch (XMLStreamException ex) { + throw new IllegalStateException("Could not read next tag: " + ex.getMessage(), ex); + } + } + if (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT || + streamReader.getEventType() == XMLStreamConstants.END_ELEMENT) { + result = streamReader.getName(); + } + } - @Override - public void saxSource(XMLReader reader, InputSource inputSource) throws Exception { - // Do nothing - } + @Override + public void saxSource(XMLReader reader, InputSource inputSource) throws Exception { + // Do nothing + } - @Override - public void streamSource(InputStream inputStream) throws Exception { - // Do nothing - } + @Override + public void streamSource(InputStream inputStream) throws Exception { + // Do nothing + } - @Override - public void streamSource(Reader reader) throws Exception { - // Do nothing - } + @Override + public void streamSource(Reader reader) throws Exception { + // Do nothing + } - @Override - public void source(String systemId) throws Exception { - // Do nothing - } - } + @Override + public void source(String systemId) throws Exception { + // Do nothing + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/AbstractSoapMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/AbstractSoapMessage.java index c070cce0..6762e882 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/AbstractSoapMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/AbstractSoapMessage.java @@ -30,37 +30,37 @@ import org.springframework.ws.mime.AbstractMimeMessage; */ public abstract class AbstractSoapMessage extends AbstractMimeMessage implements SoapMessage { - private SoapVersion version; + private SoapVersion version; - /** Returns {@code getEnvelope().getBody()}. */ - @Override - public final SoapBody getSoapBody() { - return getEnvelope().getBody(); - } + /** Returns {@code getEnvelope().getBody()}. */ + @Override + public final SoapBody getSoapBody() { + return getEnvelope().getBody(); + } - /** Returns {@code getEnvelope().getHeader()}. */ - @Override - public final SoapHeader getSoapHeader() { - return getEnvelope().getHeader(); - } + /** Returns {@code getEnvelope().getHeader()}. */ + @Override + public final SoapHeader getSoapHeader() { + return getEnvelope().getHeader(); + } - /** Returns {@code getSoapBody().getPayloadSource()}. */ - @Override - public final Source getPayloadSource() { - return getSoapBody().getPayloadSource(); - } + /** Returns {@code getSoapBody().getPayloadSource()}. */ + @Override + public final Source getPayloadSource() { + return getSoapBody().getPayloadSource(); + } - /** Returns {@code getSoapBody().getPayloadResult()}. */ - @Override - public final Result getPayloadResult() { - return getSoapBody().getPayloadResult(); - } + /** Returns {@code getSoapBody().getPayloadResult()}. */ + @Override + public final Result getPayloadResult() { + return getSoapBody().getPayloadResult(); + } - /** Returns {@code getSoapBody().hasFault()}. */ - @Override - public final boolean hasFault() { - return getSoapBody().hasFault(); - } + /** Returns {@code getSoapBody().hasFault()}. */ + @Override + public final boolean hasFault() { + return getSoapBody().hasFault(); + } /** Returns {@code getSoapBody().getFault().getFaultCode()}. */ @Override @@ -73,31 +73,31 @@ public abstract class AbstractSoapMessage extends AbstractMimeMessage implements } /** Returns {@code getSoapBody().getFault().getFaultStringOrReason()}. */ - @Override - public final String getFaultReason() { - if (hasFault()) { - return getSoapBody().getFault().getFaultStringOrReason(); - } - else { - return null; - } - } + @Override + public final String getFaultReason() { + if (hasFault()) { + return getSoapBody().getFault().getFaultStringOrReason(); + } + else { + return null; + } + } - @Override - public SoapVersion getVersion() { - if (version == null) { - String envelopeNamespace = getEnvelope().getName().getNamespaceURI(); - if (SoapVersion.SOAP_11.getEnvelopeNamespaceUri().equals(envelopeNamespace)) { - version = SoapVersion.SOAP_11; - } - else if (SoapVersion.SOAP_12.getEnvelopeNamespaceUri().equals(envelopeNamespace)) { - version = SoapVersion.SOAP_12; - } - else { - throw new IllegalStateException( - "Unknown Envelope namespace uri '" + envelopeNamespace + "'. " + "Cannot deduce SoapVersion."); - } - } - return version; - } + @Override + public SoapVersion getVersion() { + if (version == null) { + String envelopeNamespace = getEnvelope().getName().getNamespaceURI(); + if (SoapVersion.SOAP_11.getEnvelopeNamespaceUri().equals(envelopeNamespace)) { + version = SoapVersion.SOAP_11; + } + else if (SoapVersion.SOAP_12.getEnvelopeNamespaceUri().equals(envelopeNamespace)) { + version = SoapVersion.SOAP_12; + } + else { + throw new IllegalStateException( + "Unknown Envelope namespace uri '" + envelopeNamespace + "'. " + "Cannot deduce SoapVersion."); + } + } + return version; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBody.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBody.java index 0cdf957c..491f7e8b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBody.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBody.java @@ -38,82 +38,82 @@ import org.springframework.ws.WebServiceMessage; */ public interface SoapBody extends SoapElement { - /** - * Returns a {@code Source} that represents the contents of the body. - * - * @return the message contents - * @see WebServiceMessage#getPayloadSource() - */ - Source getPayloadSource(); + /** + * Returns a {@code Source} that represents the contents of the body. + * + * @return the message contents + * @see WebServiceMessage#getPayloadSource() + */ + Source getPayloadSource(); - /** - * Returns a {@code Result} that represents the contents of the body. - * - *

Calling this method removes the current content of the body. - * - * @return the message contents - * @see WebServiceMessage#getPayloadResult() - */ - Result getPayloadResult(); + /** + * Returns a {@code Result} that represents the contents of the body. + * + *

Calling this method removes the current content of the body. + * + * @return the message contents + * @see WebServiceMessage#getPayloadResult() + */ + Result getPayloadResult(); - /** - * Adds a {@code MustUnderstand} fault to the body. A {@code MustUnderstand} is returned when a SOAP - * header with a {@code MustUnderstand} attribute is not understood. - * - *

Adding a fault removes the current content of the body. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @return the created {@code SoapFault} - */ - SoapFault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + /** + * Adds a {@code MustUnderstand} fault to the body. A {@code MustUnderstand} is returned when a SOAP + * header with a {@code MustUnderstand} attribute is not understood. + * + *

Adding a fault removes the current content of the body. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @return the created {@code SoapFault} + */ + SoapFault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - /** - * Adds a {@code Client}/{@code Sender} fault to the body. For SOAP 1.1, this adds a fault with a - * {@code Client} fault code. For SOAP 1.2, this adds a fault with a {@code Sender} code. - * - *

Adding a fault removes the current content of the body. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @return the created {@code SoapFault} - */ - SoapFault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + /** + * Adds a {@code Client}/{@code Sender} fault to the body. For SOAP 1.1, this adds a fault with a + * {@code Client} fault code. For SOAP 1.2, this adds a fault with a {@code Sender} code. + * + *

Adding a fault removes the current content of the body. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @return the created {@code SoapFault} + */ + SoapFault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - /** - * Adds a {@code Server}/{@code Receiver} fault to the body. For SOAP 1.1, this adds a fault with a - * {@code Server} fault code. For SOAP 1.2, this adds a fault with a {@code Receiver} code. - * - *

Adding a fault removes the current content of the body. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @return the created {@code SoapFault} - */ - SoapFault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + /** + * Adds a {@code Server}/{@code Receiver} fault to the body. For SOAP 1.1, this adds a fault with a + * {@code Server} fault code. For SOAP 1.2, this adds a fault with a {@code Receiver} code. + * + *

Adding a fault removes the current content of the body. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @return the created {@code SoapFault} + */ + SoapFault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - /** - * Adds a {@code VersionMismatch} fault to the body. - * - *

Adding a fault removes the current content of the body. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @return the created {@code SoapFault} - */ - SoapFault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + /** + * Adds a {@code VersionMismatch} fault to the body. + * + *

Adding a fault removes the current content of the body. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @return the created {@code SoapFault} + */ + SoapFault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - /** - * Indicates whether this body has a {@code SoapFault}. - * - * @return {@code true} if the body has a fault; {@code false} otherwise - */ - boolean hasFault(); + /** + * Indicates whether this body has a {@code SoapFault}. + * + * @return {@code true} if the body has a fault; {@code false} otherwise + */ + boolean hasFault(); - /** - * Returns the {@code SoapFault} of this body. - * - * @return the {@code SoapFault}, or {@code null} if none is present - */ - SoapFault getFault(); + /** + * Returns the {@code SoapFault} of this body. + * + * @return the {@code SoapFault}, or {@code null} if none is present + */ + SoapFault getFault(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBodyException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBodyException.java index 80f8fe29..4612a9cc 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBodyException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapBodyException.java @@ -25,16 +25,16 @@ package org.springframework.ws.soap; @SuppressWarnings("serial") public class SoapBodyException extends SoapMessageException { - public SoapBodyException(String msg) { - super(msg); - } + public SoapBodyException(String msg) { + super(msg); + } - public SoapBodyException(String msg, Throwable ex) { - super(msg, ex); - } + public SoapBodyException(String msg, Throwable ex) { + super(msg, ex); + } - public SoapBodyException(Throwable ex) { - super("Could not access body: " + ex.getMessage(), ex); - } + public SoapBodyException(Throwable ex) { + super("Could not access body: " + ex.getMessage(), ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElement.java index 89d711d2..cd749ffd 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElement.java @@ -29,58 +29,58 @@ import javax.xml.transform.Source; */ public interface SoapElement { - /** - * Returns the qualified name of this element. - * - * @return the qualified name of this element - */ - QName getName(); + /** + * Returns the qualified name of this element. + * + * @return the qualified name of this element + */ + QName getName(); - /** - * Returns the {@code Source} of this element. This includes the element itself, i.e. - * {@code SoapEnvelope.getSource()} will include the {@code Envelope} tag. - * - * @return the {@code Source} of this element - */ - Source getSource(); + /** + * Returns the {@code Source} of this element. This includes the element itself, i.e. + * {@code SoapEnvelope.getSource()} will include the {@code Envelope} tag. + * + * @return the {@code Source} of this element + */ + Source getSource(); - /** - * Adds an attribute with the specified qualified name and value to this element. - * - * @param name the qualified name of the attribute - * @param value the value of the attribute - */ - void addAttribute(QName name, String value); + /** + * Adds an attribute with the specified qualified name and value to this element. + * + * @param name the qualified name of the attribute + * @param value the value of the attribute + */ + void addAttribute(QName name, String value); - /** - * Removes the attribute with the specified name. - * - * @param name the qualified name of the attribute to remove - */ - void removeAttribute(QName name); + /** + * Removes the attribute with the specified name. + * + * @param name the qualified name of the attribute to remove + */ + void removeAttribute(QName name); - /** - * Returns the value of the attribute with the specified qualified name. - * - * @param name the qualified name - * @return the value, or {@code null} if there is no such attribute - */ - String getAttributeValue(QName name); + /** + * Returns the value of the attribute with the specified qualified name. + * + * @param name the qualified name + * @return the value, or {@code null} if there is no such attribute + */ + String getAttributeValue(QName name); - /** - * Returns an {@code Iterator} over all of the attributes in element as {@link QName qualified names}. - * - * @return an iterator over all the attribute names - */ - Iterator getAllAttributes(); + /** + * Returns an {@code Iterator} over all of the attributes in element as {@link QName qualified names}. + * + * @return an iterator over all the attribute names + */ + Iterator getAllAttributes(); - /** - * Adds a namespace declaration with the specified prefix and URI to this element. - * - * @param prefix the namespace prefix. Can be empty or null to declare the default namespace - * @param namespaceUri the namespace uri - * @throws SoapElementException in case of errors - */ - void addNamespaceDeclaration(String prefix, String namespaceUri); + /** + * Adds a namespace declaration with the specified prefix and URI to this element. + * + * @param prefix the namespace prefix. Can be empty or null to declare the default namespace + * @param namespaceUri the namespace uri + * @throws SoapElementException in case of errors + */ + void addNamespaceDeclaration(String prefix, String namespaceUri); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElementException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElementException.java index c47feb18..d089877e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElementException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapElementException.java @@ -25,16 +25,16 @@ package org.springframework.ws.soap; @SuppressWarnings("serial") public class SoapElementException extends SoapMessageException { - public SoapElementException(String msg) { - super(msg); - } + public SoapElementException(String msg) { + super(msg); + } - public SoapElementException(String msg, Throwable ex) { - super(msg, ex); - } + public SoapElementException(String msg, Throwable ex) { + super(msg, ex); + } - public SoapElementException(Throwable ex) { - super("Could not access element: " + ex.getMessage(), ex); - } + public SoapElementException(Throwable ex) { + super("Could not access element: " + ex.getMessage(), ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelope.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelope.java index 1cbc4921..43efa055 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelope.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelope.java @@ -25,20 +25,20 @@ package org.springframework.ws.soap; */ public interface SoapEnvelope extends SoapElement { - /** - * Returns the {@code SoapHeader}. Returns {@code null} if no header is present. - * - * @return the {@code SoapHeader}, or {@code null} - * @throws SoapHeaderException if the header cannot be returned - */ - SoapHeader getHeader() throws SoapHeaderException; + /** + * Returns the {@code SoapHeader}. Returns {@code null} if no header is present. + * + * @return the {@code SoapHeader}, or {@code null} + * @throws SoapHeaderException if the header cannot be returned + */ + SoapHeader getHeader() throws SoapHeaderException; - /** - * Returns the {@code SoapBody}. - * - * @return the {@code SoapBody} - * @throws SoapBodyException if the header cannot be returned - */ - SoapBody getBody() throws SoapBodyException; + /** + * Returns the {@code SoapBody}. + * + * @return the {@code SoapBody} + * @throws SoapBodyException if the header cannot be returned + */ + SoapBody getBody() throws SoapBodyException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelopeException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelopeException.java index e7e1576b..dec7ab0b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelopeException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapEnvelopeException.java @@ -25,16 +25,16 @@ package org.springframework.ws.soap; @SuppressWarnings("serial") public class SoapEnvelopeException extends SoapMessageException { - public SoapEnvelopeException(String msg) { - super(msg); - } + public SoapEnvelopeException(String msg) { + super(msg); + } - public SoapEnvelopeException(String msg, Throwable ex) { - super(msg, ex); - } + public SoapEnvelopeException(String msg, Throwable ex) { + super(msg, ex); + } - public SoapEnvelopeException(Throwable ex) { - super("Could not access envelope: " + ex.getMessage(), ex); - } + public SoapEnvelopeException(Throwable ex) { + super("Could not access envelope: " + ex.getMessage(), ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFault.java index 303e164b..6d411ab7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFault.java @@ -29,32 +29,32 @@ import javax.xml.namespace.QName; */ public interface SoapFault extends SoapElement { - /** Returns the fault code. */ - QName getFaultCode(); + /** Returns the fault code. */ + QName getFaultCode(); - /** - * Returns the fault string or reason. For SOAP 1.1, this returns the fault string. For SOAP 1.2, this returns the - * fault reason for the default locale. - */ - String getFaultStringOrReason(); + /** + * Returns the fault string or reason. For SOAP 1.1, this returns the fault string. For SOAP 1.2, this returns the + * fault reason for the default locale. + */ + String getFaultStringOrReason(); - /** Returns the fault actor or role. For SOAP 1.1, this returns the actor. For SOAP 1.2, this returns the role. */ - String getFaultActorOrRole(); + /** Returns the fault actor or role. For SOAP 1.1, this returns the actor. For SOAP 1.2, this returns the role. */ + String getFaultActorOrRole(); - /** Sets the fault actor. For SOAP 1.1, this sets the actor. For SOAP 1.2, this sets the role. */ - void setFaultActorOrRole(String faultActor); + /** Sets the fault actor. For SOAP 1.1, this sets the actor. For SOAP 1.2, this sets the role. */ + void setFaultActorOrRole(String faultActor); - /** - * Returns the optional detail element for this {@code SoapFault}. - * - * @return a fault detail - */ - SoapFaultDetail getFaultDetail(); + /** + * Returns the optional detail element for this {@code SoapFault}. + * + * @return a fault detail + */ + SoapFaultDetail getFaultDetail(); - /** - * Creates an optional {@code SoapFaultDetail} object and assigns it to this fault. - * - * @return the created detail - */ - SoapFaultDetail addFaultDetail(); + /** + * Creates an optional {@code SoapFaultDetail} object and assigns it to this fault. + * + * @return the created detail + */ + SoapFaultDetail addFaultDetail(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetail.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetail.java index 8b09fb75..d8cabd76 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetail.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetail.java @@ -30,29 +30,29 @@ import javax.xml.transform.Result; */ public interface SoapFaultDetail extends SoapElement { - /** - * Adds a new {@code SoapFaultDetailElement} with the specified qualified name to this detail. - * - * @param name the qualified name of the new detail element - * @return the created {@code SoapFaultDetailElement} - */ - SoapFaultDetailElement addFaultDetailElement(QName name); + /** + * Adds a new {@code SoapFaultDetailElement} with the specified qualified name to this detail. + * + * @param name the qualified name of the new detail element + * @return the created {@code SoapFaultDetailElement} + */ + SoapFaultDetailElement addFaultDetailElement(QName name); - /** - * Returns a {@code Result} that represents the concents of the detail. - * - *

The result can be used for marshalling. - * - * @return the {@code Result} of this element - */ - Result getResult(); + /** + * Returns a {@code Result} that represents the concents of the detail. + * + *

The result can be used for marshalling. + * + * @return the {@code Result} of this element + */ + Result getResult(); - /** - * Gets an iterator over all of the {@code SoapFaultDetailElement}s in this detail. - * - * @return an iterator over all the {@code SoapFaultDetailElement}s - * @see SoapFaultDetailElement - */ - Iterator getDetailEntries(); + /** + * Gets an iterator over all of the {@code SoapFaultDetailElement}s in this detail. + * + * @return an iterator over all the {@code SoapFaultDetailElement}s + * @see SoapFaultDetailElement + */ + Iterator getDetailEntries(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetailElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetailElement.java index a7598485..149fee10 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetailElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultDetailElement.java @@ -28,9 +28,9 @@ import javax.xml.transform.Result; */ public interface SoapFaultDetailElement extends SoapElement { - /** Returns a {@code Result} that allows for writing to the contents of the detail element. */ - Result getResult(); + /** Returns a {@code Result} that allows for writing to the contents of the detail element. */ + Result getResult(); - /** Adds a new text node to this element. */ - void addText(String text); + /** Adds a new text node to this element. */ + void addText(String text); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultException.java index fe4c7afb..d68f53ae 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapFaultException.java @@ -25,16 +25,16 @@ package org.springframework.ws.soap; @SuppressWarnings("serial") public class SoapFaultException extends SoapEnvelopeException { - public SoapFaultException(String msg) { - super(msg); - } + public SoapFaultException(String msg) { + super(msg); + } - public SoapFaultException(String msg, Throwable ex) { - super(msg, ex); - } + public SoapFaultException(String msg, Throwable ex) { + super(msg, ex); + } - public SoapFaultException(Throwable ex) { - super("Could not access fault: " + ex.getMessage(), ex); - } + public SoapFaultException(Throwable ex) { + super("Could not access fault: " + ex.getMessage(), ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeader.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeader.java index 8019f5ca..96753b99 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeader.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeader.java @@ -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,65 +31,65 @@ import javax.xml.transform.Result; */ public interface SoapHeader extends SoapElement { - /** - * Returns a {@code Result} that represents the contents of the header. - * - *

The result can be used for marshalling. - * - * @return the {@code Result} of this element - */ - Result getResult(); + /** + * Returns a {@code Result} that represents the contents of the header. + * + *

The result can be used for marshalling. + * + * @return the {@code Result} of this element + */ + Result getResult(); - /** - * Adds a new {@code SoapHeaderElement} with the specified qualified name to this header. - * - * @param name the qualified name of the new header element - * @return the created {@code SoapHeaderElement} - * @throws SoapHeaderException if the header cannot be created - */ - SoapHeaderElement addHeaderElement(QName name) throws SoapHeaderException; + /** + * Adds a new {@code SoapHeaderElement} with the specified qualified name to this header. + * + * @param name the qualified name of the new header element + * @return the created {@code SoapHeaderElement} + * @throws SoapHeaderException if the header cannot be created + */ + SoapHeaderElement addHeaderElement(QName name) throws SoapHeaderException; - /** - * Removes the {@code SoapHeaderElement} with the specified qualified name from this header. - * - *

This method will only remove the first child element with the specified name. If no element is found with the - * specified name, this method has no effect. - * - * @param name the qualified name of the header element to be removed - * @throws SoapHeaderException if the header cannot be removed - */ - void removeHeaderElement(QName name) throws SoapHeaderException; + /** + * Removes the {@code SoapHeaderElement} with the specified qualified name from this header. + * + *

This method will only remove the first child element with the specified name. If no element is found with the + * specified name, this method has no effect. + * + * @param name the qualified name of the header element to be removed + * @throws SoapHeaderException if the header cannot be removed + */ + void removeHeaderElement(QName name) throws SoapHeaderException; - /** - * Returns an {@code Iterator} over all the {@code SoapHeaderElement}s that have the specified actor or - * role and that have a {@code MustUnderstand} attribute whose value is equivalent to {@code true}. - * - * @param actorOrRole the actor (SOAP 1.1) or role (SOAP 1.2) for which to search - * @return an iterator over all the header elements that contain the specified actor/role and are marked as - * {@code MustUnderstand} - * @throws SoapHeaderException if the headers cannot be returned - * @see SoapHeaderElement - */ - Iterator examineMustUnderstandHeaderElements(String actorOrRole) throws SoapHeaderException; + /** + * Returns an {@code Iterator} over all the {@code SoapHeaderElement}s that have the specified actor or + * role and that have a {@code MustUnderstand} attribute whose value is equivalent to {@code true}. + * + * @param actorOrRole the actor (SOAP 1.1) or role (SOAP 1.2) for which to search + * @return an iterator over all the header elements that contain the specified actor/role and are marked as + * {@code MustUnderstand} + * @throws SoapHeaderException if the headers cannot be returned + * @see SoapHeaderElement + */ + Iterator examineMustUnderstandHeaderElements(String actorOrRole) throws SoapHeaderException; - /** - * Returns an {@code Iterator} over all the {@code SoapHeaderElement}s in this header. - * - * @return an iterator over all the header elements - * @throws SoapHeaderException if the header cannot be returned - * @see SoapHeaderElement - */ - Iterator examineAllHeaderElements() throws SoapHeaderException; - - /** - * Returns an {@code Iterator} over all the {@code SoapHeaderElement}s with the given qualified name in this header. - * - * @param name the qualified name for which to search - * @return an iterator over all the header elements - * @throws SoapHeaderException if the header cannot be returned - * @see SoapHeaderElement - * @since 2.0.3 - */ - Iterator examineHeaderElements(QName name) throws SoapHeaderException; + /** + * Returns an {@code Iterator} over all the {@code SoapHeaderElement}s in this header. + * + * @return an iterator over all the header elements + * @throws SoapHeaderException if the header cannot be returned + * @see SoapHeaderElement + */ + Iterator examineAllHeaderElements() throws SoapHeaderException; + + /** + * Returns an {@code Iterator} over all the {@code SoapHeaderElement}s with the given qualified name in this header. + * + * @param name the qualified name for which to search + * @return an iterator over all the header elements + * @throws SoapHeaderException if the header cannot be returned + * @see SoapHeaderElement + * @since 2.0.3 + */ + Iterator examineHeaderElements(QName name) throws SoapHeaderException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderElement.java index 926cfddf..e599bd81 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderElement.java @@ -28,52 +28,52 @@ import javax.xml.transform.Result; */ public interface SoapHeaderElement extends SoapElement { - /** - * Returns the actor or role for this header element. In a SOAP 1.1 compliant message, this will read the - * {@code actor} attribute; in SOAP 1.2, the {@code role} attribute. - * - * @return the role of the header - */ - String getActorOrRole() throws SoapHeaderException; + /** + * Returns the actor or role for this header element. In a SOAP 1.1 compliant message, this will read the + * {@code actor} attribute; in SOAP 1.2, the {@code role} attribute. + * + * @return the role of the header + */ + String getActorOrRole() throws SoapHeaderException; - /** - * Sets the actor or role for this header element. In a SOAP 1.1 compliant message, this will result in an - * {@code actor} attribute being set; in SOAP 1.2, a {@code actorOrRole} attribute. - * - * @param actorOrRole the actorOrRole value - */ - void setActorOrRole(String actorOrRole) throws SoapHeaderException; + /** + * Sets the actor or role for this header element. In a SOAP 1.1 compliant message, this will result in an + * {@code actor} attribute being set; in SOAP 1.2, a {@code actorOrRole} attribute. + * + * @param actorOrRole the actorOrRole value + */ + void setActorOrRole(String actorOrRole) throws SoapHeaderException; - /** - * Indicates whether the {@code mustUnderstand} attribute for this header element is set. - * - * @return {@code true} if the {@code mustUnderstand} attribute is set; {@code false} otherwise - */ - boolean getMustUnderstand() throws SoapHeaderException; + /** + * Indicates whether the {@code mustUnderstand} attribute for this header element is set. + * + * @return {@code true} if the {@code mustUnderstand} attribute is set; {@code false} otherwise + */ + boolean getMustUnderstand() throws SoapHeaderException; - /** - * Sets the {@code mustUnderstand} attribute for this header element. If the attribute is on, the role who - * receives the header must process it. - * - * @param mustUnderstand {@code true} to set the {@code mustUnderstand} attribute on; {@code false} - * to turn it off - */ - void setMustUnderstand(boolean mustUnderstand) throws SoapHeaderException; + /** + * Sets the {@code mustUnderstand} attribute for this header element. If the attribute is on, the role who + * receives the header must process it. + * + * @param mustUnderstand {@code true} to set the {@code mustUnderstand} attribute on; {@code false} + * to turn it off + */ + void setMustUnderstand(boolean mustUnderstand) throws SoapHeaderException; - /** Returns a {@code Result} that allows for writing to the contents of the header element. */ - Result getResult() throws SoapHeaderException; + /** Returns a {@code Result} that allows for writing to the contents of the header element. */ + Result getResult() throws SoapHeaderException; - /** - * Returns the text content of this header element, if any. - * - * @return the text content of this header element - */ - String getText(); + /** + * Returns the text content of this header element, if any. + * + * @return the text content of this header element + */ + String getText(); - /** - * Sets the text content of this header element. - * - * @param content the new text content of this header element - */ - void setText(String content); + /** + * Sets the text content of this header element. + * + * @param content the new text content of this header element + */ + void setText(String content); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderException.java index f17b8bfb..82be6dde 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapHeaderException.java @@ -25,16 +25,16 @@ package org.springframework.ws.soap; @SuppressWarnings("serial") public class SoapHeaderException extends SoapMessageException { - public SoapHeaderException(String msg) { - super(msg); - } + public SoapHeaderException(String msg) { + super(msg); + } - public SoapHeaderException(String msg, Throwable ex) { - super(msg, ex); - } + public SoapHeaderException(String msg, Throwable ex) { + super(msg, ex); + } - public SoapHeaderException(Throwable ex) { - super("Could not access header: " + ex.getMessage(), ex); - } + public SoapHeaderException(Throwable ex) { + super("Could not access header: " + ex.getMessage(), ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessage.java index e5a528d0..bbae2df5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessage.java @@ -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,61 +34,61 @@ import org.w3c.dom.Document; */ public interface SoapMessage extends MimeMessage, FaultAwareWebServiceMessage { - /** Returns the {@code SoapEnvelope} associated with this {@code SoapMessage}. */ - SoapEnvelope getEnvelope() throws SoapEnvelopeException; + /** Returns the {@code SoapEnvelope} associated with this {@code SoapMessage}. */ + SoapEnvelope getEnvelope() throws SoapEnvelopeException; - /** - * Get the SOAP Action for this message, or {@code null} if not present. - * - * @return the SOAP Action. - */ - String getSoapAction(); + /** + * Get the SOAP Action for this message, or {@code null} if not present. + * + * @return the SOAP Action. + */ + String getSoapAction(); - /** - * Sets the SOAP Action for this message. - * - * @param soapAction the SOAP Action. - */ - void setSoapAction(String soapAction); + /** + * Sets the SOAP Action for this message. + * + * @param soapAction the SOAP Action. + */ + void setSoapAction(String soapAction); - /** - * Returns the {@code SoapBody} associated with this {@code SoapMessage}. This is a convenience method for - * {@code getEnvelope().getBody()}. - * - * @see SoapEnvelope#getBody() - */ - SoapBody getSoapBody() throws SoapBodyException; + /** + * Returns the {@code SoapBody} associated with this {@code SoapMessage}. This is a convenience method for + * {@code getEnvelope().getBody()}. + * + * @see SoapEnvelope#getBody() + */ + SoapBody getSoapBody() throws SoapBodyException; - /** - * Returns the {@code SoapHeader} associated with this {@code SoapMessage}. This is a convenience method - * for {@code getEnvelope().getHeader()}. - * - * @see SoapEnvelope#getHeader() - */ - SoapHeader getSoapHeader() throws SoapHeaderException; + /** + * Returns the {@code SoapHeader} associated with this {@code SoapMessage}. This is a convenience method + * for {@code getEnvelope().getHeader()}. + * + * @see SoapEnvelope#getHeader() + */ + SoapHeader getSoapHeader() throws SoapHeaderException; - /** - * Returns the SOAP version of this message. This can be either SOAP 1.1 or SOAP 1.2. - * - * @return the SOAP version - * @see SoapVersion#SOAP_11 - * @see SoapVersion#SOAP_12 - */ - SoapVersion getVersion(); + /** + * Returns the SOAP version of this message. This can be either SOAP 1.1 or SOAP 1.2. + * + * @return the SOAP version + * @see SoapVersion#SOAP_11 + * @see SoapVersion#SOAP_12 + */ + SoapVersion getVersion(); - /** - * Returns this message as a {@link Document}. - * - * Depending on the underlying implementation, this Document may be 'live' or not. - * @return this soap message as a DOM document - */ - Document getDocument(); + /** + * Returns this message as a {@link Document}. + * + * Depending on the underlying implementation, this Document may be 'live' or not. + * @return this soap message as a DOM document + */ + Document getDocument(); - /** - * Sets the contents of the message to the given {@link Document}. - * - * @param document the soap message as a DOM document - */ - void setDocument(Document document); + /** + * Sets the contents of the message to the given {@link Document}. + * + * @param document the soap message as a DOM document + */ + void setDocument(Document document); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageCreationException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageCreationException.java index 3670969c..8c684b9b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageCreationException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageCreationException.java @@ -25,13 +25,13 @@ package org.springframework.ws.soap; @SuppressWarnings("serial") public class SoapMessageCreationException extends SoapMessageException { - /** Constructor for {@code SoapMessageCreationException}. */ - public SoapMessageCreationException(String msg) { - super(msg); - } + /** Constructor for {@code SoapMessageCreationException}. */ + public SoapMessageCreationException(String msg) { + super(msg); + } - /** Constructor for {@code SoapMessageCreationException}. */ - public SoapMessageCreationException(String msg, Throwable ex) { - super(msg, ex); - } + /** Constructor for {@code SoapMessageCreationException}. */ + public SoapMessageCreationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageException.java index 5ab990a9..9658d7d1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageException.java @@ -27,13 +27,13 @@ import org.springframework.ws.WebServiceMessageException; @SuppressWarnings("serial") public abstract class SoapMessageException extends WebServiceMessageException { - /** Constructor for {@code SoapMessageException}. */ - public SoapMessageException(String msg) { - super(msg); - } + /** Constructor for {@code SoapMessageException}. */ + public SoapMessageException(String msg) { + super(msg); + } - /** Constructor for {@code SoapMessageException}. */ - public SoapMessageException(String msg, Throwable ex) { - super(msg, ex); - } + /** Constructor for {@code SoapMessageException}. */ + public SoapMessageException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageFactory.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageFactory.java index 86327cb6..49432e78 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageFactory.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapMessageFactory.java @@ -32,34 +32,34 @@ import org.springframework.ws.WebServiceMessageFactory; */ public interface SoapMessageFactory extends WebServiceMessageFactory { - /** - * Sets the SOAP Version used by this factory. - * - * @param version the version constant - * @see SoapVersion#SOAP_11 - * @see SoapVersion#SOAP_12 - */ - void setSoapVersion(SoapVersion version); + /** + * Sets the SOAP Version used by this factory. + * + * @param version the version constant + * @see SoapVersion#SOAP_11 + * @see SoapVersion#SOAP_12 + */ + void setSoapVersion(SoapVersion version); - /** - * Creates a new, empty {@code SoapMessage}. - * - * @return the empty message - */ - @Override - SoapMessage createWebServiceMessage(); + /** + * Creates a new, empty {@code SoapMessage}. + * + * @return the empty message + */ + @Override + SoapMessage createWebServiceMessage(); - /** - * Reads a {@link SoapMessage} from the given input stream. - * - *

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 java.io.IOException if an I/O exception occurs - */ - @Override - SoapMessage createWebServiceMessage(InputStream inputStream) throws IOException; + /** + * Reads a {@link SoapMessage} from the given input stream. + * + *

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 java.io.IOException if an I/O exception occurs + */ + @Override + SoapMessage createWebServiceMessage(InputStream inputStream) throws IOException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapVersion.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapVersion.java index 9108cb8a..27a935b1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapVersion.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/SoapVersion.java @@ -29,255 +29,255 @@ import javax.xml.namespace.QName; */ public interface SoapVersion { - /** - * Represents version 1.1 of the SOAP specification. - * - * @see SOAP 1.1 specification - */ - SoapVersion SOAP_11 = new SoapVersion() { + /** + * Represents version 1.1 of the SOAP specification. + * + * @see SOAP 1.1 specification + */ + SoapVersion SOAP_11 = new SoapVersion() { - private static final String ENVELOPE_NAMESPACE_URI = "http://schemas.xmlsoap.org/soap/envelope/"; + private static final String ENVELOPE_NAMESPACE_URI = "http://schemas.xmlsoap.org/soap/envelope/"; - private static final String NEXT_ROLE_URI = "http://schemas.xmlsoap.org/soap/actor/next"; + private static final String NEXT_ROLE_URI = "http://schemas.xmlsoap.org/soap/actor/next"; - private static final String CONTENT_TYPE = "text/xml"; + private static final String CONTENT_TYPE = "text/xml"; - private QName ENVELOPE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Envelope"); + private QName ENVELOPE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Envelope"); - private QName HEADER_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Header"); + private QName HEADER_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Header"); - private QName BODY_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Body"); + private QName BODY_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Body"); - private QName FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Fault"); + private QName FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Fault"); - private QName MUST_UNDERSTAND_ATTRIBUTE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "mustUnderstand"); + private QName MUST_UNDERSTAND_ATTRIBUTE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "mustUnderstand"); - private QName ACTOR_NAME = new QName(ENVELOPE_NAMESPACE_URI, "actor"); + private QName ACTOR_NAME = new QName(ENVELOPE_NAMESPACE_URI, "actor"); - private QName CLIENT_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Client"); + private QName CLIENT_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Client"); - private QName SERVER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Server"); + private QName SERVER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Server"); - private QName MUST_UNDERSTAND_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "MustUnderstand"); + private QName MUST_UNDERSTAND_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "MustUnderstand"); - private QName VERSION_MISMATCH_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "VersionMismatch"); + private QName VERSION_MISMATCH_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "VersionMismatch"); - public QName getBodyName() { - return BODY_NAME; - } + public QName getBodyName() { + return BODY_NAME; + } - public QName getEnvelopeName() { - return ENVELOPE_NAME; - } + public QName getEnvelopeName() { + return ENVELOPE_NAME; + } - public String getEnvelopeNamespaceUri() { - return ENVELOPE_NAMESPACE_URI; - } + public String getEnvelopeNamespaceUri() { + return ENVELOPE_NAMESPACE_URI; + } - public QName getFaultName() { - return FAULT_NAME; - } + public QName getFaultName() { + return FAULT_NAME; + } - public QName getHeaderName() { - return HEADER_NAME; - } + public QName getHeaderName() { + return HEADER_NAME; + } - public String getNextActorOrRoleUri() { - return NEXT_ROLE_URI; - } + public String getNextActorOrRoleUri() { + return NEXT_ROLE_URI; + } - public String getNoneActorOrRoleUri() { - return ""; - } + public String getNoneActorOrRoleUri() { + return ""; + } - public QName getServerOrReceiverFaultName() { - return SERVER_FAULT_NAME; - } + public QName getServerOrReceiverFaultName() { + return SERVER_FAULT_NAME; + } - public String getUltimateReceiverRoleUri() { - return ""; - } + public String getUltimateReceiverRoleUri() { + return ""; + } - public QName getActorOrRoleName() { - return ACTOR_NAME; - } + public QName getActorOrRoleName() { + return ACTOR_NAME; + } - public QName getClientOrSenderFaultName() { - return CLIENT_FAULT_NAME; - } + public QName getClientOrSenderFaultName() { + return CLIENT_FAULT_NAME; + } - public String getContentType() { - return CONTENT_TYPE; - } + public String getContentType() { + return CONTENT_TYPE; + } - public QName getMustUnderstandAttributeName() { - return MUST_UNDERSTAND_ATTRIBUTE_NAME; - } + public QName getMustUnderstandAttributeName() { + return MUST_UNDERSTAND_ATTRIBUTE_NAME; + } - public QName getMustUnderstandFaultName() { - return MUST_UNDERSTAND_FAULT_NAME; - } + public QName getMustUnderstandFaultName() { + return MUST_UNDERSTAND_FAULT_NAME; + } - public QName getVersionMismatchFaultName() { - return VERSION_MISMATCH_FAULT_NAME; - } + public QName getVersionMismatchFaultName() { + return VERSION_MISMATCH_FAULT_NAME; + } - public String toString() { - return "SOAP 1.1"; - } - }; + public String toString() { + return "SOAP 1.1"; + } + }; - /** - * Represents version 1.2 of the SOAP specification. - * - * @see SOAP 1.2 specification - */ - SoapVersion SOAP_12 = new SoapVersion() { + /** + * Represents version 1.2 of the SOAP specification. + * + * @see SOAP 1.2 specification + */ + SoapVersion SOAP_12 = new SoapVersion() { - private static final String ENVELOPE_NAMESPACE_URI = "http://www.w3.org/2003/05/soap-envelope"; + private static final String ENVELOPE_NAMESPACE_URI = "http://www.w3.org/2003/05/soap-envelope"; - private static final String NEXT_ROLE_URI = ENVELOPE_NAMESPACE_URI + "/role/next"; + private static final String NEXT_ROLE_URI = ENVELOPE_NAMESPACE_URI + "/role/next"; - private static final String NONE_ROLE_URI = ENVELOPE_NAMESPACE_URI + "/role/none"; + private static final String NONE_ROLE_URI = ENVELOPE_NAMESPACE_URI + "/role/none"; - private static final String ULTIMATE_RECEIVER_ROLE_URI = ENVELOPE_NAMESPACE_URI + "/role/ultimateReceiver"; + private static final String ULTIMATE_RECEIVER_ROLE_URI = ENVELOPE_NAMESPACE_URI + "/role/ultimateReceiver"; - private static final String CONTENT_TYPE = "application/soap+xml"; + private static final String CONTENT_TYPE = "application/soap+xml"; - private QName ENVELOPE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Envelope"); + private QName ENVELOPE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Envelope"); - private QName HEADER_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Header"); + private QName HEADER_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Header"); - private QName BODY_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Body"); + private QName BODY_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Body"); - private QName FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Fault"); + private QName FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Fault"); - private QName MUST_UNDERSTAND_ATTRIBUTE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "mustUnderstand"); + private QName MUST_UNDERSTAND_ATTRIBUTE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "mustUnderstand"); - private QName ROLE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "role"); + private QName ROLE_NAME = new QName(ENVELOPE_NAMESPACE_URI, "role"); - private QName SENDER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Sender"); + private QName SENDER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Sender"); - private QName RECEIVER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Receiver"); + private QName RECEIVER_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "Receiver"); - private QName MUST_UNDERSTAND_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "MustUnderstand"); + private QName MUST_UNDERSTAND_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "MustUnderstand"); - private QName VERSION_MISMATCH_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "VersionMismatch"); + private QName VERSION_MISMATCH_FAULT_NAME = new QName(ENVELOPE_NAMESPACE_URI, "VersionMismatch"); - public QName getBodyName() { - return BODY_NAME; - } + public QName getBodyName() { + return BODY_NAME; + } - public QName getEnvelopeName() { - return ENVELOPE_NAME; - } + public QName getEnvelopeName() { + return ENVELOPE_NAME; + } - public String getEnvelopeNamespaceUri() { - return ENVELOPE_NAMESPACE_URI; - } + public String getEnvelopeNamespaceUri() { + return ENVELOPE_NAMESPACE_URI; + } - public QName getFaultName() { - return FAULT_NAME; - } + public QName getFaultName() { + return FAULT_NAME; + } - public QName getHeaderName() { - return HEADER_NAME; - } + public QName getHeaderName() { + return HEADER_NAME; + } - public String getNextActorOrRoleUri() { - return NEXT_ROLE_URI; - } + public String getNextActorOrRoleUri() { + return NEXT_ROLE_URI; + } - public String getNoneActorOrRoleUri() { - return NONE_ROLE_URI; - } + public String getNoneActorOrRoleUri() { + return NONE_ROLE_URI; + } - public QName getServerOrReceiverFaultName() { - return RECEIVER_FAULT_NAME; - } + public QName getServerOrReceiverFaultName() { + return RECEIVER_FAULT_NAME; + } - public String getUltimateReceiverRoleUri() { - return ULTIMATE_RECEIVER_ROLE_URI; - } + public String getUltimateReceiverRoleUri() { + return ULTIMATE_RECEIVER_ROLE_URI; + } - public QName getActorOrRoleName() { - return ROLE_NAME; - } + public QName getActorOrRoleName() { + return ROLE_NAME; + } - public QName getClientOrSenderFaultName() { - return SENDER_FAULT_NAME; - } + public QName getClientOrSenderFaultName() { + return SENDER_FAULT_NAME; + } - public String getContentType() { - return CONTENT_TYPE; - } + public String getContentType() { + return CONTENT_TYPE; + } - public QName getMustUnderstandAttributeName() { - return MUST_UNDERSTAND_ATTRIBUTE_NAME; - } + public QName getMustUnderstandAttributeName() { + return MUST_UNDERSTAND_ATTRIBUTE_NAME; + } - public QName getMustUnderstandFaultName() { - return MUST_UNDERSTAND_FAULT_NAME; - } + public QName getMustUnderstandFaultName() { + return MUST_UNDERSTAND_FAULT_NAME; + } - public QName getVersionMismatchFaultName() { - return VERSION_MISMATCH_FAULT_NAME; - } + public QName getVersionMismatchFaultName() { + return VERSION_MISMATCH_FAULT_NAME; + } - public String toString() { - return "SOAP 1.2"; - } + public String toString() { + return "SOAP 1.2"; + } - }; + }; - /** Returns the qualified name for a SOAP body. */ - QName getBodyName(); + /** Returns the qualified name for a SOAP body. */ + QName getBodyName(); - /** Returns the {@code Content-Type} MIME header for a SOAP message. */ - String getContentType(); + /** Returns the {@code Content-Type} MIME header for a SOAP message. */ + String getContentType(); - /** Returns the qualified name for a SOAP envelope. */ - QName getEnvelopeName(); + /** Returns the qualified name for a SOAP envelope. */ + QName getEnvelopeName(); - /** Returns the namespace URI for the SOAP envelope namespace. */ - String getEnvelopeNamespaceUri(); + /** Returns the namespace URI for the SOAP envelope namespace. */ + String getEnvelopeNamespaceUri(); - /** Returns the qualified name for a SOAP fault. */ - QName getFaultName(); + /** Returns the qualified name for a SOAP fault. */ + QName getFaultName(); - /** Returns the qualified name for a SOAP header. */ - QName getHeaderName(); + /** Returns the qualified name for a SOAP header. */ + QName getHeaderName(); - /** Returns the qualified name of the SOAP {@code MustUnderstand} attribute. */ - QName getMustUnderstandAttributeName(); + /** Returns the qualified name of the SOAP {@code MustUnderstand} attribute. */ + QName getMustUnderstandAttributeName(); - /** - * Returns the URI indicating that a header element is intended for the next SOAP application that processes the - * message. - */ - String getNextActorOrRoleUri(); + /** + * Returns the URI indicating that a header element is intended for the next SOAP application that processes the + * message. + */ + String getNextActorOrRoleUri(); - /** Returns the URI indicating that a header element should never be directly processed. */ - String getNoneActorOrRoleUri(); + /** Returns the URI indicating that a header element should never be directly processed. */ + String getNoneActorOrRoleUri(); - /** Returns the qualified name of the {@code MustUnderstand} SOAP Fault value. */ - QName getMustUnderstandFaultName(); + /** Returns the qualified name of the {@code MustUnderstand} SOAP Fault value. */ + QName getMustUnderstandFaultName(); - /** Returns the qualified name of the Receiver/Server SOAP Fault value. */ - QName getServerOrReceiverFaultName(); + /** Returns the qualified name of the Receiver/Server SOAP Fault value. */ + QName getServerOrReceiverFaultName(); - /** Returns the qualified name of the {@code VersionMismatch} SOAP Fault value. */ - QName getVersionMismatchFaultName(); + /** Returns the qualified name of the {@code VersionMismatch} SOAP Fault value. */ + QName getVersionMismatchFaultName(); - /** Returns the qualified name of the SOAP {@code actor}/{@code role} attribute. */ - QName getActorOrRoleName(); + /** Returns the qualified name of the SOAP {@code actor}/{@code role} attribute. */ + QName getActorOrRoleName(); - /** Returns the qualified name of the Sender/Client SOAP Fault value. */ - QName getClientOrSenderFaultName(); + /** Returns the qualified name of the Sender/Client SOAP Fault value. */ + QName getClientOrSenderFaultName(); - /** - * Returns the URI indicating that a header element should only be processed by nodes acting as the ultimate - * receiver of a message. - */ - String getUltimateReceiverRoleUri(); + /** + * Returns the URI indicating that a header element should only be processed by nodes acting as the ultimate + * receiver of a message. + */ + String getUltimateReceiverRoleUri(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/AddressingException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/AddressingException.java index 8a5734de..2967c8fe 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/AddressingException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/AddressingException.java @@ -27,11 +27,11 @@ import org.springframework.ws.WebServiceException; @SuppressWarnings("serial") public class AddressingException extends WebServiceException { - public AddressingException(String msg) { - super(msg); - } + public AddressingException(String msg) { + super(msg); + } - public AddressingException(String msg, Throwable ex) { - super(msg, ex); - } + public AddressingException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/client/ActionCallback.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/client/ActionCallback.java index b1c441e2..916c52c4 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/client/ActionCallback.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/client/ActionCallback.java @@ -43,9 +43,9 @@ import org.springframework.ws.transport.context.TransportContextHolder; * WebServiceTemplate template = new WebServiceTemplate(messageFactory); * Result result = new DOMResult(); * template.sendSourceAndReceiveToResult( - * new StringSource("<content xmlns=\"http://tempuri.org\"/>"), - * new ActionCallback(new URI("http://tempuri.org/Action")), - * result); + * new StringSource("<content xmlns=\"http://tempuri.org\"/>"), + * new ActionCallback(new URI("http://tempuri.org/Action")), + * result); * * * @author Arjen Poutsma @@ -53,196 +53,196 @@ import org.springframework.ws.transport.context.TransportContextHolder; */ public class ActionCallback implements WebServiceMessageCallback { - private final AddressingVersion version; + private final AddressingVersion version; - private final URI action; + private final URI action; - private final URI to; + private final URI to; - private MessageIdStrategy messageIdStrategy; + private MessageIdStrategy messageIdStrategy; - private EndpointReference from; + private EndpointReference from; - private EndpointReference replyTo; + private EndpointReference replyTo; - private EndpointReference faultTo; + private EndpointReference faultTo; - /** - * Create a new {@code ActionCallback} with the given {@code Action}. - * - *

The {@code To} header of the outgoing message will reflect the {@link org.springframework.ws.transport.WebServiceConnection#getUri() - * connection URI}. - * - *

The {@link AddressingVersion} is set to {@link Addressing10}. - * - * @param action the value of the action property to set - */ - public ActionCallback(String action) throws URISyntaxException { - this(new URI(action), new Addressing10(), null); - } + /** + * Create a new {@code ActionCallback} with the given {@code Action}. + * + *

The {@code To} header of the outgoing message will reflect the {@link org.springframework.ws.transport.WebServiceConnection#getUri() + * connection URI}. + * + *

The {@link AddressingVersion} is set to {@link Addressing10}. + * + * @param action the value of the action property to set + */ + public ActionCallback(String action) throws URISyntaxException { + this(new URI(action), new Addressing10(), null); + } - /** - * Create a new {@code ActionCallback} with the given {@code Action}. - * - *

The {@code To} header of the outgoing message will reflect the {@link org.springframework.ws.transport.WebServiceConnection#getUri() - * connection URI}. - * - *

The {@link AddressingVersion} is set to {@link Addressing10}. - * - * @param action the value of the action property to set - */ - public ActionCallback(URI action) { - this(action, new Addressing10(), null); - } + /** + * Create a new {@code ActionCallback} with the given {@code Action}. + * + *

The {@code To} header of the outgoing message will reflect the {@link org.springframework.ws.transport.WebServiceConnection#getUri() + * connection URI}. + * + *

The {@link AddressingVersion} is set to {@link Addressing10}. + * + * @param action the value of the action property to set + */ + public ActionCallback(URI action) { + this(action, new Addressing10(), null); + } - /** - * Create a new {@code ActionCallback} with the given version and {@code Action}. - * - *

The {@code To} header of the outgoing message will reflect the {@link org.springframework.ws.transport.WebServiceConnection#getUri() - * connection URI}. - * - * @param action the value of the action property to set - * @param version the WS-Addressing version to use - */ - public ActionCallback(URI action, AddressingVersion version) { - this(action, version, null); - } + /** + * Create a new {@code ActionCallback} with the given version and {@code Action}. + * + *

The {@code To} header of the outgoing message will reflect the {@link org.springframework.ws.transport.WebServiceConnection#getUri() + * connection URI}. + * + * @param action the value of the action property to set + * @param version the WS-Addressing version to use + */ + public ActionCallback(URI action, AddressingVersion version) { + this(action, version, null); + } - /** - * Create a new {@code ActionCallback} with the given version, {@code Action}, and optional - * {@code To}. - * - * @param action the value of the action property - * @param version the WS-Addressing version to use - * @param action the value of the destination property - */ - public ActionCallback(URI action, AddressingVersion version, URI to) { - Assert.notNull(action, "'action' must not be null"); - Assert.notNull(version, "'version' must not be null"); - this.action = action; - this.version = version; - this.to = to; - messageIdStrategy = new UuidMessageIdStrategy(); - } + /** + * Create a new {@code ActionCallback} with the given version, {@code Action}, and optional + * {@code To}. + * + * @param action the value of the action property + * @param version the WS-Addressing version to use + * @param action the value of the destination property + */ + public ActionCallback(URI action, AddressingVersion version, URI to) { + Assert.notNull(action, "'action' must not be null"); + Assert.notNull(version, "'version' must not be null"); + this.action = action; + this.version = version; + this.to = to; + messageIdStrategy = new UuidMessageIdStrategy(); + } - /** - * Returns the WS-Addressing version - * @return - */ - public AddressingVersion getVersion() { - return version; - } + /** + * Returns the WS-Addressing version + * @return + */ + public AddressingVersion getVersion() { + return version; + } - /** - * Returns the message id strategy used for creating WS-Addressing MessageIds. - * - *

By default, the {@link UuidMessageIdStrategy} is used. - */ - public MessageIdStrategy getMessageIdStrategy() { - return messageIdStrategy; - } + /** + * Returns the message id strategy used for creating WS-Addressing MessageIds. + * + *

By default, the {@link UuidMessageIdStrategy} is used. + */ + public MessageIdStrategy getMessageIdStrategy() { + return messageIdStrategy; + } - /** - * Sets the message id strategy used for creating WS-Addressing MessageIds. - * - *

By default, the {@link UuidMessageIdStrategy} is used. - */ - public void setMessageIdStrategy(MessageIdStrategy messageIdStrategy) { - Assert.notNull(messageIdStrategy, "'messageIdStrategy' must not be null"); - this.messageIdStrategy = messageIdStrategy; - } + /** + * Sets the message id strategy used for creating WS-Addressing MessageIds. + * + *

By default, the {@link UuidMessageIdStrategy} is used. + */ + public void setMessageIdStrategy(MessageIdStrategy messageIdStrategy) { + Assert.notNull(messageIdStrategy, "'messageIdStrategy' must not be null"); + this.messageIdStrategy = messageIdStrategy; + } - /** - * Returns the {@code Action}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getAction() - */ - public URI getAction() { - return action; - } + /** + * Returns the {@code Action}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getAction() + */ + public URI getAction() { + return action; + } - /** - * Returns the {@code From}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFrom() - */ - public EndpointReference getFrom() { - return from; - } + /** + * Returns the {@code From}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFrom() + */ + public EndpointReference getFrom() { + return from; + } - /** - * Sets the {@code From}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFrom() - */ - public void setFrom(EndpointReference from) { - this.from = from; - } + /** + * Sets the {@code From}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFrom() + */ + public void setFrom(EndpointReference from) { + this.from = from; + } - /** - * Returns the {@code ReplyTo}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getReplyTo() - */ - public EndpointReference getReplyTo() { - return replyTo; - } + /** + * Returns the {@code ReplyTo}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getReplyTo() + */ + public EndpointReference getReplyTo() { + return replyTo; + } - /** - * Sets the {@code ReplyTo}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getReplyTo() - */ - public void setReplyTo(EndpointReference replyTo) { - this.replyTo = replyTo; - } + /** + * Sets the {@code ReplyTo}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getReplyTo() + */ + public void setReplyTo(EndpointReference replyTo) { + this.replyTo = replyTo; + } - /** - * Returns the {@code FaultTo}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFaultTo() - */ - public EndpointReference getFaultTo() { - return faultTo; - } + /** + * Returns the {@code FaultTo}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFaultTo() + */ + public EndpointReference getFaultTo() { + return faultTo; + } - /** - * Sets the {@code FaultTo}. - * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFaultTo() - */ - public void setFaultTo(EndpointReference faultTo) { - this.faultTo = faultTo; - } + /** + * Sets the {@code FaultTo}. + * @see org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getFaultTo() + */ + public void setFaultTo(EndpointReference faultTo) { + this.faultTo = faultTo; + } - /** - * Returns the {@code Destination} for outgoing messages. - * - *

Defaults to the {@link org.springframework.ws.transport.WebServiceConnection#getUri() connection URI} if no - * destination was set. - */ - protected URI getTo() { - if (to == null) { - TransportContext transportContext = TransportContextHolder.getTransportContext(); - if (transportContext != null && transportContext.getConnection() != null) { - try { - return transportContext.getConnection().getUri(); - } - catch (URISyntaxException ex) { - // ignore - } - } - throw new IllegalStateException("Could not obtain connection URI from Transport Context"); - } - else { - return to; - } - } + /** + * Returns the {@code Destination} for outgoing messages. + * + *

Defaults to the {@link org.springframework.ws.transport.WebServiceConnection#getUri() connection URI} if no + * destination was set. + */ + protected URI getTo() { + if (to == null) { + TransportContext transportContext = TransportContextHolder.getTransportContext(); + if (transportContext != null && transportContext.getConnection() != null) { + try { + return transportContext.getConnection().getUri(); + } + catch (URISyntaxException ex) { + // ignore + } + } + throw new IllegalStateException("Could not obtain connection URI from Transport Context"); + } + else { + return to; + } + } - @Override - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - Assert.isInstanceOf(SoapMessage.class, message); - SoapMessage soapMessage = (SoapMessage) message; - URI messageId = getMessageIdStrategy().newMessageId(soapMessage); - MessageAddressingProperties map = - new MessageAddressingProperties(getTo(), getFrom(), getReplyTo(), getFaultTo(), getAction(), messageId); - version.addAddressingHeaders(soapMessage, map); - } + @Override + public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { + Assert.isInstanceOf(SoapMessage.class, message); + SoapMessage soapMessage = (SoapMessage) message; + URI messageId = getMessageIdStrategy().newMessageId(soapMessage); + MessageAddressingProperties map = + new MessageAddressingProperties(getTo(), getFrom(), getReplyTo(), getFaultTo(), getAction(), messageId); + version.addAddressingHeaders(soapMessage, map); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/EndpointReference.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/EndpointReference.java index 09992616..a5bc5da0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/EndpointReference.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/EndpointReference.java @@ -34,75 +34,75 @@ import org.w3c.dom.Node; */ public final class EndpointReference implements Serializable { - private static final long serialVersionUID = 8999416009328865260L; + private static final long serialVersionUID = 8999416009328865260L; - private final URI address; + private final URI address; - private final List referenceProperties; + private final List referenceProperties; - private final List referenceParameters; + private final List referenceParameters; - /** - * Creates a new instance of the {@link EndpointReference} class with the given address. The reference parameters - * and properties are empty. - * - * @param address the endpoint address - */ - public EndpointReference(URI address) { - Assert.notNull(address, "address must not be null"); - this.address = address; - this.referenceParameters = Collections.emptyList(); - this.referenceProperties = Collections.emptyList(); - } + /** + * Creates a new instance of the {@link EndpointReference} class with the given address. The reference parameters + * and properties are empty. + * + * @param address the endpoint address + */ + public EndpointReference(URI address) { + Assert.notNull(address, "address must not be null"); + this.address = address; + this.referenceParameters = Collections.emptyList(); + this.referenceProperties = Collections.emptyList(); + } - /** - * Creates a new instance of the {@link EndpointReference} class with the given address, reference properties, and - * reference parameters. - * - * @param address the endpoint address - * @param referenceProperties the reference properties, as a list of {@link Node} - * @param referenceParameters the reference parameters, as a list of {@link Node} - */ - public EndpointReference(URI address, List referenceProperties, List referenceParameters) { - Assert.notNull(address, "address must not be null"); - Assert.notNull(referenceProperties, "referenceProperties must not be null"); - Assert.notNull(referenceParameters, "referenceParameters must not be null"); - this.address = address; - this.referenceProperties = referenceProperties; - this.referenceParameters = referenceParameters; - } + /** + * Creates a new instance of the {@link EndpointReference} class with the given address, reference properties, and + * reference parameters. + * + * @param address the endpoint address + * @param referenceProperties the reference properties, as a list of {@link Node} + * @param referenceParameters the reference parameters, as a list of {@link Node} + */ + public EndpointReference(URI address, List referenceProperties, List referenceParameters) { + Assert.notNull(address, "address must not be null"); + Assert.notNull(referenceProperties, "referenceProperties must not be null"); + Assert.notNull(referenceParameters, "referenceParameters must not be null"); + this.address = address; + this.referenceProperties = referenceProperties; + this.referenceParameters = referenceParameters; + } - /** Returns the address of the endpoint. */ - public URI getAddress() { - return address; - } + /** Returns the address of the endpoint. */ + public URI getAddress() { + return address; + } - /** Returns the reference properties of the endpoint, as a list of {@link Node} objects. */ - public List getReferenceProperties() { - return referenceProperties; - } + /** Returns the reference properties of the endpoint, as a list of {@link Node} objects. */ + public List getReferenceProperties() { + return referenceProperties; + } - /** Returns the reference parameters of the endpoint, as a list of {@link Node} objects. */ - public List getReferenceParameters() { - return referenceParameters; - } + /** Returns the reference parameters of the endpoint, as a list of {@link Node} objects. */ + public List getReferenceParameters() { + return referenceParameters; + } - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o != null && o instanceof EndpointReference) { - EndpointReference other = (EndpointReference) o; - return address.equals(other.address); - } - return false; - } + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o != null && o instanceof EndpointReference) { + EndpointReference other = (EndpointReference) o; + return address.equals(other.address); + } + return false; + } - public int hashCode() { - return address.hashCode(); - } + public int hashCode() { + return address.hashCode(); + } - public String toString() { - return address.toString(); - } + public String toString() { + return address.toString(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/MessageAddressingProperties.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/MessageAddressingProperties.java index 6d048539..19906156 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/MessageAddressingProperties.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/core/MessageAddressingProperties.java @@ -34,128 +34,128 @@ import org.w3c.dom.Node; */ public final class MessageAddressingProperties implements Serializable { - private static final long serialVersionUID = -6980663311446506672L; + private static final long serialVersionUID = -6980663311446506672L; - private final URI to; + private final URI to; - private final EndpointReference from; + private final EndpointReference from; - private final EndpointReference replyTo; + private final EndpointReference replyTo; - private final EndpointReference faultTo; + private final EndpointReference faultTo; - private final URI action; + private final URI action; - private final URI messageId; + private final URI messageId; - private final URI relatesTo; + private final URI relatesTo; - private final List referenceProperties; + private final List referenceProperties; - private final List referenceParameters; + private final List referenceParameters; - /** - * Constructs a new {@link MessageAddressingProperties} with the given parameters. - * - * @param to the value of the destination property - * @param from the value of the source endpoint property - * @param replyTo the value of the reply endpoint property - * @param faultTo the value of the fault endpoint property - * @param action the value of the action property - * @param messageId the value of the message id property - */ - public MessageAddressingProperties(URI to, - EndpointReference from, - EndpointReference replyTo, - EndpointReference faultTo, - URI action, - URI messageId) { - this.to = to; - this.from = from; - this.replyTo = replyTo; - this.faultTo = faultTo; - this.action = action; - this.messageId = messageId; - this.relatesTo = null; - this.referenceProperties = Collections.emptyList(); - this.referenceParameters = Collections.emptyList(); - } + /** + * Constructs a new {@link MessageAddressingProperties} with the given parameters. + * + * @param to the value of the destination property + * @param from the value of the source endpoint property + * @param replyTo the value of the reply endpoint property + * @param faultTo the value of the fault endpoint property + * @param action the value of the action property + * @param messageId the value of the message id property + */ + public MessageAddressingProperties(URI to, + EndpointReference from, + EndpointReference replyTo, + EndpointReference faultTo, + URI action, + URI messageId) { + this.to = to; + this.from = from; + this.replyTo = replyTo; + this.faultTo = faultTo; + this.action = action; + this.messageId = messageId; + this.relatesTo = null; + this.referenceProperties = Collections.emptyList(); + this.referenceParameters = Collections.emptyList(); + } - /** - * Constructs a new {@link MessageAddressingProperties} that forms a reply to the given EPR. - * - * @param epr the endpoint reference to create a reply for - * @param action the value of the action property - * @param messageId the value of the message id property - * @param relatesTo the value of the relates to property - */ - private MessageAddressingProperties(EndpointReference epr, URI action, URI messageId, URI relatesTo) { - this.to = epr.getAddress(); - this.action = action; - this.messageId = messageId; - this.relatesTo = relatesTo; - this.referenceParameters = epr.getReferenceParameters(); - this.referenceProperties = epr.getReferenceProperties(); - this.from = null; - this.replyTo = null; - this.faultTo = null; - } + /** + * Constructs a new {@link MessageAddressingProperties} that forms a reply to the given EPR. + * + * @param epr the endpoint reference to create a reply for + * @param action the value of the action property + * @param messageId the value of the message id property + * @param relatesTo the value of the relates to property + */ + private MessageAddressingProperties(EndpointReference epr, URI action, URI messageId, URI relatesTo) { + this.to = epr.getAddress(); + this.action = action; + this.messageId = messageId; + this.relatesTo = relatesTo; + this.referenceParameters = epr.getReferenceParameters(); + this.referenceProperties = epr.getReferenceProperties(); + this.from = null; + this.replyTo = null; + this.faultTo = null; + } - /** Returns the value of the destination property. */ - public URI getTo() { - return to; - } + /** Returns the value of the destination property. */ + public URI getTo() { + return to; + } - /** Returns the value of the source endpoint property. */ - public EndpointReference getFrom() { - return from; - } + /** Returns the value of the source endpoint property. */ + public EndpointReference getFrom() { + return from; + } - /** Returns the value of the reply endpoint property. */ - public EndpointReference getReplyTo() { - return replyTo; - } + /** Returns the value of the reply endpoint property. */ + public EndpointReference getReplyTo() { + return replyTo; + } - /** Returns the value of the fault endpoint property. */ - public EndpointReference getFaultTo() { - return faultTo; - } + /** Returns the value of the fault endpoint property. */ + public EndpointReference getFaultTo() { + return faultTo; + } - /** Returns the value of the action property. */ - public URI getAction() { - return action; - } + /** Returns the value of the action property. */ + public URI getAction() { + return action; + } - /** Returns the value of the message id property. */ - public URI getMessageId() { - return messageId; - } + /** Returns the value of the message id property. */ + public URI getMessageId() { + return messageId; + } - /** Returns the value of the relationship property. */ - public URI getRelatesTo() { - return relatesTo; - } + /** Returns the value of the relationship property. */ + public URI getRelatesTo() { + return relatesTo; + } - /** Returns the endpoint properties. Returns an empty list of none are set. */ - public List getReferenceProperties() { - return Collections.unmodifiableList(referenceProperties); - } + /** Returns the endpoint properties. Returns an empty list of none are set. */ + public List getReferenceProperties() { + return Collections.unmodifiableList(referenceProperties); + } - /** Returns the endpoint parameters. Returns an empty list of none are set. */ - public List getReferenceParameters() { - return Collections.unmodifiableList(referenceParameters); - } + /** Returns the endpoint parameters. Returns an empty list of none are set. */ + public List getReferenceParameters() { + return Collections.unmodifiableList(referenceParameters); + } - /** - * Creates a {@link MessageAddressingProperties} that can be used for creating a reply to the given {@link - * EndpointReference}. The {@link #getTo() destination} property will be populated with the {@link - * EndpointReference#getAddress() address} of the given EPR, and the {@link #getRelatesTo() relationship} property - * will be set to the {@link #getMessageId() message id} property of this instance. the action is specified, the - * - * @param epr the endpoint reference to create a reply to - * @param action the action - */ - public MessageAddressingProperties getReplyProperties(EndpointReference epr, URI action, URI messageId) { - return new MessageAddressingProperties(epr, action, messageId, this.messageId); - } + /** + * Creates a {@link MessageAddressingProperties} that can be used for creating a reply to the given {@link + * EndpointReference}. The {@link #getTo() destination} property will be populated with the {@link + * EndpointReference#getAddress() address} of the given EPR, and the {@link #getRelatesTo() relationship} property + * will be set to the {@link #getMessageId() message id} property of this instance. the action is specified, the + * + * @param epr the endpoint reference to create a reply to + * @param action the action + */ + public MessageAddressingProperties getReplyProperties(EndpointReference epr, URI action, URI messageId) { + return new MessageAddressingProperties(epr, action, messageId, this.messageId); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/MessageIdStrategy.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/MessageIdStrategy.java index 94faf692..6a898763 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/MessageIdStrategy.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/MessageIdStrategy.java @@ -28,20 +28,20 @@ import org.springframework.ws.soap.SoapMessage; */ public interface MessageIdStrategy { - /** - * Indicates whether the given {@code MessageID} value is a duplicate or not - * - * @param messageId the message id - * @return {@code true} if a duplicate; {@code false} otherwise - */ - boolean isDuplicate(URI messageId); + /** + * Indicates whether the given {@code MessageID} value is a duplicate or not + * + * @param messageId the message id + * @return {@code true} if a duplicate; {@code false} otherwise + */ + boolean isDuplicate(URI messageId); - /** - * Returns a new WS-Addressing {@code MessageID} for the given {@link SoapMessage}. - * - * @param message the message to create an id for - * @return the new message id - */ - URI newMessageId(SoapMessage message); + /** + * Returns a new WS-Addressing {@code MessageID} for the given {@link SoapMessage}. + * + * @param message the message to create an id for + * @return the new message id + */ + URI newMessageId(SoapMessage message); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategy.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategy.java index a54dfbfa..9ceb415b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategy.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategy.java @@ -32,16 +32,16 @@ import org.springframework.ws.soap.SoapMessage; */ public class UuidMessageIdStrategy implements MessageIdStrategy { - public static final String PREFIX = "urn:uuid:"; + public static final String PREFIX = "urn:uuid:"; - /** Returns {@code false}. */ - @Override - public boolean isDuplicate(URI messageId) { - return false; - } + /** Returns {@code false}. */ + @Override + public boolean isDuplicate(URI messageId) { + return false; + } - @Override - public URI newMessageId(SoapMessage message) { - return URI.create(PREFIX + UUID.randomUUID().toString()); - } + @Override + public URI newMessageId(SoapMessage message) { + return URI.create(PREFIX + UUID.randomUUID().toString()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionEndpointMapping.java index 3765bcea..fe193bdf 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionEndpointMapping.java @@ -29,7 +29,7 @@ import org.springframework.ws.soap.addressing.core.MessageAddressingProperties; * implementations. Provides infrastructure for mapping endpoints to actions. * *

By default, this mapping creates a {@code Action} for reply messages based on the request message, plus the - * extra {@link #setOutputActionSuffix(String) suffix}, and a * By default, this mapping creates a {@code Action} + * extra {@link #setOutputActionSuffix(String) suffix}, and a * By default, this mapping creates a {@code Action} * for reply messages based on the request message, plus the extra {@link #setOutputActionSuffix(String) suffix}. * * @author Arjen Poutsma @@ -37,142 +37,142 @@ import org.springframework.ws.soap.addressing.core.MessageAddressingProperties; */ public abstract class AbstractActionEndpointMapping extends AbstractAddressingEndpointMapping { - /** The defaults suffix to add to the request {@code Action} for reply messages. */ - public static final String DEFAULT_OUTPUT_ACTION_SUFFIX = "Response"; + /** The defaults suffix to add to the request {@code Action} for reply messages. */ + public static final String DEFAULT_OUTPUT_ACTION_SUFFIX = "Response"; - /** The defaults suffix to add to response {@code Action} for reply messages. */ - public static final String DEFAULT_FAULT_ACTION_SUFFIX = "Fault"; + /** The defaults suffix to add to response {@code Action} for reply messages. */ + public static final String DEFAULT_FAULT_ACTION_SUFFIX = "Fault"; - // keys are action URIs, values are endpoints - private final Map endpointMap = new HashMap(); + // keys are action URIs, values are endpoints + private final Map endpointMap = new HashMap(); - private String outputActionSuffix = DEFAULT_OUTPUT_ACTION_SUFFIX; + private String outputActionSuffix = DEFAULT_OUTPUT_ACTION_SUFFIX; - private String faultActionSuffix = DEFAULT_OUTPUT_ACTION_SUFFIX; + private String faultActionSuffix = DEFAULT_OUTPUT_ACTION_SUFFIX; - /** Returns the suffix to add to request {@code Action}s for reply messages. */ - public String getOutputActionSuffix() { - return outputActionSuffix; - } + /** Returns the suffix to add to request {@code Action}s for reply messages. */ + public String getOutputActionSuffix() { + return outputActionSuffix; + } - /** - * Sets the suffix to add to request {@code Action}s for reply messages. - * - * @see #DEFAULT_OUTPUT_ACTION_SUFFIX - */ - public void setOutputActionSuffix(String outputActionSuffix) { - Assert.hasText(outputActionSuffix, "'outputActionSuffix' must not be empty"); - this.outputActionSuffix = outputActionSuffix; - } + /** + * Sets the suffix to add to request {@code Action}s for reply messages. + * + * @see #DEFAULT_OUTPUT_ACTION_SUFFIX + */ + public void setOutputActionSuffix(String outputActionSuffix) { + Assert.hasText(outputActionSuffix, "'outputActionSuffix' must not be empty"); + this.outputActionSuffix = outputActionSuffix; + } - /** Returns the suffix to add to request {@code Action}s for reply fault messages. */ - public String getFaultActionSuffix() { - return faultActionSuffix; - } + /** Returns the suffix to add to request {@code Action}s for reply fault messages. */ + public String getFaultActionSuffix() { + return faultActionSuffix; + } - /** - * Sets the suffix to add to request {@code Action}s for reply fault messages. - * - * @see #DEFAULT_FAULT_ACTION_SUFFIX - */ - public void setFaultActionSuffix(String faultActionSuffix) { - Assert.hasText(faultActionSuffix, "'faultActionSuffix' must not be empty"); - this.faultActionSuffix = faultActionSuffix; - } + /** + * Sets the suffix to add to request {@code Action}s for reply fault messages. + * + * @see #DEFAULT_FAULT_ACTION_SUFFIX + */ + public void setFaultActionSuffix(String faultActionSuffix) { + Assert.hasText(faultActionSuffix, "'faultActionSuffix' must not be empty"); + this.faultActionSuffix = faultActionSuffix; + } - @Override - protected final Object getEndpointInternal(MessageAddressingProperties map) { - URI action = map.getAction(); - if (logger.isDebugEnabled()) { - logger.debug("Looking up endpoint for action [" + action + "]"); - } - Object endpoint = lookupEndpoint(action); - if (endpoint != null) { - URI endpointAddress = getEndpointAddress(endpoint); - if (endpointAddress == null || endpointAddress.equals(map.getTo())) { - return endpoint; - } - } - return null; - } + @Override + protected final Object getEndpointInternal(MessageAddressingProperties map) { + URI action = map.getAction(); + if (logger.isDebugEnabled()) { + logger.debug("Looking up endpoint for action [" + action + "]"); + } + Object endpoint = lookupEndpoint(action); + if (endpoint != null) { + URI endpointAddress = getEndpointAddress(endpoint); + if (endpointAddress == null || endpointAddress.equals(map.getTo())) { + return endpoint; + } + } + return null; + } - /** - * Returns the address property of the given endpoint. The value of this property should match the {@link - * MessageAddressingProperties#getTo() destination} of incoming messages. May return {@code null} to ignore - * the destination. - * - * @param endpoint the endpoint to return the address for - * @return the endpoint address; or {@code null} to ignore the destination property - */ - protected abstract URI getEndpointAddress(Object endpoint); + /** + * Returns the address property of the given endpoint. The value of this property should match the {@link + * MessageAddressingProperties#getTo() destination} of incoming messages. May return {@code null} to ignore + * the destination. + * + * @param endpoint the endpoint to return the address for + * @return the endpoint address; or {@code null} to ignore the destination property + */ + protected abstract URI getEndpointAddress(Object endpoint); - /** - * Looks up an endpoint instance for the given action. All keys are tried in order. - * - * @param action the action URI - * @return the associated endpoint instance, or {@code null} if not found - */ - protected Object lookupEndpoint(URI action) { - return endpointMap.get(action); - } + /** + * Looks up an endpoint instance for the given action. All keys are tried in order. + * + * @param action the action URI + * @return the associated endpoint instance, or {@code null} if not found + */ + protected Object lookupEndpoint(URI action) { + return endpointMap.get(action); + } - /** - * Register the specified endpoint for the given action URI. - * - * @param action the action the bean should be mapped to - * @param endpoint the endpoint instance or endpoint bean name String (a bean name will automatically be resolved - * into the corresponding endpoint bean) - * @throws org.springframework.beans.BeansException - * if the endpoint couldn't be registered - * @throws IllegalStateException if there is a conflicting endpoint registered - */ - protected void registerEndpoint(URI action, Object endpoint) throws BeansException, IllegalStateException { - Assert.notNull(action, "Action must not be null"); - Assert.notNull(endpoint, "Endpoint object must not be null"); - Object resolvedEndpoint = endpoint; + /** + * Register the specified endpoint for the given action URI. + * + * @param action the action the bean should be mapped to + * @param endpoint the endpoint instance or endpoint bean name String (a bean name will automatically be resolved + * into the corresponding endpoint bean) + * @throws org.springframework.beans.BeansException + * if the endpoint couldn't be registered + * @throws IllegalStateException if there is a conflicting endpoint registered + */ + protected void registerEndpoint(URI action, Object endpoint) throws BeansException, IllegalStateException { + Assert.notNull(action, "Action must not be null"); + Assert.notNull(endpoint, "Endpoint object must not be null"); + Object resolvedEndpoint = endpoint; - if (endpoint instanceof String) { - String endpointName = (String) endpoint; - if (getApplicationContext().isSingleton(endpointName)) { - resolvedEndpoint = getApplicationContext().getBean(endpointName); - } - } - Object mappedEndpoint = this.endpointMap.get(action); - if (mappedEndpoint != null) { - if (mappedEndpoint != resolvedEndpoint) { - throw new IllegalStateException("Cannot map endpoint [" + endpoint + "] to action [" + action + - "]: There is already endpoint [" + resolvedEndpoint + "] mapped."); - } - } - else { - this.endpointMap.put(action, resolvedEndpoint); - if (logger.isDebugEnabled()) { - logger.debug("Mapped Action [" + action + "] onto endpoint [" + resolvedEndpoint + "]"); - } - } - } + if (endpoint instanceof String) { + String endpointName = (String) endpoint; + if (getApplicationContext().isSingleton(endpointName)) { + resolvedEndpoint = getApplicationContext().getBean(endpointName); + } + } + Object mappedEndpoint = this.endpointMap.get(action); + if (mappedEndpoint != null) { + if (mappedEndpoint != resolvedEndpoint) { + throw new IllegalStateException("Cannot map endpoint [" + endpoint + "] to action [" + action + + "]: There is already endpoint [" + resolvedEndpoint + "] mapped."); + } + } + else { + this.endpointMap.put(action, resolvedEndpoint); + if (logger.isDebugEnabled()) { + logger.debug("Mapped Action [" + action + "] onto endpoint [" + resolvedEndpoint + "]"); + } + } + } - @Override - protected URI getResponseAction(Object endpoint, MessageAddressingProperties requestMap) { - URI requestAction = requestMap.getAction(); - if (requestAction != null) { - return URI.create(requestAction.toString() + getOutputActionSuffix()); - } - else { - return null; - } - } + @Override + protected URI getResponseAction(Object endpoint, MessageAddressingProperties requestMap) { + URI requestAction = requestMap.getAction(); + if (requestAction != null) { + return URI.create(requestAction.toString() + getOutputActionSuffix()); + } + else { + return null; + } + } - @Override - protected URI getFaultAction(Object endpoint, MessageAddressingProperties requestMap) { - URI requestAction = requestMap.getAction(); - if (requestAction != null) { - return URI.create(requestAction.toString() + getFaultActionSuffix()); - } - else { - return null; - } - } + @Override + protected URI getFaultAction(Object endpoint, MessageAddressingProperties requestMap) { + URI requestAction = requestMap.getAction(); + if (requestAction != null) { + return URI.create(requestAction.toString() + getFaultActionSuffix()); + } + else { + return null; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionMethodEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionMethodEndpointMapping.java index 65579a28..b9557938 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionMethodEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractActionMethodEndpointMapping.java @@ -33,40 +33,40 @@ import org.springframework.ws.server.endpoint.MethodEndpoint; */ public abstract class AbstractActionMethodEndpointMapping extends AbstractActionEndpointMapping { - /** - * Helper method that registers the methods of the given bean. This method iterates over the methods of the bean, - * and calls {@link #getActionForMethod(java.lang.reflect.Method)} for each. If this returns a URI, the method is - * registered using {@link #registerEndpoint(java.net.URI, Object)}. - * - * @see #getActionForMethod (java.lang.reflect.Method) - */ - protected void registerMethods(Object endpoint) { - Assert.notNull(endpoint, "'endpoint' must not be null"); - Method[] methods = AopUtils.getTargetClass(endpoint).getMethods(); - for (Method method : methods) { - if (method.isSynthetic() || method.getDeclaringClass().equals(Object.class)) { - continue; - } - URI action = getActionForMethod(method); - if (action != null) { - registerEndpoint(action, new MethodEndpoint(endpoint, method)); - } - } - } + /** + * Helper method that registers the methods of the given bean. This method iterates over the methods of the bean, + * and calls {@link #getActionForMethod(java.lang.reflect.Method)} for each. If this returns a URI, the method is + * registered using {@link #registerEndpoint(java.net.URI, Object)}. + * + * @see #getActionForMethod (java.lang.reflect.Method) + */ + protected void registerMethods(Object endpoint) { + Assert.notNull(endpoint, "'endpoint' must not be null"); + Method[] methods = AopUtils.getTargetClass(endpoint).getMethods(); + for (Method method : methods) { + if (method.isSynthetic() || method.getDeclaringClass().equals(Object.class)) { + continue; + } + URI action = getActionForMethod(method); + if (action != null) { + registerEndpoint(action, new MethodEndpoint(endpoint, method)); + } + } + } - /** Returns the action value for the specified method. */ - protected abstract URI getActionForMethod(Method method); + /** Returns the action value for the specified method. */ + protected abstract URI getActionForMethod(Method method); - /** - * Return the class or interface to use for method reflection. - * - *

Default implementation delegates to {@link AopUtils#getTargetClass(Object)}. - * - * @param endpoint the bean instance (might be an AOP proxy) - * @return the bean class to expose - */ - protected Class getEndpointClass(Object endpoint) { - return AopUtils.getTargetClass(endpoint); - } + /** + * Return the class or interface to use for method reflection. + * + *

Default implementation delegates to {@link AopUtils#getTargetClass(Object)}. + * + * @param endpoint the bean instance (might be an AOP proxy) + * @return the bean class to expose + */ + protected Class getEndpointClass(Object endpoint) { + return AopUtils.getTargetClass(endpoint); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractAddressingEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractAddressingEndpointMapping.java index d117530d..86224849 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractAddressingEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AbstractAddressingEndpointMapping.java @@ -69,61 +69,61 @@ import java.util.*; * @since 1.5.0 */ public abstract class AbstractAddressingEndpointMapping extends TransformerObjectSupport - implements SoapEndpointMapping, ApplicationContextAware, InitializingBean, Ordered { + implements SoapEndpointMapping, ApplicationContextAware, InitializingBean, Ordered { - private String[] actorsOrRoles; + private String[] actorsOrRoles; - private boolean isUltimateReceiver = true; + private boolean isUltimateReceiver = true; - private MessageIdStrategy messageIdStrategy; + private MessageIdStrategy messageIdStrategy; - private WebServiceMessageSender[] messageSenders = new WebServiceMessageSender[0]; + private WebServiceMessageSender[] messageSenders = new WebServiceMessageSender[0]; - private AddressingVersion[] versions; + private AddressingVersion[] versions; - private EndpointInterceptor[] preInterceptors = new EndpointInterceptor[0]; + private EndpointInterceptor[] preInterceptors = new EndpointInterceptor[0]; - private EndpointInterceptor[] postInterceptors = new EndpointInterceptor[0]; + private EndpointInterceptor[] postInterceptors = new EndpointInterceptor[0]; private SmartEndpointInterceptor[] smartInterceptors = new SmartEndpointInterceptor[0]; private ApplicationContext applicationContext; - private int order = Integer.MAX_VALUE; // default: same as non-Ordered + private int order = Integer.MAX_VALUE; // default: same as non-Ordered - /** Protected constructor. Initializes the default settings. */ - protected AbstractAddressingEndpointMapping() { - initDefaultStrategies(); - } + /** Protected constructor. Initializes the default settings. */ + protected AbstractAddressingEndpointMapping() { + initDefaultStrategies(); + } - /** - * Initializes the default implementation for this mapping's strategies: the {@link - * org.springframework.ws.soap.addressing.version.Addressing200408} and {@link org.springframework.ws.soap.addressing.version.Addressing10} - * versions of the specification, and the {@link UuidMessageIdStrategy}. - */ - protected void initDefaultStrategies() { - this.versions = new AddressingVersion[]{new Addressing200408(), new Addressing10()}; - messageIdStrategy = new UuidMessageIdStrategy(); - } + /** + * Initializes the default implementation for this mapping's strategies: the {@link + * org.springframework.ws.soap.addressing.version.Addressing200408} and {@link org.springframework.ws.soap.addressing.version.Addressing10} + * versions of the specification, and the {@link UuidMessageIdStrategy}. + */ + protected void initDefaultStrategies() { + this.versions = new AddressingVersion[]{new Addressing200408(), new Addressing10()}; + messageIdStrategy = new UuidMessageIdStrategy(); + } - @Override - public final void setActorOrRole(String actorOrRole) { - Assert.notNull(actorOrRole, "actorOrRole must not be null"); - actorsOrRoles = new String[]{actorOrRole}; - } + @Override + public final void setActorOrRole(String actorOrRole) { + Assert.notNull(actorOrRole, "actorOrRole must not be null"); + actorsOrRoles = new String[]{actorOrRole}; + } - @Override - public final void setActorsOrRoles(String[] actorsOrRoles) { - Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); - this.actorsOrRoles = actorsOrRoles; - } + @Override + public final void setActorsOrRoles(String[] actorsOrRoles) { + Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); + this.actorsOrRoles = actorsOrRoles; + } - @Override - public final void setUltimateReceiver(boolean ultimateReceiver) { - this.isUltimateReceiver = ultimateReceiver; - } + @Override + public final void setUltimateReceiver(boolean ultimateReceiver) { + this.isUltimateReceiver = ultimateReceiver; + } public ApplicationContext getApplicationContext() { return applicationContext; @@ -136,48 +136,48 @@ public abstract class AbstractAddressingEndpointMapping extends TransformerObjec } @Override - public final int getOrder() { - return order; - } + public final int getOrder() { + return order; + } - /** - * Specify the order value for this mapping. - * - *

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. + * + *

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; + } /** * Set additional interceptors to be applied before the implicit WS-Addressing interceptor, e.g. * {@code XwsSecurityInterceptor}. - */ - public final void setPreInterceptors(EndpointInterceptor[] preInterceptors) { - Assert.notNull(preInterceptors, "'preInterceptors' must not be null"); - this.preInterceptors = preInterceptors; - } + */ + public final void setPreInterceptors(EndpointInterceptor[] preInterceptors) { + Assert.notNull(preInterceptors, "'preInterceptors' must not be null"); + this.preInterceptors = preInterceptors; + } - /** - * Set additional interceptors to be applied after the implicit WS-Addressing interceptor, e.g. - * {@code PayloadLoggingInterceptor}. - */ - public final void setPostInterceptors(EndpointInterceptor[] postInterceptors) { - Assert.notNull(postInterceptors, "'postInterceptors' must not be null"); - this.postInterceptors = postInterceptors; - } + /** + * Set additional interceptors to be applied after the implicit WS-Addressing interceptor, e.g. + * {@code PayloadLoggingInterceptor}. + */ + public final void setPostInterceptors(EndpointInterceptor[] postInterceptors) { + Assert.notNull(postInterceptors, "'postInterceptors' must not be null"); + this.postInterceptors = postInterceptors; + } - /** - * Sets the message id strategy used for creating WS-Addressing MessageIds. - * - *

By default, the {@link UuidMessageIdStrategy} is used. - */ - public final void setMessageIdStrategy(MessageIdStrategy messageIdStrategy) { - Assert.notNull(messageIdStrategy, "'messageIdStrategy' must not be null"); - this.messageIdStrategy = messageIdStrategy; - } + /** + * Sets the message id strategy used for creating WS-Addressing MessageIds. + * + *

By default, the {@link UuidMessageIdStrategy} is used. + */ + public final void setMessageIdStrategy(MessageIdStrategy messageIdStrategy) { + Assert.notNull(messageIdStrategy, "'messageIdStrategy' must not be null"); + this.messageIdStrategy = messageIdStrategy; + } /** * Returns the message id strategy used for creating WS-Addressing MessageIds. @@ -208,7 +208,7 @@ public abstract class AbstractAddressingEndpointMapping extends TransformerObjec public final void setMessageSenders(WebServiceMessageSender[] messageSenders) { Assert.notNull(messageSenders, "'messageSenders' must not be null"); this.messageSenders = messageSenders; - } + } /** * Returns the message senders, which are used to send out-of-band reply messages. @@ -223,12 +223,12 @@ public abstract class AbstractAddressingEndpointMapping extends TransformerObjec * Sets the WS-Addressing versions to be supported by this mapping. * *

By default, this array is set to support {@link org.springframework.ws.soap.addressing.version.Addressing200408 - * the August 2004} and the {@link org.springframework.ws.soap.addressing.version.Addressing10 May 2006} versions of - * the specification. - */ - public final void setVersions(AddressingVersion[] versions) { - this.versions = versions; - } + * the August 2004} and the {@link org.springframework.ws.soap.addressing.version.Addressing10 May 2006} versions of + * the specification. + */ + public final void setVersions(AddressingVersion[] versions) { + this.versions = versions; + } @Override public void afterPropertiesSet() throws Exception { @@ -246,75 +246,75 @@ public abstract class AbstractAddressingEndpointMapping extends TransformerObjec } } - @Override - public final EndpointInvocationChain getEndpoint(MessageContext messageContext) throws TransformerException { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - SoapMessage request = (SoapMessage) messageContext.getRequest(); - for (AddressingVersion version : versions) { - if (supports(version, request)) { - if (logger.isDebugEnabled()) { - logger.debug("Request [" + request + "] uses [" + version + "]"); - } - MessageAddressingProperties requestMap = version.getMessageAddressingProperties(request); - if (requestMap == null) { - return null; - } - Object endpoint = getEndpointInternal(requestMap); - if (endpoint == null) { - return null; - } - return getEndpointInvocationChain(endpoint, version, requestMap, messageContext); - } - } - return null; - } + @Override + public final EndpointInvocationChain getEndpoint(MessageContext messageContext) throws TransformerException { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + SoapMessage request = (SoapMessage) messageContext.getRequest(); + for (AddressingVersion version : versions) { + if (supports(version, request)) { + if (logger.isDebugEnabled()) { + logger.debug("Request [" + request + "] uses [" + version + "]"); + } + MessageAddressingProperties requestMap = version.getMessageAddressingProperties(request); + if (requestMap == null) { + return null; + } + Object endpoint = getEndpointInternal(requestMap); + if (endpoint == null) { + return null; + } + return getEndpointInvocationChain(endpoint, version, requestMap, messageContext); + } + } + return null; + } - /** - * Creates a {@link SoapEndpointInvocationChain} based on the given endpoint and {@link - * org.springframework.ws.soap.addressing.version.AddressingVersion}. - */ - private EndpointInvocationChain getEndpointInvocationChain(Object endpoint, - AddressingVersion version, - MessageAddressingProperties requestMap, - MessageContext messageContext) { - URI responseAction = getResponseAction(endpoint, requestMap); - URI faultAction = getFaultAction(endpoint, requestMap); + /** + * Creates a {@link SoapEndpointInvocationChain} based on the given endpoint and {@link + * org.springframework.ws.soap.addressing.version.AddressingVersion}. + */ + private EndpointInvocationChain getEndpointInvocationChain(Object endpoint, + AddressingVersion version, + MessageAddressingProperties requestMap, + MessageContext messageContext) { + URI responseAction = getResponseAction(endpoint, requestMap); + URI faultAction = getFaultAction(endpoint, requestMap); - WebServiceMessageSender[] messageSenders = getMessageSenders(endpoint); - MessageIdStrategy messageIdStrategy = getMessageIdStrategy(endpoint); + WebServiceMessageSender[] messageSenders = getMessageSenders(endpoint); + MessageIdStrategy messageIdStrategy = getMessageIdStrategy(endpoint); - List interceptors = new ArrayList(); - interceptors.addAll(Arrays.asList(preInterceptors)); + List interceptors = new ArrayList(); + interceptors.addAll(Arrays.asList(preInterceptors)); - AddressingEndpointInterceptor addressingInterceptor = new AddressingEndpointInterceptor(version, messageIdStrategy, - messageSenders, responseAction, faultAction); - interceptors.add(addressingInterceptor); - interceptors.addAll(Arrays.asList(postInterceptors)); + AddressingEndpointInterceptor addressingInterceptor = new AddressingEndpointInterceptor(version, messageIdStrategy, + messageSenders, responseAction, faultAction); + interceptors.add(addressingInterceptor); + interceptors.addAll(Arrays.asList(postInterceptors)); - if (this.smartInterceptors != null) { - for (SmartEndpointInterceptor smartInterceptor : smartInterceptors) { - if (smartInterceptor.shouldIntercept(messageContext, endpoint)) { - interceptors.add(smartInterceptor); - } - } - } + if (this.smartInterceptors != null) { + for (SmartEndpointInterceptor smartInterceptor : smartInterceptors) { + if (smartInterceptor.shouldIntercept(messageContext, endpoint)) { + interceptors.add(smartInterceptor); + } + } + } - return new SoapEndpointInvocationChain(endpoint, - interceptors.toArray(new EndpointInterceptor[interceptors.size()]), actorsOrRoles, isUltimateReceiver); - } + return new SoapEndpointInvocationChain(endpoint, + interceptors.toArray(new EndpointInterceptor[interceptors.size()]), actorsOrRoles, isUltimateReceiver); + } - private boolean supports(AddressingVersion version, SoapMessage request) { - SoapHeader header = request.getSoapHeader(); - if (header != null) { - for (Iterator iterator = header.examineAllHeaderElements(); iterator.hasNext();) { - SoapHeaderElement headerElement = iterator.next(); - if (version.understands(headerElement)) { - return true; - } - } - } - return false; - } + private boolean supports(AddressingVersion version, SoapMessage request) { + SoapHeader header = request.getSoapHeader(); + if (header != null) { + for (Iterator iterator = header.examineAllHeaderElements(); iterator.hasNext();) { + SoapHeaderElement headerElement = iterator.next(); + if (version.understands(headerElement)) { + return true; + } + } + } + return false; + } /** * Returns the message senders for the given endpoint. Default implementation returns @@ -339,32 +339,32 @@ public abstract class AbstractAddressingEndpointMapping extends TransformerObjec } /** - * Lookup an endpoint for the given {@link MessageAddressingProperties}, returning {@code null} if no specific + * Lookup an endpoint for the given {@link MessageAddressingProperties}, returning {@code null} if no specific * one is found. This template method is called by {@link #getEndpoint(MessageContext)}. * - * @param map the message addressing properties - * @return the endpoint, or {@code null} - */ - protected abstract Object getEndpointInternal(MessageAddressingProperties map); + * @param map the message addressing properties + * @return the endpoint, or {@code null} + */ + protected abstract Object getEndpointInternal(MessageAddressingProperties map); - /** - * Provides the WS-Addressing Action for response messages, given the endpoint, and request Message Addressing - * Properties. - * - * @param endpoint the mapped endpoint - * @param requestMap the MAP for the request - * @return the response Action - */ - protected abstract URI getResponseAction(Object endpoint, MessageAddressingProperties requestMap); + /** + * Provides the WS-Addressing Action for response messages, given the endpoint, and request Message Addressing + * Properties. + * + * @param endpoint the mapped endpoint + * @param requestMap the MAP for the request + * @return the response Action + */ + protected abstract URI getResponseAction(Object endpoint, MessageAddressingProperties requestMap); - /** - * Provides the WS-Addressing Action for response fault messages, given the endpoint, and request Message Addressing - * Properties. - * - * @param endpoint the mapped endpoint - * @param requestMap the MAP for the request - * @return the response Action - */ - protected abstract URI getFaultAction(Object endpoint, MessageAddressingProperties requestMap); + /** + * Provides the WS-Addressing Action for response fault messages, given the endpoint, and request Message Addressing + * Properties. + * + * @param endpoint the mapped endpoint + * @param requestMap the MAP for the request + * @return the response Action + */ + protected abstract URI getFaultAction(Object endpoint, MessageAddressingProperties requestMap); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AddressingEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AddressingEndpointInterceptor.java index 8f044356..175b4c26 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AddressingEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AddressingEndpointInterceptor.java @@ -43,150 +43,150 @@ import org.springframework.ws.transport.WebServiceMessageSender; */ class AddressingEndpointInterceptor implements SoapEndpointInterceptor { - private static final Log logger = LogFactory.getLog(AddressingEndpointInterceptor.class); + private static final Log logger = LogFactory.getLog(AddressingEndpointInterceptor.class); - private final AddressingVersion version; + private final AddressingVersion version; - private final MessageIdStrategy messageIdStrategy; + private final MessageIdStrategy messageIdStrategy; - private final WebServiceMessageSender[] messageSenders; + private final WebServiceMessageSender[] messageSenders; - private URI replyAction; + private URI replyAction; - private URI faultAction; + private URI faultAction; - AddressingEndpointInterceptor(AddressingVersion version, - MessageIdStrategy messageIdStrategy, - WebServiceMessageSender[] messageSenders, - URI replyAction, - URI faultAction) { - Assert.notNull(version, "version must not be null"); - Assert.notNull(messageIdStrategy, "messageIdStrategy must not be null"); - Assert.notNull(messageSenders, "'messageSenders' must not be null"); - this.version = version; - this.messageIdStrategy = messageIdStrategy; - this.messageSenders = messageSenders; - this.replyAction = replyAction; - this.faultAction = faultAction; - } + AddressingEndpointInterceptor(AddressingVersion version, + MessageIdStrategy messageIdStrategy, + WebServiceMessageSender[] messageSenders, + URI replyAction, + URI faultAction) { + Assert.notNull(version, "version must not be null"); + Assert.notNull(messageIdStrategy, "messageIdStrategy must not be null"); + Assert.notNull(messageSenders, "'messageSenders' must not be null"); + this.version = version; + this.messageIdStrategy = messageIdStrategy; + this.messageSenders = messageSenders; + this.replyAction = replyAction; + this.faultAction = faultAction; + } - @Override - public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - SoapMessage request = (SoapMessage) messageContext.getRequest(); - MessageAddressingProperties requestMap = version.getMessageAddressingProperties(request); - if (!version.hasRequiredProperties(requestMap)) { - version.addMessageAddressingHeaderRequiredFault((SoapMessage) messageContext.getResponse()); - return false; - } - if (messageIdStrategy.isDuplicate(requestMap.getMessageId())) { - version.addInvalidAddressingHeaderFault((SoapMessage) messageContext.getResponse()); - return false; - } - return true; - } + @Override + public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + SoapMessage request = (SoapMessage) messageContext.getRequest(); + MessageAddressingProperties requestMap = version.getMessageAddressingProperties(request); + if (!version.hasRequiredProperties(requestMap)) { + version.addMessageAddressingHeaderRequiredFault((SoapMessage) messageContext.getResponse()); + return false; + } + if (messageIdStrategy.isDuplicate(requestMap.getMessageId())) { + version.addInvalidAddressingHeaderFault((SoapMessage) messageContext.getResponse()); + return false; + } + return true; + } - @Override - public final boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { - return handleResponseOrFault(messageContext, false); - } + @Override + public final boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { + return handleResponseOrFault(messageContext, false); + } - @Override - public final boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return handleResponseOrFault(messageContext, true); - } + @Override + public final boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { + return handleResponseOrFault(messageContext, true); + } - private boolean handleResponseOrFault(MessageContext messageContext, boolean isFault) throws Exception { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse()); - MessageAddressingProperties requestMap = - version.getMessageAddressingProperties((SoapMessage) messageContext.getRequest()); - EndpointReference replyEpr = !isFault ? requestMap.getReplyTo() : requestMap.getFaultTo(); - if (handleNoneAddress(messageContext, replyEpr)) { - return false; - } - SoapMessage reply = (SoapMessage) messageContext.getResponse(); - URI replyMessageId = getMessageId(reply); - URI action = isFault ? faultAction : replyAction; - MessageAddressingProperties replyMap = requestMap.getReplyProperties(replyEpr, action, replyMessageId); - version.addAddressingHeaders(reply, replyMap); - if (handleAnonymousAddress(messageContext, replyEpr)) { - return true; - } - else { - sendOutOfBand(messageContext, replyEpr); - return false; - } - } + private boolean handleResponseOrFault(MessageContext messageContext, boolean isFault) throws Exception { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse()); + MessageAddressingProperties requestMap = + version.getMessageAddressingProperties((SoapMessage) messageContext.getRequest()); + EndpointReference replyEpr = !isFault ? requestMap.getReplyTo() : requestMap.getFaultTo(); + if (handleNoneAddress(messageContext, replyEpr)) { + return false; + } + SoapMessage reply = (SoapMessage) messageContext.getResponse(); + URI replyMessageId = getMessageId(reply); + URI action = isFault ? faultAction : replyAction; + MessageAddressingProperties replyMap = requestMap.getReplyProperties(replyEpr, action, replyMessageId); + version.addAddressingHeaders(reply, replyMap); + if (handleAnonymousAddress(messageContext, replyEpr)) { + return true; + } + else { + sendOutOfBand(messageContext, replyEpr); + return false; + } + } - private boolean handleNoneAddress(MessageContext messageContext, EndpointReference replyEpr) { - if (replyEpr == null || version.hasNoneAddress(replyEpr)) { - if (logger.isDebugEnabled()) { - logger.debug( - "Request [" + messageContext.getRequest() + "] has [" + replyEpr + "] reply address; reply [" + - messageContext.getResponse() + "] discarded"); - } - messageContext.clearResponse(); - return true; - } - return false; - } + private boolean handleNoneAddress(MessageContext messageContext, EndpointReference replyEpr) { + if (replyEpr == null || version.hasNoneAddress(replyEpr)) { + if (logger.isDebugEnabled()) { + logger.debug( + "Request [" + messageContext.getRequest() + "] has [" + replyEpr + "] reply address; reply [" + + messageContext.getResponse() + "] discarded"); + } + messageContext.clearResponse(); + return true; + } + return false; + } - private boolean handleAnonymousAddress(MessageContext messageContext, EndpointReference replyEpr) { - if (version.hasAnonymousAddress(replyEpr)) { - if (logger.isDebugEnabled()) { - logger.debug("Request [" + messageContext.getRequest() + "] has [" + replyEpr + - "] reply address; sending in-band reply [" + messageContext.getResponse() + "]"); - } - return true; - } - return false; - } + private boolean handleAnonymousAddress(MessageContext messageContext, EndpointReference replyEpr) { + if (version.hasAnonymousAddress(replyEpr)) { + if (logger.isDebugEnabled()) { + logger.debug("Request [" + messageContext.getRequest() + "] has [" + replyEpr + + "] reply address; sending in-band reply [" + messageContext.getResponse() + "]"); + } + return true; + } + return false; + } - private void sendOutOfBand(MessageContext messageContext, EndpointReference replyEpr) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("Request [" + messageContext.getRequest() + "] has [" + replyEpr + - "] reply address; sending out-of-band reply [" + messageContext.getResponse() + "]"); - } + private void sendOutOfBand(MessageContext messageContext, EndpointReference replyEpr) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("Request [" + messageContext.getRequest() + "] has [" + replyEpr + + "] reply address; sending out-of-band reply [" + messageContext.getResponse() + "]"); + } - boolean supported = false; - for (WebServiceMessageSender messageSender : messageSenders) { - if (messageSender.supports(replyEpr.getAddress())) { - supported = true; - WebServiceConnection connection = null; - try { - connection = messageSender.createConnection(replyEpr.getAddress()); - connection.send(messageContext.getResponse()); - break; - } - finally { - messageContext.clearResponse(); - if (connection != null) { - connection.close(); - } - } - } - } - if (!supported && logger.isWarnEnabled()) { - logger.warn("Could not send out-of-band response to [" + replyEpr.getAddress() + "]. " + - "Configure WebServiceMessageSenders which support this uri."); - } - } + boolean supported = false; + for (WebServiceMessageSender messageSender : messageSenders) { + if (messageSender.supports(replyEpr.getAddress())) { + supported = true; + WebServiceConnection connection = null; + try { + connection = messageSender.createConnection(replyEpr.getAddress()); + connection.send(messageContext.getResponse()); + break; + } + finally { + messageContext.clearResponse(); + if (connection != null) { + connection.close(); + } + } + } + } + if (!supported && logger.isWarnEnabled()) { + logger.warn("Could not send out-of-band response to [" + replyEpr.getAddress() + "]. " + + "Configure WebServiceMessageSenders which support this uri."); + } + } - private URI getMessageId(SoapMessage response) { - URI responseMessageId = messageIdStrategy.newMessageId(response); - if (logger.isTraceEnabled()) { - logger.trace("Generated reply MessageID [" + responseMessageId + "] for [" + response + "]"); - } - return responseMessageId; - } + private URI getMessageId(SoapMessage response) { + URI responseMessageId = messageIdStrategy.newMessageId(response); + if (logger.isTraceEnabled()) { + logger.trace("Generated reply MessageID [" + responseMessageId + "] for [" + response + "]"); + } + return responseMessageId; + } - @Override - public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) { - } + @Override + public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) { + } - @Override - public boolean understands(SoapHeaderElement header) { - return version.understands(header); - } + @Override + public boolean understands(SoapHeaderElement header) { + return version.understands(header); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AnnotationActionEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AnnotationActionEndpointMapping.java index 941f1b1d..52cdac7c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AnnotationActionEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/AnnotationActionEndpointMapping.java @@ -41,10 +41,10 @@ import org.springframework.ws.soap.addressing.server.annotation.Address; * @Endpoint * @Address("mailto:joe@fabrikam123.example") * public class MyEndpoint{ - * @Action("http://fabrikam123.example/mail/Delete") - * public Source doSomethingWithRequest() { - * ... - * } + * @Action("http://fabrikam123.example/mail/Delete") + * public Source doSomethingWithRequest() { + * ... + * } * } * * @@ -59,96 +59,96 @@ import org.springframework.ws.soap.addressing.server.annotation.Address; */ public class AnnotationActionEndpointMapping extends AbstractActionMethodEndpointMapping implements BeanPostProcessor { - /** Returns the 'endpoint' annotation type. Default is {@link Endpoint}. */ - protected Class getEndpointAnnotationType() { - return Endpoint.class; - } + /** Returns the 'endpoint' annotation type. Default is {@link Endpoint}. */ + protected Class getEndpointAnnotationType() { + return Endpoint.class; + } - /** - * Returns the action value for the specified method. Default implementation looks for the {@link Action} annotation - * value. - */ - @Override - protected URI getActionForMethod(Method method) { - Action action = method.getAnnotation(Action.class); - if (action != null && StringUtils.hasText(action.value())) { - try { - return new URI(action.value()); - } - catch (URISyntaxException e) { - throw new IllegalArgumentException( - "Invalid Action annotation [" + action.value() + "] on [" + method + "]"); - } - } - return null; - } + /** + * Returns the action value for the specified method. Default implementation looks for the {@link Action} annotation + * value. + */ + @Override + protected URI getActionForMethod(Method method) { + Action action = method.getAnnotation(Action.class); + if (action != null && StringUtils.hasText(action.value())) { + try { + return new URI(action.value()); + } + catch (URISyntaxException e) { + throw new IllegalArgumentException( + "Invalid Action annotation [" + action.value() + "] on [" + method + "]"); + } + } + return null; + } - /** - * Returns the address property of the given {@link MethodEndpoint}, by looking for the {@link Address} annotation. - * The value of this property should match the {@link org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getTo() - * destination} of incoming messages. Returns {@code null} if the anotation is not present, thus ignoring the - * destination property. - * - * @param endpoint the method endpoint to return the address for - * @return the endpoint address; or {@code null} to ignore the destination property - */ - @Override - protected URI getEndpointAddress(Object endpoint) { - MethodEndpoint methodEndpoint = (MethodEndpoint) endpoint; - Class endpointClass = methodEndpoint.getMethod().getDeclaringClass(); - Address address = AnnotationUtils.findAnnotation(endpointClass, Address.class); - if (address != null && StringUtils.hasText(address.value())) { - return getActionUri(address.value(), methodEndpoint); - } - else { - return null; - } - } + /** + * Returns the address property of the given {@link MethodEndpoint}, by looking for the {@link Address} annotation. + * The value of this property should match the {@link org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getTo() + * destination} of incoming messages. Returns {@code null} if the anotation is not present, thus ignoring the + * destination property. + * + * @param endpoint the method endpoint to return the address for + * @return the endpoint address; or {@code null} to ignore the destination property + */ + @Override + protected URI getEndpointAddress(Object endpoint) { + MethodEndpoint methodEndpoint = (MethodEndpoint) endpoint; + Class endpointClass = methodEndpoint.getMethod().getDeclaringClass(); + Address address = AnnotationUtils.findAnnotation(endpointClass, Address.class); + if (address != null && StringUtils.hasText(address.value())) { + return getActionUri(address.value(), methodEndpoint); + } + else { + return null; + } + } - @Override - protected URI getResponseAction(Object endpoint, MessageAddressingProperties map) { - MethodEndpoint methodEndpoint = (MethodEndpoint) endpoint; - Action action = methodEndpoint.getMethod().getAnnotation(Action.class); - if (action != null && StringUtils.hasText(action.output())) { - return getActionUri(action.output(), methodEndpoint); - } - else { - return super.getResponseAction(endpoint, map); - } - } + @Override + protected URI getResponseAction(Object endpoint, MessageAddressingProperties map) { + MethodEndpoint methodEndpoint = (MethodEndpoint) endpoint; + Action action = methodEndpoint.getMethod().getAnnotation(Action.class); + if (action != null && StringUtils.hasText(action.output())) { + return getActionUri(action.output(), methodEndpoint); + } + else { + return super.getResponseAction(endpoint, map); + } + } - @Override - protected URI getFaultAction(Object endpoint, MessageAddressingProperties map) { - MethodEndpoint methodEndpoint = (MethodEndpoint) endpoint; - Action action = methodEndpoint.getMethod().getAnnotation(Action.class); - if (action != null && StringUtils.hasText(action.fault())) { - return getActionUri(action.fault(), methodEndpoint); - } - else { - return super.getResponseAction(endpoint, map); - } - } + @Override + protected URI getFaultAction(Object endpoint, MessageAddressingProperties map) { + MethodEndpoint methodEndpoint = (MethodEndpoint) endpoint; + Action action = methodEndpoint.getMethod().getAnnotation(Action.class); + if (action != null && StringUtils.hasText(action.fault())) { + return getActionUri(action.fault(), methodEndpoint); + } + else { + return super.getResponseAction(endpoint, map); + } + } - private URI getActionUri(String action, MethodEndpoint methodEndpoint) { - try { - return new URI(action); - } - catch (URISyntaxException e) { - throw new IllegalArgumentException( - "Invalid Action annotation [" + action + "] on [" + methodEndpoint + "]"); - } - } + private URI getActionUri(String action, MethodEndpoint methodEndpoint) { + try { + return new URI(action); + } + catch (URISyntaxException e) { + throw new IllegalArgumentException( + "Invalid Action annotation [" + action + "] on [" + methodEndpoint + "]"); + } + } - @Override - public final Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - return bean; - } + @Override + public final Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + return bean; + } - @Override - public final Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (AopUtils.getTargetClass(bean).getAnnotation(getEndpointAnnotationType()) != null) { - registerMethods(bean); - } - return bean; - } + @Override + public final Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (AopUtils.getTargetClass(bean).getAnnotation(getEndpointAnnotationType()) != null) { + registerMethods(bean); + } + return bean; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMapping.java index 4470dcd4..118e9c22 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMapping.java @@ -50,87 +50,87 @@ import org.springframework.beans.BeansException; */ public class SimpleActionEndpointMapping extends AbstractActionEndpointMapping { - // contents will be copied over to endpointMap - private final Map actionMap = new HashMap(); + // contents will be copied over to endpointMap + private final Map actionMap = new HashMap(); - private URI address; + private URI address; - /** - * Map action URIs to endpoint bean names. This is the typical way of configuring this EndpointMapping. - * - * @param mappings properties with URLs as keys and bean names as values - * @see #setActionMap(java.util.Map) - */ - public void setMappings(Properties mappings) throws URISyntaxException { - setActionMap(mappings); - } + /** + * Map action URIs to endpoint bean names. This is the typical way of configuring this EndpointMapping. + * + * @param mappings properties with URLs as keys and bean names as values + * @see #setActionMap(java.util.Map) + */ + public void setMappings(Properties mappings) throws URISyntaxException { + setActionMap(mappings); + } - /** - * Set a Map with action URIs as keys and handler beans (or handler bean names) as values. Convenient for population - * with bean references. - * - * @param actionMap map with action URIs as keys and beans as values - * @see #setMappings - */ - public void setActionMap(Map actionMap) throws URISyntaxException { - for (Map.Entry entry : actionMap.entrySet()) { - URI action; - if (entry.getKey() instanceof String) { - action = new URI((String) entry.getKey()); - } - else if (entry.getKey() instanceof URI) { - action = (URI) entry.getKey(); - } - else { - throw new IllegalArgumentException("Invalid key [" + entry.getKey() + "]; expected String or URI"); - } - this.actionMap.put(action, entry.getValue()); - } - } + /** + * Set a Map with action URIs as keys and handler beans (or handler bean names) as values. Convenient for population + * with bean references. + * + * @param actionMap map with action URIs as keys and beans as values + * @see #setMappings + */ + public void setActionMap(Map actionMap) throws URISyntaxException { + for (Map.Entry entry : actionMap.entrySet()) { + URI action; + if (entry.getKey() instanceof String) { + action = new URI((String) entry.getKey()); + } + else if (entry.getKey() instanceof URI) { + action = (URI) entry.getKey(); + } + else { + throw new IllegalArgumentException("Invalid key [" + entry.getKey() + "]; expected String or URI"); + } + this.actionMap.put(action, entry.getValue()); + } + } - /** - * Set the address property. If set, value of this property is compared to the {@link - * org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getTo() destination} property of the - * incominging message. - * - * @param address the address URI - */ - public void setAddress(URI address) { - this.address = address; - } + /** + * Set the address property. If set, value of this property is compared to the {@link + * org.springframework.ws.soap.addressing.core.MessageAddressingProperties#getTo() destination} property of the + * incominging message. + * + * @param address the address URI + */ + public void setAddress(URI address) { + this.address = address; + } - @Override - public void afterPropertiesSet() throws Exception { - super.afterPropertiesSet(); - registerEndpoints(actionMap); - } + @Override + public void afterPropertiesSet() throws Exception { + super.afterPropertiesSet(); + registerEndpoints(actionMap); + } - /** - * Register all endpoints specified in the action map. - * - * @param actionMap Map with action URIs as keys and endppint beans or bean names as values - * @throws BeansException if an endpoint couldn't be registered - * @throws IllegalStateException if there is a conflicting endpoint registered - */ - protected void registerEndpoints(Map actionMap) throws BeansException { - if (actionMap.isEmpty()) { - logger.warn("Neither 'actionMap' nor 'mappings' set on SimpleActionEndpointMapping"); - } - else { - for (Map.Entry entry : actionMap.entrySet()) { - URI action = entry.getKey(); - Object endpoint = entry.getValue(); - // Remove whitespace from endpoint bean name. - if (endpoint instanceof String) { - endpoint = ((String) endpoint).trim(); - } - registerEndpoint(action, endpoint); - } - } - } + /** + * Register all endpoints specified in the action map. + * + * @param actionMap Map with action URIs as keys and endppint beans or bean names as values + * @throws BeansException if an endpoint couldn't be registered + * @throws IllegalStateException if there is a conflicting endpoint registered + */ + protected void registerEndpoints(Map actionMap) throws BeansException { + if (actionMap.isEmpty()) { + logger.warn("Neither 'actionMap' nor 'mappings' set on SimpleActionEndpointMapping"); + } + else { + for (Map.Entry entry : actionMap.entrySet()) { + URI action = entry.getKey(); + Object endpoint = entry.getValue(); + // Remove whitespace from endpoint bean name. + if (endpoint instanceof String) { + endpoint = ((String) endpoint).trim(); + } + registerEndpoint(action, endpoint); + } + } + } - @Override - protected URI getEndpointAddress(Object endpoint) { - return address; - } + @Override + protected URI getEndpointAddress(Object endpoint) { + return address; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AbstractAddressingVersion.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AbstractAddressingVersion.java index 092d491b..969895ad 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AbstractAddressingVersion.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AbstractAddressingVersion.java @@ -62,376 +62,376 @@ import org.springframework.xml.xpath.XPathExpressionFactory; */ public abstract class AbstractAddressingVersion extends TransformerObjectSupport implements AddressingVersion { - private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - private final XPathExpression toExpression; + private final XPathExpression toExpression; - private final XPathExpression actionExpression; + private final XPathExpression actionExpression; - private final XPathExpression messageIdExpression; + private final XPathExpression messageIdExpression; - private final XPathExpression fromExpression; + private final XPathExpression fromExpression; - private final XPathExpression replyToExpression; + private final XPathExpression replyToExpression; - private final XPathExpression faultToExpression; + private final XPathExpression faultToExpression; - private final XPathExpression addressExpression; + private final XPathExpression addressExpression; - private final XPathExpression referencePropertiesExpression; + private final XPathExpression referencePropertiesExpression; - private final XPathExpression referenceParametersExpression; + private final XPathExpression referenceParametersExpression; - protected AbstractAddressingVersion() { - Map namespaces = new HashMap(); - namespaces.put(getNamespacePrefix(), getNamespaceUri()); - toExpression = createNormalizedExpression(getToName(), namespaces); - actionExpression = createNormalizedExpression(getActionName(), namespaces); - messageIdExpression = createNormalizedExpression(getMessageIdName(), namespaces); - fromExpression = createExpression(getFromName(), namespaces); - replyToExpression = createExpression(getReplyToName(), namespaces); - faultToExpression = createExpression(getFaultToName(), namespaces); - addressExpression = createNormalizedExpression(getAddressName(), namespaces); - if (getReferencePropertiesName() != null) { - referencePropertiesExpression = createChildrenExpression(getReferencePropertiesName(), namespaces); - } - else { - referencePropertiesExpression = null; - } - if (getReferenceParametersName() != null) { - referenceParametersExpression = createChildrenExpression(getReferenceParametersName(), namespaces); - } - else { - referenceParametersExpression = null; - } - } + protected AbstractAddressingVersion() { + Map namespaces = new HashMap(); + namespaces.put(getNamespacePrefix(), getNamespaceUri()); + toExpression = createNormalizedExpression(getToName(), namespaces); + actionExpression = createNormalizedExpression(getActionName(), namespaces); + messageIdExpression = createNormalizedExpression(getMessageIdName(), namespaces); + fromExpression = createExpression(getFromName(), namespaces); + replyToExpression = createExpression(getReplyToName(), namespaces); + faultToExpression = createExpression(getFaultToName(), namespaces); + addressExpression = createNormalizedExpression(getAddressName(), namespaces); + if (getReferencePropertiesName() != null) { + referencePropertiesExpression = createChildrenExpression(getReferencePropertiesName(), namespaces); + } + else { + referencePropertiesExpression = null; + } + if (getReferenceParametersName() != null) { + referenceParametersExpression = createChildrenExpression(getReferenceParametersName(), namespaces); + } + else { + referenceParametersExpression = null; + } + } - private XPathExpression createExpression(QName name, Map namespaces) { - String expression = name.getPrefix() + ":" + name.getLocalPart(); - return XPathExpressionFactory.createXPathExpression(expression, namespaces); - } + private XPathExpression createExpression(QName name, Map namespaces) { + String expression = name.getPrefix() + ":" + name.getLocalPart(); + return XPathExpressionFactory.createXPathExpression(expression, namespaces); + } - private XPathExpression createNormalizedExpression(QName name, Map namespaces) { - String expression = "normalize-space(" + name.getPrefix() + ":" + name.getLocalPart() + ")"; - return XPathExpressionFactory.createXPathExpression(expression, namespaces); - } + private XPathExpression createNormalizedExpression(QName name, Map namespaces) { + String expression = "normalize-space(" + name.getPrefix() + ":" + name.getLocalPart() + ")"; + return XPathExpressionFactory.createXPathExpression(expression, namespaces); + } - private XPathExpression createChildrenExpression(QName name, Map namespaces) { - String expression = name.getPrefix() + ":" + name.getLocalPart() + "/*"; - return XPathExpressionFactory.createXPathExpression(expression, namespaces); - } + private XPathExpression createChildrenExpression(QName name, Map namespaces) { + String expression = name.getPrefix() + ":" + name.getLocalPart() + "/*"; + return XPathExpressionFactory.createXPathExpression(expression, namespaces); + } - @Override - public MessageAddressingProperties getMessageAddressingProperties(SoapMessage message) { - Element headerElement = getSoapHeaderElement(message); - URI to = getUri(headerElement, toExpression); - if (to == null) { - to = getDefaultTo(); - } - EndpointReference from = getEndpointReference(fromExpression.evaluateAsNode(headerElement)); - EndpointReference replyTo = getEndpointReference(replyToExpression.evaluateAsNode(headerElement)); - if (replyTo == null) { - replyTo = getDefaultReplyTo(from); - } - EndpointReference faultTo = getEndpointReference(faultToExpression.evaluateAsNode(headerElement)); - if (faultTo == null) { - faultTo = replyTo; - } - URI action = getUri(headerElement, actionExpression); - URI messageId = getUri(headerElement, messageIdExpression); - return new MessageAddressingProperties(to, from, replyTo, faultTo, action, messageId); - } + @Override + public MessageAddressingProperties getMessageAddressingProperties(SoapMessage message) { + Element headerElement = getSoapHeaderElement(message); + URI to = getUri(headerElement, toExpression); + if (to == null) { + to = getDefaultTo(); + } + EndpointReference from = getEndpointReference(fromExpression.evaluateAsNode(headerElement)); + EndpointReference replyTo = getEndpointReference(replyToExpression.evaluateAsNode(headerElement)); + if (replyTo == null) { + replyTo = getDefaultReplyTo(from); + } + EndpointReference faultTo = getEndpointReference(faultToExpression.evaluateAsNode(headerElement)); + if (faultTo == null) { + faultTo = replyTo; + } + URI action = getUri(headerElement, actionExpression); + URI messageId = getUri(headerElement, messageIdExpression); + return new MessageAddressingProperties(to, from, replyTo, faultTo, action, messageId); + } - private URI getUri(Node node, XPathExpression expression) { - String messageId = expression.evaluateAsString(node); - if (!StringUtils.hasLength(messageId)) { - return null; - } - try { - return new URI(messageId); - } - catch (URISyntaxException e) { - return null; - } - } + private URI getUri(Node node, XPathExpression expression) { + String messageId = expression.evaluateAsString(node); + if (!StringUtils.hasLength(messageId)) { + return null; + } + try { + return new URI(messageId); + } + catch (URISyntaxException e) { + return null; + } + } - private Element getSoapHeaderElement(SoapMessage message) { - Source source = message.getSoapHeader().getSource(); - if (source instanceof DOMSource) { - DOMSource domSource = (DOMSource) source; - if (domSource.getNode() != null && domSource.getNode().getNodeType() == Node.ELEMENT_NODE) { - return (Element) domSource.getNode(); - } - } - try { - DOMResult domResult = new DOMResult(); - transform(source, domResult); - Document document = (Document) domResult.getNode(); - return document.getDocumentElement(); - } - catch (TransformerException ex) { - throw new AddressingException("Could not transform SoapHeader to Document", ex); - } - } + private Element getSoapHeaderElement(SoapMessage message) { + Source source = message.getSoapHeader().getSource(); + if (source instanceof DOMSource) { + DOMSource domSource = (DOMSource) source; + if (domSource.getNode() != null && domSource.getNode().getNodeType() == Node.ELEMENT_NODE) { + return (Element) domSource.getNode(); + } + } + try { + DOMResult domResult = new DOMResult(); + transform(source, domResult); + Document document = (Document) domResult.getNode(); + return document.getDocumentElement(); + } + catch (TransformerException ex) { + throw new AddressingException("Could not transform SoapHeader to Document", ex); + } + } - /** Given a ReplyTo, FaultTo, or From node, returns an endpoint reference. */ - private EndpointReference getEndpointReference(Node node) { - if (node == null) { - return null; - } - URI address = getUri(node, addressExpression); - if (address == null) { - return null; - } - List referenceProperties = - referencePropertiesExpression != null ? referencePropertiesExpression.evaluateAsNodeList(node) : - Collections.emptyList(); - List referenceParameters = - referenceParametersExpression != null ? referenceParametersExpression.evaluateAsNodeList(node) : - Collections.emptyList(); - return new EndpointReference(address, referenceProperties, referenceParameters); - } + /** Given a ReplyTo, FaultTo, or From node, returns an endpoint reference. */ + private EndpointReference getEndpointReference(Node node) { + if (node == null) { + return null; + } + URI address = getUri(node, addressExpression); + if (address == null) { + return null; + } + List referenceProperties = + referencePropertiesExpression != null ? referencePropertiesExpression.evaluateAsNodeList(node) : + Collections.emptyList(); + List referenceParameters = + referenceParametersExpression != null ? referenceParametersExpression.evaluateAsNodeList(node) : + Collections.emptyList(); + return new EndpointReference(address, referenceProperties, referenceParameters); + } - @Override - public void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) { - SoapHeader header = message.getSoapHeader(); - header.addNamespaceDeclaration(getNamespacePrefix(), getNamespaceUri()); - // To - if (map.getTo() != null) { - SoapHeaderElement to = header.addHeaderElement(getToName()); - to.setText(map.getTo().toString()); - to.setMustUnderstand(true); - } - // From - if (map.getFrom() != null) { - SoapHeaderElement from = header.addHeaderElement(getFromName()); - addEndpointReference(from, map.getFrom()); - } - //ReplyTo - if (map.getReplyTo() != null) { - SoapHeaderElement replyTo = header.addHeaderElement(getReplyToName()); - addEndpointReference(replyTo, map.getReplyTo()); - } - // FaultTo - if (map.getFaultTo() != null) { - SoapHeaderElement faultTo = header.addHeaderElement(getFaultToName()); - addEndpointReference(faultTo, map.getFaultTo()); - } - // Action - SoapHeaderElement action = header.addHeaderElement(getActionName()); - action.setText(map.getAction().toString()); - // MessageID - if (map.getMessageId() != null) { - SoapHeaderElement messageId = header.addHeaderElement(getMessageIdName()); - messageId.setText(map.getMessageId().toString()); - } - // RelatesTo - if (map.getRelatesTo() != null) { - SoapHeaderElement relatesTo = header.addHeaderElement(getRelatesToName()); - relatesTo.setText(map.getRelatesTo().toString()); - } - addReferenceNodes(header.getResult(), map.getReferenceParameters()); - addReferenceNodes(header.getResult(), map.getReferenceProperties()); - } + @Override + public void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) { + SoapHeader header = message.getSoapHeader(); + header.addNamespaceDeclaration(getNamespacePrefix(), getNamespaceUri()); + // To + if (map.getTo() != null) { + SoapHeaderElement to = header.addHeaderElement(getToName()); + to.setText(map.getTo().toString()); + to.setMustUnderstand(true); + } + // From + if (map.getFrom() != null) { + SoapHeaderElement from = header.addHeaderElement(getFromName()); + addEndpointReference(from, map.getFrom()); + } + //ReplyTo + if (map.getReplyTo() != null) { + SoapHeaderElement replyTo = header.addHeaderElement(getReplyToName()); + addEndpointReference(replyTo, map.getReplyTo()); + } + // FaultTo + if (map.getFaultTo() != null) { + SoapHeaderElement faultTo = header.addHeaderElement(getFaultToName()); + addEndpointReference(faultTo, map.getFaultTo()); + } + // Action + SoapHeaderElement action = header.addHeaderElement(getActionName()); + action.setText(map.getAction().toString()); + // MessageID + if (map.getMessageId() != null) { + SoapHeaderElement messageId = header.addHeaderElement(getMessageIdName()); + messageId.setText(map.getMessageId().toString()); + } + // RelatesTo + if (map.getRelatesTo() != null) { + SoapHeaderElement relatesTo = header.addHeaderElement(getRelatesToName()); + relatesTo.setText(map.getRelatesTo().toString()); + } + addReferenceNodes(header.getResult(), map.getReferenceParameters()); + addReferenceNodes(header.getResult(), map.getReferenceProperties()); + } - @Override - public final boolean understands(SoapHeaderElement headerElement) { - return getNamespaceUri().equals(headerElement.getName().getNamespaceURI()); - } + @Override + public final boolean understands(SoapHeaderElement headerElement) { + return getNamespaceUri().equals(headerElement.getName().getNamespaceURI()); + } - /** Adds ReplyTo, FaultTo, or From EPR to the given header Element. */ - protected void addEndpointReference(SoapHeaderElement headerElement, EndpointReference epr) { - if (epr == null || epr.getAddress() == null) { - return; - } - try { - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - Element address = document.createElementNS(getNamespaceUri(), QNameUtils.toQualifiedName(getAddressName())); - address.setTextContent(epr.getAddress().toString()); - transform(new DOMSource(address), headerElement.getResult()); - if (getReferenceParametersName() != null && !epr.getReferenceParameters().isEmpty()) { - Element referenceParams = document.createElementNS(getNamespaceUri(), - QNameUtils.toQualifiedName(getReferenceParametersName())); - addReferenceNodes(new DOMResult(referenceParams), epr.getReferenceParameters()); - transform(new DOMSource(referenceParams), headerElement.getResult()); - } - if (getReferencePropertiesName() != null && !epr.getReferenceProperties().isEmpty()) { - Element referenceProps = document.createElementNS(getNamespaceUri(), - QNameUtils.toQualifiedName(getReferencePropertiesName())); - addReferenceNodes(new DOMResult(referenceProps), epr.getReferenceProperties()); - transform(new DOMSource(referenceProps), headerElement.getResult()); - } - } - catch (ParserConfigurationException ex) { - throw new AddressingException("Could not add Endpoint Reference [" + epr + "] to header element", ex); - } - catch (TransformerException ex) { - throw new AddressingException("Could not add reference properties/parameters to message", ex); - } - } + /** Adds ReplyTo, FaultTo, or From EPR to the given header Element. */ + protected void addEndpointReference(SoapHeaderElement headerElement, EndpointReference epr) { + if (epr == null || epr.getAddress() == null) { + return; + } + try { + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + Element address = document.createElementNS(getNamespaceUri(), QNameUtils.toQualifiedName(getAddressName())); + address.setTextContent(epr.getAddress().toString()); + transform(new DOMSource(address), headerElement.getResult()); + if (getReferenceParametersName() != null && !epr.getReferenceParameters().isEmpty()) { + Element referenceParams = document.createElementNS(getNamespaceUri(), + QNameUtils.toQualifiedName(getReferenceParametersName())); + addReferenceNodes(new DOMResult(referenceParams), epr.getReferenceParameters()); + transform(new DOMSource(referenceParams), headerElement.getResult()); + } + if (getReferencePropertiesName() != null && !epr.getReferenceProperties().isEmpty()) { + Element referenceProps = document.createElementNS(getNamespaceUri(), + QNameUtils.toQualifiedName(getReferencePropertiesName())); + addReferenceNodes(new DOMResult(referenceProps), epr.getReferenceProperties()); + transform(new DOMSource(referenceProps), headerElement.getResult()); + } + } + catch (ParserConfigurationException ex) { + throw new AddressingException("Could not add Endpoint Reference [" + epr + "] to header element", ex); + } + catch (TransformerException ex) { + throw new AddressingException("Could not add reference properties/parameters to message", ex); + } + } - protected void addReferenceNodes(Result result, List nodes) { - try { - for (Node node : nodes) { - DOMSource source = new DOMSource(node); - transform(source, result); - } - } - catch (TransformerException ex) { - throw new AddressingException("Could not add reference properties/parameters to message", ex); - } - } + protected void addReferenceNodes(Result result, List nodes) { + try { + for (Node node : nodes) { + DOMSource source = new DOMSource(node); + transform(source, result); + } + } + catch (TransformerException ex) { + throw new AddressingException("Could not add reference properties/parameters to message", ex); + } + } - @Override - public final SoapFault addInvalidAddressingHeaderFault(SoapMessage message) { - return addAddressingFault(message, getInvalidAddressingHeaderFaultSubcode(), - getInvalidAddressingHeaderFaultReason()); - } + @Override + public final SoapFault addInvalidAddressingHeaderFault(SoapMessage message) { + return addAddressingFault(message, getInvalidAddressingHeaderFaultSubcode(), + getInvalidAddressingHeaderFaultReason()); + } - @Override - public final SoapFault addMessageAddressingHeaderRequiredFault(SoapMessage message) { - return addAddressingFault(message, getMessageAddressingHeaderRequiredFaultSubcode(), - getMessageAddressingHeaderRequiredFaultReason()); - } + @Override + public final SoapFault addMessageAddressingHeaderRequiredFault(SoapMessage message) { + return addAddressingFault(message, getMessageAddressingHeaderRequiredFaultSubcode(), + getMessageAddressingHeaderRequiredFaultReason()); + } - private SoapFault addAddressingFault(SoapMessage message, QName subcode, String reason) { - if (message.getSoapBody() instanceof Soap11Body) { - Soap11Body soapBody = (Soap11Body) message.getSoapBody(); - return soapBody.addFault(subcode, reason, Locale.ENGLISH); - } - else if (message.getSoapBody() instanceof Soap12Body) { - Soap12Body soapBody = (Soap12Body) message.getSoapBody(); - Soap12Fault soapFault = - soapBody.addClientOrSenderFault(reason, Locale.ENGLISH); - soapFault.addFaultSubcode(subcode); - return soapFault; - } - return null; - } + private SoapFault addAddressingFault(SoapMessage message, QName subcode, String reason) { + if (message.getSoapBody() instanceof Soap11Body) { + Soap11Body soapBody = (Soap11Body) message.getSoapBody(); + return soapBody.addFault(subcode, reason, Locale.ENGLISH); + } + else if (message.getSoapBody() instanceof Soap12Body) { + Soap12Body soapBody = (Soap12Body) message.getSoapBody(); + Soap12Fault soapFault = + soapBody.addClientOrSenderFault(reason, Locale.ENGLISH); + soapFault.addFaultSubcode(subcode); + return soapFault; + } + return null; + } - /* - * Address URIs - */ + /* + * Address URIs + */ - @Override - public final boolean hasAnonymousAddress(EndpointReference epr) { - URI anonymous = getAnonymous(); - return anonymous != null && anonymous.equals(epr.getAddress()); - } + @Override + public final boolean hasAnonymousAddress(EndpointReference epr) { + URI anonymous = getAnonymous(); + return anonymous != null && anonymous.equals(epr.getAddress()); + } - @Override - public final boolean hasNoneAddress(EndpointReference epr) { - URI none = getNone(); - return none != null && none.equals(epr.getAddress()); - } + @Override + public final boolean hasNoneAddress(EndpointReference epr) { + URI none = getNone(); + return none != null && none.equals(epr.getAddress()); + } - /** Returns the prefix associated with the WS-Addressing namespace handled by this specification. */ - protected String getNamespacePrefix() { - return "wsa"; - } + /** Returns the prefix associated with the WS-Addressing namespace handled by this specification. */ + protected String getNamespacePrefix() { + return "wsa"; + } - /** Returns the WS-Addressing namespace handled by this specification. */ - protected abstract String getNamespaceUri(); + /** Returns the WS-Addressing namespace handled by this specification. */ + protected abstract String getNamespaceUri(); - /* - * Message addressing properties - */ + /* + * Message addressing properties + */ - /** Returns the qualified name of the {@code To} addressing header. */ - protected QName getToName() { - return new QName(getNamespaceUri(), "To", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code To} addressing header. */ + protected QName getToName() { + return new QName(getNamespaceUri(), "To", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code From} addressing header. */ - protected QName getFromName() { - return new QName(getNamespaceUri(), "From", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code From} addressing header. */ + protected QName getFromName() { + return new QName(getNamespaceUri(), "From", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code ReplyTo} addressing header. */ - protected QName getReplyToName() { - return new QName(getNamespaceUri(), "ReplyTo", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code ReplyTo} addressing header. */ + protected QName getReplyToName() { + return new QName(getNamespaceUri(), "ReplyTo", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code FaultTo} addressing header. */ - protected QName getFaultToName() { - return new QName(getNamespaceUri(), "FaultTo", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code FaultTo} addressing header. */ + protected QName getFaultToName() { + return new QName(getNamespaceUri(), "FaultTo", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code Action} addressing header. */ - protected QName getActionName() { - return new QName(getNamespaceUri(), "Action", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code Action} addressing header. */ + protected QName getActionName() { + return new QName(getNamespaceUri(), "Action", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code MessageID} addressing header. */ - protected QName getMessageIdName() { - return new QName(getNamespaceUri(), "MessageID", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code MessageID} addressing header. */ + protected QName getMessageIdName() { + return new QName(getNamespaceUri(), "MessageID", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code RelatesTo} addressing header. */ - protected QName getRelatesToName() { - return new QName(getNamespaceUri(), "RelatesTo", getNamespacePrefix()); - } + /** Returns the qualified name of the {@code RelatesTo} addressing header. */ + protected QName getRelatesToName() { + return new QName(getNamespaceUri(), "RelatesTo", getNamespacePrefix()); + } - /** Returns the qualified name of the {@code RelatesTo} addressing header. */ - protected QName getRelationshipTypeName() { - return new QName("RelationshipType"); - } + /** Returns the qualified name of the {@code RelatesTo} addressing header. */ + protected QName getRelationshipTypeName() { + return new QName("RelationshipType"); + } - /** - * Returns the qualified name of the {@code ReferenceProperties} in the endpoint reference. Returns - * {@code null} when reference properties are not supported by this version of the spec. - */ - protected QName getReferencePropertiesName() { - return new QName(getNamespaceUri(), "ReferenceProperties", getNamespacePrefix()); - } + /** + * Returns the qualified name of the {@code ReferenceProperties} in the endpoint reference. Returns + * {@code null} when reference properties are not supported by this version of the spec. + */ + protected QName getReferencePropertiesName() { + return new QName(getNamespaceUri(), "ReferenceProperties", getNamespacePrefix()); + } - /** - * Returns the qualified name of the {@code ReferenceParameters} in the endpoint reference. Returns - * {@code null} when reference parameters are not supported by this version of the spec. - */ - protected QName getReferenceParametersName() { - return new QName(getNamespaceUri(), "ReferenceParameters", getNamespacePrefix()); - } + /** + * Returns the qualified name of the {@code ReferenceParameters} in the endpoint reference. Returns + * {@code null} when reference parameters are not supported by this version of the spec. + */ + protected QName getReferenceParametersName() { + return new QName(getNamespaceUri(), "ReferenceParameters", getNamespacePrefix()); + } - /* - * Endpoint Reference - */ + /* + * Endpoint Reference + */ - /** The qualified name of the {@code Address} in {@code EndpointReference}. */ - protected QName getAddressName() { - return new QName(getNamespaceUri(), "Address", getNamespacePrefix()); - } + /** The qualified name of the {@code Address} in {@code EndpointReference}. */ + protected QName getAddressName() { + return new QName(getNamespaceUri(), "Address", getNamespacePrefix()); + } - /** Returns the default To URI. */ - protected abstract URI getDefaultTo(); + /** Returns the default To URI. */ + protected abstract URI getDefaultTo(); - /** Returns the default ReplyTo EPR. Can be based on the From EPR, or the anonymous URI. */ - protected abstract EndpointReference getDefaultReplyTo(EndpointReference from); + /** Returns the default ReplyTo EPR. Can be based on the From EPR, or the anonymous URI. */ + protected abstract EndpointReference getDefaultReplyTo(EndpointReference from); - /* - * Address URIs - */ + /* + * Address URIs + */ - /** Returns the anonymous URI. */ - protected abstract URI getAnonymous(); + /** Returns the anonymous URI. */ + protected abstract URI getAnonymous(); - /** Returns the none URI, or {@code null} if the spec does not define it. */ - protected abstract URI getNone(); + /** Returns the none URI, or {@code null} if the spec does not define it. */ + protected abstract URI getNone(); - /* - * Faults - */ + /* + * Faults + */ - /** Returns the qualified name of the fault subcode that indicates that a header is missing. */ - protected abstract QName getMessageAddressingHeaderRequiredFaultSubcode(); + /** Returns the qualified name of the fault subcode that indicates that a header is missing. */ + protected abstract QName getMessageAddressingHeaderRequiredFaultSubcode(); - /** Returns the reason of the fault that indicates that a header is missing. */ - protected abstract String getMessageAddressingHeaderRequiredFaultReason(); + /** Returns the reason of the fault that indicates that a header is missing. */ + protected abstract String getMessageAddressingHeaderRequiredFaultReason(); - /** Returns the qualified name of the fault subcode that indicates that a header is invalid. */ - protected abstract QName getInvalidAddressingHeaderFaultSubcode(); + /** Returns the qualified name of the fault subcode that indicates that a header is invalid. */ + protected abstract QName getInvalidAddressingHeaderFaultSubcode(); - /** Returns the reason of the fault that indicates that a header is invalid. */ - protected abstract String getInvalidAddressingHeaderFaultReason(); + /** Returns the reason of the fault that indicates that a header is invalid. */ + protected abstract String getInvalidAddressingHeaderFaultReason(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing10.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing10.java index 649578c0..6f6f487f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing10.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing10.java @@ -35,78 +35,78 @@ import org.springframework.ws.soap.addressing.core.MessageAddressingProperties; public class Addressing10 extends AbstractAddressingVersion { - private static final String NAMESPACE_URI = "http://www.w3.org/2005/08/addressing"; + private static final String NAMESPACE_URI = "http://www.w3.org/2005/08/addressing"; - @Override - public void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) { - Assert.notNull(map.getAction(), "'Action' is required"); - super.addAddressingHeaders(message, map); - } + @Override + public void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) { + Assert.notNull(map.getAction(), "'Action' is required"); + super.addAddressingHeaders(message, map); + } - @Override - public boolean hasRequiredProperties(MessageAddressingProperties map) { - if (map.getAction() == null) { - return false; - } - if (map.getReplyTo() != null || map.getFaultTo() != null) { - return map.getMessageId() != null; - } - return true; + @Override + public boolean hasRequiredProperties(MessageAddressingProperties map) { + if (map.getAction() == null) { + return false; + } + if (map.getReplyTo() != null || map.getFaultTo() != null) { + return map.getMessageId() != null; + } + return true; - } + } - @Override - protected String getNamespaceUri() { - return NAMESPACE_URI; - } + @Override + protected String getNamespaceUri() { + return NAMESPACE_URI; + } - @Override - protected QName getReferencePropertiesName() { - return null; - } + @Override + protected QName getReferencePropertiesName() { + return null; + } - @Override - protected URI getDefaultTo() { - return getAnonymous(); - } + @Override + protected URI getDefaultTo() { + return getAnonymous(); + } - @Override - protected EndpointReference getDefaultReplyTo(EndpointReference from) { - return new EndpointReference(getAnonymous()); - } + @Override + protected EndpointReference getDefaultReplyTo(EndpointReference from) { + return new EndpointReference(getAnonymous()); + } - @Override - protected final URI getAnonymous() { - return URI.create(NAMESPACE_URI + "/anonymous"); - } + @Override + protected final URI getAnonymous() { + return URI.create(NAMESPACE_URI + "/anonymous"); + } - @Override - protected final URI getNone() { - return URI.create(NAMESPACE_URI + "/none"); - } + @Override + protected final URI getNone() { + return URI.create(NAMESPACE_URI + "/none"); + } - @Override - protected final QName getMessageAddressingHeaderRequiredFaultSubcode() { - return new QName(NAMESPACE_URI, "MessageAddressingHeaderRequired", - getNamespacePrefix()); - } + @Override + protected final QName getMessageAddressingHeaderRequiredFaultSubcode() { + return new QName(NAMESPACE_URI, "MessageAddressingHeaderRequired", + getNamespacePrefix()); + } - @Override - protected final String getMessageAddressingHeaderRequiredFaultReason() { - return "A required header representing a Message Addressing Property is not present"; - } + @Override + protected final String getMessageAddressingHeaderRequiredFaultReason() { + return "A required header representing a Message Addressing Property is not present"; + } - @Override - protected QName getInvalidAddressingHeaderFaultSubcode() { - return new QName(NAMESPACE_URI, "InvalidAddressingHeader", getNamespacePrefix()); - } + @Override + protected QName getInvalidAddressingHeaderFaultSubcode() { + return new QName(NAMESPACE_URI, "InvalidAddressingHeader", getNamespacePrefix()); + } - @Override - protected String getInvalidAddressingHeaderFaultReason() { - return "A header representing a Message Addressing Property is not valid and the message cannot be processed"; - } + @Override + protected String getInvalidAddressingHeaderFaultReason() { + return "A header representing a Message Addressing Property is not valid and the message cannot be processed"; + } - public String toString() { - return "WS-Addressing 1.0"; - } + public String toString() { + return "WS-Addressing 1.0"; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing200408.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing200408.java index 3712149a..2ebbe5a9 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing200408.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/Addressing200408.java @@ -30,82 +30,82 @@ import org.springframework.ws.soap.addressing.core.MessageAddressingProperties; * * @author Arjen Poutsma * @see Web Services Addressing, August - * 2004 + * 2004 * @since 1.5.0 */ public class Addressing200408 extends AbstractAddressingVersion { - private static final String NAMESPACE_URI = "http://schemas.xmlsoap.org/ws/2004/08/addressing"; + private static final String NAMESPACE_URI = "http://schemas.xmlsoap.org/ws/2004/08/addressing"; - @Override - public void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) { - Assert.notNull(map.getAction(), "'Action' is required"); - Assert.notNull(map.getTo(), "'To' is required"); - super.addAddressingHeaders(message, map); - } + @Override + public void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map) { + Assert.notNull(map.getAction(), "'Action' is required"); + Assert.notNull(map.getTo(), "'To' is required"); + super.addAddressingHeaders(message, map); + } - @Override - public boolean hasRequiredProperties(MessageAddressingProperties map) { - if (map.getTo() == null) { - return false; - } - if (map.getAction() == null) { - return false; - } - if (map.getReplyTo() != null || map.getFaultTo() != null) { - return map.getMessageId() != null; - } - return true; - } + @Override + public boolean hasRequiredProperties(MessageAddressingProperties map) { + if (map.getTo() == null) { + return false; + } + if (map.getAction() == null) { + return false; + } + if (map.getReplyTo() != null || map.getFaultTo() != null) { + return map.getMessageId() != null; + } + return true; + } - @Override - protected final URI getAnonymous() { - return URI.create(NAMESPACE_URI + "/role/anonymous"); - } + @Override + protected final URI getAnonymous() { + return URI.create(NAMESPACE_URI + "/role/anonymous"); + } - @Override - protected final String getInvalidAddressingHeaderFaultReason() { - return "A message information header is not valid and the message cannot be processed."; - } + @Override + protected final String getInvalidAddressingHeaderFaultReason() { + return "A message information header is not valid and the message cannot be processed."; + } - @Override - protected final QName getInvalidAddressingHeaderFaultSubcode() { - return new QName(NAMESPACE_URI, "InvalidMessageInformationHeader", - getNamespacePrefix()); - } + @Override + protected final QName getInvalidAddressingHeaderFaultSubcode() { + return new QName(NAMESPACE_URI, "InvalidMessageInformationHeader", + getNamespacePrefix()); + } - @Override - protected final String getMessageAddressingHeaderRequiredFaultReason() { - return "A required message information header, To, MessageID, or Action, is not present."; - } + @Override + protected final String getMessageAddressingHeaderRequiredFaultReason() { + return "A required message information header, To, MessageID, or Action, is not present."; + } - @Override - protected final QName getMessageAddressingHeaderRequiredFaultSubcode() { - return new QName(NAMESPACE_URI, "MessageInformationHeaderRequired", - getNamespacePrefix()); - } + @Override + protected final QName getMessageAddressingHeaderRequiredFaultSubcode() { + return new QName(NAMESPACE_URI, "MessageInformationHeaderRequired", + getNamespacePrefix()); + } - @Override - protected final String getNamespaceUri() { - return NAMESPACE_URI; - } + @Override + protected final String getNamespaceUri() { + return NAMESPACE_URI; + } - @Override - protected URI getDefaultTo() { - return null; - } + @Override + protected URI getDefaultTo() { + return null; + } - @Override - protected final EndpointReference getDefaultReplyTo(EndpointReference from) { - return from; - } + @Override + protected final EndpointReference getDefaultReplyTo(EndpointReference from) { + return from; + } - @Override - protected final URI getNone() { - return null; - } + @Override + protected final URI getNone() { + return null; + } - public String toString() { - return "WS-Addressing August 2004"; - } + public String toString() { + return "WS-Addressing August 2004"; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AddressingVersion.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AddressingVersion.java index 97871271..e0ee7aa1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AddressingVersion.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/addressing/version/AddressingVersion.java @@ -30,76 +30,76 @@ import org.springframework.ws.soap.addressing.core.MessageAddressingProperties; */ public interface AddressingVersion { - /** - * Returns the {@link org.springframework.ws.soap.addressing.core.MessageAddressingProperties} for the given - * message. - * - * @param message the message to find the map for - * @return the message addressing properties - * @see Message Addressing Properties - */ - MessageAddressingProperties getMessageAddressingProperties(SoapMessage message); + /** + * Returns the {@link org.springframework.ws.soap.addressing.core.MessageAddressingProperties} for the given + * message. + * + * @param message the message to find the map for + * @return the message addressing properties + * @see Message Addressing Properties + */ + MessageAddressingProperties getMessageAddressingProperties(SoapMessage message); - /** - * Adds addressing SOAP headers to the given message, using the given {@link MessageAddressingProperties}. - * - * @param message the message to add the headers to - * @param map the message addressing properties - */ - void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map); + /** + * Adds addressing SOAP headers to the given message, using the given {@link MessageAddressingProperties}. + * + * @param message the message to add the headers to + * @param map the message addressing properties + */ + void addAddressingHeaders(SoapMessage message, MessageAddressingProperties map); - /** - * Given a {@code SoapHeaderElement}, return whether or not this version understands it. - * - * @param headerElement the header - * @return {@code true} if understood, {@code false} otherwise - */ - boolean understands(SoapHeaderElement headerElement); + /** + * Given a {@code SoapHeaderElement}, return whether or not this version understands it. + * + * @param headerElement the header + * @return {@code true} if understood, {@code false} otherwise + */ + boolean understands(SoapHeaderElement headerElement); - /** - * Indicates whether the given {@link MessageAddressingProperties} has all required properties. - * - * @return {@code true} if the to and action properties have been set, and - if a reply or fault endpoint has - * been set - also checks for the message id - */ - boolean hasRequiredProperties(MessageAddressingProperties map); + /** + * Indicates whether the given {@link MessageAddressingProperties} has all required properties. + * + * @return {@code true} if the to and action properties have been set, and - if a reply or fault endpoint has + * been set - also checks for the message id + */ + boolean hasRequiredProperties(MessageAddressingProperties map); - /* - * Address URIs - */ + /* + * Address URIs + */ - /** - * Indicates whether the given endpoint reference has a Anonymous address. This address is used to indicate that a - * message should be sent in-band. - * - * @see Formulating a Reply Message - */ - boolean hasAnonymousAddress(EndpointReference epr); + /** + * Indicates whether the given endpoint reference has a Anonymous address. This address is used to indicate that a + * message should be sent in-band. + * + * @see Formulating a Reply Message + */ + boolean hasAnonymousAddress(EndpointReference epr); - /** - * Indicates whether the given endpoint reference has a None address. Messages to be sent to this address will not - * be sent. - * - * @see Sending a Message to an EPR - */ - boolean hasNoneAddress(EndpointReference epr); + /** + * Indicates whether the given endpoint reference has a None address. Messages to be sent to this address will not + * be sent. + * + * @see Sending a Message to an EPR + */ + boolean hasNoneAddress(EndpointReference epr); - /* - * Faults - */ + /* + * Faults + */ - /** - * Adds a Invalid Addressing Header fault to the given message. - * - * @see Invalid Addressing Header - */ - SoapFault addInvalidAddressingHeaderFault(SoapMessage message); + /** + * Adds a Invalid Addressing Header fault to the given message. + * + * @see Invalid Addressing Header + */ + SoapFault addInvalidAddressingHeaderFault(SoapMessage message); - /** - * Adds a Message Addressing Header Required fault to the given message. - * - * @see Message Addressing Header Required - */ - SoapFault addMessageAddressingHeaderRequiredFault(SoapMessage message); + /** + * Adds a Message Addressing Header Required fault to the given message. + * + * @see Message Addressing Header Required + */ + SoapFault addMessageAddressingHeaderRequiredFault(SoapMessage message); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AbstractPayload.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AbstractPayload.java index 9deadd8f..b3a082df 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AbstractPayload.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AbstractPayload.java @@ -37,54 +37,54 @@ import org.apache.axiom.soap.SOAPFactory; */ abstract class AbstractPayload extends Payload { - private final SOAPBody axiomBody; + private final SOAPBody axiomBody; - private final SOAPFactory axiomFactory; + private final SOAPFactory axiomFactory; - protected AbstractPayload(SOAPBody axiomBody, SOAPFactory axiomFactory) { - Assert.notNull(axiomBody, "'axiomBody' must not be null"); - Assert.notNull(axiomFactory, "'axiomFactory' must not be null"); - this.axiomBody = axiomBody; - this.axiomFactory = axiomFactory; - } + protected AbstractPayload(SOAPBody axiomBody, SOAPFactory axiomFactory) { + Assert.notNull(axiomBody, "'axiomBody' must not be null"); + Assert.notNull(axiomFactory, "'axiomFactory' must not be null"); + this.axiomBody = axiomBody; + this.axiomFactory = axiomFactory; + } - @Override - public final Source getSource() { - try { - OMElement payloadElement = getPayloadElement(); - if (payloadElement != null) { - XMLStreamReader streamReader = getStreamReader(payloadElement); - return StaxUtils.createCustomStaxSource(streamReader); - } - else { - return null; - } - } - catch (OMException ex) { - throw new AxiomSoapBodyException(ex); - } - } + @Override + public final Source getSource() { + try { + OMElement payloadElement = getPayloadElement(); + if (payloadElement != null) { + XMLStreamReader streamReader = getStreamReader(payloadElement); + return StaxUtils.createCustomStaxSource(streamReader); + } + else { + return null; + } + } + catch (OMException ex) { + throw new AxiomSoapBodyException(ex); + } + } - protected abstract XMLStreamReader getStreamReader(OMElement payloadElement); + protected abstract XMLStreamReader getStreamReader(OMElement payloadElement); - @Override - public final Result getResult() { - AxiomUtils.removeContents(getAxiomBody()); - return getResultInternal(); - } + @Override + public final Result getResult() { + AxiomUtils.removeContents(getAxiomBody()); + return getResultInternal(); + } - protected abstract Result getResultInternal(); + protected abstract Result getResultInternal(); - public SOAPFactory getAxiomFactory() { - return axiomFactory; - } + public SOAPFactory getAxiomFactory() { + return axiomFactory; + } - protected SOAPBody getAxiomBody() { - return axiomBody; - } + protected SOAPBody getAxiomBody() { + return axiomBody; + } - protected OMElement getPayloadElement() throws OMException { - return getAxiomBody().getFirstElement(); - } + protected OMElement getPayloadElement() throws OMException { + return getAxiomBody().getFirstElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachment.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachment.java index 0eb8f119..c1ef1e18 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachment.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachment.java @@ -31,40 +31,40 @@ import org.springframework.ws.mime.Attachment; */ class AxiomAttachment implements Attachment { - private final DataHandler dataHandler; + private final DataHandler dataHandler; - private final String contentId; + private final String contentId; - public AxiomAttachment(String contentId, DataHandler dataHandler) { - Assert.notNull(contentId, "contentId must not be null"); - Assert.notNull(dataHandler, "dataHandler must not be null"); - this.contentId = contentId; - this.dataHandler = dataHandler; - } + public AxiomAttachment(String contentId, DataHandler dataHandler) { + Assert.notNull(contentId, "contentId must not be null"); + Assert.notNull(dataHandler, "dataHandler must not be null"); + this.contentId = contentId; + this.dataHandler = dataHandler; + } - @Override - public String getContentId() { - return contentId; - } + @Override + public String getContentId() { + return contentId; + } - @Override - public String getContentType() { - return dataHandler.getContentType(); - } + @Override + public String getContentType() { + return dataHandler.getContentType(); + } - @Override - public InputStream getInputStream() throws IOException { - return dataHandler.getInputStream(); - } + @Override + public InputStream getInputStream() throws IOException { + return dataHandler.getInputStream(); + } - @Override - public long getSize() { - // Axiom does not support getting the size of attachments. - return -1; - } + @Override + public long getSize() { + // Axiom does not support getting the size of attachments. + return -1; + } - @Override - public DataHandler getDataHandler() { - return dataHandler; - } + @Override + public DataHandler getDataHandler() { + return dataHandler; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachmentException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachmentException.java index d480c9ac..e4180307 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachmentException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomAttachmentException.java @@ -22,15 +22,15 @@ import org.springframework.ws.mime.AttachmentException; @SuppressWarnings("serial") public class AxiomAttachmentException extends AttachmentException { - public AxiomAttachmentException(String msg) { - super(msg); - } + public AxiomAttachmentException(String msg) { + super(msg); + } - public AxiomAttachmentException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomAttachmentException(String msg, Throwable ex) { + super(msg, ex); + } - public AxiomAttachmentException(Throwable ex) { - super(ex); - } + public AxiomAttachmentException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomHandler.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomHandler.java index 6e4fd3c4..aa7b247d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomHandler.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomHandler.java @@ -202,9 +202,9 @@ class AxiomHandler implements ContentHandler, LexicalHandler { "apos".equals(name); } - /* - * Unsupported - */ + /* + * Unsupported + */ @Override public void setDocumentLocator(Locator locator) { diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomResult.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomResult.java index 7726112e..6e9dcd94 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomResult.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomResult.java @@ -33,29 +33,29 @@ import org.xml.sax.ext.LexicalHandler; */ class AxiomResult extends SAXResult { - AxiomResult(OMContainer container, OMFactory factory) { - AxiomHandler handler = new AxiomHandler(container, factory); - super.setHandler(handler); - super.setLexicalHandler(handler); - } + AxiomResult(OMContainer container, OMFactory factory) { + AxiomHandler handler = new AxiomHandler(container, factory); + super.setHandler(handler); + super.setLexicalHandler(handler); + } - /** - * Throws a {@code UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - public void setHandler(ContentHandler handler) { - throw new UnsupportedOperationException("setHandler is not supported"); - } + /** + * Throws a {@code UnsupportedOperationException}. + * + * @throws UnsupportedOperationException always + */ + @Override + public void setHandler(ContentHandler handler) { + throw new UnsupportedOperationException("setHandler is not supported"); + } - /** - * Throws a {@code UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - public void setLexicalHandler(LexicalHandler handler) { - throw new UnsupportedOperationException("setLexicalHandler is not supported"); - } + /** + * Throws a {@code UnsupportedOperationException}. + * + * @throws UnsupportedOperationException always + */ + @Override + public void setLexicalHandler(LexicalHandler handler) { + throw new UnsupportedOperationException("setLexicalHandler is not supported"); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Body.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Body.java index 7848264f..f0cbab7d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Body.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Body.java @@ -43,119 +43,119 @@ import org.springframework.ws.soap.soap11.Soap11Fault; */ class AxiomSoap11Body extends AxiomSoapBody implements Soap11Body { - private final boolean langAttributeOnSoap11FaultString; + private final boolean langAttributeOnSoap11FaultString; - AxiomSoap11Body(SOAPBody axiomBody, - SOAPFactory axiomFactory, - boolean payloadCaching, - boolean langAttributeOnSoap11FaultString) { - super(axiomBody, axiomFactory, payloadCaching); - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + AxiomSoap11Body(SOAPBody axiomBody, + SOAPFactory axiomFactory, + boolean payloadCaching, + boolean langAttributeOnSoap11FaultString) { + super(axiomBody, axiomFactory, payloadCaching); + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } - @Override - public Soap11Fault addMustUnderstandFault(String faultString, Locale locale) { - SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_MUST_UNDERSTAND, faultString, locale); - return new AxiomSoap11Fault(fault, getAxiomFactory()); - } + @Override + public Soap11Fault addMustUnderstandFault(String faultString, Locale locale) { + SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_MUST_UNDERSTAND, faultString, locale); + return new AxiomSoap11Fault(fault, getAxiomFactory()); + } - @Override - public Soap11Fault addClientOrSenderFault(String faultString, Locale locale) { - SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_SENDER, faultString, locale); - return new AxiomSoap11Fault(fault, getAxiomFactory()); - } + @Override + public Soap11Fault addClientOrSenderFault(String faultString, Locale locale) { + SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_SENDER, faultString, locale); + return new AxiomSoap11Fault(fault, getAxiomFactory()); + } - @Override - public Soap11Fault addServerOrReceiverFault(String faultString, Locale locale) { - SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_RECEIVER, faultString, locale); - return new AxiomSoap11Fault(fault, getAxiomFactory()); - } + @Override + public Soap11Fault addServerOrReceiverFault(String faultString, Locale locale) { + SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_RECEIVER, faultString, locale); + return new AxiomSoap11Fault(fault, getAxiomFactory()); + } - @Override - public Soap11Fault addVersionMismatchFault(String faultString, Locale locale) { - SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_VERSION_MISMATCH, faultString, locale); - return new AxiomSoap11Fault(fault, getAxiomFactory()); - } + @Override + public Soap11Fault addVersionMismatchFault(String faultString, Locale locale) { + SOAPFault fault = addStandardFault(SOAP11Constants.FAULT_CODE_VERSION_MISMATCH, faultString, locale); + return new AxiomSoap11Fault(fault, getAxiomFactory()); + } - @Override - public Soap11Fault addFault(QName code, String faultString, Locale faultStringLocale) { - Assert.notNull(code, "No faultCode given"); - Assert.hasLength(faultString, "faultString cannot be empty"); - if (!StringUtils.hasLength(code.getNamespaceURI())) { - throw new IllegalArgumentException( - "A fault code with namespace and local part must be specific for a custom fault code"); - } - if (!langAttributeOnSoap11FaultString) { - faultStringLocale = null; - } - try { - AxiomUtils.removeContents(getAxiomBody()); - SOAPFault fault = getAxiomFactory().createSOAPFault(getAxiomBody()); - SOAPFaultCode faultCode = getAxiomFactory().createSOAPFaultCode(fault); - setValueText(code, fault, faultCode); - SOAPFaultReason faultReason = getAxiomFactory().createSOAPFaultReason(fault); - if (faultStringLocale != null) { - addLangAttribute(faultStringLocale, faultReason); - } - faultReason.setText(faultString); - return new AxiomSoap11Fault(fault, getAxiomFactory()); + @Override + public Soap11Fault addFault(QName code, String faultString, Locale faultStringLocale) { + Assert.notNull(code, "No faultCode given"); + Assert.hasLength(faultString, "faultString cannot be empty"); + if (!StringUtils.hasLength(code.getNamespaceURI())) { + throw new IllegalArgumentException( + "A fault code with namespace and local part must be specific for a custom fault code"); + } + if (!langAttributeOnSoap11FaultString) { + faultStringLocale = null; + } + try { + AxiomUtils.removeContents(getAxiomBody()); + SOAPFault fault = getAxiomFactory().createSOAPFault(getAxiomBody()); + SOAPFaultCode faultCode = getAxiomFactory().createSOAPFaultCode(fault); + setValueText(code, fault, faultCode); + SOAPFaultReason faultReason = getAxiomFactory().createSOAPFaultReason(fault); + if (faultStringLocale != null) { + addLangAttribute(faultStringLocale, faultReason); + } + faultReason.setText(faultString); + return new AxiomSoap11Fault(fault, getAxiomFactory()); - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapFaultException(ex); - } - } + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapFaultException(ex); + } + } - private void setValueText(QName code, SOAPFault fault, SOAPFaultCode faultCode) { - String prefix = code.getPrefix(); - if (StringUtils.hasLength(code.getNamespaceURI()) && StringUtils.hasLength(prefix)) { - OMNamespace namespace = fault.findNamespaceURI(prefix); - if (namespace == null) { - fault.declareNamespace(code.getNamespaceURI(), prefix); - } - } - else if (StringUtils.hasLength(code.getNamespaceURI())) { - OMNamespace namespace = fault.findNamespace(code.getNamespaceURI(), null); - if (namespace == null) { - namespace = fault.declareNamespace(code.getNamespaceURI(), ""); - } - code = new QName(code.getNamespaceURI(), code.getLocalPart(), - namespace.getPrefix()); - } - faultCode.setText(code); - } + private void setValueText(QName code, SOAPFault fault, SOAPFaultCode faultCode) { + String prefix = code.getPrefix(); + if (StringUtils.hasLength(code.getNamespaceURI()) && StringUtils.hasLength(prefix)) { + OMNamespace namespace = fault.findNamespaceURI(prefix); + if (namespace == null) { + fault.declareNamespace(code.getNamespaceURI(), prefix); + } + } + else if (StringUtils.hasLength(code.getNamespaceURI())) { + OMNamespace namespace = fault.findNamespace(code.getNamespaceURI(), null); + if (namespace == null) { + namespace = fault.declareNamespace(code.getNamespaceURI(), ""); + } + code = new QName(code.getNamespaceURI(), code.getLocalPart(), + namespace.getPrefix()); + } + faultCode.setText(code); + } - private SOAPFault addStandardFault(String localName, String faultString, Locale locale) { - Assert.notNull(faultString, "No faultString given"); - try { - AxiomUtils.removeContents(getAxiomBody()); - SOAPFault fault = getAxiomFactory().createSOAPFault(getAxiomBody()); - SOAPFaultCode faultCode = getAxiomFactory().createSOAPFaultCode(fault); - faultCode.setText(new QName(fault.getNamespace().getNamespaceURI(), localName, - fault.getNamespace().getPrefix())); - SOAPFaultReason faultReason = getAxiomFactory().createSOAPFaultReason(fault); - if (locale != null) { - addLangAttribute(locale, faultReason); - } - faultReason.setText(faultString); - return fault; - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapFaultException(ex); - } - } + private SOAPFault addStandardFault(String localName, String faultString, Locale locale) { + Assert.notNull(faultString, "No faultString given"); + try { + AxiomUtils.removeContents(getAxiomBody()); + SOAPFault fault = getAxiomFactory().createSOAPFault(getAxiomBody()); + SOAPFaultCode faultCode = getAxiomFactory().createSOAPFaultCode(fault); + faultCode.setText(new QName(fault.getNamespace().getNamespaceURI(), localName, + fault.getNamespace().getPrefix())); + SOAPFaultReason faultReason = getAxiomFactory().createSOAPFaultReason(fault); + if (locale != null) { + addLangAttribute(locale, faultReason); + } + faultReason.setText(faultString); + return fault; + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapFaultException(ex); + } + } - private void addLangAttribute(Locale locale, SOAPFaultReason faultReason) { - OMNamespace xmlNamespace = getAxiomFactory().createOMNamespace("http://www.w3.org/XML/1998/namespace", "xml"); - OMAttribute langAttribute = - getAxiomFactory().createOMAttribute("lang", xmlNamespace, AxiomUtils.toLanguage(locale)); - faultReason.addAttribute(langAttribute); - } + private void addLangAttribute(Locale locale, SOAPFaultReason faultReason) { + OMNamespace xmlNamespace = getAxiomFactory().createOMNamespace("http://www.w3.org/XML/1998/namespace", "xml"); + OMAttribute langAttribute = + getAxiomFactory().createOMAttribute("lang", xmlNamespace, AxiomUtils.toLanguage(locale)); + faultReason.addAttribute(langAttribute); + } - @Override - public Soap11Fault getFault() { - SOAPFault axiomFault = getAxiomBody().getFault(); - return axiomFault != null ? new AxiomSoap11Fault(axiomFault, getAxiomFactory()) : null; - } + @Override + public Soap11Fault getFault() { + SOAPFault axiomFault = getAxiomBody().getFault(); + return axiomFault != null ? new AxiomSoap11Fault(axiomFault, getAxiomFactory()) : null; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Fault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Fault.java index 858f3ebd..6be8c276 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Fault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Fault.java @@ -34,37 +34,37 @@ import org.springframework.ws.soap.soap11.Soap11Fault; */ class AxiomSoap11Fault extends AxiomSoapFault implements Soap11Fault { - AxiomSoap11Fault(SOAPFault axiomFault, SOAPFactory axiomFactory) { - super(axiomFault, axiomFactory); - } + AxiomSoap11Fault(SOAPFault axiomFault, SOAPFactory axiomFactory) { + super(axiomFault, axiomFactory); + } - @Override - public QName getFaultCode() { - return getAxiomFault().getCode().getTextAsQName(); - } + @Override + public QName getFaultCode() { + return getAxiomFault().getCode().getTextAsQName(); + } - @Override - public String getFaultStringOrReason() { - if (getAxiomFault().getReason() != null) { - return getAxiomFault().getReason().getText(); - } - return null; - } + @Override + public String getFaultStringOrReason() { + if (getAxiomFault().getReason() != null) { + return getAxiomFault().getReason().getText(); + } + return null; + } - @Override - public Locale getFaultStringLocale() { - if (getAxiomFault().getReason() != null) { - OMAttribute langAttribute = - getAxiomFault().getReason().getAttribute(new QName("http://www.w3.org/XML/1998/namespace", "lang")); - if (langAttribute != null) { - String xmlLangString = langAttribute.getAttributeValue(); - if (xmlLangString != null) { - return AxiomUtils.toLocale(xmlLangString); - } + @Override + public Locale getFaultStringLocale() { + if (getAxiomFault().getReason() != null) { + OMAttribute langAttribute = + getAxiomFault().getReason().getAttribute(new QName("http://www.w3.org/XML/1998/namespace", "lang")); + if (langAttribute != null) { + String xmlLangString = langAttribute.getAttributeValue(); + if (xmlLangString != null) { + return AxiomUtils.toLocale(xmlLangString); + } - } - } - return null; - } + } + } + return null; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Header.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Header.java index 0a88aadc..9ec4a7bf 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Header.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Header.java @@ -37,27 +37,27 @@ import org.springframework.ws.soap.soap11.Soap11Header; */ class AxiomSoap11Header extends AxiomSoapHeader implements Soap11Header { - AxiomSoap11Header(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { - super(axiomHeader, axiomFactory); - } + AxiomSoap11Header(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { + super(axiomHeader, axiomFactory); + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineHeaderElementsToProcess(final String[] actors) { - RolePlayer rolePlayer = null; - if (!ObjectUtils.isEmpty(actors)) { - rolePlayer = new RolePlayer() { + @Override + @SuppressWarnings("unchecked") + public Iterator examineHeaderElementsToProcess(final String[] actors) { + RolePlayer rolePlayer = null; + if (!ObjectUtils.isEmpty(actors)) { + rolePlayer = new RolePlayer() { - public List getRoles() { - return Arrays.asList(actors); - } + public List getRoles() { + return Arrays.asList(actors); + } - public boolean isUltimateDestination() { - return false; - } - }; - } - Iterator result = (Iterator)getAxiomHeader().getHeadersToProcess(rolePlayer); - return new AxiomSoapHeaderElementIterator(result); - } + public boolean isUltimateDestination() { + return false; + } + }; + } + Iterator result = (Iterator)getAxiomHeader().getHeadersToProcess(rolePlayer); + return new AxiomSoapHeaderElementIterator(result); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Body.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Body.java index a375cd48..d045f4cf 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Body.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Body.java @@ -42,70 +42,70 @@ import org.springframework.ws.soap.soap12.Soap12Fault; */ class AxiomSoap12Body extends AxiomSoapBody implements Soap12Body { - AxiomSoap12Body(SOAPBody axiomBody, SOAPFactory axiomFactory, boolean payloadCaching) { - super(axiomBody, axiomFactory, payloadCaching); - } + AxiomSoap12Body(SOAPBody axiomBody, SOAPFactory axiomFactory, boolean payloadCaching) { + super(axiomBody, axiomFactory, payloadCaching); + } - @Override - public Soap12Fault addMustUnderstandFault(String reason, Locale locale) { - Assert.notNull(locale, "No locale given"); - SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_MUST_UNDERSTAND, reason, locale); - return new AxiomSoap12Fault(fault, getAxiomFactory()); - } + @Override + public Soap12Fault addMustUnderstandFault(String reason, Locale locale) { + Assert.notNull(locale, "No locale given"); + SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_MUST_UNDERSTAND, reason, locale); + return new AxiomSoap12Fault(fault, getAxiomFactory()); + } - @Override - public Soap12Fault addClientOrSenderFault(String reason, Locale locale) { - Assert.notNull(locale, "No locale given"); - SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_SENDER, reason, locale); - return new AxiomSoap12Fault(fault, getAxiomFactory()); - } + @Override + public Soap12Fault addClientOrSenderFault(String reason, Locale locale) { + Assert.notNull(locale, "No locale given"); + SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_SENDER, reason, locale); + return new AxiomSoap12Fault(fault, getAxiomFactory()); + } - @Override - public Soap12Fault addServerOrReceiverFault(String reason, Locale locale) { - Assert.notNull(locale, "No locale given"); - SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_RECEIVER, reason, locale); - return new AxiomSoap12Fault(fault, getAxiomFactory()); - } + @Override + public Soap12Fault addServerOrReceiverFault(String reason, Locale locale) { + Assert.notNull(locale, "No locale given"); + SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_RECEIVER, reason, locale); + return new AxiomSoap12Fault(fault, getAxiomFactory()); + } - @Override - public Soap12Fault addVersionMismatchFault(String reason, Locale locale) { - Assert.notNull(locale, "No locale given"); - SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_VERSION_MISMATCH, reason, locale); - return new AxiomSoap12Fault(fault, getAxiomFactory()); - } + @Override + public Soap12Fault addVersionMismatchFault(String reason, Locale locale) { + Assert.notNull(locale, "No locale given"); + SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_VERSION_MISMATCH, reason, locale); + return new AxiomSoap12Fault(fault, getAxiomFactory()); + } - @Override - public Soap12Fault addDataEncodingUnknownFault(QName[] subcodes, String reason, Locale locale) { - Assert.notNull(locale, "No locale given"); - SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_DATA_ENCODING_UNKNOWN, reason, locale); - return new AxiomSoap12Fault(fault, getAxiomFactory()); - } + @Override + public Soap12Fault addDataEncodingUnknownFault(QName[] subcodes, String reason, Locale locale) { + Assert.notNull(locale, "No locale given"); + SOAPFault fault = addStandardFault(SOAP12Constants.FAULT_CODE_DATA_ENCODING_UNKNOWN, reason, locale); + return new AxiomSoap12Fault(fault, getAxiomFactory()); + } - private SOAPFault addStandardFault(String localName, String faultStringOrReason, Locale locale) { - Assert.notNull(faultStringOrReason, "No faultStringOrReason given"); - try { - AxiomUtils.removeContents(getAxiomBody()); - SOAPFault fault = getAxiomFactory().createSOAPFault(getAxiomBody()); - SOAPFaultCode code = getAxiomFactory().createSOAPFaultCode(fault); - SOAPFaultValue value = getAxiomFactory().createSOAPFaultValue(code); - value.setText(fault.getNamespace().getPrefix() + ":" + localName); - SOAPFaultReason reason = getAxiomFactory().createSOAPFaultReason(fault); - SOAPFaultText text = getAxiomFactory().createSOAPFaultText(reason); - if (locale != null) { - text.setLang(AxiomUtils.toLanguage(locale)); - } - text.setText(faultStringOrReason); - return fault; - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapFaultException(ex); - } - } + private SOAPFault addStandardFault(String localName, String faultStringOrReason, Locale locale) { + Assert.notNull(faultStringOrReason, "No faultStringOrReason given"); + try { + AxiomUtils.removeContents(getAxiomBody()); + SOAPFault fault = getAxiomFactory().createSOAPFault(getAxiomBody()); + SOAPFaultCode code = getAxiomFactory().createSOAPFaultCode(fault); + SOAPFaultValue value = getAxiomFactory().createSOAPFaultValue(code); + value.setText(fault.getNamespace().getPrefix() + ":" + localName); + SOAPFaultReason reason = getAxiomFactory().createSOAPFaultReason(fault); + SOAPFaultText text = getAxiomFactory().createSOAPFaultText(reason); + if (locale != null) { + text.setLang(AxiomUtils.toLanguage(locale)); + } + text.setText(faultStringOrReason); + return fault; + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapFaultException(ex); + } + } - @Override - public Soap12Fault getFault() { - SOAPFault axiomFault = getAxiomBody().getFault(); - return axiomFault != null ? new AxiomSoap12Fault(axiomFault, getAxiomFactory()) : null; - } + @Override + public Soap12Fault getFault() { + SOAPFault axiomFault = getAxiomBody().getFault(); + return axiomFault != null ? new AxiomSoap12Fault(axiomFault, getAxiomFactory()) : null; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Fault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Fault.java index 8315c3a1..af837c67 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Fault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Fault.java @@ -40,116 +40,116 @@ import org.springframework.ws.soap.soap12.Soap12Fault; /** Axiom-specific version of {@code org.springframework.ws.soap.Soap12Fault}. */ class AxiomSoap12Fault extends AxiomSoapFault implements Soap12Fault { - AxiomSoap12Fault(SOAPFault axiomFault, SOAPFactory axiomFactory) { - super(axiomFault, axiomFactory); - } + AxiomSoap12Fault(SOAPFault axiomFault, SOAPFactory axiomFactory) { + super(axiomFault, axiomFactory); + } - @Override - public QName getFaultCode() { - return getAxiomFault().getCode().getValue().getTextAsQName(); - } + @Override + public QName getFaultCode() { + return getAxiomFault().getCode().getValue().getTextAsQName(); + } - @Override - public Iterator getFaultSubcodes() { - List subcodes = new ArrayList(); - SOAPFaultSubCode subcode = getAxiomFault().getCode().getSubCode(); - while (subcode != null) { - subcodes.add(subcode.getValue().getTextAsQName()); - subcode = subcode.getSubCode(); - } - return subcodes.iterator(); - } + @Override + public Iterator getFaultSubcodes() { + List subcodes = new ArrayList(); + SOAPFaultSubCode subcode = getAxiomFault().getCode().getSubCode(); + while (subcode != null) { + subcodes.add(subcode.getValue().getTextAsQName()); + subcode = subcode.getSubCode(); + } + return subcodes.iterator(); + } - @Override - public void addFaultSubcode(QName subcode) { - SOAPFaultCode faultCode = getAxiomFault().getCode(); - SOAPFaultSubCode faultSubCode = null; - if (faultCode.getSubCode() == null) { - faultSubCode = getAxiomFactory().createSOAPFaultSubCode(faultCode); - } - else { - faultSubCode = faultCode.getSubCode(); - while (true) { - if (faultSubCode.getSubCode() != null) { - faultSubCode = faultSubCode.getSubCode(); - } - else { - faultSubCode = getAxiomFactory().createSOAPFaultSubCode(faultSubCode); - break; - } - } - } - SOAPFaultValue faultValue = getAxiomFactory().createSOAPFaultValue(faultSubCode); - setValueText(subcode, faultValue); - } + @Override + public void addFaultSubcode(QName subcode) { + SOAPFaultCode faultCode = getAxiomFault().getCode(); + SOAPFaultSubCode faultSubCode = null; + if (faultCode.getSubCode() == null) { + faultSubCode = getAxiomFactory().createSOAPFaultSubCode(faultCode); + } + else { + faultSubCode = faultCode.getSubCode(); + while (true) { + if (faultSubCode.getSubCode() != null) { + faultSubCode = faultSubCode.getSubCode(); + } + else { + faultSubCode = getAxiomFactory().createSOAPFaultSubCode(faultSubCode); + break; + } + } + } + SOAPFaultValue faultValue = getAxiomFactory().createSOAPFaultValue(faultSubCode); + setValueText(subcode, faultValue); + } - private void setValueText(QName code, SOAPFaultValue faultValue) { - String prefix = code.getPrefix(); - if (StringUtils.hasLength(code.getNamespaceURI()) && StringUtils.hasLength(prefix)) { - OMNamespace namespace = getAxiomFault().findNamespaceURI(prefix); - if (namespace == null) { - getAxiomFault().declareNamespace(code.getNamespaceURI(), prefix); - } - } - else if (StringUtils.hasLength(code.getNamespaceURI())) { - OMNamespace namespace = getAxiomFault().findNamespace(code.getNamespaceURI(), null); - if (namespace == null) { - throw new IllegalArgumentException("Could not resolve namespace of code [" + code + "]"); - } - code = new QName(code.getNamespaceURI(), code.getLocalPart(), - namespace.getPrefix()); - } - faultValue.setText(prefix + ":" + code.getLocalPart()); - } + private void setValueText(QName code, SOAPFaultValue faultValue) { + String prefix = code.getPrefix(); + if (StringUtils.hasLength(code.getNamespaceURI()) && StringUtils.hasLength(prefix)) { + OMNamespace namespace = getAxiomFault().findNamespaceURI(prefix); + if (namespace == null) { + getAxiomFault().declareNamespace(code.getNamespaceURI(), prefix); + } + } + else if (StringUtils.hasLength(code.getNamespaceURI())) { + OMNamespace namespace = getAxiomFault().findNamespace(code.getNamespaceURI(), null); + if (namespace == null) { + throw new IllegalArgumentException("Could not resolve namespace of code [" + code + "]"); + } + code = new QName(code.getNamespaceURI(), code.getLocalPart(), + namespace.getPrefix()); + } + faultValue.setText(prefix + ":" + code.getLocalPart()); + } - @Override - public String getFaultNode() { - SOAPFaultNode faultNode = getAxiomFault().getNode(); - if (faultNode == null) { - return null; - } - else { - return faultNode.getFaultNodeValue(); - } - } + @Override + public String getFaultNode() { + SOAPFaultNode faultNode = getAxiomFault().getNode(); + if (faultNode == null) { + return null; + } + else { + return faultNode.getFaultNodeValue(); + } + } - @Override - public void setFaultNode(String uri) { - try { - SOAPFaultNode faultNode = getAxiomFactory().createSOAPFaultNode(getAxiomFault()); - faultNode.setFaultNodeValue(uri); - getAxiomFault().setNode(faultNode); - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapFaultException(ex); - } - } + @Override + public void setFaultNode(String uri) { + try { + SOAPFaultNode faultNode = getAxiomFactory().createSOAPFaultNode(getAxiomFault()); + faultNode.setFaultNodeValue(uri); + getAxiomFault().setNode(faultNode); + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapFaultException(ex); + } + } - @Override - public String getFaultStringOrReason() { - return getFaultReasonText(Locale.getDefault()); - } + @Override + public String getFaultStringOrReason() { + return getFaultReasonText(Locale.getDefault()); + } - @Override - public String getFaultReasonText(Locale locale) { - SOAPFaultReason faultReason = getAxiomFault().getReason(); - String language = AxiomUtils.toLanguage(locale); - SOAPFaultText faultText = faultReason.getSOAPFaultText(language); - return faultText != null ? faultText.getText() : null; - } + @Override + public String getFaultReasonText(Locale locale) { + SOAPFaultReason faultReason = getAxiomFault().getReason(); + String language = AxiomUtils.toLanguage(locale); + SOAPFaultText faultText = faultReason.getSOAPFaultText(language); + return faultText != null ? faultText.getText() : null; + } - @Override - public void setFaultReasonText(Locale locale, String text) { - SOAPFaultReason faultReason = getAxiomFault().getReason(); - String language = AxiomUtils.toLanguage(locale); - try { - SOAPFaultText faultText = getAxiomFactory().createSOAPFaultText(faultReason); - faultText.setLang(language); - faultText.setText(text); - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapFaultException(ex); - } - } + @Override + public void setFaultReasonText(Locale locale, String text) { + SOAPFaultReason faultReason = getAxiomFault().getReason(); + String language = AxiomUtils.toLanguage(locale); + try { + SOAPFaultText faultText = getAxiomFactory().createSOAPFaultText(faultReason); + faultText.setLang(language); + faultText.setText(text); + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapFaultException(ex); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Header.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Header.java index 792367ed..b8e20497 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Header.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap12Header.java @@ -43,61 +43,61 @@ import org.springframework.ws.soap.soap12.Soap12Header; */ class AxiomSoap12Header extends AxiomSoapHeader implements Soap12Header { - AxiomSoap12Header(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { - super(axiomHeader, axiomFactory); - } + AxiomSoap12Header(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { + super(axiomHeader, axiomFactory); + } - @Override - public SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName) { - try { - SOAPHeaderBlock notUnderstood = - getAxiomHeader().addHeaderBlock("NotUnderstood", getAxiomHeader().getNamespace()); - OMNamespace headerNamespace = - notUnderstood.declareNamespace(headerName.getNamespaceURI(), - headerName.getPrefix()); - notUnderstood.addAttribute("qname", headerNamespace.getPrefix() + ":" + headerName.getLocalPart(), null); - return new AxiomSoapHeaderElement(notUnderstood, getAxiomFactory()); - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName) { + try { + SOAPHeaderBlock notUnderstood = + getAxiomHeader().addHeaderBlock("NotUnderstood", getAxiomHeader().getNamespace()); + OMNamespace headerNamespace = + notUnderstood.declareNamespace(headerName.getNamespaceURI(), + headerName.getPrefix()); + notUnderstood.addAttribute("qname", headerNamespace.getPrefix() + ":" + headerName.getLocalPart(), null); + return new AxiomSoapHeaderElement(notUnderstood, getAxiomFactory()); + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - public SoapHeaderElement addUpgradeHeaderElement(String[] supportedSoapUris) { - try { - SOAPHeaderBlock upgrade = getAxiomHeader().addHeaderBlock("Upgrade", getAxiomHeader().getNamespace()); - for (String supportedSoapUri : supportedSoapUris) { - OMElement supportedEnvelope = getAxiomFactory() - .createOMElement("SupportedEnvelope", getAxiomHeader().getNamespace(), upgrade); - OMNamespace namespace = supportedEnvelope.declareNamespace(supportedSoapUri, ""); - supportedEnvelope.addAttribute("qname", namespace.getPrefix() + ":Envelope", null); - } - return new AxiomSoapHeaderElement(upgrade, getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement addUpgradeHeaderElement(String[] supportedSoapUris) { + try { + SOAPHeaderBlock upgrade = getAxiomHeader().addHeaderBlock("Upgrade", getAxiomHeader().getNamespace()); + for (String supportedSoapUri : supportedSoapUris) { + OMElement supportedEnvelope = getAxiomFactory() + .createOMElement("SupportedEnvelope", getAxiomHeader().getNamespace(), upgrade); + OMNamespace namespace = supportedEnvelope.declareNamespace(supportedSoapUri, ""); + supportedEnvelope.addAttribute("qname", namespace.getPrefix() + ":Envelope", null); + } + return new AxiomSoapHeaderElement(upgrade, getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineHeaderElementsToProcess(final String[] roles, final boolean isUltimateDestination) - throws SoapHeaderException { - RolePlayer rolePlayer = null; - if (!ObjectUtils.isEmpty(roles)) { - rolePlayer = new RolePlayer() { + @Override + @SuppressWarnings("unchecked") + public Iterator examineHeaderElementsToProcess(final String[] roles, final boolean isUltimateDestination) + throws SoapHeaderException { + RolePlayer rolePlayer = null; + if (!ObjectUtils.isEmpty(roles)) { + rolePlayer = new RolePlayer() { - public List getRoles() { - return Arrays.asList(roles); - } + public List getRoles() { + return Arrays.asList(roles); + } - public boolean isUltimateDestination() { - return isUltimateDestination; - } - }; - } - Iterator result = (Iterator)getAxiomHeader().getHeadersToProcess(rolePlayer); - return new AxiomSoapHeaderElementIterator(result); - } + public boolean isUltimateDestination() { + return isUltimateDestination; + } + }; + } + Iterator result = (Iterator)getAxiomHeader().getHeadersToProcess(rolePlayer); + return new AxiomSoapHeaderElementIterator(result); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBody.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBody.java index 93fbfcbd..1eff994b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBody.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBody.java @@ -37,44 +37,44 @@ import org.springframework.ws.stream.StreamingPayload; */ abstract class AxiomSoapBody extends AxiomSoapElement implements SoapBody { - private final Payload payload; + private final Payload payload; - protected AxiomSoapBody(SOAPBody axiomBody, SOAPFactory axiomFactory, boolean payloadCaching) { - super(axiomBody, axiomFactory); - if (payloadCaching) { - payload = new CachingPayload(axiomBody, axiomFactory); - } - else { - payload = new NonCachingPayload(axiomBody, axiomFactory); - } - } + protected AxiomSoapBody(SOAPBody axiomBody, SOAPFactory axiomFactory, boolean payloadCaching) { + super(axiomBody, axiomFactory); + if (payloadCaching) { + payload = new CachingPayload(axiomBody, axiomFactory); + } + else { + payload = new NonCachingPayload(axiomBody, axiomFactory); + } + } - @Override - public Source getPayloadSource() { - return payload.getSource(); - } + @Override + public Source getPayloadSource() { + return payload.getSource(); + } - @Override - public Result getPayloadResult() { - return payload.getResult(); - } + @Override + public Result getPayloadResult() { + return payload.getResult(); + } - @Override - public boolean hasFault() { - return getAxiomBody().hasFault(); - } + @Override + public boolean hasFault() { + return getAxiomBody().hasFault(); + } - protected final SOAPBody getAxiomBody() { - return (SOAPBody) getAxiomElement(); - } + protected final SOAPBody getAxiomBody() { + return (SOAPBody) getAxiomElement(); + } - public void setStreamingPayload(StreamingPayload payload) { - Assert.notNull(payload, "'payload' must not be null"); - OMDataSource dataSource = new StreamingOMDataSource(payload); - OMElement payloadElement = getAxiomFactory().createOMElement(dataSource, payload.getName()); + public void setStreamingPayload(StreamingPayload payload) { + Assert.notNull(payload, "'payload' must not be null"); + OMDataSource dataSource = new StreamingOMDataSource(payload); + OMElement payloadElement = getAxiomFactory().createOMElement(dataSource, payload.getName()); - SOAPBody soapBody = getAxiomBody(); - AxiomUtils.removeContents(soapBody); - soapBody.addChild(payloadElement); - } + SOAPBody soapBody = getAxiomBody(); + AxiomUtils.removeContents(soapBody); + soapBody.addChild(payloadElement); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBodyException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBodyException.java index 76d20f0f..4632fede 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBodyException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapBodyException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapEnvelopeException; @SuppressWarnings("serial") public class AxiomSoapBodyException extends SoapEnvelopeException { - public AxiomSoapBodyException(String msg) { - super(msg); - } + public AxiomSoapBodyException(String msg) { + super(msg); + } - public AxiomSoapBodyException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapBodyException(String msg, Throwable ex) { + super(msg, ex); + } - public AxiomSoapBodyException(Throwable ex) { - super(ex); - } + public AxiomSoapBodyException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElement.java index c2aeb61e..7d4303bd 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElement.java @@ -41,114 +41,114 @@ import org.springframework.ws.soap.SoapElement; */ class AxiomSoapElement implements SoapElement { - private final OMElement axiomElement; + private final OMElement axiomElement; - private final SOAPFactory axiomFactory; + private final SOAPFactory axiomFactory; - protected AxiomSoapElement(OMElement axiomElement, SOAPFactory axiomFactory) { - Assert.notNull(axiomElement, "axiomElement must not be null"); - Assert.notNull(axiomFactory, "axiomFactory must not be null"); - this.axiomElement = axiomElement; - this.axiomFactory = axiomFactory; - } + protected AxiomSoapElement(OMElement axiomElement, SOAPFactory axiomFactory) { + Assert.notNull(axiomElement, "axiomElement must not be null"); + Assert.notNull(axiomFactory, "axiomFactory must not be null"); + this.axiomElement = axiomElement; + this.axiomFactory = axiomFactory; + } - @Override - public final QName getName() { - try { - return axiomElement.getQName(); - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + @Override + public final QName getName() { + try { + return axiomElement.getQName(); + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - @Override - public final Source getSource() { - try { - return StaxUtils.createCustomStaxSource(axiomElement.getXMLStreamReader()); - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + @Override + public final Source getSource() { + try { + return StaxUtils.createCustomStaxSource(axiomElement.getXMLStreamReader()); + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - @Override - public final void addAttribute(QName name, String value) { - try { - String namespaceUri = name.getNamespaceURI(); - String prefix = name.getPrefix(); - if (StringUtils.hasLength(namespaceUri) && !StringUtils.hasLength(prefix)) { - prefix = null; - } - OMNamespace namespace = - getAxiomFactory().createOMNamespace(namespaceUri, prefix); - OMAttribute attribute = getAxiomFactory().createOMAttribute(name.getLocalPart(), namespace, value); - getAxiomElement().addAttribute(attribute); - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + @Override + public final void addAttribute(QName name, String value) { + try { + String namespaceUri = name.getNamespaceURI(); + String prefix = name.getPrefix(); + if (StringUtils.hasLength(namespaceUri) && !StringUtils.hasLength(prefix)) { + prefix = null; + } + OMNamespace namespace = + getAxiomFactory().createOMNamespace(namespaceUri, prefix); + OMAttribute attribute = getAxiomFactory().createOMAttribute(name.getLocalPart(), namespace, value); + getAxiomElement().addAttribute(attribute); + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - @Override - public void removeAttribute(QName name) { - try { - OMAttribute attribute = getAxiomElement().getAttribute(name); - if (attribute != null) { - getAxiomElement().removeAttribute(attribute); - } - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + @Override + public void removeAttribute(QName name) { + try { + OMAttribute attribute = getAxiomElement().getAttribute(name); + if (attribute != null) { + getAxiomElement().removeAttribute(attribute); + } + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - @Override - public final String getAttributeValue(QName name) { - try { - return getAxiomElement().getAttributeValue(name); - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + @Override + public final String getAttributeValue(QName name) { + try { + return getAxiomElement().getAttributeValue(name); + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - @Override - public final Iterator getAllAttributes() { - try { - List results = new ArrayList(); - for (Iterator iterator = getAxiomElement().getAllAttributes(); iterator.hasNext();) { - OMAttribute attribute = (OMAttribute) iterator.next(); - results.add(attribute.getQName()); - } - return results.iterator(); + @Override + public final Iterator getAllAttributes() { + try { + List results = new ArrayList(); + for (Iterator iterator = getAxiomElement().getAllAttributes(); iterator.hasNext();) { + OMAttribute attribute = (OMAttribute) iterator.next(); + results.add(attribute.getQName()); + } + return results.iterator(); - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - @Override - public void addNamespaceDeclaration(String prefix, String namespaceUri) { - try { - if (StringUtils.hasLength(prefix)) { - getAxiomElement().declareNamespace(namespaceUri, prefix); - } - else { - getAxiomElement().declareDefaultNamespace(namespaceUri); - } - } - catch (OMException ex) { - throw new AxiomSoapElementException(ex); - } - } + @Override + public void addNamespaceDeclaration(String prefix, String namespaceUri) { + try { + if (StringUtils.hasLength(prefix)) { + getAxiomElement().declareNamespace(namespaceUri, prefix); + } + else { + getAxiomElement().declareDefaultNamespace(namespaceUri); + } + } + catch (OMException ex) { + throw new AxiomSoapElementException(ex); + } + } - protected final OMElement getAxiomElement() { - return axiomElement; - } + protected final OMElement getAxiomElement() { + return axiomElement; + } - protected final SOAPFactory getAxiomFactory() { - return axiomFactory; - } + protected final SOAPFactory getAxiomFactory() { + return axiomFactory; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElementException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElementException.java index c280d85c..099e5bd3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElementException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapElementException.java @@ -21,15 +21,15 @@ import org.springframework.ws.soap.SoapElementException; @SuppressWarnings("serial") public class AxiomSoapElementException extends SoapElementException { - public AxiomSoapElementException(String msg) { - super(msg); - } + public AxiomSoapElementException(String msg) { + super(msg); + } - public AxiomSoapElementException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapElementException(String msg, Throwable ex) { + super(msg, ex); + } - public AxiomSoapElementException(Throwable ex) { - super(ex); - } + public AxiomSoapElementException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelope.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelope.java index 86588612..2d36133b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelope.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelope.java @@ -36,72 +36,72 @@ import org.springframework.ws.soap.SoapHeader; */ class AxiomSoapEnvelope extends AxiomSoapElement implements SoapEnvelope { - boolean payloadCaching; + boolean payloadCaching; - private AxiomSoapBody body; + private AxiomSoapBody body; - private final boolean langAttributeOnSoap11FaultString; + private final boolean langAttributeOnSoap11FaultString; - AxiomSoapEnvelope(SOAPEnvelope axiomEnvelope, - SOAPFactory axiomFactory, - boolean payloadCaching, - boolean langAttributeOnSoap11FaultString) { - super(axiomEnvelope, axiomFactory); - this.payloadCaching = payloadCaching; - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + AxiomSoapEnvelope(SOAPEnvelope axiomEnvelope, + SOAPFactory axiomFactory, + boolean payloadCaching, + boolean langAttributeOnSoap11FaultString) { + super(axiomEnvelope, axiomFactory); + this.payloadCaching = payloadCaching; + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } - @Override - public SoapHeader getHeader() { - try { - if (getAxiomEnvelope().getHeader() == null) { - return null; - } - else { - SOAPHeader axiomHeader = getAxiomEnvelope().getHeader(); - String namespaceURI = getAxiomEnvelope().getNamespace().getNamespaceURI(); - if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { - return new AxiomSoap11Header(axiomHeader, getAxiomFactory()); - } - else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { - return new AxiomSoap12Header(axiomHeader, getAxiomFactory()); - } - else { - throw new AxiomSoapEnvelopeException("Unknown SOAP namespace \"" + namespaceURI + "\""); - } - } - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + public SoapHeader getHeader() { + try { + if (getAxiomEnvelope().getHeader() == null) { + return null; + } + else { + SOAPHeader axiomHeader = getAxiomEnvelope().getHeader(); + String namespaceURI = getAxiomEnvelope().getNamespace().getNamespaceURI(); + if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { + return new AxiomSoap11Header(axiomHeader, getAxiomFactory()); + } + else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { + return new AxiomSoap12Header(axiomHeader, getAxiomFactory()); + } + else { + throw new AxiomSoapEnvelopeException("Unknown SOAP namespace \"" + namespaceURI + "\""); + } + } + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - public SoapBody getBody() { - if (body == null) { - try { - SOAPBody axiomBody = getAxiomEnvelope().getBody(); - String namespaceURI = getAxiomEnvelope().getNamespace().getNamespaceURI(); - if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { - body = new AxiomSoap11Body(axiomBody, getAxiomFactory(), payloadCaching, - langAttributeOnSoap11FaultString); - } - else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { - body = new AxiomSoap12Body(axiomBody, getAxiomFactory(), payloadCaching); - } - else { - throw new AxiomSoapEnvelopeException("Unknown SOAP namespace \"" + namespaceURI + "\""); - } - } - catch (OMException ex) { - throw new AxiomSoapBodyException(ex); - } - } - return body; - } + @Override + public SoapBody getBody() { + if (body == null) { + try { + SOAPBody axiomBody = getAxiomEnvelope().getBody(); + String namespaceURI = getAxiomEnvelope().getNamespace().getNamespaceURI(); + if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { + body = new AxiomSoap11Body(axiomBody, getAxiomFactory(), payloadCaching, + langAttributeOnSoap11FaultString); + } + else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(namespaceURI)) { + body = new AxiomSoap12Body(axiomBody, getAxiomFactory(), payloadCaching); + } + else { + throw new AxiomSoapEnvelopeException("Unknown SOAP namespace \"" + namespaceURI + "\""); + } + } + catch (OMException ex) { + throw new AxiomSoapBodyException(ex); + } + } + return body; + } - protected SOAPEnvelope getAxiomEnvelope() { - return (SOAPEnvelope) getAxiomElement(); - } + protected SOAPEnvelope getAxiomEnvelope() { + return (SOAPEnvelope) getAxiomElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelopeException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelopeException.java index cebe9450..013fdc36 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelopeException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapEnvelopeException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapEnvelopeException; @SuppressWarnings("serial") public class AxiomSoapEnvelopeException extends SoapEnvelopeException { - public AxiomSoapEnvelopeException(String msg) { - super(msg); - } + public AxiomSoapEnvelopeException(String msg) { + super(msg); + } - public AxiomSoapEnvelopeException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapEnvelopeException(String msg, Throwable ex) { + super(msg, ex); + } - public AxiomSoapEnvelopeException(Throwable ex) { - super(ex); - } + public AxiomSoapEnvelopeException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFault.java index 11cc8c69..102b0087 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFault.java @@ -29,54 +29,54 @@ import org.springframework.ws.soap.SoapFaultDetail; /** @author Arjen Poutsma */ abstract class AxiomSoapFault extends AxiomSoapElement implements SoapFault { - protected AxiomSoapFault(SOAPFault axiomFault, SOAPFactory axiomFactory) { - super(axiomFault, axiomFactory); - } + protected AxiomSoapFault(SOAPFault axiomFault, SOAPFactory axiomFactory) { + super(axiomFault, axiomFactory); + } - @Override - public String getFaultActorOrRole() { - SOAPFaultRole faultRole = getAxiomFault().getRole(); - return faultRole != null ? faultRole.getRoleValue() : null; - } + @Override + public String getFaultActorOrRole() { + SOAPFaultRole faultRole = getAxiomFault().getRole(); + return faultRole != null ? faultRole.getRoleValue() : null; + } - @Override - public void setFaultActorOrRole(String actor) { - try { - SOAPFaultRole axiomFaultRole = getAxiomFactory().createSOAPFaultRole(getAxiomFault()); - axiomFaultRole.setRoleValue(actor); - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapFaultException(ex); - } + @Override + public void setFaultActorOrRole(String actor) { + try { + SOAPFaultRole axiomFaultRole = getAxiomFactory().createSOAPFaultRole(getAxiomFault()); + axiomFaultRole.setRoleValue(actor); + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapFaultException(ex); + } - } + } - @Override - public SoapFaultDetail getFaultDetail() { - try { - SOAPFaultDetail axiomFaultDetail = getAxiomFault().getDetail(); - return axiomFaultDetail != null ? new AxiomSoapFaultDetail(axiomFaultDetail, getAxiomFactory()) : null; - } - catch (OMException ex) { - throw new AxiomSoapFaultException(ex); - } + @Override + public SoapFaultDetail getFaultDetail() { + try { + SOAPFaultDetail axiomFaultDetail = getAxiomFault().getDetail(); + return axiomFaultDetail != null ? new AxiomSoapFaultDetail(axiomFaultDetail, getAxiomFactory()) : null; + } + catch (OMException ex) { + throw new AxiomSoapFaultException(ex); + } - } + } - @Override - public SoapFaultDetail addFaultDetail() { - try { - SOAPFaultDetail axiomFaultDetail = getAxiomFactory().createSOAPFaultDetail(getAxiomFault()); - return new AxiomSoapFaultDetail(axiomFaultDetail, getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapFaultException(ex); - } + @Override + public SoapFaultDetail addFaultDetail() { + try { + SOAPFaultDetail axiomFaultDetail = getAxiomFactory().createSOAPFaultDetail(getAxiomFault()); + return new AxiomSoapFaultDetail(axiomFaultDetail, getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapFaultException(ex); + } - } + } - protected SOAPFault getAxiomFault() { - return (SOAPFault) getAxiomElement(); - } + protected SOAPFault getAxiomFault() { + return (SOAPFault) getAxiomElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetail.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetail.java index f012c224..aee020e0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetail.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetail.java @@ -36,66 +36,66 @@ import org.springframework.ws.soap.SoapFaultDetailElement; */ class AxiomSoapFaultDetail extends AxiomSoapElement implements SoapFaultDetail { - public AxiomSoapFaultDetail(SOAPFaultDetail axiomFaultDetail, SOAPFactory axiomFactory) { - super(axiomFaultDetail, axiomFactory); - } + public AxiomSoapFaultDetail(SOAPFaultDetail axiomFaultDetail, SOAPFactory axiomFactory) { + super(axiomFaultDetail, axiomFactory); + } - @Override - public SoapFaultDetailElement addFaultDetailElement(QName name) { - try { - OMElement element = getAxiomFactory().createOMElement(name, getAxiomFaultDetail()); - return new AxiomSoapFaultDetailElement(element, getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapFaultException(ex); - } + @Override + public SoapFaultDetailElement addFaultDetailElement(QName name) { + try { + OMElement element = getAxiomFactory().createOMElement(name, getAxiomFaultDetail()); + return new AxiomSoapFaultDetailElement(element, getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapFaultException(ex); + } - } + } - @Override - @SuppressWarnings("unchecked") - public Iterator getDetailEntries() { - return new AxiomSoapFaultDetailElementIterator(getAxiomFaultDetail().getChildElements()); - } + @Override + @SuppressWarnings("unchecked") + public Iterator getDetailEntries() { + return new AxiomSoapFaultDetailElementIterator(getAxiomFaultDetail().getChildElements()); + } - @Override - public Result getResult() { - return new AxiomResult(getAxiomFaultDetail(), getAxiomFactory()); - } + @Override + public Result getResult() { + return new AxiomResult(getAxiomFaultDetail(), getAxiomFactory()); + } - protected SOAPFaultDetail getAxiomFaultDetail() { - return (SOAPFaultDetail) getAxiomElement(); - } + protected SOAPFaultDetail getAxiomFaultDetail() { + return (SOAPFaultDetail) getAxiomElement(); + } - private class AxiomSoapFaultDetailElementIterator implements Iterator { + private class AxiomSoapFaultDetailElementIterator implements Iterator { - private final Iterator axiomIterator; + private final Iterator axiomIterator; - private AxiomSoapFaultDetailElementIterator(Iterator axiomIterator) { - this.axiomIterator = axiomIterator; - } + private AxiomSoapFaultDetailElementIterator(Iterator axiomIterator) { + this.axiomIterator = axiomIterator; + } - @Override - public boolean hasNext() { - return axiomIterator.hasNext(); - } + @Override + public boolean hasNext() { + return axiomIterator.hasNext(); + } - @Override - public SoapFaultDetailElement next() { - try { - OMElement axiomElement = axiomIterator.next(); - return new AxiomSoapFaultDetailElement(axiomElement, getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapFaultException(ex); - } + @Override + public SoapFaultDetailElement next() { + try { + OMElement axiomElement = axiomIterator.next(); + return new AxiomSoapFaultDetailElement(axiomElement, getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapFaultException(ex); + } - } + } - @Override - public void remove() { - axiomIterator.remove(); - } - } + @Override + public void remove() { + axiomIterator.remove(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailElement.java index 7cc3c6a9..b506e466 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailElement.java @@ -32,29 +32,29 @@ import org.springframework.ws.soap.SoapFaultDetailElement; */ class AxiomSoapFaultDetailElement extends AxiomSoapElement implements SoapFaultDetailElement { - public AxiomSoapFaultDetailElement(OMElement axiomElement, SOAPFactory soapFactory) { - super(axiomElement, soapFactory); - } + public AxiomSoapFaultDetailElement(OMElement axiomElement, SOAPFactory soapFactory) { + super(axiomElement, soapFactory); + } - @Override - public Result getResult() { - try { - return new AxiomResult(getAxiomElement(), getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapFaultException(ex); - } + @Override + public Result getResult() { + try { + return new AxiomResult(getAxiomElement(), getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapFaultException(ex); + } - } + } - @Override - public void addText(String text) { - try { - getAxiomElement().setText(text); - } - catch (OMException ex) { - throw new AxiomSoapFaultException(ex); - } - } + @Override + public void addText(String text) { + try { + getAxiomElement().setText(text); + } + catch (OMException ex) { + throw new AxiomSoapFaultException(ex); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultException.java index bf420524..159f22f7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapFaultException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapFaultException; @SuppressWarnings("serial") public class AxiomSoapFaultException extends SoapFaultException { - public AxiomSoapFaultException(String msg) { - super(msg); - } + public AxiomSoapFaultException(String msg) { + super(msg); + } - public AxiomSoapFaultException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapFaultException(String msg, Throwable ex) { + super(msg, ex); + } - public AxiomSoapFaultException(Throwable ex) { - super(ex); - } + public AxiomSoapFaultException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeader.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeader.java index 3bb805eb..f88c902a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeader.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeader.java @@ -39,106 +39,106 @@ import org.springframework.ws.soap.SoapHeaderException; */ abstract class AxiomSoapHeader extends AxiomSoapElement implements SoapHeader { - AxiomSoapHeader(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { - super(axiomHeader, axiomFactory); - } + AxiomSoapHeader(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { + super(axiomHeader, axiomFactory); + } - @Override - public Result getResult() { - return new AxiomResult(getAxiomHeader(), getAxiomFactory()); - } + @Override + public Result getResult() { + return new AxiomResult(getAxiomHeader(), getAxiomFactory()); + } - @Override - public SoapHeaderElement addHeaderElement(QName name) { - try { - OMNamespace namespace = - getAxiomFactory().createOMNamespace(name.getNamespaceURI(), - name.getPrefix()); - SOAPHeaderBlock axiomHeaderBlock = getAxiomHeader().addHeaderBlock(name.getLocalPart(), namespace); - return new AxiomSoapHeaderElement(axiomHeaderBlock, getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement addHeaderElement(QName name) { + try { + OMNamespace namespace = + getAxiomFactory().createOMNamespace(name.getNamespaceURI(), + name.getPrefix()); + SOAPHeaderBlock axiomHeaderBlock = getAxiomHeader().addHeaderBlock(name.getLocalPart(), namespace); + return new AxiomSoapHeaderElement(axiomHeaderBlock, getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - public void removeHeaderElement(QName name) throws SoapHeaderException { - try { - OMElement element = getAxiomHeader().getFirstChildWithName(name); - if (element != null) { - element.detach(); - } - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + public void removeHeaderElement(QName name) throws SoapHeaderException { + try { + OMElement element = getAxiomHeader().getFirstChildWithName(name); + if (element != null) { + element.detach(); + } + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineMustUnderstandHeaderElements(String role) { - try { - return new AxiomSoapHeaderElementIterator(getAxiomHeader().examineMustUnderstandHeaderBlocks(role)); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineMustUnderstandHeaderElements(String role) { + try { + return new AxiomSoapHeaderElementIterator(getAxiomHeader().examineMustUnderstandHeaderBlocks(role)); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineAllHeaderElements() { - try { - return new AxiomSoapHeaderElementIterator(getAxiomHeader().examineAllHeaderBlocks()); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineAllHeaderElements() { + try { + return new AxiomSoapHeaderElementIterator(getAxiomHeader().examineAllHeaderBlocks()); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineHeaderElements(QName name) throws SoapHeaderException { - try { - return new AxiomSoapHeaderElementIterator(getAxiomHeader().getChildrenWithName(name)); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineHeaderElements(QName name) throws SoapHeaderException { + try { + return new AxiomSoapHeaderElementIterator(getAxiomHeader().getChildrenWithName(name)); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - protected SOAPHeader getAxiomHeader() { - return (SOAPHeader) getAxiomElement(); - } + protected SOAPHeader getAxiomHeader() { + return (SOAPHeader) getAxiomElement(); + } - protected class AxiomSoapHeaderElementIterator implements Iterator { + protected class AxiomSoapHeaderElementIterator implements Iterator { - private final Iterator axiomIterator; + private final Iterator axiomIterator; - protected AxiomSoapHeaderElementIterator(Iterator axiomIterator) { - this.axiomIterator = axiomIterator; - } + protected AxiomSoapHeaderElementIterator(Iterator axiomIterator) { + this.axiomIterator = axiomIterator; + } - @Override - public boolean hasNext() { - return axiomIterator.hasNext(); - } + @Override + public boolean hasNext() { + return axiomIterator.hasNext(); + } - @Override - public SoapHeaderElement next() { - try { - SOAPHeaderBlock axiomHeaderBlock = axiomIterator.next(); - return new AxiomSoapHeaderElement(axiomHeaderBlock, getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement next() { + try { + SOAPHeaderBlock axiomHeaderBlock = axiomIterator.next(); + return new AxiomSoapHeaderElement(axiomHeaderBlock, getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } + } - @Override - public void remove() { - axiomIterator.remove(); - } - } + @Override + public void remove() { + axiomIterator.remove(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderElement.java index 6d74723d..84d404c4 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderElement.java @@ -27,53 +27,53 @@ import org.springframework.ws.soap.SoapHeaderElement; /** Axiom-specific version of {@code org.springframework.ws.soap.SoapHeaderHeaderElement}. */ class AxiomSoapHeaderElement extends AxiomSoapElement implements SoapHeaderElement { - public AxiomSoapHeaderElement(SOAPHeaderBlock axiomHeaderBlock, SOAPFactory axiomFactory) { - super(axiomHeaderBlock, axiomFactory); - } + public AxiomSoapHeaderElement(SOAPHeaderBlock axiomHeaderBlock, SOAPFactory axiomFactory) { + super(axiomHeaderBlock, axiomFactory); + } - @Override - public String getActorOrRole() { - return getAxiomHeaderBlock().getRole(); - } + @Override + public String getActorOrRole() { + return getAxiomHeaderBlock().getRole(); + } - @Override - public void setActorOrRole(String role) { - getAxiomHeaderBlock().setRole(role); - } + @Override + public void setActorOrRole(String role) { + getAxiomHeaderBlock().setRole(role); + } - @Override - public boolean getMustUnderstand() { - return getAxiomHeaderBlock().getMustUnderstand(); - } + @Override + public boolean getMustUnderstand() { + return getAxiomHeaderBlock().getMustUnderstand(); + } - @Override - public void setMustUnderstand(boolean mustUnderstand) { - getAxiomHeaderBlock().setMustUnderstand(mustUnderstand); - } + @Override + public void setMustUnderstand(boolean mustUnderstand) { + getAxiomHeaderBlock().setMustUnderstand(mustUnderstand); + } - @Override - public Result getResult() { - try { - return new AxiomResult(getAxiomHeaderBlock(), getAxiomFactory()); - } - catch (OMException ex) { - throw new AxiomSoapHeaderException(ex); - } + @Override + public Result getResult() { + try { + return new AxiomResult(getAxiomHeaderBlock(), getAxiomFactory()); + } + catch (OMException ex) { + throw new AxiomSoapHeaderException(ex); + } - } + } - @Override - public String getText() { - return getAxiomHeaderBlock().getText(); - } + @Override + public String getText() { + return getAxiomHeaderBlock().getText(); + } - @Override - public void setText(String content) { - getAxiomHeaderBlock().setText(content); - } + @Override + public void setText(String content) { + getAxiomHeaderBlock().setText(content); + } - protected SOAPHeaderBlock getAxiomHeaderBlock() { - return (SOAPHeaderBlock) getAxiomElement(); - } + protected SOAPHeaderBlock getAxiomHeaderBlock() { + return (SOAPHeaderBlock) getAxiomElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderException.java index 9b5debc1..026c7204 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapHeaderException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapHeaderException; @SuppressWarnings("serial") public class AxiomSoapHeaderException extends SoapHeaderException { - public AxiomSoapHeaderException(String msg) { - super(msg); - } + public AxiomSoapHeaderException(String msg) { + super(msg); + } - public AxiomSoapHeaderException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapHeaderException(String msg, Throwable ex) { + super(msg, ex); + } - public AxiomSoapHeaderException(Throwable ex) { - super(ex); - } + public AxiomSoapHeaderException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessage.java index 56646001..ecebb500 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessage.java @@ -63,351 +63,351 @@ import org.springframework.ws.transport.TransportOutputStream; */ public class AxiomSoapMessage extends AbstractSoapMessage implements StreamingWebServiceMessage { - private static final String EMPTY_SOAP_ACTION = "\"\""; + private static final String EMPTY_SOAP_ACTION = "\"\""; - private SOAPMessage axiomMessage; + private SOAPMessage axiomMessage; - private final SOAPFactory axiomFactory; + private final SOAPFactory axiomFactory; - private final Attachments attachments; + private final Attachments attachments; - private final boolean payloadCaching; + private final boolean payloadCaching; - private AxiomSoapEnvelope envelope; + private AxiomSoapEnvelope envelope; - private String soapAction; + private String soapAction; - private final boolean langAttributeOnSoap11FaultString; + private final boolean langAttributeOnSoap11FaultString; - private OMOutputFormat outputFormat; + private OMOutputFormat outputFormat; - /** - * Create a new, empty {@code AxiomSoapMessage}. - * - * @param soapFactory the AXIOM SOAPFactory - */ - public AxiomSoapMessage(SOAPFactory soapFactory) { - this(soapFactory, true, true); - } + /** + * Create a new, empty {@code AxiomSoapMessage}. + * + * @param soapFactory the AXIOM SOAPFactory + */ + public AxiomSoapMessage(SOAPFactory soapFactory) { + this(soapFactory, true, true); + } - /** - * Create a new, empty {@code AxiomSoapMessage}. - * - * @param soapFactory the AXIOM SOAPFactory - */ - public AxiomSoapMessage(SOAPFactory soapFactory, boolean payloadCaching, boolean langAttributeOnSoap11FaultString) { - SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope(); - axiomFactory = soapFactory; - axiomMessage = axiomFactory.createSOAPMessage(); - axiomMessage.setSOAPEnvelope(soapEnvelope); - attachments = new Attachments(); - this.payloadCaching = payloadCaching; - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - soapAction = EMPTY_SOAP_ACTION; - } + /** + * Create a new, empty {@code AxiomSoapMessage}. + * + * @param soapFactory the AXIOM SOAPFactory + */ + public AxiomSoapMessage(SOAPFactory soapFactory, boolean payloadCaching, boolean langAttributeOnSoap11FaultString) { + SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope(); + axiomFactory = soapFactory; + axiomMessage = axiomFactory.createSOAPMessage(); + axiomMessage.setSOAPEnvelope(soapEnvelope); + attachments = new Attachments(); + this.payloadCaching = payloadCaching; + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + soapAction = EMPTY_SOAP_ACTION; + } - /** - * Create a new {@code AxiomSoapMessage} based on the given AXIOM {@code SOAPMessage}. - * - * @param soapMessage the AXIOM SOAPMessage - * @param soapAction the value of the SOAP Action header - * @param payloadCaching whether the contents of the SOAP body should be cached or not - */ - public AxiomSoapMessage(SOAPMessage soapMessage, - String soapAction, - boolean payloadCaching, - boolean langAttributeOnSoap11FaultString) { - this(soapMessage, new Attachments(), soapAction, payloadCaching, langAttributeOnSoap11FaultString); - } + /** + * Create a new {@code AxiomSoapMessage} based on the given AXIOM {@code SOAPMessage}. + * + * @param soapMessage the AXIOM SOAPMessage + * @param soapAction the value of the SOAP Action header + * @param payloadCaching whether the contents of the SOAP body should be cached or not + */ + public AxiomSoapMessage(SOAPMessage soapMessage, + String soapAction, + boolean payloadCaching, + boolean langAttributeOnSoap11FaultString) { + this(soapMessage, new Attachments(), soapAction, payloadCaching, langAttributeOnSoap11FaultString); + } - /** - * Create a new {@code AxiomSoapMessage} based on the given AXIOM {@code SOAPMessage} and attachments. - * - * @param soapMessage the AXIOM SOAPMessage - * @param attachments the attachments - * @param soapAction the value of the SOAP Action header - * @param payloadCaching whether the contents of the SOAP body should be cached or not - */ - public AxiomSoapMessage(SOAPMessage soapMessage, - Attachments attachments, - String soapAction, - boolean payloadCaching, - boolean langAttributeOnSoap11FaultString) { - Assert.notNull(soapMessage, "'soapMessage' must not be null"); - Assert.notNull(attachments, "'attachments' must not be null"); - axiomMessage = soapMessage; - axiomFactory = (SOAPFactory) soapMessage.getSOAPEnvelope().getOMFactory(); - this.attachments = attachments; - if (!StringUtils.hasLength(soapAction)) { - soapAction = EMPTY_SOAP_ACTION; - } - this.soapAction = soapAction; - this.payloadCaching = payloadCaching; - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + /** + * Create a new {@code AxiomSoapMessage} based on the given AXIOM {@code SOAPMessage} and attachments. + * + * @param soapMessage the AXIOM SOAPMessage + * @param attachments the attachments + * @param soapAction the value of the SOAP Action header + * @param payloadCaching whether the contents of the SOAP body should be cached or not + */ + public AxiomSoapMessage(SOAPMessage soapMessage, + Attachments attachments, + String soapAction, + boolean payloadCaching, + boolean langAttributeOnSoap11FaultString) { + Assert.notNull(soapMessage, "'soapMessage' must not be null"); + Assert.notNull(attachments, "'attachments' must not be null"); + axiomMessage = soapMessage; + axiomFactory = (SOAPFactory) soapMessage.getSOAPEnvelope().getOMFactory(); + this.attachments = attachments; + if (!StringUtils.hasLength(soapAction)) { + soapAction = EMPTY_SOAP_ACTION; + } + this.soapAction = soapAction; + this.payloadCaching = payloadCaching; + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } - /** Return the AXIOM {@code SOAPMessage} that this {@code AxiomSoapMessage} is based on. */ - public final SOAPMessage getAxiomMessage() { - return axiomMessage; - } + /** Return the AXIOM {@code SOAPMessage} that this {@code AxiomSoapMessage} is based on. */ + public final SOAPMessage getAxiomMessage() { + return axiomMessage; + } - /** - * Sets the AXIOM {@code SOAPMessage} that this {@code AxiomSoapMessage} is based on. - * - *

Calling this method also clears the SOAP Action property. - */ - public final void setAxiomMessage(SOAPMessage axiomMessage) { - Assert.notNull(axiomMessage, "'axiomMessage' must not be null"); - this.axiomMessage = axiomMessage; - this.envelope = null; - this.soapAction = EMPTY_SOAP_ACTION; - } + /** + * Sets the AXIOM {@code SOAPMessage} that this {@code AxiomSoapMessage} is based on. + * + *

Calling this method also clears the SOAP Action property. + */ + public final void setAxiomMessage(SOAPMessage axiomMessage) { + Assert.notNull(axiomMessage, "'axiomMessage' must not be null"); + this.axiomMessage = axiomMessage; + this.envelope = null; + this.soapAction = EMPTY_SOAP_ACTION; + } - /** - * Sets the {@link OMOutputFormat} to be used when writing the message. - * - * @see #writeTo(java.io.OutputStream) - */ - public void setOutputFormat(OMOutputFormat outputFormat) { - this.outputFormat = outputFormat; - } + /** + * Sets the {@link OMOutputFormat} to be used when writing the message. + * + * @see #writeTo(java.io.OutputStream) + */ + public void setOutputFormat(OMOutputFormat outputFormat) { + this.outputFormat = outputFormat; + } - @Override - public void setStreamingPayload(StreamingPayload payload) { - AxiomSoapBody soapBody = (AxiomSoapBody) getSoapBody(); - soapBody.setStreamingPayload(payload); - } + @Override + public void setStreamingPayload(StreamingPayload payload) { + AxiomSoapBody soapBody = (AxiomSoapBody) getSoapBody(); + soapBody.setStreamingPayload(payload); + } - @Override - public SoapEnvelope getEnvelope() { - if (envelope == null) { - try { - envelope = new AxiomSoapEnvelope(axiomMessage.getSOAPEnvelope(), axiomFactory, payloadCaching, - langAttributeOnSoap11FaultString); - } - catch (SOAPProcessingException ex) { - throw new AxiomSoapEnvelopeException(ex); - } - } - return envelope; - } + @Override + public SoapEnvelope getEnvelope() { + if (envelope == null) { + try { + envelope = new AxiomSoapEnvelope(axiomMessage.getSOAPEnvelope(), axiomFactory, payloadCaching, + langAttributeOnSoap11FaultString); + } + catch (SOAPProcessingException ex) { + throw new AxiomSoapEnvelopeException(ex); + } + } + return envelope; + } - @Override - public String getSoapAction() { - return soapAction; - } + @Override + public String getSoapAction() { + return soapAction; + } - @Override - public void setSoapAction(String soapAction) { - soapAction = SoapUtils.escapeAction(soapAction); - this.soapAction = soapAction; - } + @Override + public void setSoapAction(String soapAction) { + soapAction = SoapUtils.escapeAction(soapAction); + this.soapAction = soapAction; + } - @Override - public Document getDocument() { - return AxiomUtils.toDocument(axiomMessage.getSOAPEnvelope()); - } + @Override + public Document getDocument() { + return AxiomUtils.toDocument(axiomMessage.getSOAPEnvelope()); + } - @Override - public void setDocument(Document document) { - // save the Soap Action - String soapAction = getSoapAction(); - SOAPEnvelope envelope = AxiomUtils.toEnvelope(document); - SOAPMessage newMessage = axiomFactory.createSOAPMessage(); - newMessage.setSOAPEnvelope(envelope); + @Override + public void setDocument(Document document) { + // save the Soap Action + String soapAction = getSoapAction(); + SOAPEnvelope envelope = AxiomUtils.toEnvelope(document); + SOAPMessage newMessage = axiomFactory.createSOAPMessage(); + newMessage.setSOAPEnvelope(envelope); - // replace the Axiom message - setAxiomMessage(newMessage); - // restore the Soap Action - setSoapAction(soapAction); - } + // replace the Axiom message + setAxiomMessage(newMessage); + // restore the Soap Action + setSoapAction(soapAction); + } - @Override - public boolean isXopPackage() { - try { - return MTOMConstants.MTOM_TYPE.equals(attachments.getAttachmentSpecType()); - } - catch (OMException ex) { - return false; - } - catch (NullPointerException ex) { - // gotta love Axis2 - return false; - } - } + @Override + public boolean isXopPackage() { + try { + return MTOMConstants.MTOM_TYPE.equals(attachments.getAttachmentSpecType()); + } + catch (OMException ex) { + return false; + } + catch (NullPointerException ex) { + // gotta love Axis2 + return false; + } + } - @Override - public boolean convertToXopPackage() { - return false; - } + @Override + public boolean convertToXopPackage() { + return false; + } - @Override - public Attachment getAttachment(String contentId) { - Assert.hasLength(contentId, "contentId must not be empty"); - if (contentId.startsWith("<") && contentId.endsWith(">")) { - contentId = contentId.substring(1, contentId.length() - 1); - } - DataHandler dataHandler = attachments.getDataHandler(contentId); - return dataHandler != null ? new AxiomAttachment(contentId, dataHandler) : null; - } + @Override + public Attachment getAttachment(String contentId) { + Assert.hasLength(contentId, "contentId must not be empty"); + if (contentId.startsWith("<") && contentId.endsWith(">")) { + contentId = contentId.substring(1, contentId.length() - 1); + } + DataHandler dataHandler = attachments.getDataHandler(contentId); + return dataHandler != null ? new AxiomAttachment(contentId, dataHandler) : null; + } - @Override - public Iterator getAttachments() { - return new AxiomAttachmentIterator(); - } + @Override + public Iterator getAttachments() { + return new AxiomAttachmentIterator(); + } - @Override - public Attachment addAttachment(String contentId, DataHandler dataHandler) { - Assert.hasLength(contentId, "contentId must not be empty"); - Assert.notNull(dataHandler, "dataHandler must not be null"); - attachments.addDataHandler(contentId, dataHandler); - return new AxiomAttachment(contentId, dataHandler); - } + @Override + public Attachment addAttachment(String contentId, DataHandler dataHandler) { + Assert.hasLength(contentId, "contentId must not be empty"); + Assert.notNull(dataHandler, "dataHandler must not be null"); + attachments.addDataHandler(contentId, dataHandler); + return new AxiomAttachment(contentId, dataHandler); + } - @Override - public void writeTo(OutputStream outputStream) throws IOException { - try { + @Override + public void writeTo(OutputStream outputStream) throws IOException { + try { - OMOutputFormat outputFormat = getOutputFormat(); - if (outputStream instanceof TransportOutputStream) { - TransportOutputStream transportOutputStream = (TransportOutputStream) outputStream; - String contentType = outputFormat.getContentType(); - if (!(outputFormat.isDoingSWA() || outputFormat.isOptimized())) { - String charsetEncoding = axiomMessage.getCharsetEncoding(); - contentType += "; charset=" + charsetEncoding; - } - SoapVersion version = getVersion(); - if (SoapVersion.SOAP_11 == version) { - transportOutputStream.addHeader(TransportConstants.HEADER_SOAP_ACTION, soapAction); - transportOutputStream.addHeader(TransportConstants.HEADER_ACCEPT, version.getContentType()); - } - else if (SoapVersion.SOAP_12 == version) { - contentType += "; action=" + soapAction; - transportOutputStream.addHeader(TransportConstants.HEADER_ACCEPT, version.getContentType()); - } - transportOutputStream.addHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType); + OMOutputFormat outputFormat = getOutputFormat(); + if (outputStream instanceof TransportOutputStream) { + TransportOutputStream transportOutputStream = (TransportOutputStream) outputStream; + String contentType = outputFormat.getContentType(); + if (!(outputFormat.isDoingSWA() || outputFormat.isOptimized())) { + String charsetEncoding = axiomMessage.getCharsetEncoding(); + contentType += "; charset=" + charsetEncoding; + } + SoapVersion version = getVersion(); + if (SoapVersion.SOAP_11 == version) { + transportOutputStream.addHeader(TransportConstants.HEADER_SOAP_ACTION, soapAction); + transportOutputStream.addHeader(TransportConstants.HEADER_ACCEPT, version.getContentType()); + } + else if (SoapVersion.SOAP_12 == version) { + contentType += "; action=" + soapAction; + transportOutputStream.addHeader(TransportConstants.HEADER_ACCEPT, version.getContentType()); + } + transportOutputStream.addHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType); - } - if (!(outputFormat.isOptimized()) & outputFormat.isDoingSWA()) { - writeSwAMessage(outputStream, outputFormat); - } - else { - if (payloadCaching) { - axiomMessage.serialize(outputStream, outputFormat); - } - else { - axiomMessage.serializeAndConsume(outputStream, outputFormat); - } - } - outputStream.flush(); - } - catch (XMLStreamException ex) { - throw new AxiomSoapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); - } - catch (OMException ex) { - throw new AxiomSoapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); - } - } + } + if (!(outputFormat.isOptimized()) & outputFormat.isDoingSWA()) { + writeSwAMessage(outputStream, outputFormat); + } + else { + if (payloadCaching) { + axiomMessage.serialize(outputStream, outputFormat); + } + else { + axiomMessage.serializeAndConsume(outputStream, outputFormat); + } + } + outputStream.flush(); + } + catch (XMLStreamException ex) { + throw new AxiomSoapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); + } + catch (OMException ex) { + throw new AxiomSoapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); + } + } - private OMOutputFormat getOutputFormat() { - if (outputFormat != null) { - return outputFormat; - } - else { - String charsetEncoding = axiomMessage.getCharsetEncoding(); + private OMOutputFormat getOutputFormat() { + if (outputFormat != null) { + return outputFormat; + } + else { + String charsetEncoding = axiomMessage.getCharsetEncoding(); - OMOutputFormat outputFormat = new OMOutputFormat(); - outputFormat.setCharSetEncoding(charsetEncoding); - outputFormat.setSOAP11(getVersion() == SoapVersion.SOAP_11); - if (isXopPackage()) { - outputFormat.setDoOptimize(true); - } - else if (!attachments.getContentIDSet().isEmpty()) { - outputFormat.setDoingSWA(true); - } - return outputFormat; - } - } + OMOutputFormat outputFormat = new OMOutputFormat(); + outputFormat.setCharSetEncoding(charsetEncoding); + outputFormat.setSOAP11(getVersion() == SoapVersion.SOAP_11); + if (isXopPackage()) { + outputFormat.setDoOptimize(true); + } + else if (!attachments.getContentIDSet().isEmpty()) { + outputFormat.setDoingSWA(true); + } + return outputFormat; + } + } - private void writeSwAMessage(OutputStream outputStream, OMOutputFormat format) - throws XMLStreamException, UnsupportedEncodingException { - StringWriter writer = new StringWriter(); - SOAPEnvelope envelope = axiomMessage.getSOAPEnvelope(); - if (payloadCaching) { - envelope.serialize(writer, format); - } - else { - envelope.serializeAndConsume(writer, format); - } + private void writeSwAMessage(OutputStream outputStream, OMOutputFormat format) + throws XMLStreamException, UnsupportedEncodingException { + StringWriter writer = new StringWriter(); + SOAPEnvelope envelope = axiomMessage.getSOAPEnvelope(); + if (payloadCaching) { + envelope.serialize(writer, format); + } + else { + envelope.serializeAndConsume(writer, format); + } - try { - OMMultipartWriter mpw = new OMMultipartWriter(outputStream, format); + try { + OMMultipartWriter mpw = new OMMultipartWriter(outputStream, format); - Writer rootPartWriter = new OutputStreamWriter(mpw.writeRootPart(), - format.getCharSetEncoding()); - rootPartWriter.write(writer.toString()); - rootPartWriter.close(); + Writer rootPartWriter = new OutputStreamWriter(mpw.writeRootPart(), + format.getCharSetEncoding()); + rootPartWriter.write(writer.toString()); + rootPartWriter.close(); - // Get the collection of ids associated with the attachments - for (String id: attachments.getAllContentIDs()) { - mpw.writePart(attachments.getDataHandler(id), id); - } + // Get the collection of ids associated with the attachments + for (String id: attachments.getAllContentIDs()) { + mpw.writePart(attachments.getDataHandler(id), id); + } - mpw.complete(); - } - catch (IOException ex) { - throw new OMException("Error writing SwA message", ex); - } - } + mpw.complete(); + } + catch (IOException ex) { + throw new OMException("Error writing SwA message", ex); + } + } - public String toString() { - StringBuilder builder = new StringBuilder("AxiomSoapMessage"); - if (payloadCaching) { - try { - SOAPEnvelope envelope = axiomMessage.getSOAPEnvelope(); - if (envelope != null) { - SOAPBody body = envelope.getBody(); - if (body != null) { - OMElement bodyElement = body.getFirstElement(); - if (bodyElement != null) { - builder.append(' '); - builder.append(bodyElement.getQName()); - } - } - } - } - catch (OMException ex) { - // ignore - } - } - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("AxiomSoapMessage"); + if (payloadCaching) { + try { + SOAPEnvelope envelope = axiomMessage.getSOAPEnvelope(); + if (envelope != null) { + SOAPBody body = envelope.getBody(); + if (body != null) { + OMElement bodyElement = body.getFirstElement(); + if (bodyElement != null) { + builder.append(' '); + builder.append(bodyElement.getQName()); + } + } + } + } + catch (OMException ex) { + // ignore + } + } + return builder.toString(); + } - private class AxiomAttachmentIterator implements Iterator { + private class AxiomAttachmentIterator implements Iterator { - private final Iterator iterator; + private final Iterator iterator; - @SuppressWarnings("unchecked") - private AxiomAttachmentIterator() { - iterator = attachments.getContentIDSet().iterator(); - } + @SuppressWarnings("unchecked") + private AxiomAttachmentIterator() { + iterator = attachments.getContentIDSet().iterator(); + } - @Override - public boolean hasNext() { - return iterator.hasNext(); - } + @Override + public boolean hasNext() { + return iterator.hasNext(); + } - @Override - public Attachment next() { - String contentId = iterator.next(); - DataHandler dataHandler = attachments.getDataHandler(contentId); - return new AxiomAttachment(contentId, dataHandler); - } + @Override + public Attachment next() { + String contentId = iterator.next(); + DataHandler dataHandler = attachments.getDataHandler(contentId); + return new AxiomAttachment(contentId, dataHandler); + } - @Override - public void remove() { - iterator.remove(); - } - } + @Override + public void remove() { + iterator.remove(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageCreationException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageCreationException.java index bf6ad5b1..93815f9d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageCreationException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageCreationException.java @@ -25,11 +25,11 @@ import org.springframework.ws.soap.SoapMessageCreationException; @SuppressWarnings("serial") public class AxiomSoapMessageCreationException extends SoapMessageCreationException { - public AxiomSoapMessageCreationException(String msg) { - super(msg); - } + public AxiomSoapMessageCreationException(String msg) { + super(msg); + } - public AxiomSoapMessageCreationException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapMessageCreationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageException.java index 6db0a3ad..7aba23c4 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageException.java @@ -25,11 +25,11 @@ import org.springframework.ws.soap.SoapMessageException; @SuppressWarnings("serial") public class AxiomSoapMessageException extends SoapMessageException { - public AxiomSoapMessageException(String msg) { - super(msg); - } + public AxiomSoapMessageException(String msg) { + super(msg); + } - public AxiomSoapMessageException(String msg, Throwable ex) { - super(msg, ex); - } + public AxiomSoapMessageException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageFactory.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageFactory.java index a8477a98..3b9ee1e8 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageFactory.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoapMessageFactory.java @@ -81,105 +81,105 @@ import org.springframework.ws.transport.TransportInputStream; */ public class AxiomSoapMessageFactory implements SoapMessageFactory, InitializingBean { - private static final String CHARSET_PARAMETER = "charset"; + private static final String CHARSET_PARAMETER = "charset"; - private static final String DEFAULT_CHARSET_ENCODING = "UTF-8"; + private static final String DEFAULT_CHARSET_ENCODING = "UTF-8"; - private static final String MULTI_PART_RELATED_CONTENT_TYPE = "multipart/related"; + private static final String MULTI_PART_RELATED_CONTENT_TYPE = "multipart/related"; - private static final Log logger = LogFactory.getLog(AxiomSoapMessageFactory.class); + private static final Log logger = LogFactory.getLog(AxiomSoapMessageFactory.class); - private XMLInputFactory inputFactory; + private XMLInputFactory inputFactory; - private boolean payloadCaching = true; + private boolean payloadCaching = true; - private boolean attachmentCaching = false; + private boolean attachmentCaching = false; - private File attachmentCacheDir; + private File attachmentCacheDir; - private int attachmentCacheThreshold = 4096; + private int attachmentCacheThreshold = 4096; - // use SOAP 1.1 by default - private SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory(); + // use SOAP 1.1 by default + private SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory(); - private boolean langAttributeOnSoap11FaultString = true; + private boolean langAttributeOnSoap11FaultString = true; private boolean replacingEntityReferences = false; private boolean supportingExternalEntities = false; - /** - * Indicates whether the SOAP Body payload should be cached or not. Default is {@code true}. - * - *

Setting this to {@code false} will increase performance, but also result in the fact that the message - * payload can only be read once. - */ - public void setPayloadCaching(boolean payloadCaching) { - this.payloadCaching = payloadCaching; - } + /** + * Indicates whether the SOAP Body payload should be cached or not. Default is {@code true}. + * + *

Setting this to {@code false} will increase performance, but also result in the fact that the message + * payload can only be read once. + */ + public void setPayloadCaching(boolean payloadCaching) { + this.payloadCaching = payloadCaching; + } - /** - * Indicates whether SOAP attachments should be cached or not. Default is {@code false}. - * - *

Setting this to {@code true} will cause Axiom to store larger attachments on disk, rather than in memory. - * This decreases memory consumption, but decreases performance. - */ - public void setAttachmentCaching(boolean attachmentCaching) { - this.attachmentCaching = attachmentCaching; - } + /** + * Indicates whether SOAP attachments should be cached or not. Default is {@code false}. + * + *

Setting this to {@code true} will cause Axiom to store larger attachments on disk, rather than in memory. + * This decreases memory consumption, but decreases performance. + */ + public void setAttachmentCaching(boolean attachmentCaching) { + this.attachmentCaching = attachmentCaching; + } - /** - * Sets the directory where SOAP attachments will be stored. Only used when {@link #setAttachmentCaching(boolean) - * attachmentCaching} is set to {@code true}. - * - *

The parameter should be an existing, writable directory. This property defaults to the temporary directory of the - * operating system (i.e. the value of the {@code java.io.tmpdir} system property). - */ - public void setAttachmentCacheDir(File attachmentCacheDir) { - Assert.notNull(attachmentCacheDir, "'attachmentCacheDir' must not be null"); - Assert.isTrue(attachmentCacheDir.isDirectory(), "'attachmentCacheDir' must be a directory"); - Assert.isTrue(attachmentCacheDir.canWrite(), "'attachmentCacheDir' must be writable"); - this.attachmentCacheDir = attachmentCacheDir; - } + /** + * Sets the directory where SOAP attachments will be stored. Only used when {@link #setAttachmentCaching(boolean) + * attachmentCaching} is set to {@code true}. + * + *

The parameter should be an existing, writable directory. This property defaults to the temporary directory of the + * operating system (i.e. the value of the {@code java.io.tmpdir} system property). + */ + public void setAttachmentCacheDir(File attachmentCacheDir) { + Assert.notNull(attachmentCacheDir, "'attachmentCacheDir' must not be null"); + Assert.isTrue(attachmentCacheDir.isDirectory(), "'attachmentCacheDir' must be a directory"); + Assert.isTrue(attachmentCacheDir.canWrite(), "'attachmentCacheDir' must be writable"); + this.attachmentCacheDir = attachmentCacheDir; + } - /** - * Sets the threshold for attachments caching, in bytes. Attachments larger than this threshold will be cached in - * the {@link #setAttachmentCacheDir(File) attachment cache directory}. Only used when {@link - * #setAttachmentCaching(boolean) attachmentCaching} is set to {@code true}. - * - *

Defaults to 4096 bytes (i.e. 4 kilobytes). - */ - public void setAttachmentCacheThreshold(int attachmentCacheThreshold) { - Assert.isTrue(attachmentCacheThreshold > 0, "'attachmentCacheThreshold' must be larger than 0"); - this.attachmentCacheThreshold = attachmentCacheThreshold; - } + /** + * Sets the threshold for attachments caching, in bytes. Attachments larger than this threshold will be cached in + * the {@link #setAttachmentCacheDir(File) attachment cache directory}. Only used when {@link + * #setAttachmentCaching(boolean) attachmentCaching} is set to {@code true}. + * + *

Defaults to 4096 bytes (i.e. 4 kilobytes). + */ + public void setAttachmentCacheThreshold(int attachmentCacheThreshold) { + Assert.isTrue(attachmentCacheThreshold > 0, "'attachmentCacheThreshold' must be larger than 0"); + this.attachmentCacheThreshold = attachmentCacheThreshold; + } - @Override - public void setSoapVersion(SoapVersion version) { - if (SoapVersion.SOAP_11 == version) { - soapFactory = OMAbstractFactory.getSOAP11Factory(); - } - else if (SoapVersion.SOAP_12 == version) { - soapFactory = OMAbstractFactory.getSOAP12Factory(); - } - else { - throw new IllegalArgumentException( - "Invalid version [" + version + "]. " + "Expected the SOAP_11 or SOAP_12 constant"); - } - } + @Override + public void setSoapVersion(SoapVersion version) { + if (SoapVersion.SOAP_11 == version) { + soapFactory = OMAbstractFactory.getSOAP11Factory(); + } + else if (SoapVersion.SOAP_12 == version) { + soapFactory = OMAbstractFactory.getSOAP12Factory(); + } + else { + throw new IllegalArgumentException( + "Invalid version [" + version + "]. " + "Expected the SOAP_11 or SOAP_12 constant"); + } + } - /** - * Defines whether a {@code xml:lang} attribute should be set on SOAP 1.1 {@code } elements. - * - *

The default is {@code true}, to comply with WS-I, but this flag can be set to {@code false} to the older W3C SOAP - * 1.1 specification. - * - * @see WS-I Basic Profile 1.1 - */ - public void setLangAttributeOnSoap11FaultString(boolean langAttributeOnSoap11FaultString) { - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + /** + * Defines whether a {@code xml:lang} attribute should be set on SOAP 1.1 {@code } elements. + * + *

The default is {@code true}, to comply with WS-I, but this flag can be set to {@code false} to the older W3C SOAP + * 1.1 specification. + * + * @see WS-I Basic Profile 1.1 + */ + public void setLangAttributeOnSoap11FaultString(boolean langAttributeOnSoap11FaultString) { + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } /** * Sets whether internal entity references should be replaced with their replacement @@ -199,192 +199,192 @@ public class AxiomSoapMessageFactory implements SoapMessageFactory, Initializing } @Override - public void afterPropertiesSet() throws Exception { - if (logger.isInfoEnabled()) { - logger.info(payloadCaching ? "Enabled payload caching" : "Disabled payload caching"); - } - if (attachmentCacheDir == null) { - String tempDir = System.getProperty("java.io.tmpdir"); - setAttachmentCacheDir(new File(tempDir)); - } + public void afterPropertiesSet() throws Exception { + if (logger.isInfoEnabled()) { + logger.info(payloadCaching ? "Enabled payload caching" : "Disabled payload caching"); + } + if (attachmentCacheDir == null) { + String tempDir = System.getProperty("java.io.tmpdir"); + setAttachmentCacheDir(new File(tempDir)); + } inputFactory = createXmlInputFactory(); - } + } - @Override - public AxiomSoapMessage createWebServiceMessage() { - return new AxiomSoapMessage(soapFactory, payloadCaching, langAttributeOnSoap11FaultString); - } + @Override + public AxiomSoapMessage createWebServiceMessage() { + return new AxiomSoapMessage(soapFactory, payloadCaching, langAttributeOnSoap11FaultString); + } - @Override - public AxiomSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException { - Assert.isInstanceOf(TransportInputStream.class, inputStream, - "AxiomSoapMessageFactory requires a TransportInputStream"); - if (inputFactory == null) { - inputFactory = createXmlInputFactory(); - } - TransportInputStream transportInputStream = (TransportInputStream) inputStream; - String contentType = getHeaderValue(transportInputStream, TransportConstants.HEADER_CONTENT_TYPE); - if (!StringUtils.hasLength(contentType)) { - if (logger.isDebugEnabled()) { - logger.debug("TransportInputStream has no Content-Type header; defaulting to \"" + - SoapVersion.SOAP_11.getContentType() + "\""); - } - contentType = SoapVersion.SOAP_11.getContentType(); - } - String soapAction = getHeaderValue(transportInputStream, TransportConstants.HEADER_SOAP_ACTION); - if (!StringUtils.hasLength(soapAction)) { - soapAction = SoapUtils.extractActionFromContentType(contentType); - } - try { - if (isMultiPartRelated(contentType)) { - return createMultiPartAxiomSoapMessage(inputStream, contentType, soapAction); - } - else { - return createAxiomSoapMessage(inputStream, contentType, soapAction); - } - } - catch (XMLStreamException ex) { - throw new AxiomSoapMessageCreationException("Could not parse request: " + ex.getMessage(), ex); - } - catch (OMException ex) { - throw new AxiomSoapMessageCreationException("Could not create message: " + ex.getMessage(), ex); - } - } + @Override + public AxiomSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException { + Assert.isInstanceOf(TransportInputStream.class, inputStream, + "AxiomSoapMessageFactory requires a TransportInputStream"); + if (inputFactory == null) { + inputFactory = createXmlInputFactory(); + } + TransportInputStream transportInputStream = (TransportInputStream) inputStream; + String contentType = getHeaderValue(transportInputStream, TransportConstants.HEADER_CONTENT_TYPE); + if (!StringUtils.hasLength(contentType)) { + if (logger.isDebugEnabled()) { + logger.debug("TransportInputStream has no Content-Type header; defaulting to \"" + + SoapVersion.SOAP_11.getContentType() + "\""); + } + contentType = SoapVersion.SOAP_11.getContentType(); + } + String soapAction = getHeaderValue(transportInputStream, TransportConstants.HEADER_SOAP_ACTION); + if (!StringUtils.hasLength(soapAction)) { + soapAction = SoapUtils.extractActionFromContentType(contentType); + } + try { + if (isMultiPartRelated(contentType)) { + return createMultiPartAxiomSoapMessage(inputStream, contentType, soapAction); + } + else { + return createAxiomSoapMessage(inputStream, contentType, soapAction); + } + } + catch (XMLStreamException ex) { + throw new AxiomSoapMessageCreationException("Could not parse request: " + ex.getMessage(), ex); + } + catch (OMException ex) { + throw new AxiomSoapMessageCreationException("Could not create message: " + ex.getMessage(), ex); + } + } - private String getHeaderValue(TransportInputStream transportInputStream, String header) throws IOException { - String contentType = null; - Iterator iterator = transportInputStream.getHeaders(header); - if (iterator.hasNext()) { - contentType = iterator.next(); - } - return contentType; - } + private String getHeaderValue(TransportInputStream transportInputStream, String header) throws IOException { + String contentType = null; + Iterator iterator = transportInputStream.getHeaders(header); + if (iterator.hasNext()) { + contentType = iterator.next(); + } + return contentType; + } - private boolean isMultiPartRelated(String contentType) { - contentType = contentType.toLowerCase(Locale.ENGLISH); - return contentType.contains(MULTI_PART_RELATED_CONTENT_TYPE); - } + private boolean isMultiPartRelated(String contentType) { + contentType = contentType.toLowerCase(Locale.ENGLISH); + return contentType.contains(MULTI_PART_RELATED_CONTENT_TYPE); + } - /** Creates an AxiomSoapMessage without attachments. */ - private AxiomSoapMessage createAxiomSoapMessage(InputStream inputStream, String contentType, String soapAction) - throws XMLStreamException { - XMLStreamReader reader = inputFactory.createXMLStreamReader(inputStream, getCharSetEncoding(contentType)); - String envelopeNamespace = getSoapEnvelopeNamespace(contentType); - StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(reader, soapFactory, envelopeNamespace); - SOAPMessage soapMessage = builder.getSoapMessage(); - return new AxiomSoapMessage(soapMessage, soapAction, payloadCaching, langAttributeOnSoap11FaultString); - } + /** Creates an AxiomSoapMessage without attachments. */ + private AxiomSoapMessage createAxiomSoapMessage(InputStream inputStream, String contentType, String soapAction) + throws XMLStreamException { + XMLStreamReader reader = inputFactory.createXMLStreamReader(inputStream, getCharSetEncoding(contentType)); + String envelopeNamespace = getSoapEnvelopeNamespace(contentType); + StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(reader, soapFactory, envelopeNamespace); + SOAPMessage soapMessage = builder.getSoapMessage(); + return new AxiomSoapMessage(soapMessage, soapAction, payloadCaching, langAttributeOnSoap11FaultString); + } - /** Creates an AxiomSoapMessage with attachments. */ - private AxiomSoapMessage createMultiPartAxiomSoapMessage(InputStream inputStream, - String contentType, - String soapAction) throws XMLStreamException { - Attachments attachments = - new Attachments(inputStream, contentType, attachmentCaching, attachmentCacheDir.getAbsolutePath(), - Integer.toString(attachmentCacheThreshold)); - XMLStreamReader reader = inputFactory.createXMLStreamReader(attachments.getRootPartInputStream(), - getCharSetEncoding(attachments.getRootPartContentType())); - StAXSOAPModelBuilder builder; - String envelopeNamespace = getSoapEnvelopeNamespace(contentType); - if (MTOMConstants.SWA_TYPE.equals(attachments.getAttachmentSpecType()) || - MTOMConstants.SWA_TYPE_12.equals(attachments.getAttachmentSpecType())) { - builder = new StAXSOAPModelBuilder(reader, soapFactory, envelopeNamespace); - } - else if (MTOMConstants.MTOM_TYPE.equals(attachments.getAttachmentSpecType())) { - builder = new MTOMStAXSOAPModelBuilder(reader, attachments, envelopeNamespace); - } - else { - throw new AxiomSoapMessageCreationException( - "Unknown attachment type: [" + attachments.getAttachmentSpecType() + "]"); - } - return new AxiomSoapMessage(builder.getSoapMessage(), attachments, soapAction, payloadCaching, - langAttributeOnSoap11FaultString); - } + /** Creates an AxiomSoapMessage with attachments. */ + private AxiomSoapMessage createMultiPartAxiomSoapMessage(InputStream inputStream, + String contentType, + String soapAction) throws XMLStreamException { + Attachments attachments = + new Attachments(inputStream, contentType, attachmentCaching, attachmentCacheDir.getAbsolutePath(), + Integer.toString(attachmentCacheThreshold)); + XMLStreamReader reader = inputFactory.createXMLStreamReader(attachments.getRootPartInputStream(), + getCharSetEncoding(attachments.getRootPartContentType())); + StAXSOAPModelBuilder builder; + String envelopeNamespace = getSoapEnvelopeNamespace(contentType); + if (MTOMConstants.SWA_TYPE.equals(attachments.getAttachmentSpecType()) || + MTOMConstants.SWA_TYPE_12.equals(attachments.getAttachmentSpecType())) { + builder = new StAXSOAPModelBuilder(reader, soapFactory, envelopeNamespace); + } + else if (MTOMConstants.MTOM_TYPE.equals(attachments.getAttachmentSpecType())) { + builder = new MTOMStAXSOAPModelBuilder(reader, attachments, envelopeNamespace); + } + else { + throw new AxiomSoapMessageCreationException( + "Unknown attachment type: [" + attachments.getAttachmentSpecType() + "]"); + } + return new AxiomSoapMessage(builder.getSoapMessage(), attachments, soapAction, payloadCaching, + langAttributeOnSoap11FaultString); + } - private String getSoapEnvelopeNamespace(String contentType) { - if (contentType.contains(SOAP11Constants.SOAP_11_CONTENT_TYPE)) { - return SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI; - } - else if (contentType.contains(SOAP12Constants.SOAP_12_CONTENT_TYPE)) { - return SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI; - } - else { - throw new AxiomSoapMessageCreationException("Unknown content type '" + contentType + "'"); - } + private String getSoapEnvelopeNamespace(String contentType) { + if (contentType.contains(SOAP11Constants.SOAP_11_CONTENT_TYPE)) { + return SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI; + } + else if (contentType.contains(SOAP12Constants.SOAP_12_CONTENT_TYPE)) { + return SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI; + } + else { + throw new AxiomSoapMessageCreationException("Unknown content type '" + contentType + "'"); + } - } + } - /** - * Returns the character set from the given content type. Mostly copied - * - * @return the character set encoding - */ - protected String getCharSetEncoding(String contentType) { - int charSetIdx = contentType.indexOf(CHARSET_PARAMETER); - if (charSetIdx == -1) { - return DEFAULT_CHARSET_ENCODING; - } - int eqIdx = contentType.indexOf("=", charSetIdx); + /** + * Returns the character set from the given content type. Mostly copied + * + * @return the character set encoding + */ + protected String getCharSetEncoding(String contentType) { + int charSetIdx = contentType.indexOf(CHARSET_PARAMETER); + if (charSetIdx == -1) { + return DEFAULT_CHARSET_ENCODING; + } + int eqIdx = contentType.indexOf("=", charSetIdx); - int indexOfSemiColon = contentType.indexOf(";", eqIdx); - String value; + int indexOfSemiColon = contentType.indexOf(";", eqIdx); + String value; - if (indexOfSemiColon > 0) { - value = contentType.substring(eqIdx + 1, indexOfSemiColon); - } - else { - value = contentType.substring(eqIdx + 1, contentType.length()).trim(); - } - if (value.startsWith("\"")) { - value = value.substring(1); - } - if (value.endsWith("\"")) { - return value.substring(0, value.length() - 1); - } - if ("null".equalsIgnoreCase(value)) { - return DEFAULT_CHARSET_ENCODING; - } - else { - return value.trim(); - } - } + if (indexOfSemiColon > 0) { + value = contentType.substring(eqIdx + 1, indexOfSemiColon); + } + else { + value = contentType.substring(eqIdx + 1, contentType.length()).trim(); + } + if (value.startsWith("\"")) { + value = value.substring(1); + } + if (value.endsWith("\"")) { + return value.substring(0, value.length() - 1); + } + if ("null".equalsIgnoreCase(value)) { + return DEFAULT_CHARSET_ENCODING; + } + else { + return value.trim(); + } + } - /** - * Create a {@code XMLInputFactory} that this resolver will use to create {@link XMLStreamReader} objects. - * - *

Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached, - * so this method will only be called once. - * - *

By default this method creates a standard {@link XMLInputFactory} and configures it - * based on the {@link #setReplacingEntityReferences(boolean) replacingEntityReferences} - * and {@link #setSupportingExternalEntities(boolean) supportingExternalEntities} properties. - * - * @return the created factory - */ - protected XMLInputFactory createXmlInputFactory() { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, replacingEntityReferences); - inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, supportingExternalEntities); - return inputFactory; - } + /** + * Create a {@code XMLInputFactory} that this resolver will use to create {@link XMLStreamReader} objects. + * + *

Can be overridden in subclasses, adding further initialization of the factory. The resulting factory is cached, + * so this method will only be called once. + * + *

By default this method creates a standard {@link XMLInputFactory} and configures it + * based on the {@link #setReplacingEntityReferences(boolean) replacingEntityReferences} + * and {@link #setSupportingExternalEntities(boolean) supportingExternalEntities} properties. + * + * @return the created factory + */ + protected XMLInputFactory createXmlInputFactory() { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, replacingEntityReferences); + inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, supportingExternalEntities); + return inputFactory; + } - public String toString() { - StringBuilder builder = new StringBuilder("AxiomSoapMessageFactory["); - if (soapFactory.getSOAPVersion() == SOAP11Version.getSingleton()) { - builder.append("SOAP 1.1"); - } - else if (soapFactory.getSOAPVersion() == SOAP12Version.getSingleton()) { - builder.append("SOAP 1.2"); - } - builder.append(','); - if (payloadCaching) { - builder.append("PayloadCaching enabled"); - } - else { - builder.append("PayloadCaching disabled"); - } - builder.append(']'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("AxiomSoapMessageFactory["); + if (soapFactory.getSOAPVersion() == SOAP11Version.getSingleton()) { + builder.append("SOAP 1.1"); + } + else if (soapFactory.getSOAPVersion() == SOAP12Version.getSingleton()) { + builder.append("SOAP 1.2"); + } + builder.append(','); + if (payloadCaching) { + builder.append("PayloadCaching enabled"); + } + else { + builder.append("PayloadCaching disabled"); + } + builder.append(']'); + return builder.toString(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/CachingPayload.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/CachingPayload.java index 3842d59c..6f04992b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/CachingPayload.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/CachingPayload.java @@ -32,18 +32,18 @@ import org.apache.axiom.soap.SOAPFactory; @SuppressWarnings("Since15") class CachingPayload extends AbstractPayload { - CachingPayload(SOAPBody axiomBody, SOAPFactory axiomFactory) { - super(axiomBody, axiomFactory); - } + CachingPayload(SOAPBody axiomBody, SOAPFactory axiomFactory) { + super(axiomBody, axiomFactory); + } - @Override - protected XMLStreamReader getStreamReader(OMElement payloadElement) { - return payloadElement.getXMLStreamReader(); - } + @Override + protected XMLStreamReader getStreamReader(OMElement payloadElement) { + return payloadElement.getXMLStreamReader(); + } - @Override - public Result getResultInternal() { - return new AxiomResult(getAxiomBody(), getAxiomFactory()); - } + @Override + public Result getResultInternal() { + return new AxiomResult(getAxiomBody(), getAxiomFactory()); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/NonCachingPayload.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/NonCachingPayload.java index e7968b2d..a16272ea 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/NonCachingPayload.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/NonCachingPayload.java @@ -43,252 +43,252 @@ import org.springframework.util.xml.StaxUtils; */ class NonCachingPayload extends AbstractPayload { - private static final int BUF_SIZE = 1024; + private static final int BUF_SIZE = 1024; - NonCachingPayload(SOAPBody axiomBody, SOAPFactory axiomFactory) { - super(axiomBody, axiomFactory); - } + NonCachingPayload(SOAPBody axiomBody, SOAPFactory axiomFactory) { + super(axiomBody, axiomFactory); + } - @Override - public Result getResultInternal() { - return StaxUtils.createCustomStaxResult(new DelegatingStreamWriter()); - } + @Override + public Result getResultInternal() { + return StaxUtils.createCustomStaxResult(new DelegatingStreamWriter()); + } - @Override - protected XMLStreamReader getStreamReader(OMElement payloadElement) { - return payloadElement.getXMLStreamReaderWithoutCaching(); - } + @Override + protected XMLStreamReader getStreamReader(OMElement payloadElement) { + return payloadElement.getXMLStreamReaderWithoutCaching(); + } - private class DelegatingStreamWriter implements XMLStreamWriter { + private class DelegatingStreamWriter implements XMLStreamWriter { - private final ByteArrayOutputStream baos = new ByteArrayOutputStream(BUF_SIZE); + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(BUF_SIZE); - private final XMLStreamWriter delegate; + private final XMLStreamWriter delegate; - private QName name; + private QName name; - private String encoding = "UTF-8"; + private String encoding = "UTF-8"; - private int elementDepth = 0; + private int elementDepth = 0; - private boolean payloadAdded = false; + private boolean payloadAdded = false; - private DelegatingStreamWriter() { - try { - this.delegate = StAXUtils.createXMLStreamWriter(baos); - } - catch (XMLStreamException ex) { - throw new AxiomSoapBodyException("Could not determine payload root element", ex); - } - } + private DelegatingStreamWriter() { + try { + this.delegate = StAXUtils.createXMLStreamWriter(baos); + } + catch (XMLStreamException ex) { + throw new AxiomSoapBodyException("Could not determine payload root element", ex); + } + } - @Override - public void writeStartDocument() throws XMLStreamException { - // ignored - } + @Override + public void writeStartDocument() throws XMLStreamException { + // ignored + } - @Override - public void writeStartDocument(String version) throws XMLStreamException { - // ignored - } + @Override + public void writeStartDocument(String version) throws XMLStreamException { + // ignored + } - @Override - public void writeStartDocument(String encoding, String version) throws XMLStreamException { - this.encoding = encoding; - } + @Override + public void writeStartDocument(String encoding, String version) throws XMLStreamException { + this.encoding = encoding; + } - @Override - public void writeStartElement(String localName) throws XMLStreamException { - if (name == null) { - name = new QName(localName); - } - elementDepth++; - delegate.writeStartElement(localName); - } + @Override + public void writeStartElement(String localName) throws XMLStreamException { + if (name == null) { + name = new QName(localName); + } + elementDepth++; + delegate.writeStartElement(localName); + } - @Override - public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - if (name == null) { - name = new QName(namespaceURI, localName); - } - elementDepth++; - delegate.writeStartElement(namespaceURI, localName); - } + @Override + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + if (name == null) { + name = new QName(namespaceURI, localName); + } + elementDepth++; + delegate.writeStartElement(namespaceURI, localName); + } - @Override - public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - if (name == null) { - name = new QName(namespaceURI, localName, prefix); - } - elementDepth++; - delegate.writeStartElement(prefix, localName, namespaceURI); - } + @Override + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + if (name == null) { + name = new QName(namespaceURI, localName, prefix); + } + elementDepth++; + delegate.writeStartElement(prefix, localName, namespaceURI); + } - @Override - public void writeEndElement() throws XMLStreamException { - elementDepth--; - delegate.writeEndElement(); - addPayload(); - } + @Override + public void writeEndElement() throws XMLStreamException { + elementDepth--; + delegate.writeEndElement(); + addPayload(); + } - private void addPayload() throws XMLStreamException { - if (elementDepth <= 0 && !payloadAdded) { - delegate.flush(); - if (baos.size() > 0) { - byte[] buf = baos.toByteArray(); - OMDataSource dataSource = new ByteArrayDataSource(buf, encoding); - OMNamespace namespace = - getAxiomFactory().createOMNamespace(name.getNamespaceURI(), name.getPrefix()); - OMElement payloadElement = - getAxiomFactory().createOMElement(dataSource, name.getLocalPart(), namespace); - getAxiomBody().addChild(payloadElement); - payloadAdded = true; - } - } - } + private void addPayload() throws XMLStreamException { + if (elementDepth <= 0 && !payloadAdded) { + delegate.flush(); + if (baos.size() > 0) { + byte[] buf = baos.toByteArray(); + OMDataSource dataSource = new ByteArrayDataSource(buf, encoding); + OMNamespace namespace = + getAxiomFactory().createOMNamespace(name.getNamespaceURI(), name.getPrefix()); + OMElement payloadElement = + getAxiomFactory().createOMElement(dataSource, name.getLocalPart(), namespace); + getAxiomBody().addChild(payloadElement); + payloadAdded = true; + } + } + } - @Override - public void writeEmptyElement(String localName) throws XMLStreamException { - if (name == null) { - name = new QName(localName); - } - delegate.writeEmptyElement(localName); - addPayload(); - } + @Override + public void writeEmptyElement(String localName) throws XMLStreamException { + if (name == null) { + name = new QName(localName); + } + delegate.writeEmptyElement(localName); + addPayload(); + } - @Override - public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - if (name == null) { - name = new QName(namespaceURI, localName); - } - delegate.writeEmptyElement(namespaceURI, localName); - addPayload(); - } + @Override + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + if (name == null) { + name = new QName(namespaceURI, localName); + } + delegate.writeEmptyElement(namespaceURI, localName); + addPayload(); + } - @Override - public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - if (name == null) { - name = new QName(namespaceURI, localName, prefix); - } - delegate.writeEmptyElement(prefix, localName, namespaceURI); - addPayload(); - } + @Override + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + if (name == null) { + name = new QName(namespaceURI, localName, prefix); + } + delegate.writeEmptyElement(prefix, localName, namespaceURI); + addPayload(); + } - @Override - public void writeEndDocument() throws XMLStreamException { - elementDepth = 0; - delegate.writeEndDocument(); - addPayload(); - } + @Override + public void writeEndDocument() throws XMLStreamException { + elementDepth = 0; + delegate.writeEndDocument(); + addPayload(); + } - // Delegation + // Delegation - @Override - public void close() throws XMLStreamException { - addPayload(); - delegate.close(); - } + @Override + public void close() throws XMLStreamException { + addPayload(); + delegate.close(); + } - @Override - public void flush() throws XMLStreamException { - delegate.flush(); - } + @Override + public void flush() throws XMLStreamException { + delegate.flush(); + } - @Override - public NamespaceContext getNamespaceContext() { - return delegate.getNamespaceContext(); - } + @Override + public NamespaceContext getNamespaceContext() { + return delegate.getNamespaceContext(); + } - @Override - public String getPrefix(String uri) throws XMLStreamException { - return delegate.getPrefix(uri); - } + @Override + public String getPrefix(String uri) throws XMLStreamException { + return delegate.getPrefix(uri); + } - @Override - public Object getProperty(String name) throws IllegalArgumentException { - return delegate.getProperty(name); - } + @Override + public Object getProperty(String name) throws IllegalArgumentException { + return delegate.getProperty(name); + } - @Override - public void setDefaultNamespace(String uri) throws XMLStreamException { - delegate.setDefaultNamespace(uri); - } + @Override + public void setDefaultNamespace(String uri) throws XMLStreamException { + delegate.setDefaultNamespace(uri); + } - @Override - public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { - delegate.setNamespaceContext(context); - } + @Override + public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { + delegate.setNamespaceContext(context); + } - @Override - public void setPrefix(String prefix, String uri) throws XMLStreamException { - delegate.setPrefix(prefix, uri); - } + @Override + public void setPrefix(String prefix, String uri) throws XMLStreamException { + delegate.setPrefix(prefix, uri); + } - @Override - public void writeAttribute(String localName, String value) throws XMLStreamException { - delegate.writeAttribute(localName, value); - } + @Override + public void writeAttribute(String localName, String value) throws XMLStreamException { + delegate.writeAttribute(localName, value); + } - @Override - public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { - delegate.writeAttribute(namespaceURI, localName, value); - } + @Override + public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { + delegate.writeAttribute(namespaceURI, localName, value); + } - @Override - public void writeAttribute(String prefix, String namespaceURI, String localName, String value) - throws XMLStreamException { - delegate.writeAttribute(prefix, namespaceURI, localName, value); - } + @Override + public void writeAttribute(String prefix, String namespaceURI, String localName, String value) + throws XMLStreamException { + delegate.writeAttribute(prefix, namespaceURI, localName, value); + } - @Override - public void writeCData(String data) throws XMLStreamException { - delegate.writeCData(data); - } + @Override + public void writeCData(String data) throws XMLStreamException { + delegate.writeCData(data); + } - @Override - public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - delegate.writeCharacters(text, start, len); - } + @Override + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + delegate.writeCharacters(text, start, len); + } - @Override - public void writeCharacters(String text) throws XMLStreamException { - delegate.writeCharacters(text); - } + @Override + public void writeCharacters(String text) throws XMLStreamException { + delegate.writeCharacters(text); + } - @Override - public void writeComment(String data) throws XMLStreamException { - delegate.writeComment(data); - } + @Override + public void writeComment(String data) throws XMLStreamException { + delegate.writeComment(data); + } - @Override - public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { - delegate.writeDefaultNamespace(namespaceURI); - } + @Override + public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { + delegate.writeDefaultNamespace(namespaceURI); + } - @Override - public void writeDTD(String dtd) throws XMLStreamException { - delegate.writeDTD(dtd); - } + @Override + public void writeDTD(String dtd) throws XMLStreamException { + delegate.writeDTD(dtd); + } - @Override - public void writeEntityRef(String name) throws XMLStreamException { - delegate.writeEntityRef(name); - } + @Override + public void writeEntityRef(String name) throws XMLStreamException { + delegate.writeEntityRef(name); + } - @Override - public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { - delegate.writeNamespace(prefix, namespaceURI); - } + @Override + public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { + delegate.writeNamespace(prefix, namespaceURI); + } - @Override - public void writeProcessingInstruction(String target) throws XMLStreamException { - delegate.writeProcessingInstruction(target); - } + @Override + public void writeProcessingInstruction(String target) throws XMLStreamException { + delegate.writeProcessingInstruction(target); + } - @Override - public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - delegate.writeProcessingInstruction(target, data); - } + @Override + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + delegate.writeProcessingInstruction(target, data); + } - } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/Payload.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/Payload.java index 2e8abdcf..3706aff7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/Payload.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/Payload.java @@ -27,17 +27,17 @@ import javax.xml.transform.Source; */ abstract class Payload { - /** - * Returns the source of the payload. - * - * @return the source of the payload - */ - public abstract Source getSource(); + /** + * Returns the source of the payload. + * + * @return the source of the payload + */ + public abstract Source getSource(); - /** - * Returns the result of the payload. - * - * @return the result of the payload - */ - public abstract Result getResult(); + /** + * Returns the result of the payload. + * + * @return the result of the payload + */ + public abstract Result getResult(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/StreamingOMDataSource.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/StreamingOMDataSource.java index 7b786357..dfccf097 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/StreamingOMDataSource.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/StreamingOMDataSource.java @@ -40,44 +40,44 @@ import org.springframework.ws.stream.StreamingPayload; */ class StreamingOMDataSource implements OMDataSource { - private final StreamingPayload payload; + private final StreamingPayload payload; - StreamingOMDataSource(StreamingPayload payload) { - Assert.notNull(payload, "'payload' must not be null"); - this.payload = payload; - } + StreamingOMDataSource(StreamingPayload payload) { + Assert.notNull(payload, "'payload' must not be null"); + this.payload = payload; + } - @Override - public void serialize(OutputStream output, OMOutputFormat format) throws XMLStreamException { - XMLStreamWriter streamWriter; - if (format != null && StringUtils.hasLength(format.getCharSetEncoding())) { - streamWriter = StAXUtils.createXMLStreamWriter(output, format.getCharSetEncoding()); - } - else { - streamWriter = StAXUtils.createXMLStreamWriter(output); - } - serialize(streamWriter); - } + @Override + public void serialize(OutputStream output, OMOutputFormat format) throws XMLStreamException { + XMLStreamWriter streamWriter; + if (format != null && StringUtils.hasLength(format.getCharSetEncoding())) { + streamWriter = StAXUtils.createXMLStreamWriter(output, format.getCharSetEncoding()); + } + else { + streamWriter = StAXUtils.createXMLStreamWriter(output); + } + serialize(streamWriter); + } - @Override - public void serialize(Writer writer, OMOutputFormat format) throws XMLStreamException { - XMLStreamWriter streamWriter = StAXUtils.createXMLStreamWriter(writer); - serialize(streamWriter); - } + @Override + public void serialize(Writer writer, OMOutputFormat format) throws XMLStreamException { + XMLStreamWriter streamWriter = StAXUtils.createXMLStreamWriter(writer); + serialize(streamWriter); + } - @Override - public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException { - payload.writeTo(xmlWriter); - xmlWriter.flush(); - } + @Override + public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException { + payload.writeTo(xmlWriter); + xmlWriter.flush(); + } - @Override - public XMLStreamReader getReader() throws XMLStreamException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - serialize(bos, null); + @Override + public XMLStreamReader getReader() throws XMLStreamException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + serialize(bos, null); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - return StAXUtils.createXMLStreamReader(bis); - } + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + return StAXUtils.createXMLStreamReader(bis); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/support/AxiomUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/support/AxiomUtils.java index 87408ace..86f2594d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/support/AxiomUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/support/AxiomUtils.java @@ -56,144 +56,144 @@ import org.springframework.util.StringUtils; @SuppressWarnings("Since15") public abstract class AxiomUtils { - /** - * Converts a {@code javax.xml.namespace.QName} to a {@code org.apache.axiom.om.OMNamespace}. A - * {@code OMElement} is used to resolve the namespace, or to declare a new one. - * - * @param qName the {@code QName} to convert - * @param resolveElement the element used to resolve the Q - * @return the converted SAAJ Name - * @throws OMException if conversion is unsuccessful - * @throws IllegalArgumentException if {@code qName} is not fully qualified - */ - public static OMNamespace toNamespace(QName qName, OMElement resolveElement) throws OMException { - String prefix = qName.getPrefix(); - if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) { - return resolveElement.declareNamespace(qName.getNamespaceURI(), prefix); - } - else if (StringUtils.hasLength(qName.getNamespaceURI())) { - // check for existing namespace, and declare if necessary - return resolveElement.declareNamespace(qName.getNamespaceURI(), ""); - } - else { - throw new IllegalArgumentException("qName [" + qName + "] does not contain a namespace"); - } - } + /** + * Converts a {@code javax.xml.namespace.QName} to a {@code org.apache.axiom.om.OMNamespace}. A + * {@code OMElement} is used to resolve the namespace, or to declare a new one. + * + * @param qName the {@code QName} to convert + * @param resolveElement the element used to resolve the Q + * @return the converted SAAJ Name + * @throws OMException if conversion is unsuccessful + * @throws IllegalArgumentException if {@code qName} is not fully qualified + */ + public static OMNamespace toNamespace(QName qName, OMElement resolveElement) throws OMException { + String prefix = qName.getPrefix(); + if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) { + return resolveElement.declareNamespace(qName.getNamespaceURI(), prefix); + } + else if (StringUtils.hasLength(qName.getNamespaceURI())) { + // check for existing namespace, and declare if necessary + return resolveElement.declareNamespace(qName.getNamespaceURI(), ""); + } + else { + throw new IllegalArgumentException("qName [" + qName + "] does not contain a namespace"); + } + } - /** - * Converts the given locale to a {@code xml:lang} string, as used in Axiom Faults. - * - * @param locale the locale - * @return the language string - */ - public static String toLanguage(Locale locale) { - return locale.toString().replace('_', '-'); - } + /** + * Converts the given locale to a {@code xml:lang} string, as used in Axiom Faults. + * + * @param locale the locale + * @return the language string + */ + public static String toLanguage(Locale locale) { + return locale.toString().replace('_', '-'); + } - /** - * Converts the given locale to a {@code xml:lang} string, as used in Axiom Faults. - * - * @param language the language string - * @return the locale - */ - public static Locale toLocale(String language) { - language = language.replace('-', '_'); - return StringUtils.parseLocaleString(language); - } + /** + * Converts the given locale to a {@code xml:lang} string, as used in Axiom Faults. + * + * @param language the language string + * @return the locale + */ + public static Locale toLocale(String language) { + language = language.replace('-', '_'); + return StringUtils.parseLocaleString(language); + } - /** Removes the contents (i.e. children) of the container. */ - public static void removeContents(OMContainer container) { - for (Iterator iterator = container.getChildren(); iterator.hasNext();) { - iterator.next(); - iterator.remove(); - } - } + /** Removes the contents (i.e. children) of the container. */ + public static void removeContents(OMContainer container) { + for (Iterator iterator = container.getChildren(); iterator.hasNext();) { + iterator.next(); + iterator.remove(); + } + } - /** - * Converts a given AXIOM {@link org.apache.axiom.soap.SOAPEnvelope} to a {@link Document}. - * - * @param envelope the SOAP envelope to be converted - * @return the converted document - * @throws IllegalArgumentException in case of errors - * @see org.apache.rampart.util.Axis2Util.getDocumentFromSOAPEnvelope(SOAPEnvelope, boolean) - */ - public static Document toDocument(SOAPEnvelope envelope) { - try { - if (envelope instanceof Element) { - return ((Element) envelope).getOwnerDocument(); - } - else { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - envelope.build(); - envelope.serialize(bos); + /** + * Converts a given AXIOM {@link org.apache.axiom.soap.SOAPEnvelope} to a {@link Document}. + * + * @param envelope the SOAP envelope to be converted + * @return the converted document + * @throws IllegalArgumentException in case of errors + * @see org.apache.rampart.util.Axis2Util.getDocumentFromSOAPEnvelope(SOAPEnvelope, boolean) + */ + public static Document toDocument(SOAPEnvelope envelope) { + try { + if (envelope instanceof Element) { + return ((Element) envelope).getOwnerDocument(); + } + else { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + envelope.build(); + envelope.serialize(bos); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - return documentBuilderFactory.newDocumentBuilder().parse(bis); - } - } - catch (Exception ex) { - throw new IllegalArgumentException("Error in converting SOAP Envelope to Document", ex); - } - } + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + return documentBuilderFactory.newDocumentBuilder().parse(bis); + } + } + catch (Exception ex) { + throw new IllegalArgumentException("Error in converting SOAP Envelope to Document", ex); + } + } - /** - * Converts a given {@link Document} to an AXIOM {@link org.apache.axiom.soap.SOAPEnvelope}. - * - * @param document the document to be converted - * @return the converted envelope - * @throws IllegalArgumentException in case of errors - * @see org.apache.rampart.util.Axis2Util.getSOAPEnvelopeFromDOMDocument(Document, boolean) - */ - public static SOAPEnvelope toEnvelope(Document document) { - try { - DOMImplementation implementation = document.getImplementation(); - Assert.isInstanceOf(DOMImplementationLS.class, implementation); + /** + * Converts a given {@link Document} to an AXIOM {@link org.apache.axiom.soap.SOAPEnvelope}. + * + * @param document the document to be converted + * @return the converted envelope + * @throws IllegalArgumentException in case of errors + * @see org.apache.rampart.util.Axis2Util.getSOAPEnvelopeFromDOMDocument(Document, boolean) + */ + public static SOAPEnvelope toEnvelope(Document document) { + try { + DOMImplementation implementation = document.getImplementation(); + Assert.isInstanceOf(DOMImplementationLS.class, implementation); - DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation; - LSOutput output = loadSaveImplementation.createLSOutput(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - output.setByteStream(bos); + DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation; + LSOutput output = loadSaveImplementation.createLSOutput(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + output.setByteStream(bos); - LSSerializer serializer = loadSaveImplementation.createLSSerializer(); - serializer.write(document, output); + LSSerializer serializer = loadSaveImplementation.createLSSerializer(); + serializer.write(document, output); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - XMLInputFactory inputFactory = StAXUtils.getXMLInputFactory(); + XMLInputFactory inputFactory = StAXUtils.getXMLInputFactory(); - StAXSOAPModelBuilder stAXSOAPModelBuilder = - new StAXSOAPModelBuilder(inputFactory.createXMLStreamReader(bis), null); - SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope(); + StAXSOAPModelBuilder stAXSOAPModelBuilder = + new StAXSOAPModelBuilder(inputFactory.createXMLStreamReader(bis), null); + SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope(); - // Necessary to build a correct Axiom tree, see SWS-483 - envelope.serialize(new NullOutputStream()); + // Necessary to build a correct Axiom tree, see SWS-483 + envelope.serialize(new NullOutputStream()); - return envelope; - } - catch (Exception ex) { - IllegalArgumentException iaex = - new IllegalArgumentException("Error in converting Document to SOAP Envelope"); - iaex.initCause(ex); - throw iaex; - } - } + return envelope; + } + catch (Exception ex) { + IllegalArgumentException iaex = + new IllegalArgumentException("Error in converting Document to SOAP Envelope"); + iaex.initCause(ex); + throw iaex; + } + } - /** OutputStream that does nothing. */ - private static class NullOutputStream extends OutputStream { + /** OutputStream that does nothing. */ + private static class NullOutputStream extends OutputStream { - @Override - public void write(int b) throws IOException { - } + @Override + public void write(int b) throws IOException { + } - @Override - public void write(byte[] b) throws IOException { - } + @Override + public void write(byte[] b) throws IOException { + } - @Override - public void write(byte[] b, int off, int len) throws IOException { - } - } + @Override + public void write(byte[] b, int off, int len) throws IOException { + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/client/SoapFaultClientException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/client/SoapFaultClientException.java index 82cd2500..9cec009f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/client/SoapFaultClientException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/client/SoapFaultClientException.java @@ -32,38 +32,38 @@ import org.springframework.ws.soap.SoapMessage; @SuppressWarnings("serial") public class SoapFaultClientException extends WebServiceFaultException { - private final SoapFault soapFault; + private final SoapFault soapFault; - /** - * Create a new instance of the {@code SoapFaultClientException} class. - * - * @param faultMessage the fault message - */ - public SoapFaultClientException(SoapMessage faultMessage) { - super(faultMessage); - SoapBody body = faultMessage.getSoapBody(); - soapFault = body != null ? body.getFault() : null; - } + /** + * Create a new instance of the {@code SoapFaultClientException} class. + * + * @param faultMessage the fault message + */ + public SoapFaultClientException(SoapMessage faultMessage) { + super(faultMessage); + SoapBody body = faultMessage.getSoapBody(); + soapFault = body != null ? body.getFault() : null; + } - /** Returns the {@link SoapFault}. */ - public SoapFault getSoapFault() { - return soapFault; - } + /** Returns the {@link SoapFault}. */ + public SoapFault getSoapFault() { + return soapFault; + } - /** Returns the fault code. */ - public QName getFaultCode() { - return soapFault != null ? soapFault.getFaultCode() : null; - } + /** Returns the fault code. */ + public QName getFaultCode() { + return soapFault != null ? soapFault.getFaultCode() : null; + } - /** - * Returns the fault string or reason. For SOAP 1.1, this returns the fault string. For SOAP 1.2, this returns the - * fault reason for the default locale. - * - *

Note that this message returns the same as {@link #getMessage()}. - */ - public String getFaultStringOrReason() { - return soapFault != null ? soapFault.getFaultStringOrReason() : null; - } + /** + * Returns the fault string or reason. For SOAP 1.1, this returns the fault string. For SOAP 1.2, this returns the + * fault reason for the default locale. + * + *

Note that this message returns the same as {@link #getMessage()}. + */ + public String getFaultStringOrReason() { + return soapFault != null ? soapFault.getFaultStringOrReason() : null; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapActionCallback.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapActionCallback.java index 0290b868..089709d7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapActionCallback.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapActionCallback.java @@ -32,9 +32,9 @@ import org.springframework.ws.soap.SoapMessage; * WebServiceTemplate template = new WebServiceTemplate(messageFactory); * Result result = new DOMResult(); * template.sendSourceAndReceiveToResult( - * new StringSource("<content xmlns=\"http://tempuri.org\"/>"), - * new SoapActionCallback("http://tempuri.org/SOAPAction"), - * result); + * new StringSource("<content xmlns=\"http://tempuri.org\"/>"), + * new SoapActionCallback("http://tempuri.org/SOAPAction"), + * result); * * * @author Arjen Poutsma @@ -42,21 +42,21 @@ import org.springframework.ws.soap.SoapMessage; */ public class SoapActionCallback implements WebServiceMessageCallback { - private final String soapAction; + private final String soapAction; - /** Create a new {@code SoapActionCallback} with the given string SOAPAction. */ - public SoapActionCallback(String soapAction) { - if (!StringUtils.hasText(soapAction)) { - soapAction = "\"\""; - } - this.soapAction = soapAction; - } + /** Create a new {@code SoapActionCallback} with the given string SOAPAction. */ + public SoapActionCallback(String soapAction) { + if (!StringUtils.hasText(soapAction)) { + soapAction = "\"\""; + } + this.soapAction = soapAction; + } - @Override - public void doWithMessage(WebServiceMessage message) throws IOException { - Assert.isInstanceOf(SoapMessage.class, message); - SoapMessage soapMessage = (SoapMessage) message; - soapMessage.setSoapAction(soapAction); - } + @Override + public void doWithMessage(WebServiceMessage message) throws IOException { + Assert.isInstanceOf(SoapMessage.class, message); + SoapMessage soapMessage = (SoapMessage) message; + soapMessage.setSoapAction(soapAction); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapFaultMessageResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapFaultMessageResolver.java index 762da0ff..07a3daa1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapFaultMessageResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/client/core/SoapFaultMessageResolver.java @@ -32,9 +32,9 @@ import org.springframework.ws.soap.client.SoapFaultClientException; */ public class SoapFaultMessageResolver implements FaultMessageResolver { - @Override - public void resolveFault(WebServiceMessage message) throws IOException { - SoapMessage soapMessage = (SoapMessage) message; - throw new SoapFaultClientException(soapMessage); - } + @Override + public void resolveFault(WebServiceMessage message) throws IOException { + SoapMessage soapMessage = (SoapMessage) message; + throw new SoapFaultClientException(soapMessage); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachment.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachment.java index 6a6248a7..63125120 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachment.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachment.java @@ -34,50 +34,50 @@ import org.springframework.ws.mime.Attachment; */ class SaajAttachment implements Attachment { - private final AttachmentPart saajAttachment; + private final AttachmentPart saajAttachment; - public SaajAttachment(AttachmentPart saajAttachment) { - Assert.notNull(saajAttachment, "saajAttachment must not be null"); - this.saajAttachment = saajAttachment; - } + public SaajAttachment(AttachmentPart saajAttachment) { + Assert.notNull(saajAttachment, "saajAttachment must not be null"); + this.saajAttachment = saajAttachment; + } - @Override - public String getContentId() { - return saajAttachment.getContentId(); - } + @Override + public String getContentId() { + return saajAttachment.getContentId(); + } - @Override - public String getContentType() { - return saajAttachment.getContentType(); - } + @Override + public String getContentType() { + return saajAttachment.getContentType(); + } - @Override - public InputStream getInputStream() throws IOException { - try { - return saajAttachment.getDataHandler().getInputStream(); - } - catch (SOAPException ex) { - throw new SaajAttachmentException(ex); - } - } + @Override + public InputStream getInputStream() throws IOException { + try { + return saajAttachment.getDataHandler().getInputStream(); + } + catch (SOAPException ex) { + throw new SaajAttachmentException(ex); + } + } - @Override - public long getSize() { - try { - return saajAttachment.getSize(); - } - catch (SOAPException ex) { - throw new SaajAttachmentException(ex); - } - } + @Override + public long getSize() { + try { + return saajAttachment.getSize(); + } + catch (SOAPException ex) { + throw new SaajAttachmentException(ex); + } + } - @Override - public DataHandler getDataHandler() { - try { - return saajAttachment.getDataHandler(); - } - catch (SOAPException ex) { - throw new SaajAttachmentException(ex); - } - } + @Override + public DataHandler getDataHandler() { + try { + return saajAttachment.getDataHandler(); + } + catch (SOAPException ex) { + throw new SaajAttachmentException(ex); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachmentException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachmentException.java index b5a0d335..9288f380 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachmentException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajAttachmentException.java @@ -22,15 +22,15 @@ import org.springframework.ws.mime.AttachmentException; @SuppressWarnings("serial") public class SaajAttachmentException extends AttachmentException { - public SaajAttachmentException(String msg) { - super(msg); - } + public SaajAttachmentException(String msg) { + super(msg); + } - public SaajAttachmentException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajAttachmentException(String msg, Throwable ex) { + super(msg, ex); + } - public SaajAttachmentException(Throwable ex) { - super(ex); - } + public SaajAttachmentException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Body.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Body.java index c85873be..d369d1e9 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Body.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Body.java @@ -35,64 +35,64 @@ import org.springframework.ws.soap.soap11.Soap11Fault; */ class SaajSoap11Body extends SaajSoapBody implements Soap11Body { - private final boolean langAttributeOnSoap11FaultString; + private final boolean langAttributeOnSoap11FaultString; - SaajSoap11Body(SOAPBody body, boolean langAttributeOnSoap11FaultString) { - super(body); - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + SaajSoap11Body(SOAPBody body, boolean langAttributeOnSoap11FaultString) { + super(body); + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } - @Override - public Soap11Fault getFault() { - SOAPFault fault = getSaajBody().getFault(); - return fault != null ? new SaajSoap11Fault(fault) : null; - } + @Override + public Soap11Fault getFault() { + SOAPFault fault = getSaajBody().getFault(); + return fault != null ? new SaajSoap11Fault(fault) : null; + } - @Override - public Soap11Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) { - Assert.notNull(faultCode, "No faultCode given"); - Assert.hasLength(faultString, "faultString cannot be empty"); - Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); - Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); - if (!langAttributeOnSoap11FaultString) { - faultStringLocale = null; - } - try { - getSaajBody().removeContents(); - SOAPBody body = getSaajBody(); - SOAPFault result; - if (faultStringLocale == null) { - result = body.addFault(faultCode, faultString); - } - else { - result = body.addFault(faultCode, faultString, faultStringLocale); - } - SOAPFault saajFault = result; - return new SaajSoap11Fault(saajFault); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public Soap11Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) { + Assert.notNull(faultCode, "No faultCode given"); + Assert.hasLength(faultString, "faultString cannot be empty"); + Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); + Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); + if (!langAttributeOnSoap11FaultString) { + faultStringLocale = null; + } + try { + getSaajBody().removeContents(); + SOAPBody body = getSaajBody(); + SOAPFault result; + if (faultStringLocale == null) { + result = body.addFault(faultCode, faultString); + } + else { + result = body.addFault(faultCode, faultString, faultStringLocale); + } + SOAPFault saajFault = result; + return new SaajSoap11Fault(saajFault); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - @Override - public Soap11Fault addClientOrSenderFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_11.getClientOrSenderFaultName(), faultString, locale); - } + @Override + public Soap11Fault addClientOrSenderFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_11.getClientOrSenderFaultName(), faultString, locale); + } - @Override - public Soap11Fault addMustUnderstandFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_11.getMustUnderstandFaultName(), faultString, locale); - } + @Override + public Soap11Fault addMustUnderstandFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_11.getMustUnderstandFaultName(), faultString, locale); + } - @Override - public Soap11Fault addServerOrReceiverFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_11.getServerOrReceiverFaultName(), faultString, locale); - } + @Override + public Soap11Fault addServerOrReceiverFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_11.getServerOrReceiverFaultName(), faultString, locale); + } - @Override - public Soap11Fault addVersionMismatchFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_11.getVersionMismatchFaultName(), faultString, locale); - } + @Override + public Soap11Fault addVersionMismatchFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_11.getVersionMismatchFaultName(), faultString, locale); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Fault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Fault.java index 3635f5e7..e8c3cb5e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Fault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Fault.java @@ -30,32 +30,32 @@ import org.springframework.ws.soap.soap11.Soap11Fault; */ class SaajSoap11Fault extends SaajSoapFault implements Soap11Fault { - SaajSoap11Fault(SOAPFault fault) { - super(fault); - } + SaajSoap11Fault(SOAPFault fault) { + super(fault); + } - @Override - public String getFaultActorOrRole() { - return getSaajFault().getFaultActor(); - } + @Override + public String getFaultActorOrRole() { + return getSaajFault().getFaultActor(); + } - @Override - public void setFaultActorOrRole(String faultActor) { - try { - getSaajFault().setFaultActor(faultActor); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public void setFaultActorOrRole(String faultActor) { + try { + getSaajFault().setFaultActor(faultActor); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - @Override - public String getFaultStringOrReason() { - return getSaajFault().getFaultString(); - } + @Override + public String getFaultStringOrReason() { + return getSaajFault().getFaultString(); + } - @Override - public Locale getFaultStringLocale() { - return getSaajFault().getFaultStringLocale(); - } + @Override + public Locale getFaultStringLocale() { + return getSaajFault().getFaultStringLocale(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Header.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Header.java index c39b6f01..5fee1ff7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Header.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap11Header.java @@ -36,39 +36,39 @@ import org.springframework.ws.soap.soap11.Soap11Header; */ class SaajSoap11Header extends SaajSoapHeader implements Soap11Header { - SaajSoap11Header(SOAPHeader header) { - super(header); - } + SaajSoap11Header(SOAPHeader header) { + super(header); + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineHeaderElementsToProcess(String[] actors) { - List result = new ArrayList(); - Iterator iterator = getSaajHeader().examineAllHeaderElements(); - while (iterator.hasNext()) { - SOAPHeaderElement saajHeaderElement = iterator.next(); - String headerActor = saajHeaderElement.getActor(); - if (shouldProcess(headerActor, actors)) { - result.add(saajHeaderElement); - } - } - return new SaajSoapHeaderElementIterator(result.iterator()); - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineHeaderElementsToProcess(String[] actors) { + List result = new ArrayList(); + Iterator iterator = getSaajHeader().examineAllHeaderElements(); + while (iterator.hasNext()) { + SOAPHeaderElement saajHeaderElement = iterator.next(); + String headerActor = saajHeaderElement.getActor(); + if (shouldProcess(headerActor, actors)) { + result.add(saajHeaderElement); + } + } + return new SaajSoapHeaderElementIterator(result.iterator()); + } - private boolean shouldProcess(String headerActor, String[] actors) { - if (!StringUtils.hasLength(headerActor)) { - return true; - } - if (SOAPConstants.URI_SOAP_ACTOR_NEXT.equals(headerActor)) { - return true; - } - if (!ObjectUtils.isEmpty(actors)) { - for (String actor : actors) { - if (actor.equals(headerActor)) { - return true; - } - } - } - return false; - } + private boolean shouldProcess(String headerActor, String[] actors) { + if (!StringUtils.hasLength(headerActor)) { + return true; + } + if (SOAPConstants.URI_SOAP_ACTOR_NEXT.equals(headerActor)) { + return true; + } + if (!ObjectUtils.isEmpty(actors)) { + for (String actor : actors) { + if (actor.equals(headerActor)) { + return true; + } + } + } + return false; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Body.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Body.java index 7487489c..c5168cb0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Body.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Body.java @@ -35,67 +35,67 @@ import org.springframework.ws.soap.soap12.Soap12Fault; */ class SaajSoap12Body extends SaajSoapBody implements Soap12Body { - SaajSoap12Body(SOAPBody body) { - super(body); - } + SaajSoap12Body(SOAPBody body) { + super(body); + } - @Override - public Soap12Fault getFault() { - SOAPFault fault = getSaajBody().getFault(); - return fault != null ? new SaajSoap12Fault(fault) : null; - } + @Override + public Soap12Fault getFault() { + SOAPFault fault = getSaajBody().getFault(); + return fault != null ? new SaajSoap12Fault(fault) : null; + } - @Override - public Soap12Fault addClientOrSenderFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_12.getClientOrSenderFaultName(), faultString, locale); - } + @Override + public Soap12Fault addClientOrSenderFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_12.getClientOrSenderFaultName(), faultString, locale); + } - @Override - public Soap12Fault addMustUnderstandFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_12.getMustUnderstandFaultName(), faultString, locale); - } + @Override + public Soap12Fault addMustUnderstandFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_12.getMustUnderstandFaultName(), faultString, locale); + } - @Override - public Soap12Fault addServerOrReceiverFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_12.getServerOrReceiverFaultName(), faultString, locale); - } + @Override + public Soap12Fault addServerOrReceiverFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_12.getServerOrReceiverFaultName(), faultString, locale); + } - @Override - public Soap12Fault addVersionMismatchFault(String faultString, Locale locale) { - return addFault(SoapVersion.SOAP_12.getVersionMismatchFaultName(), faultString, locale); - } + @Override + public Soap12Fault addVersionMismatchFault(String faultString, Locale locale) { + return addFault(SoapVersion.SOAP_12.getVersionMismatchFaultName(), faultString, locale); + } - @Override - public Soap12Fault addDataEncodingUnknownFault(QName[] subcodes, String reason, Locale locale) { - QName name = new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "DataEncodingUnknown"); - Soap12Fault fault = addFault(name, reason, locale); - for (QName subcode : subcodes) { - fault.addFaultSubcode(subcode); - } - return fault; - } + @Override + public Soap12Fault addDataEncodingUnknownFault(QName[] subcodes, String reason, Locale locale) { + QName name = new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "DataEncodingUnknown"); + Soap12Fault fault = addFault(name, reason, locale); + for (QName subcode : subcodes) { + fault.addFaultSubcode(subcode); + } + return fault; + } - protected Soap12Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) { - Assert.notNull(faultCode, "No faultCode given"); - Assert.hasLength(faultString, "faultString cannot be empty"); - Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); - Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); - try { - getSaajBody().removeContents(); - SOAPBody body = getSaajBody(); - SOAPFault result; - if (faultStringLocale == null) { - result = body.addFault(faultCode, faultString); - } - else { - result = body.addFault(faultCode, faultString, faultStringLocale); - } - SOAPFault saajFault = result; - return new SaajSoap12Fault(saajFault); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + protected Soap12Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) { + Assert.notNull(faultCode, "No faultCode given"); + Assert.hasLength(faultString, "faultString cannot be empty"); + Assert.hasLength(faultCode.getLocalPart(), "faultCode's localPart cannot be empty"); + Assert.hasLength(faultCode.getNamespaceURI(), "faultCode's namespaceUri cannot be empty"); + try { + getSaajBody().removeContents(); + SOAPBody body = getSaajBody(); + SOAPFault result; + if (faultStringLocale == null) { + result = body.addFault(faultCode, faultString); + } + else { + result = body.addFault(faultCode, faultString, faultStringLocale); + } + SOAPFault saajFault = result; + return new SaajSoap12Fault(saajFault); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Fault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Fault.java index 8fa14e43..dfdf861f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Fault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Fault.java @@ -30,80 +30,80 @@ import org.springframework.ws.soap.soap12.Soap12Fault; */ class SaajSoap12Fault extends SaajSoapFault implements Soap12Fault { - public SaajSoap12Fault(SOAPFault fault) { - super(fault); - } + public SaajSoap12Fault(SOAPFault fault) { + super(fault); + } - @Override - public String getFaultActorOrRole() { - return getSaajFault().getFaultRole(); - } + @Override + public String getFaultActorOrRole() { + return getSaajFault().getFaultRole(); + } - @Override - public void setFaultActorOrRole(String faultRole) { - try { - getSaajFault().setFaultRole(faultRole); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public void setFaultActorOrRole(String faultRole) { + try { + getSaajFault().setFaultRole(faultRole); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator getFaultSubcodes() { - return getSaajFault().getFaultSubcodes(); - } + @Override + @SuppressWarnings("unchecked") + public Iterator getFaultSubcodes() { + return getSaajFault().getFaultSubcodes(); + } - @Override - public void addFaultSubcode(QName subcode) { - try { - getSaajFault().appendFaultSubcode(subcode); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public void addFaultSubcode(QName subcode) { + try { + getSaajFault().appendFaultSubcode(subcode); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - @Override - public String getFaultNode() { - return getSaajFault().getFaultNode(); - } + @Override + public String getFaultNode() { + return getSaajFault().getFaultNode(); + } - @Override - public void setFaultNode(String uri) { - try { - getSaajFault().setFaultNode(uri); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } + @Override + public void setFaultNode(String uri) { + try { + getSaajFault().setFaultNode(uri); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } - } + } - @Override - public void setFaultReasonText(Locale locale, String text) { - try { - getSaajFault().addFaultReasonText(text, locale); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } + @Override + public void setFaultReasonText(Locale locale, String text) { + try { + getSaajFault().addFaultReasonText(text, locale); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } - } + } - @Override - public String getFaultReasonText(Locale locale) { - try { - return getSaajFault().getFaultReasonText(locale); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public String getFaultReasonText(Locale locale) { + try { + return getSaajFault().getFaultReasonText(locale); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - @Override - public String getFaultStringOrReason() { - return getSaajFault().getFaultString(); - } + @Override + public String getFaultStringOrReason() { + return getSaajFault().getFaultString(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Header.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Header.java index 428dad55..118dad25 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Header.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoap12Header.java @@ -39,71 +39,71 @@ import org.springframework.ws.soap.soap12.Soap12Header; */ class SaajSoap12Header extends SaajSoapHeader implements Soap12Header { - SaajSoap12Header(SOAPHeader header) { - super(header); - } + SaajSoap12Header(SOAPHeader header) { + super(header); + } - @Override - public SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName) { - try { - SOAPHeaderElement headerElement = - getSaajHeader().addNotUnderstoodHeaderElement(headerName); - return new SaajSoapHeaderElement(headerElement); - } - catch (SOAPException ex) { - throw new SaajSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName) { + try { + SOAPHeaderElement headerElement = + getSaajHeader().addNotUnderstoodHeaderElement(headerName); + return new SaajSoapHeaderElement(headerElement); + } + catch (SOAPException ex) { + throw new SaajSoapHeaderException(ex); + } + } - @Override - public SoapHeaderElement addUpgradeHeaderElement(String[] supportedSoapUris) { - try { - SOAPHeaderElement headerElement = - getSaajHeader().addUpgradeHeaderElement(supportedSoapUris); - return new SaajSoapHeaderElement(headerElement); - } - catch (SOAPException ex) { - throw new SaajSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement addUpgradeHeaderElement(String[] supportedSoapUris) { + try { + SOAPHeaderElement headerElement = + getSaajHeader().addUpgradeHeaderElement(supportedSoapUris); + return new SaajSoapHeaderElement(headerElement); + } + catch (SOAPException ex) { + throw new SaajSoapHeaderException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineHeaderElementsToProcess(String[] roles, boolean isUltimateDestination) - throws SoapHeaderException { - List result = new ArrayList(); - Iterator iterator = getSaajHeader().examineAllHeaderElements(); - while (iterator.hasNext()) { - SOAPHeaderElement saajHeaderElement = iterator.next(); - String headerRole = saajHeaderElement.getRole(); - if (shouldProcess(headerRole, roles, isUltimateDestination)) { - result.add(saajHeaderElement); - } - } - return new SaajSoapHeaderElementIterator(result.iterator()); + @Override + @SuppressWarnings("unchecked") + public Iterator examineHeaderElementsToProcess(String[] roles, boolean isUltimateDestination) + throws SoapHeaderException { + List result = new ArrayList(); + Iterator iterator = getSaajHeader().examineAllHeaderElements(); + while (iterator.hasNext()) { + SOAPHeaderElement saajHeaderElement = iterator.next(); + String headerRole = saajHeaderElement.getRole(); + if (shouldProcess(headerRole, roles, isUltimateDestination)) { + result.add(saajHeaderElement); + } + } + return new SaajSoapHeaderElementIterator(result.iterator()); - } + } - private boolean shouldProcess(String headerRole, String[] roles, boolean isUltimateDestination) { - if (!StringUtils.hasLength(headerRole)) { - return true; - } - if (SOAPConstants.URI_SOAP_1_2_ROLE_NEXT.equals(headerRole)) { - return true; - } - if (SOAPConstants.URI_SOAP_1_2_ROLE_ULTIMATE_RECEIVER.equals(headerRole)) { - return isUltimateDestination; - } - if (SOAPConstants.URI_SOAP_1_2_ROLE_NONE.equals(headerRole)) { - return false; - } - if (!ObjectUtils.isEmpty(roles)) { - for (String role : roles) { - if (role.equals(headerRole)) { - return true; - } - } - } - return false; - } + private boolean shouldProcess(String headerRole, String[] roles, boolean isUltimateDestination) { + if (!StringUtils.hasLength(headerRole)) { + return true; + } + if (SOAPConstants.URI_SOAP_1_2_ROLE_NEXT.equals(headerRole)) { + return true; + } + if (SOAPConstants.URI_SOAP_1_2_ROLE_ULTIMATE_RECEIVER.equals(headerRole)) { + return isUltimateDestination; + } + if (SOAPConstants.URI_SOAP_1_2_ROLE_NONE.equals(headerRole)) { + return false; + } + if (!ObjectUtils.isEmpty(roles)) { + for (String role : roles) { + if (role.equals(headerRole)) { + return true; + } + } + } + return false; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBody.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBody.java index a0c5c39b..6e25cdf2 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBody.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBody.java @@ -34,29 +34,29 @@ import org.springframework.ws.soap.saaj.support.SaajUtils; */ abstract class SaajSoapBody extends SaajSoapElement implements SoapBody { - public SaajSoapBody(SOAPBody body) { - super(body); - } + public SaajSoapBody(SOAPBody body) { + super(body); + } - @Override - public Source getPayloadSource() { - SOAPElement bodyElement = SaajUtils.getFirstBodyElement(getSaajBody()); - return bodyElement != null ? new DOMSource(bodyElement) : null; - } + @Override + public Source getPayloadSource() { + SOAPElement bodyElement = SaajUtils.getFirstBodyElement(getSaajBody()); + return bodyElement != null ? new DOMSource(bodyElement) : null; + } - @Override - public Result getPayloadResult() { - getSaajBody().removeContents(); - return new DOMResult(getSaajBody()); - } + @Override + public Result getPayloadResult() { + getSaajBody().removeContents(); + return new DOMResult(getSaajBody()); + } - @Override - public boolean hasFault() { - return getSaajBody().hasFault(); - } + @Override + public boolean hasFault() { + return getSaajBody().hasFault(); + } - protected SOAPBody getSaajBody() { - return getSaajElement(); - } + protected SOAPBody getSaajBody() { + return getSaajElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBodyException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBodyException.java index c3d875ad..604ce1ef 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBodyException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapBodyException.java @@ -22,15 +22,15 @@ import org.springframework.ws.soap.SoapBodyException; @SuppressWarnings("serial") public class SaajSoapBodyException extends SoapBodyException { - public SaajSoapBodyException(String msg) { - super(msg); - } + public SaajSoapBodyException(String msg) { + super(msg); + } - public SaajSoapBodyException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapBodyException(String msg, Throwable ex) { + super(msg, ex); + } - public SaajSoapBodyException(Throwable ex) { - super(ex); - } + public SaajSoapBodyException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElement.java index 454ed636..b1160b3e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElement.java @@ -34,61 +34,61 @@ import org.springframework.ws.soap.SoapElement; */ class SaajSoapElement implements SoapElement { - private final T element; + private final T element; - SaajSoapElement(T element) { - Assert.notNull(element, "element must not be null"); - this.element = element; - } + SaajSoapElement(T element) { + Assert.notNull(element, "element must not be null"); + this.element = element; + } - @Override - public Source getSource() { - return new DOMSource(element); - } + @Override + public Source getSource() { + return new DOMSource(element); + } - @Override - public QName getName() { - return element.getElementQName(); - } + @Override + public QName getName() { + return element.getElementQName(); + } - @Override - public void addAttribute(QName name, String value) { - try { - element.addAttribute(name, value); - } - catch (SOAPException ex) { - throw new SaajSoapElementException(ex); - } - } + @Override + public void addAttribute(QName name, String value) { + try { + element.addAttribute(name, value); + } + catch (SOAPException ex) { + throw new SaajSoapElementException(ex); + } + } - @Override - public void removeAttribute(QName name) { - element.removeAttribute(name); - } + @Override + public void removeAttribute(QName name) { + element.removeAttribute(name); + } - @Override - public String getAttributeValue(QName name) { - return element.getAttributeValue(name); - } + @Override + public String getAttributeValue(QName name) { + return element.getAttributeValue(name); + } - @Override - @SuppressWarnings("unchecked") - public Iterator getAllAttributes() { - return element.getAllAttributesAsQNames(); - } + @Override + @SuppressWarnings("unchecked") + public Iterator getAllAttributes() { + return element.getAllAttributesAsQNames(); + } - @Override - public void addNamespaceDeclaration(String prefix, String namespaceUri) { - try { - element.addNamespaceDeclaration(prefix, namespaceUri); - } - catch (SOAPException ex) { - throw new SaajSoapElementException(ex); - } - } + @Override + public void addNamespaceDeclaration(String prefix, String namespaceUri) { + try { + element.addNamespaceDeclaration(prefix, namespaceUri); + } + catch (SOAPException ex) { + throw new SaajSoapElementException(ex); + } + } - protected final T getSaajElement() { - return element; - } + protected final T getSaajElement() { + return element; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElementException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElementException.java index 9454d805..341233ad 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElementException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapElementException.java @@ -22,15 +22,15 @@ import org.springframework.ws.soap.SoapElementException; @SuppressWarnings("serial") public class SaajSoapElementException extends SoapElementException { - public SaajSoapElementException(String msg) { - super(msg); - } + public SaajSoapElementException(String msg) { + super(msg); + } - public SaajSoapElementException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapElementException(String msg, Throwable ex) { + super(msg, ex); + } - public SaajSoapElementException(Throwable ex) { - super(ex); - } + public SaajSoapElementException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelope.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelope.java index 44331510..424f6da9 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelope.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelope.java @@ -35,64 +35,64 @@ import org.springframework.ws.soap.SoapVersion; */ class SaajSoapEnvelope extends SaajSoapElement implements SoapEnvelope { - private SaajSoapBody body; + private SaajSoapBody body; - private SaajSoapHeader header; + private SaajSoapHeader header; - private final boolean langAttributeOnSoap11FaultString; + private final boolean langAttributeOnSoap11FaultString; - SaajSoapEnvelope(SOAPEnvelope element, boolean langAttributeOnSoap11FaultString) { - super(element); - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + SaajSoapEnvelope(SOAPEnvelope element, boolean langAttributeOnSoap11FaultString) { + super(element); + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } - @Override - public SoapBody getBody() { - if (body == null) { - try { - SOAPBody saajBody = getSaajEnvelope().getBody(); - if (saajBody.getElementQName().getNamespaceURI() - .equals(SoapVersion.SOAP_11.getEnvelopeNamespaceUri())) { - body = new SaajSoap11Body(saajBody, langAttributeOnSoap11FaultString); - } - else { - body = new SaajSoap12Body(saajBody); - } - } - catch (SOAPException ex) { - throw new SaajSoapBodyException(ex); - } - } - return body; - } + @Override + public SoapBody getBody() { + if (body == null) { + try { + SOAPBody saajBody = getSaajEnvelope().getBody(); + if (saajBody.getElementQName().getNamespaceURI() + .equals(SoapVersion.SOAP_11.getEnvelopeNamespaceUri())) { + body = new SaajSoap11Body(saajBody, langAttributeOnSoap11FaultString); + } + else { + body = new SaajSoap12Body(saajBody); + } + } + catch (SOAPException ex) { + throw new SaajSoapBodyException(ex); + } + } + return body; + } - @Override - public SoapHeader getHeader() { - if (header == null) { - try { - SOAPHeader saajHeader = getSaajEnvelope().getHeader(); - if (saajHeader != null) { - if (saajHeader.getElementQName().getNamespaceURI() - .equals(SoapVersion.SOAP_11.getEnvelopeNamespaceUri())) { - header = new SaajSoap11Header(saajHeader); - } - else { - header = new SaajSoap12Header(saajHeader); - } - } - else { - header = null; - } - } - catch (SOAPException ex) { - throw new SaajSoapHeaderException(ex); - } - } - return header; - } + @Override + public SoapHeader getHeader() { + if (header == null) { + try { + SOAPHeader saajHeader = getSaajEnvelope().getHeader(); + if (saajHeader != null) { + if (saajHeader.getElementQName().getNamespaceURI() + .equals(SoapVersion.SOAP_11.getEnvelopeNamespaceUri())) { + header = new SaajSoap11Header(saajHeader); + } + else { + header = new SaajSoap12Header(saajHeader); + } + } + else { + header = null; + } + } + catch (SOAPException ex) { + throw new SaajSoapHeaderException(ex); + } + } + return header; + } - protected SOAPEnvelope getSaajEnvelope() { - return getSaajElement(); - } + protected SOAPEnvelope getSaajEnvelope() { + return getSaajElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelopeException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelopeException.java index 55b1b151..74f68f7e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelopeException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapEnvelopeException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapEnvelopeException; @SuppressWarnings("serial") public class SaajSoapEnvelopeException extends SoapEnvelopeException { - public SaajSoapEnvelopeException(String msg) { - super(msg); - } + public SaajSoapEnvelopeException(String msg) { + super(msg); + } - public SaajSoapEnvelopeException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapEnvelopeException(String msg, Throwable ex) { + super(msg, ex); + } - public SaajSoapEnvelopeException(Throwable ex) { - super(ex); - } + public SaajSoapEnvelopeException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFault.java index e6ce9bf0..dcc90b3b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFault.java @@ -32,33 +32,33 @@ import org.springframework.ws.soap.SoapFaultDetail; */ abstract class SaajSoapFault extends SaajSoapElement implements SoapFault { - protected SaajSoapFault(SOAPFault fault) { - super(fault); - } + protected SaajSoapFault(SOAPFault fault) { + super(fault); + } - @Override - public QName getFaultCode() { - return getSaajFault().getFaultCodeAsQName(); - } + @Override + public QName getFaultCode() { + return getSaajFault().getFaultCodeAsQName(); + } - protected SOAPFault getSaajFault() { - return getSaajElement(); - } + protected SOAPFault getSaajFault() { + return getSaajElement(); + } - @Override - public SoapFaultDetail getFaultDetail() { - Detail saajDetail = getSaajFault().getDetail(); - return saajDetail != null ? new SaajSoapFaultDetail(saajDetail) : null; - } + @Override + public SoapFaultDetail getFaultDetail() { + Detail saajDetail = getSaajFault().getDetail(); + return saajDetail != null ? new SaajSoapFaultDetail(saajDetail) : null; + } - @Override - public SoapFaultDetail addFaultDetail() { - try { - Detail saajDetail = getSaajFault().addDetail(); - return new SaajSoapFaultDetail(saajDetail); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public SoapFaultDetail addFaultDetail() { + try { + Detail saajDetail = getSaajFault().addDetail(); + return new SaajSoapFaultDetail(saajDetail); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetail.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetail.java index 3ba3af14..6dc35077 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetail.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetail.java @@ -38,62 +38,62 @@ import org.springframework.ws.soap.SoapFaultDetailElement; */ class SaajSoapFaultDetail extends SaajSoapElement implements SoapFaultDetail { - public SaajSoapFaultDetail(SOAPFaultElement faultElement) { - super(faultElement); - } + public SaajSoapFaultDetail(SOAPFaultElement faultElement) { + super(faultElement); + } - @Override - public Result getResult() { - return new DOMResult(getSaajDetail()); - } + @Override + public Result getResult() { + return new DOMResult(getSaajDetail()); + } - @Override - public SoapFaultDetailElement addFaultDetailElement(QName name) { - try { - DetailEntry detailEntry = getSaajDetail().addDetailEntry(name); - return new SaajSoapFaultDetailElement(detailEntry); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public SoapFaultDetailElement addFaultDetailElement(QName name) { + try { + DetailEntry detailEntry = getSaajDetail().addDetailEntry(name); + return new SaajSoapFaultDetailElement(detailEntry); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Iterator getDetailEntries() { - Iterator iterator = getSaajDetail().getDetailEntries(); - return new SaajSoapFaultDetailElementIterator(iterator); - } + @Override + @SuppressWarnings("unchecked") + public Iterator getDetailEntries() { + Iterator iterator = getSaajDetail().getDetailEntries(); + return new SaajSoapFaultDetailElementIterator(iterator); + } - protected Detail getSaajDetail() { - return (Detail) getSaajElement(); - } + protected Detail getSaajDetail() { + return (Detail) getSaajElement(); + } - private static class SaajSoapFaultDetailElementIterator implements Iterator { + private static class SaajSoapFaultDetailElementIterator implements Iterator { - private final Iterator iterator; + private final Iterator iterator; - private SaajSoapFaultDetailElementIterator(Iterator iterator) { - Assert.notNull(iterator, "No iterator given"); - this.iterator = iterator; - } + private SaajSoapFaultDetailElementIterator(Iterator iterator) { + Assert.notNull(iterator, "No iterator given"); + this.iterator = iterator; + } - @Override - public boolean hasNext() { - return iterator.hasNext(); - } + @Override + public boolean hasNext() { + return iterator.hasNext(); + } - @Override - public SoapFaultDetailElement next() { - DetailEntry saajDetailEntry = iterator.next(); - return new SaajSoapFaultDetailElement(saajDetailEntry); - } + @Override + public SoapFaultDetailElement next() { + DetailEntry saajDetailEntry = iterator.next(); + return new SaajSoapFaultDetailElement(saajDetailEntry); + } - @Override - public void remove() { - iterator.remove(); - } - } + @Override + public void remove() { + iterator.remove(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetailElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetailElement.java index 2a10cc2c..fc4e66e3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetailElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultDetailElement.java @@ -32,27 +32,27 @@ import org.springframework.ws.soap.SoapFaultDetailElement; */ class SaajSoapFaultDetailElement extends SaajSoapElement implements SoapFaultDetailElement { - SaajSoapFaultDetailElement(DetailEntry entry) { - super(entry); - } + SaajSoapFaultDetailElement(DetailEntry entry) { + super(entry); + } - @Override - public Result getResult() { - return new DOMResult(getSaajDetailEntry()); - } + @Override + public Result getResult() { + return new DOMResult(getSaajDetailEntry()); + } - @Override - public void addText(String text) { - try { - getSaajDetailEntry().addTextNode(text); - } - catch (SOAPException ex) { - throw new SaajSoapFaultException(ex); - } - } + @Override + public void addText(String text) { + try { + getSaajDetailEntry().addTextNode(text); + } + catch (SOAPException ex) { + throw new SaajSoapFaultException(ex); + } + } - protected DetailEntry getSaajDetailEntry() { - return getSaajElement(); - } + protected DetailEntry getSaajDetailEntry() { + return getSaajElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultException.java index ef512a42..9639813c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapFaultException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapFaultException; @SuppressWarnings("serial") public class SaajSoapFaultException extends SoapFaultException { - public SaajSoapFaultException(String msg) { - super(msg); - } + public SaajSoapFaultException(String msg) { + super(msg); + } - public SaajSoapFaultException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapFaultException(String msg, Throwable ex) { + super(msg, ex); + } - public SaajSoapFaultException(Throwable ex) { - super(ex); - } + public SaajSoapFaultException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeader.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeader.java index 48e510ec..c98ad956 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeader.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeader.java @@ -38,86 +38,86 @@ import org.springframework.ws.soap.SoapHeaderException; */ abstract class SaajSoapHeader extends SaajSoapElement implements SoapHeader { - SaajSoapHeader(SOAPHeader header) { - super(header); - } + SaajSoapHeader(SOAPHeader header) { + super(header); + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineAllHeaderElements() throws SoapHeaderException { - Iterator iterator = getSaajHeader().examineAllHeaderElements(); - return new SaajSoapHeaderElementIterator(iterator); - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineAllHeaderElements() throws SoapHeaderException { + Iterator iterator = getSaajHeader().examineAllHeaderElements(); + return new SaajSoapHeaderElementIterator(iterator); + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineHeaderElements(QName name) throws SoapHeaderException { - Iterator iterator = getSaajHeader().getChildElements(name); - return new SaajSoapHeaderElementIterator(iterator); - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineHeaderElements(QName name) throws SoapHeaderException { + Iterator iterator = getSaajHeader().getChildElements(name); + return new SaajSoapHeaderElementIterator(iterator); + } - @Override - @SuppressWarnings("unchecked") - public Iterator examineMustUnderstandHeaderElements(String actorOrRole) throws SoapHeaderException { - Iterator iterator = - getSaajHeader().examineMustUnderstandHeaderElements(actorOrRole); - return new SaajSoapHeaderElementIterator(iterator); - } + @Override + @SuppressWarnings("unchecked") + public Iterator examineMustUnderstandHeaderElements(String actorOrRole) throws SoapHeaderException { + Iterator iterator = + getSaajHeader().examineMustUnderstandHeaderElements(actorOrRole); + return new SaajSoapHeaderElementIterator(iterator); + } - @Override - public SoapHeaderElement addHeaderElement(QName name) throws SoapHeaderException { - try { - SOAPHeaderElement headerElement = getSaajHeader().addHeaderElement(name); - return new SaajSoapHeaderElement(headerElement); - } - catch (SOAPException ex) { - throw new SaajSoapHeaderException(ex); - } - } + @Override + public SoapHeaderElement addHeaderElement(QName name) throws SoapHeaderException { + try { + SOAPHeaderElement headerElement = getSaajHeader().addHeaderElement(name); + return new SaajSoapHeaderElement(headerElement); + } + catch (SOAPException ex) { + throw new SaajSoapHeaderException(ex); + } + } - @SuppressWarnings("unchecked") - @Override - public void removeHeaderElement(QName name) throws SoapHeaderException { - Iterator iterator = getSaajHeader().getChildElements(name); - if (iterator.hasNext()) { - SOAPElement element = iterator.next(); - element.detachNode(); - } - } + @SuppressWarnings("unchecked") + @Override + public void removeHeaderElement(QName name) throws SoapHeaderException { + Iterator iterator = getSaajHeader().getChildElements(name); + if (iterator.hasNext()) { + SOAPElement element = iterator.next(); + element.detachNode(); + } + } - protected SOAPHeader getSaajHeader() { - return getSaajElement(); - } + protected SOAPHeader getSaajHeader() { + return getSaajElement(); + } - @Override - public Result getResult() { - return new DOMResult(getSaajHeader()); - } + @Override + public Result getResult() { + return new DOMResult(getSaajHeader()); + } - protected static class SaajSoapHeaderElementIterator implements Iterator { + protected static class SaajSoapHeaderElementIterator implements Iterator { - private final Iterator iterator; + private final Iterator iterator; - protected SaajSoapHeaderElementIterator(Iterator iterator) { - Assert.notNull(iterator, "iterator must not be null"); - this.iterator = iterator; - } + protected SaajSoapHeaderElementIterator(Iterator iterator) { + Assert.notNull(iterator, "iterator must not be null"); + this.iterator = iterator; + } - @Override - public boolean hasNext() { - return iterator.hasNext(); - } + @Override + public boolean hasNext() { + return iterator.hasNext(); + } - @Override - public SoapHeaderElement next() { - SOAPHeaderElement saajHeaderElement = iterator.next(); - return new SaajSoapHeaderElement(saajHeaderElement); - } + @Override + public SoapHeaderElement next() { + SOAPHeaderElement saajHeaderElement = iterator.next(); + return new SaajSoapHeaderElement(saajHeaderElement); + } - @Override - public void remove() { - iterator.remove(); - } - } + @Override + public void remove() { + iterator.remove(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderElement.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderElement.java index 74ce4a01..c41dec6c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderElement.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderElement.java @@ -32,47 +32,47 @@ import org.springframework.ws.soap.SoapHeaderException; */ class SaajSoapHeaderElement extends SaajSoapElement implements SoapHeaderElement { - SaajSoapHeaderElement(SOAPHeaderElement headerElement) { - super(headerElement); - } + SaajSoapHeaderElement(SOAPHeaderElement headerElement) { + super(headerElement); + } - @Override - public Result getResult() throws SoapHeaderException { - return new DOMResult(getSaajElement()); - } + @Override + public Result getResult() throws SoapHeaderException { + return new DOMResult(getSaajElement()); + } - @Override - public String getActorOrRole() throws SoapHeaderException { - return getSaajHeaderElement().getActor(); - } + @Override + public String getActorOrRole() throws SoapHeaderException { + return getSaajHeaderElement().getActor(); + } - @Override - public void setActorOrRole(String actorOrRole) throws SoapHeaderException { - getSaajHeaderElement().setActor(actorOrRole); - } + @Override + public void setActorOrRole(String actorOrRole) throws SoapHeaderException { + getSaajHeaderElement().setActor(actorOrRole); + } - @Override - public boolean getMustUnderstand() throws SoapHeaderException { - return getSaajHeaderElement().getMustUnderstand(); - } + @Override + public boolean getMustUnderstand() throws SoapHeaderException { + return getSaajHeaderElement().getMustUnderstand(); + } - @Override - public void setMustUnderstand(boolean mustUnderstand) throws SoapHeaderException { - getSaajHeaderElement().setMustUnderstand(mustUnderstand); - } + @Override + public void setMustUnderstand(boolean mustUnderstand) throws SoapHeaderException { + getSaajHeaderElement().setMustUnderstand(mustUnderstand); + } - @Override - public String getText() { - return getSaajHeaderElement().getValue(); - } + @Override + public String getText() { + return getSaajHeaderElement().getValue(); + } - @Override - public void setText(String content) { - getSaajHeaderElement().setValue(content); - } + @Override + public void setText(String content) { + getSaajHeaderElement().setValue(content); + } - protected SOAPHeaderElement getSaajHeaderElement() { - return getSaajElement(); - } + protected SOAPHeaderElement getSaajHeaderElement() { + return getSaajElement(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderException.java index 612bd82c..8b768728 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapHeaderException.java @@ -25,15 +25,15 @@ import org.springframework.ws.soap.SoapHeaderException; @SuppressWarnings("serial") public class SaajSoapHeaderException extends SoapHeaderException { - public SaajSoapHeaderException(String msg) { - super(msg); - } + public SaajSoapHeaderException(String msg) { + super(msg); + } - public SaajSoapHeaderException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapHeaderException(String msg, Throwable ex) { + super(msg, ex); + } - public SaajSoapHeaderException(Throwable ex) { - super(ex); - } + public SaajSoapHeaderException(Throwable ex) { + super(ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessage.java index 43cbec6f..0b991129 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessage.java @@ -62,340 +62,340 @@ import org.springframework.ws.transport.TransportOutputStream; */ public class SaajSoapMessage extends AbstractSoapMessage { - private static final String CONTENT_TYPE_XOP = "application/xop+xml"; + private static final String CONTENT_TYPE_XOP = "application/xop+xml"; - private final MessageFactory messageFactory; + private final MessageFactory messageFactory; - private SOAPMessage saajMessage; + private SOAPMessage saajMessage; - private SoapEnvelope envelope; + private SoapEnvelope envelope; - private final boolean langAttributeOnSoap11FaultString; + private final boolean langAttributeOnSoap11FaultString; - /** - * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. - * - * @param soapMessage the SAAJ SOAPMessage - */ - public SaajSoapMessage(SOAPMessage soapMessage) { - this(soapMessage, true, null); - } + /** + * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. + * + * @param soapMessage the SAAJ SOAPMessage + */ + public SaajSoapMessage(SOAPMessage soapMessage) { + this(soapMessage, true, null); + } - /** - * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. - * - * @param soapMessage the SAAJ SOAPMessage - * @param messageFactory the SAAJ message factory - */ - public SaajSoapMessage(SOAPMessage soapMessage, MessageFactory messageFactory) { - this(soapMessage, true, messageFactory); - } + /** + * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. + * + * @param soapMessage the SAAJ SOAPMessage + * @param messageFactory the SAAJ message factory + */ + public SaajSoapMessage(SOAPMessage soapMessage, MessageFactory messageFactory) { + this(soapMessage, true, messageFactory); + } - /** - * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. - * - * @param soapMessage the SAAJ SOAPMessage - * @param langAttributeOnSoap11FaultString - * whether a {@code xml:lang} attribute is allowed on SOAP 1.1 {@code } elements - */ - public SaajSoapMessage(SOAPMessage soapMessage, boolean langAttributeOnSoap11FaultString) { - this(soapMessage, langAttributeOnSoap11FaultString, null); - } + /** + * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. + * + * @param soapMessage the SAAJ SOAPMessage + * @param langAttributeOnSoap11FaultString + * whether a {@code xml:lang} attribute is allowed on SOAP 1.1 {@code } elements + */ + public SaajSoapMessage(SOAPMessage soapMessage, boolean langAttributeOnSoap11FaultString) { + this(soapMessage, langAttributeOnSoap11FaultString, null); + } - /** - * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. - * - * @param soapMessage the SAAJ SOAPMessage - * @param langAttributeOnSoap11FaultString - * whether a {@code xml:lang} attribute is allowed on SOAP 1.1 {@code } elements - * @param messageFactory the message factory - */ - public SaajSoapMessage(SOAPMessage soapMessage, boolean langAttributeOnSoap11FaultString, MessageFactory messageFactory) { - Assert.notNull(soapMessage, "soapMessage must not be null"); - saajMessage = soapMessage; - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - MimeHeaders headers = soapMessage.getMimeHeaders(); - if (ObjectUtils.isEmpty(headers.getHeader(TransportConstants.HEADER_SOAP_ACTION))) { - headers.addHeader(TransportConstants.HEADER_SOAP_ACTION, "\"\""); - } - this.messageFactory = messageFactory; - } + /** + * Create a new {@code SaajSoapMessage} based on the given SAAJ {@code SOAPMessage}. + * + * @param soapMessage the SAAJ SOAPMessage + * @param langAttributeOnSoap11FaultString + * whether a {@code xml:lang} attribute is allowed on SOAP 1.1 {@code } elements + * @param messageFactory the message factory + */ + public SaajSoapMessage(SOAPMessage soapMessage, boolean langAttributeOnSoap11FaultString, MessageFactory messageFactory) { + Assert.notNull(soapMessage, "soapMessage must not be null"); + saajMessage = soapMessage; + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + MimeHeaders headers = soapMessage.getMimeHeaders(); + if (ObjectUtils.isEmpty(headers.getHeader(TransportConstants.HEADER_SOAP_ACTION))) { + headers.addHeader(TransportConstants.HEADER_SOAP_ACTION, "\"\""); + } + this.messageFactory = messageFactory; + } - /** Return the SAAJ {@code SOAPMessage} that this {@code SaajSoapMessage} is based on. */ - public SOAPMessage getSaajMessage() { - return saajMessage; - } + /** Return the SAAJ {@code SOAPMessage} that this {@code SaajSoapMessage} is based on. */ + public SOAPMessage getSaajMessage() { + return saajMessage; + } - /** Sets the SAAJ {@code SOAPMessage} that this {@code SaajSoapMessage} is based on. */ - public void setSaajMessage(SOAPMessage soapMessage) { - Assert.notNull(soapMessage, "soapMessage must not be null"); - saajMessage = soapMessage; - envelope = null; - } - - @Override - public SoapEnvelope getEnvelope() { - if (envelope == null) { - try { - SOAPEnvelope saajEnvelope = getSaajMessage().getSOAPPart().getEnvelope(); - envelope = new SaajSoapEnvelope(saajEnvelope, langAttributeOnSoap11FaultString); - } - catch (SOAPException ex) { - throw new SaajSoapEnvelopeException(ex); - } - } - return envelope; - } - - @Override - public String getSoapAction() { - MimeHeaders mimeHeaders = getSaajMessage().getMimeHeaders(); - if (SoapVersion.SOAP_11 == getVersion()) { - String[] actions = mimeHeaders.getHeader(TransportConstants.HEADER_SOAP_ACTION); - return ObjectUtils.isEmpty(actions) ? TransportConstants.EMPTY_SOAP_ACTION : actions[0]; - } - else if (SoapVersion.SOAP_12 == getVersion()) { - String[] contentTypes = mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE); - return !ObjectUtils.isEmpty(contentTypes) ? SoapUtils.extractActionFromContentType(contentTypes[0]) : - TransportConstants.EMPTY_SOAP_ACTION; - } - else { - throw new IllegalStateException("Unsupported SOAP version: " + getVersion()); - } - } - - @Override - public void setSoapAction(String soapAction) { - MimeHeaders mimeHeaders = getSaajMessage().getMimeHeaders(); - soapAction = SoapUtils.escapeAction(soapAction); - if (SoapVersion.SOAP_11 == getVersion()) { - mimeHeaders.setHeader(TransportConstants.HEADER_SOAP_ACTION, soapAction); - } - else if (SoapVersion.SOAP_12 == getVersion()) { - // force save of Content Type header - try { - saajMessage.saveChanges(); - } - catch (SOAPException ex) { - throw new SaajSoapMessageException("Could not save message", ex); - } - String[] contentTypes = mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE); - String contentType = !ObjectUtils.isEmpty(contentTypes) ? contentTypes[0] : getVersion().getContentType(); - contentType = SoapUtils.setActionInContentType(contentType, soapAction); - mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType); - mimeHeaders.removeHeader(TransportConstants.HEADER_SOAP_ACTION); - } - else { - throw new IllegalStateException("Unsupported SOAP version: " + getVersion()); - } - - } - - @Override - public Document getDocument() { - Assert.state(messageFactory != null, "Could find message factory to use"); - // return saajSoapMessage.getSaajMessage().getSOAPPart(); // does not work, see SWS-345 - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - getSaajMessage().writeTo(bos); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - SOAPMessage saajMessage = messageFactory.createMessage(getSaajMessage().getMimeHeaders(), bis); - setSaajMessage(saajMessage); - return saajMessage.getSOAPPart(); - } - catch (SOAPException ex) { - throw new SaajSoapMessageException("Could not save changes", ex); - } - catch (IOException ex) { - throw new SaajSoapMessageException("Could not save changes", ex); - } - } - - @Override - public void setDocument(Document document) { - if (saajMessage.getSOAPPart() != document) { - Assert.state(messageFactory != null, "Could find message factory to use"); - try { - DOMImplementation implementation = document.getImplementation(); - Assert.isInstanceOf(DOMImplementationLS.class, implementation); - - DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation; - LSOutput output = loadSaveImplementation.createLSOutput(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - output.setByteStream(bos); - - LSSerializer serializer = loadSaveImplementation.createLSSerializer(); - serializer.write(document, output); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - - this.saajMessage = messageFactory.createMessage(saajMessage.getMimeHeaders(), bis); - - } - catch (SOAPException ex) { - throw new SaajSoapMessageException("Could not read input stream", ex); - } - catch (IOException ex) { - throw new SaajSoapMessageException("Could not read input stream", ex); - } - } - } - - @Override - public void writeTo(OutputStream outputStream) throws IOException { - MimeHeaders mimeHeaders = getSaajMessage().getMimeHeaders(); - if (ObjectUtils.isEmpty(mimeHeaders.getHeader(TransportConstants.HEADER_ACCEPT))) { - mimeHeaders.setHeader(TransportConstants.HEADER_ACCEPT, getVersion().getContentType()); - } - try { - SOAPMessage message = getSaajMessage(); - message.saveChanges(); - if (outputStream instanceof TransportOutputStream) { - TransportOutputStream transportOutputStream = (TransportOutputStream) outputStream; - // some SAAJ implementations (Axis 1) do not have a Content-Type header by default - MimeHeaders headers = message.getMimeHeaders(); - if (ObjectUtils - .isEmpty( - headers.getHeader(TransportConstants.HEADER_CONTENT_TYPE))) { - SOAPEnvelope envelope1 = message.getSOAPPart().getEnvelope(); - if (envelope1.getElementQName().getNamespaceURI() - .equals(SoapVersion.SOAP_11.getEnvelopeNamespaceUri())) { - headers.addHeader(TransportConstants.HEADER_CONTENT_TYPE, SoapVersion.SOAP_11.getContentType()); - } - else { - headers.addHeader(TransportConstants.HEADER_CONTENT_TYPE, SoapVersion.SOAP_12.getContentType()); - } - message.saveChanges(); - } - for (Iterator iterator = headers.getAllHeaders(); iterator.hasNext();) { - MimeHeader mimeHeader = (MimeHeader) iterator.next(); - transportOutputStream.addHeader(mimeHeader.getName(), mimeHeader.getValue()); - } - } - message.writeTo(outputStream); - - outputStream.flush(); - } - catch (SOAPException ex) { - throw new SaajSoapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); - } - } + /** Sets the SAAJ {@code SOAPMessage} that this {@code SaajSoapMessage} is based on. */ + public void setSaajMessage(SOAPMessage soapMessage) { + Assert.notNull(soapMessage, "soapMessage must not be null"); + saajMessage = soapMessage; + envelope = null; + } @Override - public boolean isXopPackage() { - SOAPPart saajPart = saajMessage.getSOAPPart(); - String[] contentTypes = saajPart.getMimeHeader(TransportConstants.HEADER_CONTENT_TYPE); - for (String contentType : contentTypes) { - if (contentType.contains(CONTENT_TYPE_XOP)) { - return true; - } - } - return false; - } + public SoapEnvelope getEnvelope() { + if (envelope == null) { + try { + SOAPEnvelope saajEnvelope = getSaajMessage().getSOAPPart().getEnvelope(); + envelope = new SaajSoapEnvelope(saajEnvelope, langAttributeOnSoap11FaultString); + } + catch (SOAPException ex) { + throw new SaajSoapEnvelopeException(ex); + } + } + return envelope; + } - @Override - public boolean convertToXopPackage() { - convertMessageToXop(); - convertPartToXop(); - return true; - } + @Override + public String getSoapAction() { + MimeHeaders mimeHeaders = getSaajMessage().getMimeHeaders(); + if (SoapVersion.SOAP_11 == getVersion()) { + String[] actions = mimeHeaders.getHeader(TransportConstants.HEADER_SOAP_ACTION); + return ObjectUtils.isEmpty(actions) ? TransportConstants.EMPTY_SOAP_ACTION : actions[0]; + } + else if (SoapVersion.SOAP_12 == getVersion()) { + String[] contentTypes = mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE); + return !ObjectUtils.isEmpty(contentTypes) ? SoapUtils.extractActionFromContentType(contentTypes[0]) : + TransportConstants.EMPTY_SOAP_ACTION; + } + else { + throw new IllegalStateException("Unsupported SOAP version: " + getVersion()); + } + } - private void convertMessageToXop() { - MimeHeaders mimeHeaders = saajMessage.getMimeHeaders(); - String[] oldContentTypes = mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE); - String oldContentType = - !ObjectUtils.isEmpty(oldContentTypes) ? oldContentTypes[0] : getVersion().getContentType(); - mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, - CONTENT_TYPE_XOP + ";type=" + '"' + oldContentType + '"'); - } + @Override + public void setSoapAction(String soapAction) { + MimeHeaders mimeHeaders = getSaajMessage().getMimeHeaders(); + soapAction = SoapUtils.escapeAction(soapAction); + if (SoapVersion.SOAP_11 == getVersion()) { + mimeHeaders.setHeader(TransportConstants.HEADER_SOAP_ACTION, soapAction); + } + else if (SoapVersion.SOAP_12 == getVersion()) { + // force save of Content Type header + try { + saajMessage.saveChanges(); + } + catch (SOAPException ex) { + throw new SaajSoapMessageException("Could not save message", ex); + } + String[] contentTypes = mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE); + String contentType = !ObjectUtils.isEmpty(contentTypes) ? contentTypes[0] : getVersion().getContentType(); + contentType = SoapUtils.setActionInContentType(contentType, soapAction); + mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType); + mimeHeaders.removeHeader(TransportConstants.HEADER_SOAP_ACTION); + } + else { + throw new IllegalStateException("Unsupported SOAP version: " + getVersion()); + } - private void convertPartToXop() { - SOAPPart saajPart = saajMessage.getSOAPPart(); - String[] oldContentTypes = saajPart.getMimeHeader(TransportConstants.HEADER_CONTENT_TYPE); - String oldContentType = - !ObjectUtils.isEmpty(oldContentTypes) ? oldContentTypes[0] : getVersion().getContentType(); - saajPart.setMimeHeader(TransportConstants.HEADER_CONTENT_TYPE, - CONTENT_TYPE_XOP + ";type=" + '"' + oldContentType + '"'); - } + } - @Override - @SuppressWarnings("unchecked") - public Iterator getAttachments() throws AttachmentException { - Iterator iterator = getSaajMessage().getAttachments(); - return new SaajAttachmentIterator(iterator); - } + @Override + public Document getDocument() { + Assert.state(messageFactory != null, "Could find message factory to use"); + // return saajSoapMessage.getSaajMessage().getSOAPPart(); // does not work, see SWS-345 + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + getSaajMessage().writeTo(bos); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + SOAPMessage saajMessage = messageFactory.createMessage(getSaajMessage().getMimeHeaders(), bis); + setSaajMessage(saajMessage); + return saajMessage.getSOAPPart(); + } + catch (SOAPException ex) { + throw new SaajSoapMessageException("Could not save changes", ex); + } + catch (IOException ex) { + throw new SaajSoapMessageException("Could not save changes", ex); + } + } - @Override - @SuppressWarnings("unchecked") - public Attachment getAttachment(String contentId) { - Assert.hasLength(contentId, "contentId must not be empty"); - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_ID, contentId); - Iterator iterator = getSaajMessage().getAttachments(mimeHeaders); - if (!iterator.hasNext()) { - return null; - } - AttachmentPart saajAttachment = iterator.next(); - return new SaajAttachment(saajAttachment); - } + @Override + public void setDocument(Document document) { + if (saajMessage.getSOAPPart() != document) { + Assert.state(messageFactory != null, "Could find message factory to use"); + try { + DOMImplementation implementation = document.getImplementation(); + Assert.isInstanceOf(DOMImplementationLS.class, implementation); - @Override - public Attachment addAttachment(String contentId, DataHandler dataHandler) { - Assert.hasLength(contentId, "contentId must not be empty"); - Assert.notNull(dataHandler, "dataHandler must not be null"); - SOAPMessage message = getSaajMessage(); - AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler); - message.addAttachmentPart(attachmentPart); - attachmentPart.setContentId(contentId); - attachmentPart.setMimeHeader(TransportConstants.HEADER_CONTENT_TRANSFER_ENCODING, - "binary"); - return new SaajAttachment(attachmentPart); - } + DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation; + LSOutput output = loadSaveImplementation.createLSOutput(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + output.setByteStream(bos); - public String toString() { - StringBuilder builder = new StringBuilder("SaajSoapMessage"); - try { - SOAPEnvelope envelope = saajMessage.getSOAPPart().getEnvelope(); - if (envelope != null) { - SOAPBody body = envelope.getBody(); - if (body != null) { - SOAPElement bodyElement = SaajUtils.getFirstBodyElement(body); - if (bodyElement != null) { - builder.append(' '); - builder.append(bodyElement.getElementQName()); - } - } - } - } - catch (SOAPException ex) { - // ignore - } - return builder.toString(); - } + LSSerializer serializer = loadSaveImplementation.createLSSerializer(); + serializer.write(document, output); - private static class SaajAttachmentIterator implements Iterator { + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - private final Iterator saajIterator; + this.saajMessage = messageFactory.createMessage(saajMessage.getMimeHeaders(), bis); - private SaajAttachmentIterator(Iterator saajIterator) { - this.saajIterator = saajIterator; - } + } + catch (SOAPException ex) { + throw new SaajSoapMessageException("Could not read input stream", ex); + } + catch (IOException ex) { + throw new SaajSoapMessageException("Could not read input stream", ex); + } + } + } - @Override - public boolean hasNext() { - return saajIterator.hasNext(); - } + @Override + public void writeTo(OutputStream outputStream) throws IOException { + MimeHeaders mimeHeaders = getSaajMessage().getMimeHeaders(); + if (ObjectUtils.isEmpty(mimeHeaders.getHeader(TransportConstants.HEADER_ACCEPT))) { + mimeHeaders.setHeader(TransportConstants.HEADER_ACCEPT, getVersion().getContentType()); + } + try { + SOAPMessage message = getSaajMessage(); + message.saveChanges(); + if (outputStream instanceof TransportOutputStream) { + TransportOutputStream transportOutputStream = (TransportOutputStream) outputStream; + // some SAAJ implementations (Axis 1) do not have a Content-Type header by default + MimeHeaders headers = message.getMimeHeaders(); + if (ObjectUtils + .isEmpty( + headers.getHeader(TransportConstants.HEADER_CONTENT_TYPE))) { + SOAPEnvelope envelope1 = message.getSOAPPart().getEnvelope(); + if (envelope1.getElementQName().getNamespaceURI() + .equals(SoapVersion.SOAP_11.getEnvelopeNamespaceUri())) { + headers.addHeader(TransportConstants.HEADER_CONTENT_TYPE, SoapVersion.SOAP_11.getContentType()); + } + else { + headers.addHeader(TransportConstants.HEADER_CONTENT_TYPE, SoapVersion.SOAP_12.getContentType()); + } + message.saveChanges(); + } + for (Iterator iterator = headers.getAllHeaders(); iterator.hasNext();) { + MimeHeader mimeHeader = (MimeHeader) iterator.next(); + transportOutputStream.addHeader(mimeHeader.getName(), mimeHeader.getValue()); + } + } + message.writeTo(outputStream); - @Override - public Attachment next() { - AttachmentPart saajAttachment = saajIterator.next(); - return new SaajAttachment(saajAttachment); - } + outputStream.flush(); + } + catch (SOAPException ex) { + throw new SaajSoapMessageException("Could not write message to OutputStream: " + ex.getMessage(), ex); + } + } - @Override - public void remove() { - saajIterator.remove(); - } - } + @Override + public boolean isXopPackage() { + SOAPPart saajPart = saajMessage.getSOAPPart(); + String[] contentTypes = saajPart.getMimeHeader(TransportConstants.HEADER_CONTENT_TYPE); + for (String contentType : contentTypes) { + if (contentType.contains(CONTENT_TYPE_XOP)) { + return true; + } + } + return false; + } + + @Override + public boolean convertToXopPackage() { + convertMessageToXop(); + convertPartToXop(); + return true; + } + + private void convertMessageToXop() { + MimeHeaders mimeHeaders = saajMessage.getMimeHeaders(); + String[] oldContentTypes = mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE); + String oldContentType = + !ObjectUtils.isEmpty(oldContentTypes) ? oldContentTypes[0] : getVersion().getContentType(); + mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, + CONTENT_TYPE_XOP + ";type=" + '"' + oldContentType + '"'); + } + + private void convertPartToXop() { + SOAPPart saajPart = saajMessage.getSOAPPart(); + String[] oldContentTypes = saajPart.getMimeHeader(TransportConstants.HEADER_CONTENT_TYPE); + String oldContentType = + !ObjectUtils.isEmpty(oldContentTypes) ? oldContentTypes[0] : getVersion().getContentType(); + saajPart.setMimeHeader(TransportConstants.HEADER_CONTENT_TYPE, + CONTENT_TYPE_XOP + ";type=" + '"' + oldContentType + '"'); + } + + @Override + @SuppressWarnings("unchecked") + public Iterator getAttachments() throws AttachmentException { + Iterator iterator = getSaajMessage().getAttachments(); + return new SaajAttachmentIterator(iterator); + } + + @Override + @SuppressWarnings("unchecked") + public Attachment getAttachment(String contentId) { + Assert.hasLength(contentId, "contentId must not be empty"); + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_ID, contentId); + Iterator iterator = getSaajMessage().getAttachments(mimeHeaders); + if (!iterator.hasNext()) { + return null; + } + AttachmentPart saajAttachment = iterator.next(); + return new SaajAttachment(saajAttachment); + } + + @Override + public Attachment addAttachment(String contentId, DataHandler dataHandler) { + Assert.hasLength(contentId, "contentId must not be empty"); + Assert.notNull(dataHandler, "dataHandler must not be null"); + SOAPMessage message = getSaajMessage(); + AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler); + message.addAttachmentPart(attachmentPart); + attachmentPart.setContentId(contentId); + attachmentPart.setMimeHeader(TransportConstants.HEADER_CONTENT_TRANSFER_ENCODING, + "binary"); + return new SaajAttachment(attachmentPart); + } + + public String toString() { + StringBuilder builder = new StringBuilder("SaajSoapMessage"); + try { + SOAPEnvelope envelope = saajMessage.getSOAPPart().getEnvelope(); + if (envelope != null) { + SOAPBody body = envelope.getBody(); + if (body != null) { + SOAPElement bodyElement = SaajUtils.getFirstBodyElement(body); + if (bodyElement != null) { + builder.append(' '); + builder.append(bodyElement.getElementQName()); + } + } + } + } + catch (SOAPException ex) { + // ignore + } + return builder.toString(); + } + + private static class SaajAttachmentIterator implements Iterator { + + private final Iterator saajIterator; + + private SaajAttachmentIterator(Iterator saajIterator) { + this.saajIterator = saajIterator; + } + + @Override + public boolean hasNext() { + return saajIterator.hasNext(); + } + + @Override + public Attachment next() { + AttachmentPart saajAttachment = saajIterator.next(); + return new SaajAttachment(saajAttachment); + } + + @Override + public void remove() { + saajIterator.remove(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageCreationException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageCreationException.java index dde1078b..ffe67eaa 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageCreationException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageCreationException.java @@ -25,11 +25,11 @@ import org.springframework.ws.soap.SoapMessageCreationException; @SuppressWarnings("serial") public class SaajSoapMessageCreationException extends SoapMessageCreationException { - public SaajSoapMessageCreationException(String msg) { - super(msg); - } + public SaajSoapMessageCreationException(String msg) { + super(msg); + } - public SaajSoapMessageCreationException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapMessageCreationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageException.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageException.java index 8d4aee48..26f307fc 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageException.java @@ -25,11 +25,11 @@ import org.springframework.ws.soap.SoapMessageException; @SuppressWarnings("serial") public class SaajSoapMessageException extends SoapMessageException { - public SaajSoapMessageException(String msg) { - super(msg); - } + public SaajSoapMessageException(String msg) { + super(msg); + } - public SaajSoapMessageException(String msg, Throwable ex) { - super(msg, ex); - } + public SaajSoapMessageException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageFactory.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageFactory.java index 7962bf10..7a9344f7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageFactory.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/SaajSoapMessageFactory.java @@ -59,247 +59,247 @@ import org.springframework.ws.transport.TransportInputStream; */ public class SaajSoapMessageFactory implements SoapMessageFactory, InitializingBean { - private static final Log logger = LogFactory.getLog(SaajSoapMessageFactory.class); + private static final Log logger = LogFactory.getLog(SaajSoapMessageFactory.class); - private MessageFactory messageFactory; + private MessageFactory messageFactory; - private String messageFactoryProtocol; + private String messageFactoryProtocol; - private boolean langAttributeOnSoap11FaultString = true; + private boolean langAttributeOnSoap11FaultString = true; - private Map messageProperties; + private Map messageProperties; - /** Default, empty constructor. */ - public SaajSoapMessageFactory() { - } + /** Default, empty constructor. */ + public SaajSoapMessageFactory() { + } - /** Constructor that takes a message factory as an argument. */ - public SaajSoapMessageFactory(MessageFactory messageFactory) { - this.messageFactory = messageFactory; - } + /** Constructor that takes a message factory as an argument. */ + public SaajSoapMessageFactory(MessageFactory messageFactory) { + this.messageFactory = messageFactory; + } - /** Returns the SAAJ {@code MessageFactory} used. */ - public MessageFactory getMessageFactory() { - return messageFactory; - } + /** Returns the SAAJ {@code MessageFactory} used. */ + public MessageFactory getMessageFactory() { + return messageFactory; + } - /** Sets the SAAJ {@code MessageFactory}. */ - public void setMessageFactory(MessageFactory messageFactory) { - this.messageFactory = messageFactory; - } + /** Sets the SAAJ {@code MessageFactory}. */ + public void setMessageFactory(MessageFactory messageFactory) { + this.messageFactory = messageFactory; + } - /** - * Sets the SAAJ message properties. These properties will be set on created messages. - * @see javax.xml.soap.SOAPMessage#setProperty(String, Object) - */ - public void setMessageProperties(Map messageProperties) { - this.messageProperties = messageProperties; - } + /** + * Sets the SAAJ message properties. These properties will be set on created messages. + * @see javax.xml.soap.SOAPMessage#setProperty(String, Object) + */ + public void setMessageProperties(Map messageProperties) { + this.messageProperties = messageProperties; + } - /** - * Defines whether a {@code xml:lang} attribute should be set on SOAP 1.1 {@code } elements. - * - *

The default is {@code true}, to comply with WS-I, but this flag can be set to {@code false} to the older W3C SOAP - * 1.1 specification. - * - * @see WS-I Basic Profile 1.1 - */ - public void setLangAttributeOnSoap11FaultString(boolean langAttributeOnSoap11FaultString) { - this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; - } + /** + * Defines whether a {@code xml:lang} attribute should be set on SOAP 1.1 {@code } elements. + * + *

The default is {@code true}, to comply with WS-I, but this flag can be set to {@code false} to the older W3C SOAP + * 1.1 specification. + * + * @see WS-I Basic Profile 1.1 + */ + public void setLangAttributeOnSoap11FaultString(boolean langAttributeOnSoap11FaultString) { + this.langAttributeOnSoap11FaultString = langAttributeOnSoap11FaultString; + } - @Override - public void setSoapVersion(SoapVersion version) { - if (SaajUtils.getSaajVersion() >= SaajUtils.SAAJ_13) { - if (SoapVersion.SOAP_11 == version) { - messageFactoryProtocol = SOAPConstants.SOAP_1_1_PROTOCOL; - } - else if (SoapVersion.SOAP_12 == version) { - messageFactoryProtocol = SOAPConstants.SOAP_1_2_PROTOCOL; - } - else { - throw new IllegalArgumentException( - "Invalid version [" + version + "]. Expected the SOAP_11 or SOAP_12 constant"); - } - } - else if (SoapVersion.SOAP_11 != version) { - throw new IllegalArgumentException("SAAJ 1.1 and 1.2 only support SOAP 1.1"); - } - } + @Override + public void setSoapVersion(SoapVersion version) { + if (SaajUtils.getSaajVersion() >= SaajUtils.SAAJ_13) { + if (SoapVersion.SOAP_11 == version) { + messageFactoryProtocol = SOAPConstants.SOAP_1_1_PROTOCOL; + } + else if (SoapVersion.SOAP_12 == version) { + messageFactoryProtocol = SOAPConstants.SOAP_1_2_PROTOCOL; + } + else { + throw new IllegalArgumentException( + "Invalid version [" + version + "]. Expected the SOAP_11 or SOAP_12 constant"); + } + } + else if (SoapVersion.SOAP_11 != version) { + throw new IllegalArgumentException("SAAJ 1.1 and 1.2 only support SOAP 1.1"); + } + } - @Override - public void afterPropertiesSet() { - if (messageFactory == null) { - try { - if (SaajUtils.getSaajVersion() >= SaajUtils.SAAJ_13) { - if (!StringUtils.hasLength(messageFactoryProtocol)) { - messageFactoryProtocol = SOAPConstants.SOAP_1_1_PROTOCOL; - } - if (logger.isInfoEnabled()) { - logger.info("Creating SAAJ 1.3 MessageFactory with " + messageFactoryProtocol); - } - messageFactory = MessageFactory.newInstance(messageFactoryProtocol); - } - else if (SaajUtils.getSaajVersion() == SaajUtils.SAAJ_12) { - logger.info("Creating SAAJ 1.2 MessageFactory"); - messageFactory = MessageFactory.newInstance(); - } - else if (SaajUtils.getSaajVersion() == SaajUtils.SAAJ_11) { - logger.info("Creating SAAJ 1.1 MessageFactory"); - messageFactory = MessageFactory.newInstance(); - } - else { - throw new IllegalStateException( - "SaajSoapMessageFactory requires SAAJ 1.1, which was not found on the classpath"); - } - } - catch (NoSuchMethodError ex) { - throw new SoapMessageCreationException( - "Could not create SAAJ MessageFactory. Is the version of the SAAJ specification interfaces [" + - SaajUtils.getSaajVersionString() + - "] the same as the version supported by the application server?", ex); - } - catch (SOAPException ex) { - throw new SoapMessageCreationException("Could not create SAAJ MessageFactory: " + ex.getMessage(), ex); - } - } - if (logger.isDebugEnabled()) { - logger.debug("Using MessageFactory class [" + messageFactory.getClass().getName() + "]"); - } - } + @Override + public void afterPropertiesSet() { + if (messageFactory == null) { + try { + if (SaajUtils.getSaajVersion() >= SaajUtils.SAAJ_13) { + if (!StringUtils.hasLength(messageFactoryProtocol)) { + messageFactoryProtocol = SOAPConstants.SOAP_1_1_PROTOCOL; + } + if (logger.isInfoEnabled()) { + logger.info("Creating SAAJ 1.3 MessageFactory with " + messageFactoryProtocol); + } + messageFactory = MessageFactory.newInstance(messageFactoryProtocol); + } + else if (SaajUtils.getSaajVersion() == SaajUtils.SAAJ_12) { + logger.info("Creating SAAJ 1.2 MessageFactory"); + messageFactory = MessageFactory.newInstance(); + } + else if (SaajUtils.getSaajVersion() == SaajUtils.SAAJ_11) { + logger.info("Creating SAAJ 1.1 MessageFactory"); + messageFactory = MessageFactory.newInstance(); + } + else { + throw new IllegalStateException( + "SaajSoapMessageFactory requires SAAJ 1.1, which was not found on the classpath"); + } + } + catch (NoSuchMethodError ex) { + throw new SoapMessageCreationException( + "Could not create SAAJ MessageFactory. Is the version of the SAAJ specification interfaces [" + + SaajUtils.getSaajVersionString() + + "] the same as the version supported by the application server?", ex); + } + catch (SOAPException ex) { + throw new SoapMessageCreationException("Could not create SAAJ MessageFactory: " + ex.getMessage(), ex); + } + } + if (logger.isDebugEnabled()) { + logger.debug("Using MessageFactory class [" + messageFactory.getClass().getName() + "]"); + } + } - @Override - public SaajSoapMessage createWebServiceMessage() { - try { - SOAPMessage saajMessage = messageFactory.createMessage(); - postProcess(saajMessage); - return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString, messageFactory); - } - catch (SOAPException ex) { - throw new SoapMessageCreationException("Could not create empty message: " + ex.getMessage(), ex); - } - } + @Override + public SaajSoapMessage createWebServiceMessage() { + try { + SOAPMessage saajMessage = messageFactory.createMessage(); + postProcess(saajMessage); + return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString, messageFactory); + } + catch (SOAPException ex) { + throw new SoapMessageCreationException("Could not create empty message: " + ex.getMessage(), ex); + } + } - @Override - public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException { - MimeHeaders mimeHeaders = parseMimeHeaders(inputStream); - try { - inputStream = checkForUtf8ByteOrderMark(inputStream); - SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream); - saajMessage.getSOAPPart().getEnvelope(); - postProcess(saajMessage); - return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString, messageFactory); - } - catch (SOAPException ex) { - // SAAJ 1.3 RI has a issue with handling multipart XOP content types which contain "startinfo" rather than - // "start-info", so let's try and do something about it - String contentType = StringUtils - .arrayToCommaDelimitedString(mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE)); - if (contentType.contains("startinfo")) { - contentType = contentType.replace("startinfo", "start-info"); - mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType); - try { - SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream); - postProcess(saajMessage); - return new SaajSoapMessage(saajMessage, - langAttributeOnSoap11FaultString); - } - catch (SOAPException e) { - // fall-through - } - } - SAXParseException parseException = getSAXParseException(ex); - if (parseException != null) { - throw new InvalidXmlException("Could not parse XML", parseException); - } else { - throw new SoapMessageCreationException( - "Could not create message from InputStream: " + ex.getMessage(), - ex); - } - } - } + @Override + public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException { + MimeHeaders mimeHeaders = parseMimeHeaders(inputStream); + try { + inputStream = checkForUtf8ByteOrderMark(inputStream); + SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream); + saajMessage.getSOAPPart().getEnvelope(); + postProcess(saajMessage); + return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString, messageFactory); + } + catch (SOAPException ex) { + // SAAJ 1.3 RI has a issue with handling multipart XOP content types which contain "startinfo" rather than + // "start-info", so let's try and do something about it + String contentType = StringUtils + .arrayToCommaDelimitedString(mimeHeaders.getHeader(TransportConstants.HEADER_CONTENT_TYPE)); + if (contentType.contains("startinfo")) { + contentType = contentType.replace("startinfo", "start-info"); + mimeHeaders.setHeader(TransportConstants.HEADER_CONTENT_TYPE, contentType); + try { + SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream); + postProcess(saajMessage); + return new SaajSoapMessage(saajMessage, + langAttributeOnSoap11FaultString); + } + catch (SOAPException e) { + // fall-through + } + } + SAXParseException parseException = getSAXParseException(ex); + if (parseException != null) { + throw new InvalidXmlException("Could not parse XML", parseException); + } else { + throw new SoapMessageCreationException( + "Could not create message from InputStream: " + ex.getMessage(), + ex); + } + } + } - private SAXParseException getSAXParseException(Throwable ex) { - if (ex instanceof SAXParseException) { - return (SAXParseException) ex; - } else if (ex.getCause() != null) { - return getSAXParseException(ex.getCause()); - } else { - return null; - } - } + private SAXParseException getSAXParseException(Throwable ex) { + if (ex instanceof SAXParseException) { + return (SAXParseException) ex; + } else if (ex.getCause() != null) { + return getSAXParseException(ex.getCause()); + } else { + return null; + } + } - private MimeHeaders parseMimeHeaders(InputStream inputStream) throws IOException { - MimeHeaders mimeHeaders = new MimeHeaders(); - if (inputStream instanceof TransportInputStream) { - TransportInputStream transportInputStream = (TransportInputStream) inputStream; - for (Iterator headerNames = transportInputStream.getHeaderNames(); headerNames.hasNext();) { - String headerName = headerNames.next(); - for (Iterator headerValues = transportInputStream.getHeaders(headerName); headerValues.hasNext();) { - String headerValue = headerValues.next(); - StringTokenizer tokenizer = new StringTokenizer(headerValue, ","); - while (tokenizer.hasMoreTokens()) { - mimeHeaders.addHeader(headerName, tokenizer.nextToken().trim()); - } - } - } - } - return mimeHeaders; - } + private MimeHeaders parseMimeHeaders(InputStream inputStream) throws IOException { + MimeHeaders mimeHeaders = new MimeHeaders(); + if (inputStream instanceof TransportInputStream) { + TransportInputStream transportInputStream = (TransportInputStream) inputStream; + for (Iterator headerNames = transportInputStream.getHeaderNames(); headerNames.hasNext();) { + String headerName = headerNames.next(); + for (Iterator headerValues = transportInputStream.getHeaders(headerName); headerValues.hasNext();) { + String headerValue = headerValues.next(); + StringTokenizer tokenizer = new StringTokenizer(headerValue, ","); + while (tokenizer.hasMoreTokens()) { + mimeHeaders.addHeader(headerName, tokenizer.nextToken().trim()); + } + } + } + } + return mimeHeaders; + } - /** - * Checks for the UTF-8 Byte Order Mark, and removes it if present. The SAAJ RI cannot cope with these BOMs. - * - * @see SWS-393 - * @see UTF-8 BOMs - */ - private InputStream checkForUtf8ByteOrderMark(InputStream inputStream) throws IOException { - PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3); - byte[] bytes = new byte[3]; - int bytesRead = 0; - while (bytesRead < bytes.length) { - int n = pushbackInputStream.read(bytes, bytesRead, bytes.length - bytesRead); - if (n > 0) { - bytesRead += n; - } else { - break; - } - } - if (bytesRead > 0) { - // check for the UTF-8 BOM, and remove it if there. See SWS-393 - if (!isByteOrderMark(bytes)) { - pushbackInputStream.unread(bytes, 0, bytesRead); - } - } - return pushbackInputStream; - } + /** + * Checks for the UTF-8 Byte Order Mark, and removes it if present. The SAAJ RI cannot cope with these BOMs. + * + * @see SWS-393 + * @see UTF-8 BOMs + */ + private InputStream checkForUtf8ByteOrderMark(InputStream inputStream) throws IOException { + PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3); + byte[] bytes = new byte[3]; + int bytesRead = 0; + while (bytesRead < bytes.length) { + int n = pushbackInputStream.read(bytes, bytesRead, bytes.length - bytesRead); + if (n > 0) { + bytesRead += n; + } else { + break; + } + } + if (bytesRead > 0) { + // check for the UTF-8 BOM, and remove it if there. See SWS-393 + if (!isByteOrderMark(bytes)) { + pushbackInputStream.unread(bytes, 0, bytesRead); + } + } + return pushbackInputStream; + } - private boolean isByteOrderMark(byte[] bytes) { - return bytes.length == 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF; - } + private boolean isByteOrderMark(byte[] bytes) { + return bytes.length == 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF; + } - /** - * Template method that allows for post-processing of the given {@link SOAPMessage}. - *

Default implementation sets {@linkplain SOAPMessage#setProperty(String, Object) message properties}, if any. - * @param soapMessage the message to post process - * @see #setMessageProperties(java.util.Map) - */ - protected void postProcess(SOAPMessage soapMessage) throws SOAPException { - if (!CollectionUtils.isEmpty(messageProperties)) { - for (Map.Entry entry : messageProperties.entrySet()) { - soapMessage.setProperty(entry.getKey(), entry.getValue()); - } - } - } + /** + * Template method that allows for post-processing of the given {@link SOAPMessage}. + *

Default implementation sets {@linkplain SOAPMessage#setProperty(String, Object) message properties}, if any. + * @param soapMessage the message to post process + * @see #setMessageProperties(java.util.Map) + */ + protected void postProcess(SOAPMessage soapMessage) throws SOAPException { + if (!CollectionUtils.isEmpty(messageProperties)) { + for (Map.Entry entry : messageProperties.entrySet()) { + soapMessage.setProperty(entry.getKey(), entry.getValue()); + } + } + } - public String toString() { - StringBuilder builder = new StringBuilder("SaajSoapMessageFactory["); - builder.append(SaajUtils.getSaajVersionString()); - if (SaajUtils.getSaajVersion() >= SaajUtils.SAAJ_13) { - builder.append(','); - builder.append(messageFactoryProtocol); - } - builder.append(']'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("SaajSoapMessageFactory["); + builder.append(SaajUtils.getSaajVersionString()); + if (SaajUtils.getSaajVersion() >= SaajUtils.SAAJ_13) { + builder.append(','); + builder.append(messageFactoryProtocol); + } + builder.append(']'); + return builder.toString(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajContentHandler.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajContentHandler.java index a1f3c84d..e8dc57e1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajContentHandler.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajContentHandler.java @@ -42,134 +42,134 @@ import org.springframework.util.StringUtils; */ public class SaajContentHandler implements ContentHandler { - private SOAPElement element; + private SOAPElement element; - private final SOAPEnvelope envelope; + private final SOAPEnvelope envelope; - private Map namespaces = new LinkedHashMap(); + private Map namespaces = new LinkedHashMap(); - /** - * Constructs a new instance of the {@code SaajContentHandler} that creates children of the given - * {@code SOAPElement}. - * - * @param element the element to write to - */ - public SaajContentHandler(SOAPElement element) { - Assert.notNull(element, "element must not be null"); - if (element instanceof SOAPEnvelope) { - envelope = (SOAPEnvelope) element; - } - else { - envelope = SaajUtils.getEnvelope(element); - } - this.element = element; - } + /** + * Constructs a new instance of the {@code SaajContentHandler} that creates children of the given + * {@code SOAPElement}. + * + * @param element the element to write to + */ + public SaajContentHandler(SOAPElement element) { + Assert.notNull(element, "element must not be null"); + if (element instanceof SOAPEnvelope) { + envelope = (SOAPEnvelope) element; + } + else { + envelope = SaajUtils.getEnvelope(element); + } + this.element = element; + } - @Override - public void characters(char ch[], int start, int length) throws SAXException { - try { - String text = new String(ch, start, length); - element.addTextNode(text); - } - catch (SOAPException ex) { - throw new SAXException(ex); - } - } + @Override + public void characters(char ch[], int start, int length) throws SAXException { + try { + String text = new String(ch, start, length); + element.addTextNode(text); + } + catch (SOAPException ex) { + throw new SAXException(ex); + } + } - @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - try { - String childPrefix = getPrefix(qName); - SOAPElement child = element.addChildElement(localName, childPrefix, uri); - for (int i = 0; i < atts.getLength(); i++) { - if (StringUtils.hasLength(atts.getLocalName(i))) { - String attributePrefix = getPrefix(atts.getQName(i)); - if (!"xmlns".equals(atts.getLocalName(i)) && !"xmlns".equals(attributePrefix)) { - Name attributeName = envelope.createName(atts.getLocalName(i), attributePrefix, atts.getURI(i)); - child.addAttribute(attributeName, atts.getValue(i)); - } - } - } - for (String namespacePrefix : namespaces.keySet()) { - String namespaceUri = namespaces.get(namespacePrefix); - if (!findParentNamespaceDeclaration(child, namespacePrefix, namespaceUri)) { - child.addNamespaceDeclaration(namespacePrefix, namespaceUri); - } - } - element = child; - } - catch (SOAPException ex) { - throw new SAXException(ex); - } - } + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + try { + String childPrefix = getPrefix(qName); + SOAPElement child = element.addChildElement(localName, childPrefix, uri); + for (int i = 0; i < atts.getLength(); i++) { + if (StringUtils.hasLength(atts.getLocalName(i))) { + String attributePrefix = getPrefix(atts.getQName(i)); + if (!"xmlns".equals(atts.getLocalName(i)) && !"xmlns".equals(attributePrefix)) { + Name attributeName = envelope.createName(atts.getLocalName(i), attributePrefix, atts.getURI(i)); + child.addAttribute(attributeName, atts.getValue(i)); + } + } + } + for (String namespacePrefix : namespaces.keySet()) { + String namespaceUri = namespaces.get(namespacePrefix); + if (!findParentNamespaceDeclaration(child, namespacePrefix, namespaceUri)) { + child.addNamespaceDeclaration(namespacePrefix, namespaceUri); + } + } + element = child; + } + catch (SOAPException ex) { + throw new SAXException(ex); + } + } - private boolean findParentNamespaceDeclaration(SOAPElement element, String prefix, String namespaceUri) { - String result = element.getNamespaceURI(prefix); - if (namespaceUri.equals(result)) { - return true; - } - else { - try { - SOAPElement parent = element.getParentElement(); - if (parent != null) { - return findParentNamespaceDeclaration(parent, prefix, namespaceUri); - } - } - catch (UnsupportedOperationException ex) { - // ignore - } - return false; - } - } + private boolean findParentNamespaceDeclaration(SOAPElement element, String prefix, String namespaceUri) { + String result = element.getNamespaceURI(prefix); + if (namespaceUri.equals(result)) { + return true; + } + else { + try { + SOAPElement parent = element.getParentElement(); + if (parent != null) { + return findParentNamespaceDeclaration(parent, prefix, namespaceUri); + } + } + catch (UnsupportedOperationException ex) { + // ignore + } + return false; + } + } - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - Assert.isTrue(localName.equals(element.getElementName().getLocalName()), "Invalid element on stack"); - Assert.isTrue(uri.equals(element.getElementName().getURI()), "Invalid element on stack"); - element = element.getParentElement(); - } + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + Assert.isTrue(localName.equals(element.getElementName().getLocalName()), "Invalid element on stack"); + Assert.isTrue(uri.equals(element.getElementName().getURI()), "Invalid element on stack"); + element = element.getParentElement(); + } - @Override - public void startPrefixMapping(String prefix, String uri) throws SAXException { - namespaces.put(prefix, uri); - } + @Override + public void startPrefixMapping(String prefix, String uri) throws SAXException { + namespaces.put(prefix, uri); + } - @Override - public void endPrefixMapping(String prefix) throws SAXException { - namespaces.remove(prefix); - } + @Override + public void endPrefixMapping(String prefix) throws SAXException { + namespaces.remove(prefix); + } - @Override - public void setDocumentLocator(Locator locator) { - } + @Override + public void setDocumentLocator(Locator locator) { + } - @Override - public void startDocument() throws SAXException { - } + @Override + public void startDocument() throws SAXException { + } - @Override - public void endDocument() throws SAXException { - } + @Override + public void endDocument() throws SAXException { + } - @Override - public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { - } + @Override + public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { + } - @Override - public void processingInstruction(String target, String data) throws SAXException { - } + @Override + public void processingInstruction(String target, String data) throws SAXException { + } - @Override - public void skippedEntity(String name) throws SAXException { - } + @Override + public void skippedEntity(String name) throws SAXException { + } - private String getPrefix(String qName) { - int idx = qName.indexOf(':'); - if (idx != -1) { - return qName.substring(0, idx); - } - else { - return null; - } - } + private String getPrefix(String qName) { + int idx = qName.indexOf(':'); + if (idx != -1) { + return qName.substring(0, idx); + } + else { + return null; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajUtils.java index 32ee17e3..e51b3133 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajUtils.java @@ -45,172 +45,172 @@ import org.springframework.ws.transport.TransportConstants; */ public abstract class SaajUtils { - public static final int SAAJ_11 = 0; + public static final int SAAJ_11 = 0; - public static final int SAAJ_12 = 1; + public static final int SAAJ_12 = 1; - public static final int SAAJ_13 = 2; + public static final int SAAJ_13 = 2; private static int saajVersion = SAAJ_13; - /** - * Gets the SAAJ version. - * Returns {@link #SAAJ_13} as of Spring-WS 2.2. - * - * @return a code comparable to the SAAJ_XX codes in this class - */ - public static int getSaajVersion() { - return saajVersion; - } - - /** - * Gets the SAAJ version for the specified {@link SOAPMessage}. - * Returns {@link #SAAJ_13} as of Spring-WS 2.2. - * - * @return a code comparable to the SAAJ_XX codes in this class - * @see #SAAJ_11 - * @see #SAAJ_12 - * @see #SAAJ_13 - */ - public static int getSaajVersion(SOAPMessage soapMessage) throws SOAPException { - Assert.notNull(soapMessage, "'soapMessage' must not be null"); - SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope(); - return getSaajVersion(soapEnvelope); - } - - /** - * Gets the SAAJ version for the specified {@link javax.xml.soap.SOAPElement}. - * Returns {@link #SAAJ_13} as of Spring-WS 2.2. - * - * @return a code comparable to the SAAJ_XX codes in this class - * @see #SAAJ_11 - * @see #SAAJ_12 - * @see #SAAJ_13 - */ - public static int getSaajVersion(SOAPElement soapElement) { - return SAAJ_13; - } + /** + * Gets the SAAJ version. + * Returns {@link #SAAJ_13} as of Spring-WS 2.2. + * + * @return a code comparable to the SAAJ_XX codes in this class + */ + public static int getSaajVersion() { + return saajVersion; + } /** - * Returns the SAAJ version as a String. The returned string will be "{@code SAAJ 1.3}", "{@code SAAJ - * 1.2}", or "{@code SAAJ 1.1}". - * - * @return a string representation of the SAAJ version - * @see #getSaajVersion() - */ - public static String getSaajVersionString() { - return getSaajVersionString(saajVersion); - } + * Gets the SAAJ version for the specified {@link SOAPMessage}. + * Returns {@link #SAAJ_13} as of Spring-WS 2.2. + * + * @return a code comparable to the SAAJ_XX codes in this class + * @see #SAAJ_11 + * @see #SAAJ_12 + * @see #SAAJ_13 + */ + public static int getSaajVersion(SOAPMessage soapMessage) throws SOAPException { + Assert.notNull(soapMessage, "'soapMessage' must not be null"); + SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope(); + return getSaajVersion(soapEnvelope); + } - private static String getSaajVersionString(int saajVersion) { - if (saajVersion >= SaajUtils.SAAJ_13) { - return "SAAJ 1.3"; - } - else if (saajVersion == SaajUtils.SAAJ_12) { - return "SAAJ 1.2"; - } - else if (saajVersion == SaajUtils.SAAJ_11) { - return "SAAJ 1.1"; - } - else { - return ""; - } - } + /** + * Gets the SAAJ version for the specified {@link javax.xml.soap.SOAPElement}. + * Returns {@link #SAAJ_13} as of Spring-WS 2.2. + * + * @return a code comparable to the SAAJ_XX codes in this class + * @see #SAAJ_11 + * @see #SAAJ_12 + * @see #SAAJ_13 + */ + public static int getSaajVersion(SOAPElement soapElement) { + return SAAJ_13; + } - /** - * Converts a {@link QName} to a {@link Name}. A {@link SOAPElement} is required to resolve namespaces. - * - * @param qName the {@code QName} to convert - * @param resolveElement a {@code SOAPElement} used to resolve namespaces to prefixes - * @return the converted SAAJ Name - * @throws SOAPException if conversion is unsuccessful - * @throws IllegalArgumentException if {@code qName} is not fully qualified - */ - public static Name toName(QName qName, SOAPElement resolveElement) throws SOAPException { - String qNamePrefix = qName.getPrefix(); - SOAPEnvelope envelope = getEnvelope(resolveElement); - if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(qNamePrefix)) { - return envelope.createName(qName.getLocalPart(), qNamePrefix, qName.getNamespaceURI()); - } - else if (StringUtils.hasLength(qName.getNamespaceURI())) { - Iterator prefixes; - if (getSaajVersion(resolveElement) == SAAJ_11) { - prefixes = resolveElement.getNamespacePrefixes(); - } - else { - prefixes = resolveElement.getVisibleNamespacePrefixes(); - } - while (prefixes.hasNext()) { - String prefix = (String) prefixes.next(); - if (qName.getNamespaceURI().equals(resolveElement.getNamespaceURI(prefix))) { - return envelope.createName(qName.getLocalPart(), prefix, qName.getNamespaceURI()); - } - } - return envelope.createName(qName.getLocalPart(), "", qName.getNamespaceURI()); - } - else { - return envelope.createName(qName.getLocalPart()); - } - } + /** + * Returns the SAAJ version as a String. The returned string will be "{@code SAAJ 1.3}", "{@code SAAJ + * 1.2}", or "{@code SAAJ 1.1}". + * + * @return a string representation of the SAAJ version + * @see #getSaajVersion() + */ + public static String getSaajVersionString() { + return getSaajVersionString(saajVersion); + } - /** - * Converts a {@code javax.xml.soap.Name} to a {@code javax.xml.namespace.QName}. - * - * @param name the {@code Name} to convert - * @return the converted {@code QName} - */ - public static QName toQName(Name name) { - if (StringUtils.hasLength(name.getURI()) && StringUtils.hasLength(name.getPrefix())) { - return new QName(name.getURI(), name.getLocalName(), name.getPrefix()); - } - else if (StringUtils.hasLength(name.getURI())) { - return new QName(name.getURI(), name.getLocalName()); - } - else { - return new QName(name.getLocalName()); - } - } + private static String getSaajVersionString(int saajVersion) { + if (saajVersion >= SaajUtils.SAAJ_13) { + return "SAAJ 1.3"; + } + else if (saajVersion == SaajUtils.SAAJ_12) { + return "SAAJ 1.2"; + } + else if (saajVersion == SaajUtils.SAAJ_11) { + return "SAAJ 1.1"; + } + else { + return ""; + } + } - /** - * Loads a SAAJ {@code SOAPMessage} from the given resource with a given message factory. - * - * @param resource the resource to read from - * @param messageFactory SAAJ message factory used to construct the message - * @return the loaded SAAJ message - * @throws SOAPException if the message cannot be constructed - * @throws IOException if the input stream resource cannot be loaded - */ - public static SOAPMessage loadMessage(Resource resource, MessageFactory messageFactory) - throws SOAPException, IOException { - InputStream is = resource.getInputStream(); - try { - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader(TransportConstants.HEADER_CONTENT_TYPE, "text/xml"); - mimeHeaders.addHeader(TransportConstants.HEADER_CONTENT_LENGTH, Long.toString(resource.getFile().length())); - return messageFactory.createMessage(mimeHeaders, is); - } - finally { - is.close(); - } - } + /** + * Converts a {@link QName} to a {@link Name}. A {@link SOAPElement} is required to resolve namespaces. + * + * @param qName the {@code QName} to convert + * @param resolveElement a {@code SOAPElement} used to resolve namespaces to prefixes + * @return the converted SAAJ Name + * @throws SOAPException if conversion is unsuccessful + * @throws IllegalArgumentException if {@code qName} is not fully qualified + */ + public static Name toName(QName qName, SOAPElement resolveElement) throws SOAPException { + String qNamePrefix = qName.getPrefix(); + SOAPEnvelope envelope = getEnvelope(resolveElement); + if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(qNamePrefix)) { + return envelope.createName(qName.getLocalPart(), qNamePrefix, qName.getNamespaceURI()); + } + else if (StringUtils.hasLength(qName.getNamespaceURI())) { + Iterator prefixes; + if (getSaajVersion(resolveElement) == SAAJ_11) { + prefixes = resolveElement.getNamespacePrefixes(); + } + else { + prefixes = resolveElement.getVisibleNamespacePrefixes(); + } + while (prefixes.hasNext()) { + String prefix = (String) prefixes.next(); + if (qName.getNamespaceURI().equals(resolveElement.getNamespaceURI(prefix))) { + return envelope.createName(qName.getLocalPart(), prefix, qName.getNamespaceURI()); + } + } + return envelope.createName(qName.getLocalPart(), "", qName.getNamespaceURI()); + } + else { + return envelope.createName(qName.getLocalPart()); + } + } - /** - * Returns the SAAJ {@code SOAPEnvelope} for the given element. - * - * @param element the element to return the envelope from - * @return the envelope, or {@code null} if not found - */ - public static SOAPEnvelope getEnvelope(SOAPElement element) { - Assert.notNull(element, "Element should not be null"); - do { - if (element instanceof SOAPEnvelope) { - return (SOAPEnvelope) element; - } - element = element.getParentElement(); - } - while (element != null); - return null; - } + /** + * Converts a {@code javax.xml.soap.Name} to a {@code javax.xml.namespace.QName}. + * + * @param name the {@code Name} to convert + * @return the converted {@code QName} + */ + public static QName toQName(Name name) { + if (StringUtils.hasLength(name.getURI()) && StringUtils.hasLength(name.getPrefix())) { + return new QName(name.getURI(), name.getLocalName(), name.getPrefix()); + } + else if (StringUtils.hasLength(name.getURI())) { + return new QName(name.getURI(), name.getLocalName()); + } + else { + return new QName(name.getLocalName()); + } + } + + /** + * Loads a SAAJ {@code SOAPMessage} from the given resource with a given message factory. + * + * @param resource the resource to read from + * @param messageFactory SAAJ message factory used to construct the message + * @return the loaded SAAJ message + * @throws SOAPException if the message cannot be constructed + * @throws IOException if the input stream resource cannot be loaded + */ + public static SOAPMessage loadMessage(Resource resource, MessageFactory messageFactory) + throws SOAPException, IOException { + InputStream is = resource.getInputStream(); + try { + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader(TransportConstants.HEADER_CONTENT_TYPE, "text/xml"); + mimeHeaders.addHeader(TransportConstants.HEADER_CONTENT_LENGTH, Long.toString(resource.getFile().length())); + return messageFactory.createMessage(mimeHeaders, is); + } + finally { + is.close(); + } + } + + /** + * Returns the SAAJ {@code SOAPEnvelope} for the given element. + * + * @param element the element to return the envelope from + * @return the envelope, or {@code null} if not found + */ + public static SOAPEnvelope getEnvelope(SOAPElement element) { + Assert.notNull(element, "Element should not be null"); + do { + if (element instanceof SOAPEnvelope) { + return (SOAPEnvelope) element; + } + element = element.getParentElement(); + } + while (element != null); + return null; + } /** * Returns the first child element of the given body. diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajXmlReader.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajXmlReader.java index 4b8b703a..693d305a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajXmlReader.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/saaj/support/SaajXmlReader.java @@ -43,168 +43,168 @@ import org.springframework.xml.sax.AbstractXmlReader; */ public class SaajXmlReader extends AbstractXmlReader { - private static final String NAMESPACES_FEATURE_NAME = "http://xml.org/sax/features/namespaces"; + private static final String NAMESPACES_FEATURE_NAME = "http://xml.org/sax/features/namespaces"; - private static final String NAMESPACE_PREFIXES_FEATURE_NAME = "http://xml.org/sax/features/namespace-prefixes"; + private static final String NAMESPACE_PREFIXES_FEATURE_NAME = "http://xml.org/sax/features/namespace-prefixes"; - private final Node startNode; + private final Node startNode; - private boolean namespacesFeature = true; + private boolean namespacesFeature = true; - private boolean namespacePrefixesFeature = false; + private boolean namespacePrefixesFeature = false; - /** - * Constructs a new instance of the {@code SaajXmlReader} that reads from the given {@code Node}. - * - * @param startNode the SAAJ {@code Node} to read from - */ - public SaajXmlReader(Node startNode) { - this.startNode = startNode; - } + /** + * Constructs a new instance of the {@code SaajXmlReader} that reads from the given {@code Node}. + * + * @param startNode the SAAJ {@code Node} to read from + */ + public SaajXmlReader(Node startNode) { + this.startNode = startNode; + } - @Override - public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { - if (NAMESPACES_FEATURE_NAME.equals(name)) { - return namespacesFeature; - } - else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) { - return namespacePrefixesFeature; - } - else { - return super.getFeature(name); - } - } + @Override + public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { + if (NAMESPACES_FEATURE_NAME.equals(name)) { + return namespacesFeature; + } + else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) { + return namespacePrefixesFeature; + } + else { + return super.getFeature(name); + } + } - @Override - public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { - if (NAMESPACES_FEATURE_NAME.equals(name)) { - this.namespacesFeature = value; - } - else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) { - this.namespacePrefixesFeature = value; - } - else { - super.setFeature(name, value); - } - } + @Override + public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { + if (NAMESPACES_FEATURE_NAME.equals(name)) { + this.namespacesFeature = value; + } + else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) { + this.namespacePrefixesFeature = value; + } + else { + super.setFeature(name, value); + } + } - /** - * Parses the StAX XML reader passed at construction-time. - * - *

Note that the given {@code InputSource} is not read, but ignored. - * - * @param ignored is ignored - * @throws org.xml.sax.SAXException A SAX exception, possibly wrapping a {@code XMLStreamException} - */ - @Override - public final void parse(InputSource ignored) throws SAXException { - parse(); - } + /** + * Parses the StAX XML reader passed at construction-time. + * + *

Note that the given {@code InputSource} is not read, but ignored. + * + * @param ignored is ignored + * @throws org.xml.sax.SAXException A SAX exception, possibly wrapping a {@code XMLStreamException} + */ + @Override + public final void parse(InputSource ignored) throws SAXException { + parse(); + } - /** - * Parses the StAX XML reader passed at construction-time. - * - *

Note that the given system identifier is not read, but ignored. - * - * @param ignored is ignored - * @throws SAXException A SAX exception, possibly wrapping a {@code XMLStreamException} - */ - @Override - public final void parse(String ignored) throws SAXException { - parse(); - } + /** + * Parses the StAX XML reader passed at construction-time. + * + *

Note that the given system identifier is not read, but ignored. + * + * @param ignored is ignored + * @throws SAXException A SAX exception, possibly wrapping a {@code XMLStreamException} + */ + @Override + public final void parse(String ignored) throws SAXException { + parse(); + } - private void parse() throws SAXException { - if (getContentHandler() != null) { - getContentHandler().startDocument(); - } - handleNode(startNode); - if (getContentHandler() != null) { - getContentHandler().endDocument(); - } - } + private void parse() throws SAXException { + if (getContentHandler() != null) { + getContentHandler().startDocument(); + } + handleNode(startNode); + if (getContentHandler() != null) { + getContentHandler().endDocument(); + } + } - private void handleNode(Node node) throws SAXException { - if (node instanceof SOAPElement) { - handleElement((SOAPElement) node); - } - else if (node instanceof Text) { - Text text = (Text) node; - handleText(text); - } - } + private void handleNode(Node node) throws SAXException { + if (node instanceof SOAPElement) { + handleElement((SOAPElement) node); + } + else if (node instanceof Text) { + Text text = (Text) node; + handleText(text); + } + } - private void handleElement(SOAPElement element) throws SAXException { - Name elementName = element.getElementName(); - if (getContentHandler() != null) { - if (namespacesFeature) { - for (Iterator iterator = element.getNamespacePrefixes(); iterator.hasNext();) { - String prefix = (String) iterator.next(); - String namespaceUri = element.getNamespaceURI(prefix); - getContentHandler().startPrefixMapping(prefix, namespaceUri); - } - getContentHandler() - .startElement(elementName.getURI(), elementName.getLocalName(), elementName.getQualifiedName(), - getAttributes(element)); - } - else { - getContentHandler().startElement("", "", elementName.getQualifiedName(), getAttributes(element)); - } - } - for (Iterator iterator = element.getChildElements(); iterator.hasNext();) { - Node child = (Node) iterator.next(); - handleNode(child); - } - if (getContentHandler() != null) { - if (namespacesFeature) { - getContentHandler() - .endElement(elementName.getURI(), elementName.getLocalName(), elementName.getQualifiedName()); - for (Iterator iterator = element.getNamespacePrefixes(); iterator.hasNext();) { - String prefix = (String) iterator.next(); - getContentHandler().endPrefixMapping(prefix); - } - } - else { - getContentHandler().endElement("", "", elementName.getQualifiedName()); - } - } - } + private void handleElement(SOAPElement element) throws SAXException { + Name elementName = element.getElementName(); + if (getContentHandler() != null) { + if (namespacesFeature) { + for (Iterator iterator = element.getNamespacePrefixes(); iterator.hasNext();) { + String prefix = (String) iterator.next(); + String namespaceUri = element.getNamespaceURI(prefix); + getContentHandler().startPrefixMapping(prefix, namespaceUri); + } + getContentHandler() + .startElement(elementName.getURI(), elementName.getLocalName(), elementName.getQualifiedName(), + getAttributes(element)); + } + else { + getContentHandler().startElement("", "", elementName.getQualifiedName(), getAttributes(element)); + } + } + for (Iterator iterator = element.getChildElements(); iterator.hasNext();) { + Node child = (Node) iterator.next(); + handleNode(child); + } + if (getContentHandler() != null) { + if (namespacesFeature) { + getContentHandler() + .endElement(elementName.getURI(), elementName.getLocalName(), elementName.getQualifiedName()); + for (Iterator iterator = element.getNamespacePrefixes(); iterator.hasNext();) { + String prefix = (String) iterator.next(); + getContentHandler().endPrefixMapping(prefix); + } + } + else { + getContentHandler().endElement("", "", elementName.getQualifiedName()); + } + } + } - private void handleText(Text text) throws SAXException { - if (getContentHandler() != null) { - char[] ch = text.getValue() != null ? text.getValue().toCharArray() : new char[0]; - getContentHandler().characters(ch, 0, ch.length); - } - } + private void handleText(Text text) throws SAXException { + if (getContentHandler() != null) { + char[] ch = text.getValue() != null ? text.getValue().toCharArray() : new char[0]; + getContentHandler().characters(ch, 0, ch.length); + } + } - private Attributes getAttributes(SOAPElement element) { - AttributesImpl attributes = new AttributesImpl(); + private Attributes getAttributes(SOAPElement element) { + AttributesImpl attributes = new AttributesImpl(); - for (Iterator iterator = element.getAllAttributes(); iterator.hasNext();) { - Name attributeName = (Name) iterator.next(); - String namespace = attributeName.getURI(); - if (namespace == null || !namespacesFeature) { - namespace = ""; - } - String attributeValue = element.getAttributeValue(attributeName); - attributes.addAttribute(namespace, attributeName.getLocalName(), attributeName.getQualifiedName(), "CDATA", - attributeValue); - } - if (namespacePrefixesFeature) { - for (Iterator iterator = element.getNamespacePrefixes(); iterator.hasNext();) { - String prefix = (String) iterator.next(); - String namespaceUri = element.getNamespaceURI(prefix); - String qName; - if (StringUtils.hasLength(prefix)) { - qName = "xmlns:" + prefix; - } - else { - qName = "xmlns"; - } - attributes.addAttribute("", "", qName, "CDATA", namespaceUri); - } - } - return attributes; - } + for (Iterator iterator = element.getAllAttributes(); iterator.hasNext();) { + Name attributeName = (Name) iterator.next(); + String namespace = attributeName.getURI(); + if (namespace == null || !namespacesFeature) { + namespace = ""; + } + String attributeValue = element.getAttributeValue(attributeName); + attributes.addAttribute(namespace, attributeName.getLocalName(), attributeName.getQualifiedName(), "CDATA", + attributeValue); + } + if (namespacePrefixesFeature) { + for (Iterator iterator = element.getNamespacePrefixes(); iterator.hasNext();) { + String prefix = (String) iterator.next(); + String namespaceUri = element.getNamespaceURI(prefix); + String qName; + if (StringUtils.hasLength(prefix)) { + qName = "xmlns:" + prefix; + } + else { + qName = "xmlns"; + } + attributes.addAttribute("", "", qName, "CDATA", namespaceUri); + } + } + return attributes; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SmartSoapEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SmartSoapEndpointInterceptor.java index 49e54b08..bacbf679 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SmartSoapEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SmartSoapEndpointInterceptor.java @@ -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, diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInterceptor.java index 741d4574..5e59ae90 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInterceptor.java @@ -28,12 +28,12 @@ import org.springframework.ws.soap.SoapHeaderElement; */ public interface SoapEndpointInterceptor extends EndpointInterceptor { - /** - * Given a {@link SoapHeaderElement}, return whether or not this {@link SoapEndpointInterceptor} understands it. - * - * @param header the header - * @return {@code true} if understood, {@code false} otherwise - */ - boolean understands(SoapHeaderElement header); + /** + * Given a {@link SoapHeaderElement}, return whether or not this {@link SoapEndpointInterceptor} understands it. + * + * @param header the header + * @return {@code true} if understood, {@code false} otherwise + */ + boolean understands(SoapHeaderElement header); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInvocationChain.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInvocationChain.java index 2031e5a7..53694ad1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInvocationChain.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointInvocationChain.java @@ -31,58 +31,58 @@ import org.springframework.ws.server.EndpointInvocationChain; */ public class SoapEndpointInvocationChain extends EndpointInvocationChain { - private String[] actorsOrRoles; + private String[] actorsOrRoles; - private boolean isUltimateReceiver = true; + private boolean isUltimateReceiver = true; - /** - * Create new {@code SoapEndpointInvocationChain}. - * - * @param endpoint the endpoint object to invoke - */ - public SoapEndpointInvocationChain(Object endpoint) { - super(endpoint); - } + /** + * Create new {@code SoapEndpointInvocationChain}. + * + * @param endpoint the endpoint object to invoke + */ + public SoapEndpointInvocationChain(Object endpoint) { + super(endpoint); + } - /** - * Create new {@code SoapEndpointInvocationChain}. - * - * @param endpoint the endpoint object to invoke - * @param interceptors the array of interceptors to apply - */ - public SoapEndpointInvocationChain(Object endpoint, EndpointInterceptor[] interceptors) { - super(endpoint, interceptors); - } + /** + * Create new {@code SoapEndpointInvocationChain}. + * + * @param endpoint the endpoint object to invoke + * @param interceptors the array of interceptors to apply + */ + public SoapEndpointInvocationChain(Object endpoint, EndpointInterceptor[] interceptors) { + super(endpoint, interceptors); + } - /** - * Create new {@code EndpointInvocationChain}. - * - * @param endpoint the endpoint object to invoke - * @param interceptors the array of interceptors to apply - * @param actorsOrRoles the array of actorsOrRoles to set - * @param isUltimateReceiver whether this chain fullfils the SOAP 1.2 Ultimate receiver role - */ - public SoapEndpointInvocationChain(Object endpoint, - EndpointInterceptor[] interceptors, - String[] actorsOrRoles, - boolean isUltimateReceiver) { - super(endpoint, interceptors); - this.actorsOrRoles = actorsOrRoles; - this.isUltimateReceiver = isUltimateReceiver; - } + /** + * Create new {@code EndpointInvocationChain}. + * + * @param endpoint the endpoint object to invoke + * @param interceptors the array of interceptors to apply + * @param actorsOrRoles the array of actorsOrRoles to set + * @param isUltimateReceiver whether this chain fullfils the SOAP 1.2 Ultimate receiver role + */ + public SoapEndpointInvocationChain(Object endpoint, + EndpointInterceptor[] interceptors, + String[] actorsOrRoles, + boolean isUltimateReceiver) { + super(endpoint, interceptors); + this.actorsOrRoles = actorsOrRoles; + this.isUltimateReceiver = isUltimateReceiver; + } - /** - * Gets the actors (SOAP 1.1) or roles (SOAP 1.2) associated with an invocation of this chain and its contained - * interceptors and endpoint. - * - * @return a string array of URIs for SOAP actors/roles - */ - public String[] getActorsOrRoles() { - return actorsOrRoles; - } + /** + * Gets the actors (SOAP 1.1) or roles (SOAP 1.2) associated with an invocation of this chain and its contained + * interceptors and endpoint. + * + * @return a string array of URIs for SOAP actors/roles + */ + public String[] getActorsOrRoles() { + return actorsOrRoles; + } - /** Indicates whether this chain fulfills the SOAP 1.2 Ultimate Receiver role. Default is {@code true}. */ - public boolean isUltimateReceiver() { - return isUltimateReceiver; - } + /** Indicates whether this chain fulfills the SOAP 1.2 Ultimate Receiver role. Default is {@code true}. */ + public boolean isUltimateReceiver() { + return isUltimateReceiver; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointMapping.java index 408746e8..e45cf565 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapEndpointMapping.java @@ -19,7 +19,7 @@ package org.springframework.ws.soap.server; import org.springframework.ws.server.EndpointMapping; /** - * SOAP-specific sub-interface of the {@code EndpointMapping}. Adds associated actors (SOAP 1.1) or roles (SOAP + * SOAP-specific sub-interface of the {@code EndpointMapping}. Adds associated actors (SOAP 1.1) or roles (SOAP * 1.2). Used by the {@code SoapMessageDispatcher} to determine the MustUnderstand headers for particular * endpoint. * @@ -31,12 +31,12 @@ import org.springframework.ws.server.EndpointMapping; */ public interface SoapEndpointMapping extends EndpointMapping { - /** Sets a single SOAP actor/actorOrRole to apply to all endpoints mapped by the delegate endpoint mapping. */ - void setActorOrRole(String actorOrRole); + /** Sets a single SOAP actor/actorOrRole to apply to all endpoints mapped by the delegate endpoint mapping. */ + void setActorOrRole(String actorOrRole); - /** Sets the array of SOAP actors/actorsOrRoles to apply to all endpoints mapped by the delegate endpoint mapping. */ - void setActorsOrRoles(String[] actorsOrRoles); + /** Sets the array of SOAP actors/actorsOrRoles to apply to all endpoints mapped by the delegate endpoint mapping. */ + void setActorsOrRoles(String[] actorsOrRoles); - /** Indicates whether this the endpoint fulfills the SOAP 1.2 Ultimate Receiver role. */ - void setUltimateReceiver(boolean ultimateReceiver); + /** Indicates whether this the endpoint fulfills the SOAP 1.2 Ultimate Receiver role. */ + void setUltimateReceiver(boolean ultimateReceiver); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapMessageDispatcher.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapMessageDispatcher.java index dc92550a..9075d9e4 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapMessageDispatcher.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/SoapMessageDispatcher.java @@ -47,134 +47,134 @@ import org.springframework.ws.soap.soap12.Soap12Header; */ public class SoapMessageDispatcher extends MessageDispatcher { - /** Default message used when creating a SOAP MustUnderstand fault. */ - public static final String DEFAULT_MUST_UNDERSTAND_FAULT_STRING = - "One or more mandatory SOAP header blocks not understood"; + /** Default message used when creating a SOAP MustUnderstand fault. */ + public static final String DEFAULT_MUST_UNDERSTAND_FAULT_STRING = + "One or more mandatory SOAP header blocks not understood"; - private String mustUnderstandFaultString = DEFAULT_MUST_UNDERSTAND_FAULT_STRING; + private String mustUnderstandFaultString = DEFAULT_MUST_UNDERSTAND_FAULT_STRING; - private Locale mustUnderstandFaultStringLocale = Locale.ENGLISH; + private Locale mustUnderstandFaultStringLocale = Locale.ENGLISH; - /** - * Sets the message used for {@code MustUnderstand} fault. Default to {@link - * #DEFAULT_MUST_UNDERSTAND_FAULT_STRING}. - */ - public void setMustUnderstandFaultString(String mustUnderstandFaultString) { - this.mustUnderstandFaultString = mustUnderstandFaultString; - } + /** + * Sets the message used for {@code MustUnderstand} fault. Default to {@link + * #DEFAULT_MUST_UNDERSTAND_FAULT_STRING}. + */ + public void setMustUnderstandFaultString(String mustUnderstandFaultString) { + this.mustUnderstandFaultString = mustUnderstandFaultString; + } - /** Sets the locale of the message used for {@code MustUnderstand} fault. Default to {@link Locale#ENGLISH}. */ - public void setMustUnderstandFaultStringLocale(Locale mustUnderstandFaultStringLocale) { - this.mustUnderstandFaultStringLocale = mustUnderstandFaultStringLocale; - } + /** Sets the locale of the message used for {@code MustUnderstand} fault. Default to {@link Locale#ENGLISH}. */ + public void setMustUnderstandFaultStringLocale(Locale mustUnderstandFaultStringLocale) { + this.mustUnderstandFaultStringLocale = mustUnderstandFaultStringLocale; + } - /** - * Process the headers targeted at the actor or role fullfilled by the endpoint. Also processed the - * {@code MustUnderstand} headers in the incoming SOAP request message. Iterates over all SOAP headers which - * should be understood for this role, and determines whether these are supported. Generates a SOAP MustUnderstand - * fault if a header is not understood. - * - * @param mappedEndpoint the mapped EndpointInvocationChain - * @param messageContext the message context - * @return {@code true} if all necessary headers are understood; {@code false} otherwise - * @see SoapEndpointInvocationChain#getActorsOrRoles() - * @see org.springframework.ws.soap.SoapHeader#examineMustUnderstandHeaderElements(String) - */ - @Override - protected boolean handleRequest(EndpointInvocationChain mappedEndpoint, MessageContext messageContext) { - if (messageContext.getRequest() instanceof SoapMessage) { - String[] actorsOrRoles = null; - boolean isUltimateReceiver = true; - if (mappedEndpoint instanceof SoapEndpointInvocationChain) { - SoapEndpointInvocationChain soapChain = (SoapEndpointInvocationChain) mappedEndpoint; - actorsOrRoles = soapChain.getActorsOrRoles(); - isUltimateReceiver = soapChain.isUltimateReceiver(); - } - return handleHeaders(mappedEndpoint, messageContext, actorsOrRoles, isUltimateReceiver); - } - return true; - } + /** + * Process the headers targeted at the actor or role fullfilled by the endpoint. Also processed the + * {@code MustUnderstand} headers in the incoming SOAP request message. Iterates over all SOAP headers which + * should be understood for this role, and determines whether these are supported. Generates a SOAP MustUnderstand + * fault if a header is not understood. + * + * @param mappedEndpoint the mapped EndpointInvocationChain + * @param messageContext the message context + * @return {@code true} if all necessary headers are understood; {@code false} otherwise + * @see SoapEndpointInvocationChain#getActorsOrRoles() + * @see org.springframework.ws.soap.SoapHeader#examineMustUnderstandHeaderElements(String) + */ + @Override + protected boolean handleRequest(EndpointInvocationChain mappedEndpoint, MessageContext messageContext) { + if (messageContext.getRequest() instanceof SoapMessage) { + String[] actorsOrRoles = null; + boolean isUltimateReceiver = true; + if (mappedEndpoint instanceof SoapEndpointInvocationChain) { + SoapEndpointInvocationChain soapChain = (SoapEndpointInvocationChain) mappedEndpoint; + actorsOrRoles = soapChain.getActorsOrRoles(); + isUltimateReceiver = soapChain.isUltimateReceiver(); + } + return handleHeaders(mappedEndpoint, messageContext, actorsOrRoles, isUltimateReceiver); + } + return true; + } - private boolean handleHeaders(EndpointInvocationChain mappedEndpoint, - MessageContext messageContext, - String[] actorsOrRoles, - boolean isUltimateReceiver) { - SoapMessage soapRequest = (SoapMessage) messageContext.getRequest(); - SoapHeader soapHeader = soapRequest.getSoapHeader(); - if (soapHeader == null) { - return true; - } - Iterator headerIterator; - if (soapHeader instanceof Soap11Header) { - headerIterator = ((Soap11Header) soapHeader).examineHeaderElementsToProcess(actorsOrRoles); - } - else { - headerIterator = - ((Soap12Header) soapHeader).examineHeaderElementsToProcess(actorsOrRoles, isUltimateReceiver); - } - List notUnderstoodHeaderNames = new ArrayList(); - while (headerIterator.hasNext()) { - SoapHeaderElement headerElement = headerIterator.next(); - QName headerName = headerElement.getName(); - if (headerElement.getMustUnderstand() && logger.isDebugEnabled()) { - logger.debug("Handling MustUnderstand header " + headerName); - } - if (headerElement.getMustUnderstand() && !headerUnderstood(mappedEndpoint, headerElement)) { - notUnderstoodHeaderNames.add(headerName); - } - } - if (notUnderstoodHeaderNames.isEmpty()) { - return true; - } - else { - SoapMessage response = (SoapMessage) messageContext.getResponse(); - createMustUnderstandFault(response, notUnderstoodHeaderNames, actorsOrRoles); - return false; - } - } + private boolean handleHeaders(EndpointInvocationChain mappedEndpoint, + MessageContext messageContext, + String[] actorsOrRoles, + boolean isUltimateReceiver) { + SoapMessage soapRequest = (SoapMessage) messageContext.getRequest(); + SoapHeader soapHeader = soapRequest.getSoapHeader(); + if (soapHeader == null) { + return true; + } + Iterator headerIterator; + if (soapHeader instanceof Soap11Header) { + headerIterator = ((Soap11Header) soapHeader).examineHeaderElementsToProcess(actorsOrRoles); + } + else { + headerIterator = + ((Soap12Header) soapHeader).examineHeaderElementsToProcess(actorsOrRoles, isUltimateReceiver); + } + List notUnderstoodHeaderNames = new ArrayList(); + while (headerIterator.hasNext()) { + SoapHeaderElement headerElement = headerIterator.next(); + QName headerName = headerElement.getName(); + if (headerElement.getMustUnderstand() && logger.isDebugEnabled()) { + logger.debug("Handling MustUnderstand header " + headerName); + } + if (headerElement.getMustUnderstand() && !headerUnderstood(mappedEndpoint, headerElement)) { + notUnderstoodHeaderNames.add(headerName); + } + } + if (notUnderstoodHeaderNames.isEmpty()) { + return true; + } + else { + SoapMessage response = (SoapMessage) messageContext.getResponse(); + createMustUnderstandFault(response, notUnderstoodHeaderNames, actorsOrRoles); + return false; + } + } - /** - * Handles the request for a single SOAP actor/role. Iterates over all {@code MustUnderstand} headers for a - * specific SOAP 1.1 actor or SOAP 1.2 role, and determines whether these are understood by any of the registered - * {@code SoapEndpointInterceptor}. If they are, returns {@code true}. If they are not, a SOAP fault is - * created, and false is returned. - * - * @see SoapEndpointInterceptor#understands(org.springframework.ws.soap.SoapHeaderElement) - */ - private boolean headerUnderstood(EndpointInvocationChain mappedEndpoint, SoapHeaderElement headerElement) { - EndpointInterceptor[] interceptors = mappedEndpoint.getInterceptors(); - if (ObjectUtils.isEmpty(interceptors)) { - return false; - } - for (EndpointInterceptor interceptor : interceptors) { - if (interceptor instanceof SoapEndpointInterceptor && - ((SoapEndpointInterceptor) interceptor).understands(headerElement)) { - return true; - } - } - return false; - } + /** + * Handles the request for a single SOAP actor/role. Iterates over all {@code MustUnderstand} headers for a + * specific SOAP 1.1 actor or SOAP 1.2 role, and determines whether these are understood by any of the registered + * {@code SoapEndpointInterceptor}. If they are, returns {@code true}. If they are not, a SOAP fault is + * created, and false is returned. + * + * @see SoapEndpointInterceptor#understands(org.springframework.ws.soap.SoapHeaderElement) + */ + private boolean headerUnderstood(EndpointInvocationChain mappedEndpoint, SoapHeaderElement headerElement) { + EndpointInterceptor[] interceptors = mappedEndpoint.getInterceptors(); + if (ObjectUtils.isEmpty(interceptors)) { + return false; + } + for (EndpointInterceptor interceptor : interceptors) { + if (interceptor instanceof SoapEndpointInterceptor && + ((SoapEndpointInterceptor) interceptor).understands(headerElement)) { + return true; + } + } + return false; + } - private void createMustUnderstandFault(SoapMessage soapResponse, - List notUnderstoodHeaderNames, - String[] actorsOrRoles) { - if (logger.isWarnEnabled()) { - logger.warn("Could not handle mustUnderstand headers: " + - StringUtils.collectionToCommaDelimitedString(notUnderstoodHeaderNames) + ". Returning fault"); - } - SoapBody responseBody = soapResponse.getSoapBody(); - SoapFault fault = - responseBody.addMustUnderstandFault(mustUnderstandFaultString, mustUnderstandFaultStringLocale); - if (!ObjectUtils.isEmpty(actorsOrRoles)) { - fault.setFaultActorOrRole(actorsOrRoles[0]); - } - SoapHeader header = soapResponse.getSoapHeader(); - if (header instanceof Soap12Header) { - Soap12Header soap12Header = (Soap12Header) header; - for (QName headerName : notUnderstoodHeaderNames) { - soap12Header.addNotUnderstoodHeaderElement(headerName); - } - } - } + private void createMustUnderstandFault(SoapMessage soapResponse, + List notUnderstoodHeaderNames, + String[] actorsOrRoles) { + if (logger.isWarnEnabled()) { + logger.warn("Could not handle mustUnderstand headers: " + + StringUtils.collectionToCommaDelimitedString(notUnderstoodHeaderNames) + ". Returning fault"); + } + SoapBody responseBody = soapResponse.getSoapBody(); + SoapFault fault = + responseBody.addMustUnderstandFault(mustUnderstandFaultString, mustUnderstandFaultStringLocale); + if (!ObjectUtils.isEmpty(actorsOrRoles)) { + fault.setFaultActorOrRole(actorsOrRoles[0]); + } + SoapHeader header = soapResponse.getSoapHeader(); + if (header instanceof Soap12Header) { + Soap12Header soap12Header = (Soap12Header) header; + for (QName headerName : notUnderstoodHeaderNames) { + soap12Header.addNotUnderstoodHeaderElement(headerName); + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractFaultCreatingValidatingMarshallingPayloadEndpoint.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractFaultCreatingValidatingMarshallingPayloadEndpoint.java index 522059e2..53bcb994 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractFaultCreatingValidatingMarshallingPayloadEndpoint.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractFaultCreatingValidatingMarshallingPayloadEndpoint.java @@ -46,136 +46,136 @@ import org.springframework.ws.soap.SoapMessage; */ @Deprecated public abstract class AbstractFaultCreatingValidatingMarshallingPayloadEndpoint - extends org.springframework.ws.server.endpoint.AbstractValidatingMarshallingPayloadEndpoint implements MessageSourceAware { - - /** - * Default SOAP Fault Detail name used when a global validation error occur on the request. - * - * @see #setDetailElementName(javax.xml.namespace.QName) - */ - public static final QName DEFAULT_DETAIL_ELEMENT_NAME = - new QName("http://springframework.org/spring-ws", "ValidationError", - "spring-ws"); + extends org.springframework.ws.server.endpoint.AbstractValidatingMarshallingPayloadEndpoint implements MessageSourceAware { /** - * Default SOAP Fault string used when a validation errors occur on the request. - * - * @see #setFaultStringOrReason(String) - */ - public static final String DEFAULT_FAULTSTRING_OR_REASON = "Validation error"; + * Default SOAP Fault Detail name used when a global validation error occur on the request. + * + * @see #setDetailElementName(javax.xml.namespace.QName) + */ + public static final QName DEFAULT_DETAIL_ELEMENT_NAME = + new QName("http://springframework.org/spring-ws", "ValidationError", + "spring-ws"); - private boolean addValidationErrorDetail = true; + /** + * Default SOAP Fault string used when a validation errors occur on the request. + * + * @see #setFaultStringOrReason(String) + */ + public static final String DEFAULT_FAULTSTRING_OR_REASON = "Validation error"; - private QName detailElementName = DEFAULT_DETAIL_ELEMENT_NAME; + private boolean addValidationErrorDetail = true; - private String faultStringOrReason = DEFAULT_FAULTSTRING_OR_REASON; + private QName detailElementName = DEFAULT_DETAIL_ELEMENT_NAME; - private Locale faultStringOrReasonLocale = Locale.ENGLISH; + private String faultStringOrReason = DEFAULT_FAULTSTRING_OR_REASON; - private MessageSource messageSource; + private Locale faultStringOrReasonLocale = Locale.ENGLISH; - /** - * Returns whether a SOAP Fault detail element should be created when a validation error occurs. This detail element - * will contain the exact validation errors. It is only added when the underlying message is a - * {@code SoapMessage}. Defaults to {@code true}. - * - * @see org.springframework.ws.soap.SoapFault#addFaultDetail() - */ - public boolean getAddValidationErrorDetail() { - return addValidationErrorDetail; - } + private MessageSource messageSource; - /** - * Indicates whether a SOAP Fault detail element should be created when a validation error occurs. This detail - * element will contain the exact validation errors. It is only added when the underlying message is a - * {@code SoapMessage}. Defaults to {@code true}. - * - * @see org.springframework.ws.soap.SoapFault#addFaultDetail() - */ - public void setAddValidationErrorDetail(boolean addValidationErrorDetail) { - this.addValidationErrorDetail = addValidationErrorDetail; - } + /** + * Returns whether a SOAP Fault detail element should be created when a validation error occurs. This detail element + * will contain the exact validation errors. It is only added when the underlying message is a + * {@code SoapMessage}. Defaults to {@code true}. + * + * @see org.springframework.ws.soap.SoapFault#addFaultDetail() + */ + public boolean getAddValidationErrorDetail() { + return addValidationErrorDetail; + } - /** Returns the fault detail element name when validation errors occur on the request. */ - public QName getDetailElementName() { - return detailElementName; - } + /** + * Indicates whether a SOAP Fault detail element should be created when a validation error occurs. This detail + * element will contain the exact validation errors. It is only added when the underlying message is a + * {@code SoapMessage}. Defaults to {@code true}. + * + * @see org.springframework.ws.soap.SoapFault#addFaultDetail() + */ + public void setAddValidationErrorDetail(boolean addValidationErrorDetail) { + this.addValidationErrorDetail = addValidationErrorDetail; + } - /** - * Sets the fault detail element name when validation errors occur on the request. Defaults to - * {@code DEFAULT_DETAIL_ELEMENT_NAME}. - * - * @see #DEFAULT_DETAIL_ELEMENT_NAME - */ - public void setDetailElementName(QName detailElementName) { - this.detailElementName = detailElementName; - } + /** Returns the fault detail element name when validation errors occur on the request. */ + public QName getDetailElementName() { + return detailElementName; + } - /** Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. */ - public String getFaultStringOrReason() { - return faultStringOrReason; - } + /** + * Sets the fault detail element name when validation errors occur on the request. Defaults to + * {@code DEFAULT_DETAIL_ELEMENT_NAME}. + * + * @see #DEFAULT_DETAIL_ELEMENT_NAME + */ + public void setDetailElementName(QName detailElementName) { + this.detailElementName = detailElementName; + } - /** - * Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. - * It is only added when the underlying message is a {@code SoapMessage}. Defaults to - * {@code DEFAULT_FAULTSTRING_OR_REASON}. - * - * @see #DEFAULT_FAULTSTRING_OR_REASON - */ - public void setFaultStringOrReason(String faultStringOrReason) { - this.faultStringOrReason = faultStringOrReason; - } + /** Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. */ + public String getFaultStringOrReason() { + return faultStringOrReason; + } - /** Returns the locale for SOAP fault reason and validation message resolution. */ - public Locale getFaultLocale() { - return faultStringOrReasonLocale; - } + /** + * Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. + * It is only added when the underlying message is a {@code SoapMessage}. Defaults to + * {@code DEFAULT_FAULTSTRING_OR_REASON}. + * + * @see #DEFAULT_FAULTSTRING_OR_REASON + */ + public void setFaultStringOrReason(String faultStringOrReason) { + this.faultStringOrReason = faultStringOrReason; + } - /** - * Sets the locale for SOAP fault reason and validation messages. It is only added when the underlying message is a - * {@code SoapMessage}. Defaults to English. - * - * @see java.util.Locale#ENGLISH - */ - public void setFaultStringOrReasonLocale(Locale faultStringOrReasonLocale) { - this.faultStringOrReasonLocale = faultStringOrReasonLocale; - } + /** Returns the locale for SOAP fault reason and validation message resolution. */ + public Locale getFaultLocale() { + return faultStringOrReasonLocale; + } - @Override - public final void setMessageSource(MessageSource messageSource) { - this.messageSource = messageSource; - } + /** + * Sets the locale for SOAP fault reason and validation messages. It is only added when the underlying message is a + * {@code SoapMessage}. Defaults to English. + * + * @see java.util.Locale#ENGLISH + */ + public void setFaultStringOrReasonLocale(Locale faultStringOrReasonLocale) { + this.faultStringOrReasonLocale = faultStringOrReasonLocale; + } - /** - * This implementation logs all errors, returns {@code false}, and creates a {@link - * SoapBody#addClientOrSenderFault(String,Locale) client or sender} {@link SoapFault}, adding a {@link - * SoapFaultDetail} with all errors if the {@code addValidationErrorDetail} property is {@code true}. - * - * @param messageContext the message context - * @param errors the validation errors - * @return {@code true} to continue processing the request, {@code false} (the default) otherwise - * @see Errors#getAllErrors() - */ - @Override - protected final boolean onValidationErrors(MessageContext messageContext, Object requestObject, Errors errors) { - for (ObjectError objectError : errors.getAllErrors()) { - String msg = messageSource.getMessage(objectError, getFaultLocale()); - logger.warn("Validation error on request object[" + requestObject + "]: " + msg); - } - if (messageContext.getResponse() instanceof SoapMessage) { - SoapMessage response = (SoapMessage) messageContext.getResponse(); - SoapBody body = response.getSoapBody(); - SoapFault fault = body.addClientOrSenderFault(getFaultStringOrReason(), getFaultLocale()); - if (getAddValidationErrorDetail()) { - SoapFaultDetail detail = fault.addFaultDetail(); - for (ObjectError objectError : errors.getAllErrors()) { - String msg = messageSource.getMessage(objectError, getFaultLocale()); - SoapFaultDetailElement detailElement = detail.addFaultDetailElement(getDetailElementName()); - detailElement.addText(msg); - } - } - } - return false; - } + @Override + public final void setMessageSource(MessageSource messageSource) { + this.messageSource = messageSource; + } + + /** + * This implementation logs all errors, returns {@code false}, and creates a {@link + * SoapBody#addClientOrSenderFault(String,Locale) client or sender} {@link SoapFault}, adding a {@link + * SoapFaultDetail} with all errors if the {@code addValidationErrorDetail} property is {@code true}. + * + * @param messageContext the message context + * @param errors the validation errors + * @return {@code true} to continue processing the request, {@code false} (the default) otherwise + * @see Errors#getAllErrors() + */ + @Override + protected final boolean onValidationErrors(MessageContext messageContext, Object requestObject, Errors errors) { + for (ObjectError objectError : errors.getAllErrors()) { + String msg = messageSource.getMessage(objectError, getFaultLocale()); + logger.warn("Validation error on request object[" + requestObject + "]: " + msg); + } + if (messageContext.getResponse() instanceof SoapMessage) { + SoapMessage response = (SoapMessage) messageContext.getResponse(); + SoapBody body = response.getSoapBody(); + SoapFault fault = body.addClientOrSenderFault(getFaultStringOrReason(), getFaultLocale()); + if (getAddValidationErrorDetail()) { + SoapFaultDetail detail = fault.addFaultDetail(); + for (ObjectError objectError : errors.getAllErrors()) { + String msg = messageSource.getMessage(objectError, getFaultLocale()); + SoapFaultDetailElement detailElement = detail.addFaultDetailElement(getDetailElementName()); + detailElement.addText(msg); + } + } + } + return false; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractSoapFaultDefinitionExceptionResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractSoapFaultDefinitionExceptionResolver.java index 5fd4ba3c..b85e1186 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractSoapFaultDefinitionExceptionResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/AbstractSoapFaultDefinitionExceptionResolver.java @@ -40,83 +40,83 @@ import org.springframework.ws.soap.soap12.Soap12Fault; */ public abstract class AbstractSoapFaultDefinitionExceptionResolver extends AbstractEndpointExceptionResolver { - private SoapFaultDefinition defaultFault; + private SoapFaultDefinition defaultFault; - /** Set the default fault. This fault will be returned if no specific mapping was found. */ - public void setDefaultFault(SoapFaultDefinition defaultFault) { - this.defaultFault = defaultFault; - } + /** Set the default fault. This fault will be returned if no specific mapping was found. */ + public void setDefaultFault(SoapFaultDefinition defaultFault) { + this.defaultFault = defaultFault; + } - /** - * Template method that returns the {@link SoapFaultDefinition} for the given exception. - * - * @param endpoint the executed endpoint, or {@code null} if none chosen at the time of the exception - * @param ex the exception to be handled - * @return the definition mapped to the exception, or {@code null} if none is found. - */ - protected abstract SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex); + /** + * Template method that returns the {@link SoapFaultDefinition} for the given exception. + * + * @param endpoint the executed endpoint, or {@code null} if none chosen at the time of the exception + * @param ex the exception to be handled + * @return the definition mapped to the exception, or {@code null} if none is found. + */ + protected abstract SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex); - @Override - protected final boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) { - Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(), - "AbstractSoapFaultDefinitionExceptionResolver requires a SoapMessage"); + @Override + protected final boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) { + Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(), + "AbstractSoapFaultDefinitionExceptionResolver requires a SoapMessage"); - SoapFaultDefinition definition = getFaultDefinition(endpoint, ex); - if (definition == null) { - definition = defaultFault; - } - if (definition == null) { - return false; - } + SoapFaultDefinition definition = getFaultDefinition(endpoint, ex); + if (definition == null) { + definition = defaultFault; + } + if (definition == null) { + return false; + } - String faultStringOrReason = definition.getFaultStringOrReason(); - if (!StringUtils.hasLength(faultStringOrReason)) { - faultStringOrReason = StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : ex.toString(); - } - SoapBody soapBody = ((SoapMessage) messageContext.getResponse()).getSoapBody(); - SoapFault fault; + String faultStringOrReason = definition.getFaultStringOrReason(); + if (!StringUtils.hasLength(faultStringOrReason)) { + faultStringOrReason = StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : ex.toString(); + } + SoapBody soapBody = ((SoapMessage) messageContext.getResponse()).getSoapBody(); + SoapFault fault; - if (SoapFaultDefinition.SERVER.equals(definition.getFaultCode()) || - SoapFaultDefinition.RECEIVER.equals(definition.getFaultCode())) { - fault = soapBody.addServerOrReceiverFault(faultStringOrReason, definition.getLocale()); - } - else if (SoapFaultDefinition.CLIENT.equals(definition.getFaultCode()) || - SoapFaultDefinition.SENDER.equals(definition.getFaultCode())) { - fault = soapBody.addClientOrSenderFault(faultStringOrReason, definition.getLocale()); - } - else { - if (soapBody instanceof Soap11Body) { - Soap11Body soap11Body = (Soap11Body) soapBody; - fault = soap11Body.addFault(definition.getFaultCode(), faultStringOrReason, definition.getLocale()); - } - else if (soapBody instanceof Soap12Body) { - Soap12Body soap12Body = (Soap12Body) soapBody; - Soap12Fault soap12Fault = soap12Body.addServerOrReceiverFault(faultStringOrReason, definition - .getLocale()); - soap12Fault.addFaultSubcode(definition.getFaultCode()); - fault = soap12Fault; - } - else { - throw new IllegalStateException("This class only supports SOAP 1.1 and SOAP 1.2."); - } - } - if (fault != null) { - customizeFault(endpoint, ex, fault); - } - return true; - } + if (SoapFaultDefinition.SERVER.equals(definition.getFaultCode()) || + SoapFaultDefinition.RECEIVER.equals(definition.getFaultCode())) { + fault = soapBody.addServerOrReceiverFault(faultStringOrReason, definition.getLocale()); + } + else if (SoapFaultDefinition.CLIENT.equals(definition.getFaultCode()) || + SoapFaultDefinition.SENDER.equals(definition.getFaultCode())) { + fault = soapBody.addClientOrSenderFault(faultStringOrReason, definition.getLocale()); + } + else { + if (soapBody instanceof Soap11Body) { + Soap11Body soap11Body = (Soap11Body) soapBody; + fault = soap11Body.addFault(definition.getFaultCode(), faultStringOrReason, definition.getLocale()); + } + else if (soapBody instanceof Soap12Body) { + Soap12Body soap12Body = (Soap12Body) soapBody; + Soap12Fault soap12Fault = soap12Body.addServerOrReceiverFault(faultStringOrReason, definition + .getLocale()); + soap12Fault.addFaultSubcode(definition.getFaultCode()); + fault = soap12Fault; + } + else { + throw new IllegalStateException("This class only supports SOAP 1.1 and SOAP 1.2."); + } + } + if (fault != null) { + customizeFault(endpoint, ex, fault); + } + return true; + } - /** - * Customize the {@link SoapFault} created by this resolver. Called for each created fault - * - *

The default implementation is empty. Can be overridden in subclasses to customize the properties of the fault, - * such as adding details, etc. - * - * @param endpoint the executed endpoint, or {@code null} if none chosen at the time of the exception - * @param ex the exception to be handled - * @param fault the created fault - */ - protected void customizeFault(Object endpoint, Exception ex, SoapFault fault) { - } + /** + * Customize the {@link SoapFault} created by this resolver. Called for each created fault + * + *

The default implementation is empty. Can be overridden in subclasses to customize the properties of the fault, + * such as adding details, etc. + * + * @param endpoint the executed endpoint, or {@code null} if none chosen at the time of the exception + * @param ex the exception to be handled + * @param fault the created fault + */ + protected void customizeFault(Object endpoint, Exception ex, SoapFault fault) { + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolver.java index 131345b9..12b4a719 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolver.java @@ -37,48 +37,48 @@ import org.springframework.ws.soap.SoapMessage; */ public class SimpleSoapExceptionResolver extends AbstractEndpointExceptionResolver { - private Locale locale = Locale.ENGLISH; + private Locale locale = Locale.ENGLISH; - /** - * Returns the locale for the faultstring or reason of the SOAP Fault. - * - *

Defaults to {@link Locale#ENGLISH}. - */ - public Locale getLocale() { - return locale; - } + /** + * Returns the locale for the faultstring or reason of the SOAP Fault. + * + *

Defaults to {@link Locale#ENGLISH}. + */ + public Locale getLocale() { + return locale; + } - /** - * Sets the locale for the faultstring or reason of the SOAP Fault. - * - *

Defaults to {@link Locale#ENGLISH}. - */ - public void setLocale(Locale locale) { - Assert.notNull(locale, "locale must not be null"); - this.locale = locale; - } + /** + * Sets the locale for the faultstring or reason of the SOAP Fault. + * + *

Defaults to {@link Locale#ENGLISH}. + */ + public void setLocale(Locale locale) { + Assert.notNull(locale, "locale must not be null"); + this.locale = locale; + } - @Override - protected final boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) { - Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(), - "SimpleSoapExceptionResolver requires a SoapMessage"); - SoapMessage response = (SoapMessage) messageContext.getResponse(); - String faultString = StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : ex.toString(); - SoapBody body = response.getSoapBody(); - SoapFault fault = body.addServerOrReceiverFault(faultString, getLocale()); - customizeFault(messageContext, endpoint, ex, fault); - return true; - } + @Override + protected final boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) { + Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(), + "SimpleSoapExceptionResolver requires a SoapMessage"); + SoapMessage response = (SoapMessage) messageContext.getResponse(); + String faultString = StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : ex.toString(); + SoapBody body = response.getSoapBody(); + SoapFault fault = body.addServerOrReceiverFault(faultString, getLocale()); + customizeFault(messageContext, endpoint, ex, fault); + return true; + } - /** - * Empty template method to allow subclasses an opportunity to customize the given {@link SoapFault}. Called from - * {@link #resolveExceptionInternal(MessageContext,Object,Exception)}. - * - * @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 - * @param fault the SOAP fault to be customized. - */ - protected void customizeFault(MessageContext messageContext, Object endpoint, Exception ex, SoapFault fault) { - } + /** + * Empty template method to allow subclasses an opportunity to customize the given {@link SoapFault}. Called from + * {@link #resolveExceptionInternal(MessageContext,Object,Exception)}. + * + * @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 + * @param fault the SOAP fault to be customized. + */ + protected void customizeFault(MessageContext messageContext, Object endpoint, Exception ex, SoapFault fault) { + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolver.java index 736bbb7e..d1aa5290 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolver.java @@ -31,23 +31,23 @@ import org.springframework.ws.soap.server.endpoint.annotation.SoapFault; */ public class SoapFaultAnnotationExceptionResolver extends AbstractSoapFaultDefinitionExceptionResolver { - @Override - protected final SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex) { - SoapFault faultAnnotation = ex.getClass().getAnnotation(SoapFault.class); - if (faultAnnotation != null) { - SoapFaultDefinition definition = new SoapFaultDefinition(); - if (faultAnnotation.faultCode() != FaultCode.CUSTOM) { - definition.setFaultCode(faultAnnotation.faultCode().value()); - } - else if (StringUtils.hasLength(faultAnnotation.customFaultCode())) { - definition.setFaultCode(QName.valueOf(faultAnnotation.customFaultCode())); - } - definition.setFaultStringOrReason(faultAnnotation.faultStringOrReason()); - definition.setLocale(StringUtils.parseLocaleString(faultAnnotation.locale())); - return definition; - } - else { - return null; - } - } + @Override + protected final SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex) { + SoapFault faultAnnotation = ex.getClass().getAnnotation(SoapFault.class); + if (faultAnnotation != null) { + SoapFaultDefinition definition = new SoapFaultDefinition(); + if (faultAnnotation.faultCode() != FaultCode.CUSTOM) { + definition.setFaultCode(faultAnnotation.faultCode().value()); + } + else if (StringUtils.hasLength(faultAnnotation.customFaultCode())) { + definition.setFaultCode(QName.valueOf(faultAnnotation.customFaultCode())); + } + definition.setFaultStringOrReason(faultAnnotation.faultStringOrReason()); + definition.setLocale(StringUtils.parseLocaleString(faultAnnotation.locale())); + return definition; + } + else { + return null; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinition.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinition.java index 58915201..802afe24 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinition.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinition.java @@ -30,75 +30,75 @@ import javax.xml.namespace.QName; */ public class SoapFaultDefinition { - /** - * Constant {@code QName} used to indicate that a {@code Client} fault must be created. - * - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String,java.util.Locale) - */ - public static final QName CLIENT = new QName("CLIENT"); + /** + * Constant {@code QName} used to indicate that a {@code Client} fault must be created. + * + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String,java.util.Locale) + */ + public static final QName CLIENT = new QName("CLIENT"); - /** - * Constant {@code QName} used to indicate that a {@code Receiver} fault must be created. - * - * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String,java.util.Locale) - */ - public static final QName RECEIVER = new QName("RECEIVER"); + /** + * Constant {@code QName} used to indicate that a {@code Receiver} fault must be created. + * + * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String,java.util.Locale) + */ + public static final QName RECEIVER = new QName("RECEIVER"); - /** - * Constant {@code QName} used to indicate that a {@code Sender} fault must be created. - * - * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String,java.util.Locale) - */ - public static final QName SENDER = new QName("SENDER"); + /** + * Constant {@code QName} used to indicate that a {@code Sender} fault must be created. + * + * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String,java.util.Locale) + */ + public static final QName SENDER = new QName("SENDER"); - /** - * Constant {@code QName} used to indicate that a {@code Server} fault must be created. - * - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String,java.util.Locale) - */ - public static final QName SERVER = new QName("SERVER"); + /** + * Constant {@code QName} used to indicate that a {@code Server} fault must be created. + * + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String,java.util.Locale) + */ + public static final QName SERVER = new QName("SERVER"); - private QName faultCode; + private QName faultCode; - private String faultStringOrReason; + private String faultStringOrReason; - private Locale locale = Locale.ENGLISH; + private Locale locale = Locale.ENGLISH; - /** Returns the fault code. */ - public QName getFaultCode() { - return faultCode; - } + /** Returns the fault code. */ + public QName getFaultCode() { + return faultCode; + } - /** Sets the fault code. */ - public void setFaultCode(QName faultCode) { - this.faultCode = faultCode; - } + /** Sets the fault code. */ + public void setFaultCode(QName faultCode) { + this.faultCode = faultCode; + } - /** Returns the fault string or reason text. By default, it is set to the exception message. */ - public String getFaultStringOrReason() { - return faultStringOrReason; - } + /** Returns the fault string or reason text. By default, it is set to the exception message. */ + public String getFaultStringOrReason() { + return faultStringOrReason; + } - /** Sets the fault string or reason text. By default, it is set to the exception message. */ - public void setFaultStringOrReason(String faultStringOrReason) { - this.faultStringOrReason = faultStringOrReason; - } + /** Sets the fault string or reason text. By default, it is set to the exception message. */ + public void setFaultStringOrReason(String faultStringOrReason) { + this.faultStringOrReason = faultStringOrReason; + } - /** - * Gets the fault string locale. By default, it is English. - * - * @see Locale#ENGLISH - */ - public Locale getLocale() { - return locale; - } + /** + * Gets the fault string locale. By default, it is English. + * + * @see Locale#ENGLISH + */ + public Locale getLocale() { + return locale; + } - /** - * Sets the fault string locale. By default, it is English. - * - * @see Locale#ENGLISH - */ - public void setLocale(Locale locale) { - this.locale = locale; - } + /** + * Sets the fault string locale. By default, it is English. + * + * @see Locale#ENGLISH + */ + public void setLocale(Locale locale) { + this.locale = locale; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditor.java index 6a100cfe..61cbfca7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditor.java @@ -63,37 +63,37 @@ import org.springframework.xml.namespace.QNameEditor; */ public class SoapFaultDefinitionEditor extends PropertyEditorSupport { - private static final int FAULT_CODE_INDEX = 0; + private static final int FAULT_CODE_INDEX = 0; - private static final int FAULT_STRING_INDEX = 1; + private static final int FAULT_STRING_INDEX = 1; - private static final int FAULT_STRING_LOCALE_INDEX = 2; + private static final int FAULT_STRING_LOCALE_INDEX = 2; - @Override - public void setAsText(String text) throws IllegalArgumentException { - if (!StringUtils.hasLength(text)) { - setValue(null); - } - else { - String[] tokens = StringUtils.commaDelimitedListToStringArray(text); - if (tokens.length < FAULT_STRING_INDEX) { - throw new IllegalArgumentException("Invalid amount of comma delimited values in [" + text + - "]: SoapFaultDefinitionEditor requires at least 1"); - } - SoapFaultDefinition definition = new SoapFaultDefinition(); - QNameEditor qNameEditor = new QNameEditor(); - qNameEditor.setAsText(tokens[FAULT_CODE_INDEX].trim()); - definition.setFaultCode((QName) qNameEditor.getValue()); - if (tokens.length > 1) { - definition.setFaultStringOrReason(tokens[FAULT_STRING_INDEX].trim()); - if (tokens.length > 2) { - LocaleEditor localeEditor = new LocaleEditor(); - localeEditor.setAsText(tokens[FAULT_STRING_LOCALE_INDEX].trim()); - definition.setLocale((Locale) localeEditor.getValue()); - } - } - setValue(definition); - } - } + @Override + public void setAsText(String text) throws IllegalArgumentException { + if (!StringUtils.hasLength(text)) { + setValue(null); + } + else { + String[] tokens = StringUtils.commaDelimitedListToStringArray(text); + if (tokens.length < FAULT_STRING_INDEX) { + throw new IllegalArgumentException("Invalid amount of comma delimited values in [" + text + + "]: SoapFaultDefinitionEditor requires at least 1"); + } + SoapFaultDefinition definition = new SoapFaultDefinition(); + QNameEditor qNameEditor = new QNameEditor(); + qNameEditor.setAsText(tokens[FAULT_CODE_INDEX].trim()); + definition.setFaultCode((QName) qNameEditor.getValue()); + if (tokens.length > 1) { + definition.setFaultStringOrReason(tokens[FAULT_STRING_INDEX].trim()); + if (tokens.length > 2) { + LocaleEditor localeEditor = new LocaleEditor(); + localeEditor.setAsText(tokens[FAULT_STRING_LOCALE_INDEX].trim()); + definition.setLocale((Locale) localeEditor.getValue()); + } + } + setValue(definition); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolver.java index 2c3949c2..27d49cb3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolver.java @@ -31,69 +31,69 @@ import org.springframework.util.CollectionUtils; */ public class SoapFaultMappingExceptionResolver extends AbstractSoapFaultDefinitionExceptionResolver { - private Map exceptionMappings = new LinkedHashMap(); + private Map exceptionMappings = new LinkedHashMap(); - /** - * Set the mappings between exception class names and SOAP Faults. The exception class name can be a substring, with - * no wildcard support at present. - * - *

The values of the given properties object should use the format described in - * {@code SoapFaultDefinitionEditor}. - * - *

Follows the same matching algorithm as {@code SimpleMappingExceptionResolver}. - * - * @param mappings exception patterns (can also be fully qualified class names) as keys, fault definition texts as - * values - * @see SoapFaultDefinitionEditor - */ - public void setExceptionMappings(Properties mappings) { - for (Map.Entry entry : mappings.entrySet()) { - if (entry.getKey() instanceof String && entry.getValue() instanceof String) { - exceptionMappings.put((String)entry.getKey(), (String)entry.getValue()); - } - } - } + /** + * Set the mappings between exception class names and SOAP Faults. The exception class name can be a substring, with + * no wildcard support at present. + * + *

The values of the given properties object should use the format described in + * {@code SoapFaultDefinitionEditor}. + * + *

Follows the same matching algorithm as {@code SimpleMappingExceptionResolver}. + * + * @param mappings exception patterns (can also be fully qualified class names) as keys, fault definition texts as + * values + * @see SoapFaultDefinitionEditor + */ + public void setExceptionMappings(Properties mappings) { + for (Map.Entry entry : mappings.entrySet()) { + if (entry.getKey() instanceof String && entry.getValue() instanceof String) { + exceptionMappings.put((String)entry.getKey(), (String)entry.getValue()); + } + } + } - @Override - protected SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex) { - if (!CollectionUtils.isEmpty(exceptionMappings)) { - String definitionText = null; - int deepest = Integer.MAX_VALUE; - for (String exceptionMapping : exceptionMappings.keySet()) { - int depth = getDepth(exceptionMapping, ex); - if (depth >= 0 && depth < deepest) { - deepest = depth; - definitionText = exceptionMappings.get(exceptionMapping); - } - } - if (definitionText != null) { - SoapFaultDefinitionEditor editor = new SoapFaultDefinitionEditor(); - editor.setAsText(definitionText); - return (SoapFaultDefinition) editor.getValue(); - } - } - return null; - } + @Override + protected SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex) { + if (!CollectionUtils.isEmpty(exceptionMappings)) { + String definitionText = null; + int deepest = Integer.MAX_VALUE; + for (String exceptionMapping : exceptionMappings.keySet()) { + int depth = getDepth(exceptionMapping, ex); + if (depth >= 0 && depth < deepest) { + deepest = depth; + definitionText = exceptionMappings.get(exceptionMapping); + } + } + if (definitionText != null) { + SoapFaultDefinitionEditor editor = new SoapFaultDefinitionEditor(); + editor.setAsText(definitionText); + return (SoapFaultDefinition) editor.getValue(); + } + } + return null; + } - /** - * Return the depth to the superclass matching. {@code 0} means ex matches exactly. Returns {@code -1} if - * there's no match. Otherwise, returns depth. Lowest depth wins. - * - *

Follows the same algorithm as RollbackRuleAttribute, and SimpleMappingExceptionResolver - */ - protected int getDepth(String exceptionMapping, Exception ex) { - return getDepth(exceptionMapping, ex.getClass(), 0); - } + /** + * Return the depth to the superclass matching. {@code 0} means ex matches exactly. Returns {@code -1} if + * there's no match. Otherwise, returns depth. Lowest depth wins. + * + *

Follows the same algorithm as RollbackRuleAttribute, and SimpleMappingExceptionResolver + */ + protected int getDepth(String exceptionMapping, Exception ex) { + return getDepth(exceptionMapping, ex.getClass(), 0); + } - @SuppressWarnings("unchecked") - private int getDepth(String exceptionMapping, Class exceptionClass, int depth) { - if (exceptionClass.getName().indexOf(exceptionMapping) != -1) { - return depth; - } - if (exceptionClass.equals(Throwable.class)) { - return -1; - } - return getDepth(exceptionMapping, (Class) exceptionClass.getSuperclass(), depth + 1); - } + @SuppressWarnings("unchecked") + private int getDepth(String exceptionMapping, Class exceptionClass, int depth) { + if (exceptionClass.getName().indexOf(exceptionMapping) != -1) { + return depth; + } + if (exceptionClass.equals(Throwable.class)) { + return -1; + } + return getDepth(exceptionMapping, (Class) exceptionClass.getSuperclass(), depth + 1); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolver.java index 160b2950..cc3b8ca2 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolver.java @@ -52,80 +52,80 @@ import org.springframework.xml.namespace.QNameUtils; */ public class SoapHeaderElementMethodArgumentResolver implements MethodArgumentResolver { - @Override - public boolean supportsParameter(MethodParameter parameter) { - SoapHeader soapHeader = parameter.getParameterAnnotation(SoapHeader.class); - if (soapHeader == null) { - return false; - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + SoapHeader soapHeader = parameter.getParameterAnnotation(SoapHeader.class); + if (soapHeader == null) { + return false; + } - Class parameterType = parameter.getParameterType(); + Class parameterType = parameter.getParameterType(); - // Simple SoapHeaderElement parameter - if (SoapHeaderElement.class.equals(parameterType)) { - return true; - } + // Simple SoapHeaderElement parameter + if (SoapHeaderElement.class.equals(parameterType)) { + return true; + } - // List parameter - if (List.class.equals(parameterType)) { - Type genericType = parameter.getGenericParameterType(); - if (genericType instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) genericType; - Type[] typeArguments = parameterizedType.getActualTypeArguments(); - if (typeArguments.length == 1 && SoapHeaderElement.class.equals(typeArguments[0])) { - return true; - } - } - } - return false; - } + // List parameter + if (List.class.equals(parameterType)) { + Type genericType = parameter.getGenericParameterType(); + if (genericType instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) genericType; + Type[] typeArguments = parameterizedType.getActualTypeArguments(); + if (typeArguments.length == 1 && SoapHeaderElement.class.equals(typeArguments[0])) { + return true; + } + } + } + return false; + } - @Override - public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - SoapMessage request = (SoapMessage) messageContext.getRequest(); - org.springframework.ws.soap.SoapHeader soapHeader = request.getSoapHeader(); + @Override + public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + SoapMessage request = (SoapMessage) messageContext.getRequest(); + org.springframework.ws.soap.SoapHeader soapHeader = request.getSoapHeader(); - String paramValue = parameter.getParameterAnnotation(SoapHeader.class).value(); + String paramValue = parameter.getParameterAnnotation(SoapHeader.class).value(); - Assert.isTrue(QNameUtils.validateQName(paramValue), "Invalid header qualified name [" + paramValue + "]. " + - "QName must be of the form '{namespace}localPart'."); + Assert.isTrue(QNameUtils.validateQName(paramValue), "Invalid header qualified name [" + paramValue + "]. " + + "QName must be of the form '{namespace}localPart'."); - QName qname = QName.valueOf(paramValue); + QName qname = QName.valueOf(paramValue); - Class parameterType = parameter.getParameterType(); + Class parameterType = parameter.getParameterType(); - if (SoapHeaderElement.class.equals(parameterType)) { - return extractSoapHeader(qname, soapHeader); - } - else if (List.class.equals(parameterType)) { - return extractSoapHeaderList(qname, soapHeader); - } - // should not happen - throw new UnsupportedOperationException(); - } + if (SoapHeaderElement.class.equals(parameterType)) { + return extractSoapHeader(qname, soapHeader); + } + else if (List.class.equals(parameterType)) { + return extractSoapHeaderList(qname, soapHeader); + } + // should not happen + throw new UnsupportedOperationException(); + } - private SoapHeaderElement extractSoapHeader(QName qname, org.springframework.ws.soap.SoapHeader soapHeader) { - Iterator elements = soapHeader.examineAllHeaderElements(); - while (elements.hasNext()) { - SoapHeaderElement e = elements.next(); - if (e.getName().equals(qname)) { - return e; - } - } - return null; - } + private SoapHeaderElement extractSoapHeader(QName qname, org.springframework.ws.soap.SoapHeader soapHeader) { + Iterator elements = soapHeader.examineAllHeaderElements(); + while (elements.hasNext()) { + SoapHeaderElement e = elements.next(); + if (e.getName().equals(qname)) { + return e; + } + } + return null; + } - private List extractSoapHeaderList(QName qname, - org.springframework.ws.soap.SoapHeader soapHeader) { - List result = new ArrayList(); - Iterator elements = soapHeader.examineAllHeaderElements(); - while (elements.hasNext()) { - SoapHeaderElement e = elements.next(); - if (e.getName().equals(qname)) { - result.add(e); - } - } - return result; - } + private List extractSoapHeaderList(QName qname, + org.springframework.ws.soap.SoapHeader soapHeader) { + List result = new ArrayList(); + Iterator elements = soapHeader.examineAllHeaderElements(); + while (elements.hasNext()) { + SoapHeaderElement e = elements.next(); + if (e.getName().equals(qname)) { + result.add(e); + } + } + return result; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolver.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolver.java index a65f6996..1d5ffa13 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolver.java @@ -34,33 +34,33 @@ import org.springframework.ws.soap.SoapMessage; */ public class SoapMethodArgumentResolver implements MethodArgumentResolver { - @Override - public boolean supportsParameter(MethodParameter parameter) { - Class parameterType = parameter.getParameterType(); - return SoapMessage.class.equals(parameterType) || SoapBody.class.equals(parameterType) || - SoapEnvelope.class.equals(parameterType) || SoapHeader.class.equals(parameterType); - } + @Override + public boolean supportsParameter(MethodParameter parameter) { + Class parameterType = parameter.getParameterType(); + return SoapMessage.class.equals(parameterType) || SoapBody.class.equals(parameterType) || + SoapEnvelope.class.equals(parameterType) || SoapHeader.class.equals(parameterType); + } - @Override - public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - SoapMessage request = (SoapMessage) messageContext.getRequest(); + @Override + public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + SoapMessage request = (SoapMessage) messageContext.getRequest(); - Class parameterType = parameter.getParameterType(); + Class parameterType = parameter.getParameterType(); - if (SoapMessage.class.equals(parameterType)) { - return request; - } - else if (SoapBody.class.equals(parameterType)) { - return request.getSoapBody(); - } - else if (SoapEnvelope.class.equals(parameterType)) { - return request.getEnvelope(); - } - else if (SoapHeader.class.equals(parameterType)) { - return request.getSoapHeader(); - } - // should not happen - throw new UnsupportedOperationException(); - } + if (SoapMessage.class.equals(parameterType)) { + return request; + } + else if (SoapBody.class.equals(parameterType)) { + return request.getSoapBody(); + } + else if (SoapEnvelope.class.equals(parameterType)) { + return request.getEnvelope(); + } + else if (SoapHeader.class.equals(parameterType)) { + return request.getSoapHeader(); + } + // should not happen + throw new UnsupportedOperationException(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/FaultCode.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/FaultCode.java index b7c83297..ca684d8e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/FaultCode.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/FaultCode.java @@ -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, @@ -29,54 +29,54 @@ import org.springframework.ws.soap.soap11.Soap11Body; */ public enum FaultCode { - /** - * Constant used to indicate that a fault must be created with a custom fault code. When this value is used, the - * {@code customFaultCode} string property must be used on {@link SoapFault}. - * - *

Note that custom Fault Codes are only supported on SOAP 1.1. - * - * @see SoapFault#customFaultCode() - * @see Soap11Body#addFault(javax.xml.namespace.QName,String,java.util.Locale) - */ - CUSTOM(new QName("CUSTOM")), + /** + * Constant used to indicate that a fault must be created with a custom fault code. When this value is used, the + * {@code customFaultCode} string property must be used on {@link SoapFault}. + * + *

Note that custom Fault Codes are only supported on SOAP 1.1. + * + * @see SoapFault#customFaultCode() + * @see Soap11Body#addFault(javax.xml.namespace.QName,String,java.util.Locale) + */ + CUSTOM(new QName("CUSTOM")), - /** - * Constant used to indicate that a {@code Client} fault must be created. - * - * @see SoapBody#addClientOrSenderFault(String,java.util.Locale) - */ - CLIENT(new QName("CLIENT")), + /** + * Constant used to indicate that a {@code Client} fault must be created. + * + * @see SoapBody#addClientOrSenderFault(String,java.util.Locale) + */ + CLIENT(new QName("CLIENT")), - /** - * Constant {@code QName} used to indicate that a {@code Receiver} fault must be created. - * - * @see SoapBody#addServerOrReceiverFault(String,java.util.Locale) - */ - RECEIVER(new QName("RECEIVER")), + /** + * Constant {@code QName} used to indicate that a {@code Receiver} fault must be created. + * + * @see SoapBody#addServerOrReceiverFault(String,java.util.Locale) + */ + RECEIVER(new QName("RECEIVER")), - /** - * Constant {@code QName} used to indicate that a {@code Sender} fault must be created. - * - * @see SoapBody#addServerOrReceiverFault(String,java.util.Locale) - */ - SENDER(new QName("SENDER")), + /** + * Constant {@code QName} used to indicate that a {@code Sender} fault must be created. + * + * @see SoapBody#addServerOrReceiverFault(String,java.util.Locale) + */ + SENDER(new QName("SENDER")), - /** - * Constant {@code QName} used to indicate that a {@code Server} fault must be created. - * - * @see SoapBody#addClientOrSenderFault(String,java.util.Locale) - */ - SERVER(new QName("SERVER")); + /** + * Constant {@code QName} used to indicate that a {@code Server} fault must be created. + * + * @see SoapBody#addClientOrSenderFault(String,java.util.Locale) + */ + SERVER(new QName("SERVER")); - private final QName value; + private final QName value; - private FaultCode(QName value) { - this.value = value; - } + private FaultCode(QName value) { + this.value = value; + } - public QName value() { - return value; - } + public QName value() { + return value; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapAction.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapAction.java index 9b5cbf44..901380df 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapAction.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapAction.java @@ -37,7 +37,7 @@ import java.lang.annotation.Target; @Repeatable(SoapActions.class) public @interface SoapAction { - /** Signifies the value for the request {@code SOAPAction} header that is handled by the method. */ - String value(); + /** Signifies the value for the request {@code SOAPAction} header that is handled by the method. */ + String value(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapFault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapFault.java index e236529c..79b006a0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapFault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapFault.java @@ -37,24 +37,24 @@ import javax.xml.namespace.QName; @Inherited public @interface SoapFault { - /** The fault code. */ - FaultCode faultCode(); + /** The fault code. */ + FaultCode faultCode(); - /** - * The custom fault code, to be used if {@link #faultCode()} is set to {@link FaultCode#CUSTOM}. - * - *

The format used is that of {@link QName#toString()}, i.e. "{" + Namespace URI + "}" + local part, where the - * namespace is optional. - * - *

Note that custom Fault Codes are only supported on SOAP 1.1. - */ - String customFaultCode() default ""; + /** + * The custom fault code, to be used if {@link #faultCode()} is set to {@link FaultCode#CUSTOM}. + * + *

The format used is that of {@link QName#toString()}, i.e. "{" + Namespace URI + "}" + local part, where the + * namespace is optional. + * + *

Note that custom Fault Codes are only supported on SOAP 1.1. + */ + String customFaultCode() default ""; - /** The fault string or reason text. By default, it is set to the exception message. */ - String faultStringOrReason() default ""; + /** The fault string or reason text. By default, it is set to the exception message. */ + String faultStringOrReason() default ""; - /** The fault string locale. By default, it is English. */ - String locale() default "en"; + /** The fault string locale. By default, it is English. */ + String locale() default "en"; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapHeader.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapHeader.java index 14e108c8..f544aa86 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapHeader.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/annotation/SoapHeader.java @@ -32,9 +32,9 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SoapHeader { - /** - * The qualified name of the soap header. The format used is that of {@link javax.xml.namespace.QName#toString()}, i.e. - * "{" + Namespace URI + "}" + local part, where the namespace is optional. - */ - String value(); + /** + * The qualified name of the soap header. The format used is that of {@link javax.xml.namespace.QName#toString()}, i.e. + * "{" + Namespace URI + "}" + local part, where the namespace is optional. + */ + String value(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/AbstractFaultCreatingValidatingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/AbstractFaultCreatingValidatingInterceptor.java index 8862add7..20927ff1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/AbstractFaultCreatingValidatingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/AbstractFaultCreatingValidatingInterceptor.java @@ -33,7 +33,7 @@ import org.springframework.ws.soap.SoapMessage; /** * Subclass of {@code AbstractValidatingInterceptor} that creates a SOAP Fault whenever the request message cannot * be validated. The contents of the SOAP Fault can be specified by setting the {@code addValidationErrorDetail}, - * {@code faultStringOrReason}, or {@code detailElementName} properties. Further customizing can be + * {@code faultStringOrReason}, or {@code detailElementName} properties. Further customizing can be * accomplished by overriding {@code handleRequestValidationErrors}. * * @author Arjen Poutsma @@ -47,126 +47,126 @@ import org.springframework.ws.soap.SoapMessage; */ public abstract class AbstractFaultCreatingValidatingInterceptor extends AbstractValidatingInterceptor { - /** - * Default SOAP Fault Detail name used when a validation errors occur on the request. - * - * @see #setDetailElementName(javax.xml.namespace.QName) - */ - public static final QName DEFAULT_DETAIL_ELEMENT_NAME = - new QName("http://springframework.org/spring-ws", "ValidationError", - "spring-ws"); + /** + * Default SOAP Fault Detail name used when a validation errors occur on the request. + * + * @see #setDetailElementName(javax.xml.namespace.QName) + */ + public static final QName DEFAULT_DETAIL_ELEMENT_NAME = + new QName("http://springframework.org/spring-ws", "ValidationError", + "spring-ws"); /** - * Default SOAP Fault string used when a validation errors occur on the request. - * - * @see #setFaultStringOrReason(String) - */ - public static final String DEFAULT_FAULTSTRING_OR_REASON = "Validation error"; + * Default SOAP Fault string used when a validation errors occur on the request. + * + * @see #setFaultStringOrReason(String) + */ + public static final String DEFAULT_FAULTSTRING_OR_REASON = "Validation error"; - private boolean addValidationErrorDetail = true; + private boolean addValidationErrorDetail = true; - private QName detailElementName = DEFAULT_DETAIL_ELEMENT_NAME; + private QName detailElementName = DEFAULT_DETAIL_ELEMENT_NAME; - private String faultStringOrReason = DEFAULT_FAULTSTRING_OR_REASON; + private String faultStringOrReason = DEFAULT_FAULTSTRING_OR_REASON; - private Locale faultStringOrReasonLocale = Locale.ENGLISH; + private Locale faultStringOrReasonLocale = Locale.ENGLISH; - /** - * Returns whether a SOAP Fault detail element should be created when a validation error occurs. This detail element - * will contain the exact validation errors. It is only added when the underlying message is a - * {@code SoapMessage}. Defaults to {@code true}. - * - * @see org.springframework.ws.soap.SoapFault#addFaultDetail() - */ - public boolean getAddValidationErrorDetail() { - return addValidationErrorDetail; - } + /** + * Returns whether a SOAP Fault detail element should be created when a validation error occurs. This detail element + * will contain the exact validation errors. It is only added when the underlying message is a + * {@code SoapMessage}. Defaults to {@code true}. + * + * @see org.springframework.ws.soap.SoapFault#addFaultDetail() + */ + public boolean getAddValidationErrorDetail() { + return addValidationErrorDetail; + } - /** - * Indicates whether a SOAP Fault detail element should be created when a validation error occurs. This detail - * element will contain the exact validation errors. It is only added when the underlying message is a - * {@code SoapMessage}. Defaults to {@code true}. - * - * @see org.springframework.ws.soap.SoapFault#addFaultDetail() - */ - public void setAddValidationErrorDetail(boolean addValidationErrorDetail) { - this.addValidationErrorDetail = addValidationErrorDetail; - } + /** + * Indicates whether a SOAP Fault detail element should be created when a validation error occurs. This detail + * element will contain the exact validation errors. It is only added when the underlying message is a + * {@code SoapMessage}. Defaults to {@code true}. + * + * @see org.springframework.ws.soap.SoapFault#addFaultDetail() + */ + public void setAddValidationErrorDetail(boolean addValidationErrorDetail) { + this.addValidationErrorDetail = addValidationErrorDetail; + } - /** Returns the fault detail element name when validation errors occur on the request. */ - public QName getDetailElementName() { - return detailElementName; - } + /** Returns the fault detail element name when validation errors occur on the request. */ + public QName getDetailElementName() { + return detailElementName; + } - /** - * Sets the fault detail element name when validation errors occur on the request. Defaults to - * {@code DEFAULT_DETAIL_ELEMENT_NAME}. - * - * @see #DEFAULT_DETAIL_ELEMENT_NAME - */ - public void setDetailElementName(QName detailElementName) { - this.detailElementName = detailElementName; - } + /** + * Sets the fault detail element name when validation errors occur on the request. Defaults to + * {@code DEFAULT_DETAIL_ELEMENT_NAME}. + * + * @see #DEFAULT_DETAIL_ELEMENT_NAME + */ + public void setDetailElementName(QName detailElementName) { + this.detailElementName = detailElementName; + } - /** Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. */ - public String getFaultStringOrReason() { - return faultStringOrReason; - } + /** Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. */ + public String getFaultStringOrReason() { + return faultStringOrReason; + } - /** - * Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. - * It is only added when the underlying message is a {@code SoapMessage}. Defaults to - * {@code DEFAULT_FAULTSTRING_OR_REASON}. - * - * @see #DEFAULT_FAULTSTRING_OR_REASON - */ - public void setFaultStringOrReason(String faultStringOrReason) { - this.faultStringOrReason = faultStringOrReason; - } + /** + * Sets the SOAP {@code faultstring} or {@code Reason} used when validation errors occur on the request. + * It is only added when the underlying message is a {@code SoapMessage}. Defaults to + * {@code DEFAULT_FAULTSTRING_OR_REASON}. + * + * @see #DEFAULT_FAULTSTRING_OR_REASON + */ + public void setFaultStringOrReason(String faultStringOrReason) { + this.faultStringOrReason = faultStringOrReason; + } - /** Returns the SOAP fault reason locale used when validation errors occur on the request. */ - public Locale getFaultStringOrReasonLocale() { - return faultStringOrReasonLocale; - } + /** Returns the SOAP fault reason locale used when validation errors occur on the request. */ + public Locale getFaultStringOrReasonLocale() { + return faultStringOrReasonLocale; + } - /** - * Sets the SOAP fault reason locale used when validation errors occur on the request. It is only added when the - * underlying message is a {@code SoapMessage}. Defaults to English. - * - * @see java.util.Locale#ENGLISH - */ - public void setFaultStringOrReasonLocale(Locale faultStringOrReasonLocale) { - this.faultStringOrReasonLocale = faultStringOrReasonLocale; - } + /** + * Sets the SOAP fault reason locale used when validation errors occur on the request. It is only added when the + * underlying message is a {@code SoapMessage}. Defaults to English. + * + * @see java.util.Locale#ENGLISH + */ + public void setFaultStringOrReasonLocale(Locale faultStringOrReasonLocale) { + this.faultStringOrReasonLocale = faultStringOrReasonLocale; + } - /** - * Template method that is called when the request message contains validation errors. This implementation logs all - * errors, returns {@code false}, and creates a {@link SoapBody#addClientOrSenderFault(String,Locale) client or - * sender} {@link SoapFault}, adding a {@link SoapFaultDetail} with all errors if the - * {@code addValidationErrorDetail} property is {@code true}. - * - * @param messageContext the message context - * @param errors the validation errors - * @return {@code true} to continue processing the request, {@code false} (the default) otherwise - */ - @Override - protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) - throws TransformerException { - for (SAXParseException error : errors) { - logger.warn("XML validation error on request: " + error.getMessage()); - } - if (messageContext.getResponse() instanceof SoapMessage) { - SoapMessage response = (SoapMessage) messageContext.getResponse(); - SoapBody body = response.getSoapBody(); - SoapFault fault = body.addClientOrSenderFault(getFaultStringOrReason(), getFaultStringOrReasonLocale()); - if (getAddValidationErrorDetail()) { - SoapFaultDetail detail = fault.addFaultDetail(); - for (SAXParseException error : errors) { - SoapFaultDetailElement detailElement = detail.addFaultDetailElement(getDetailElementName()); - detailElement.addText(error.getMessage()); - } - } - } - return false; - } + /** + * Template method that is called when the request message contains validation errors. This implementation logs all + * errors, returns {@code false}, and creates a {@link SoapBody#addClientOrSenderFault(String,Locale) client or + * sender} {@link SoapFault}, adding a {@link SoapFaultDetail} with all errors if the + * {@code addValidationErrorDetail} property is {@code true}. + * + * @param messageContext the message context + * @param errors the validation errors + * @return {@code true} to continue processing the request, {@code false} (the default) otherwise + */ + @Override + protected boolean handleRequestValidationErrors(MessageContext messageContext, SAXParseException[] errors) + throws TransformerException { + for (SAXParseException error : errors) { + logger.warn("XML validation error on request: " + error.getMessage()); + } + if (messageContext.getResponse() instanceof SoapMessage) { + SoapMessage response = (SoapMessage) messageContext.getResponse(); + SoapBody body = response.getSoapBody(); + SoapFault fault = body.addClientOrSenderFault(getFaultStringOrReason(), getFaultStringOrReasonLocale()); + if (getAddValidationErrorDetail()) { + SoapFaultDetail detail = fault.addFaultDetail(); + for (SAXParseException error : errors) { + SoapFaultDetailElement detailElement = detail.addFaultDetailElement(getDetailElementName()); + detailElement.addText(error.getMessage()); + } + } + } + return false; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/DelegatingSmartSoapEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/DelegatingSmartSoapEndpointInterceptor.java index 742e5ed2..424124cf 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/DelegatingSmartSoapEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/DelegatingSmartSoapEndpointInterceptor.java @@ -30,25 +30,25 @@ import org.springframework.ws.soap.server.SoapEndpointInterceptor; * @since 2.0 */ public class DelegatingSmartSoapEndpointInterceptor extends DelegatingSmartEndpointInterceptor - implements SmartSoapEndpointInterceptor { + implements SmartSoapEndpointInterceptor { - /** - * Creates a new instance of the {@code DelegatingSmartSoapEndpointInterceptor} with the given delegate. - * - * @param delegate the endpoint interceptor to delegate to. - */ - public DelegatingSmartSoapEndpointInterceptor(EndpointInterceptor delegate) { - super(delegate); - } + /** + * Creates a new instance of the {@code DelegatingSmartSoapEndpointInterceptor} with the given delegate. + * + * @param delegate the endpoint interceptor to delegate to. + */ + public DelegatingSmartSoapEndpointInterceptor(EndpointInterceptor delegate) { + super(delegate); + } - @Override - public boolean understands(SoapHeaderElement header) { - EndpointInterceptor delegate = getDelegate(); - if (delegate instanceof SoapEndpointInterceptor) { - return ((SoapEndpointInterceptor) delegate).understands(header); - } - else { - return false; - } - } + @Override + public boolean understands(SoapHeaderElement header) { + EndpointInterceptor delegate = getDelegate(); + if (delegate instanceof SoapEndpointInterceptor) { + return ((SoapEndpointInterceptor) delegate).understands(header); + } + else { + return false; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptor.java index 7e6620f6..cdde3fb8 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptor.java @@ -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, @@ -36,37 +36,37 @@ import org.springframework.xml.transform.TransformerHelper; */ public class PayloadRootSmartSoapEndpointInterceptor extends DelegatingSmartSoapEndpointInterceptor { - private TransformerHelper transformerHelper = new TransformerHelper(); + private TransformerHelper transformerHelper = new TransformerHelper(); - private final String namespaceUri; + private final String namespaceUri; - private final String localPart; + private final String localPart; - public PayloadRootSmartSoapEndpointInterceptor(EndpointInterceptor delegate, - String namespaceUri, - String localPart) { - super(delegate); - Assert.hasLength(namespaceUri, "namespaceUri can not be empty"); - this.namespaceUri = namespaceUri; - this.localPart = localPart; - } + public PayloadRootSmartSoapEndpointInterceptor(EndpointInterceptor delegate, + String namespaceUri, + String localPart) { + super(delegate); + Assert.hasLength(namespaceUri, "namespaceUri can not be empty"); + this.namespaceUri = namespaceUri; + this.localPart = localPart; + } - public void setTransformerHelper(TransformerHelper transformerHelper) { - this.transformerHelper = transformerHelper; - } + public void setTransformerHelper(TransformerHelper transformerHelper) { + this.transformerHelper = transformerHelper; + } - @Override - protected boolean shouldIntercept(WebServiceMessage request, Object endpoint) { - try { - QName payloadRootName = PayloadRootUtils.getPayloadRootQName(request.getPayloadSource(), transformerHelper); - if (payloadRootName == null || !namespaceUri.equals(payloadRootName.getNamespaceURI())) { - return false; - } - return !StringUtils.hasLength(localPart) || localPart.equals(payloadRootName.getLocalPart()); + @Override + protected boolean shouldIntercept(WebServiceMessage request, Object endpoint) { + try { + QName payloadRootName = PayloadRootUtils.getPayloadRootQName(request.getPayloadSource(), transformerHelper); + if (payloadRootName == null || !namespaceUri.equals(payloadRootName.getNamespaceURI())) { + return false; + } + return !StringUtils.hasLength(localPart) || localPart.equals(payloadRootName.getLocalPart()); - } - catch (TransformerException e) { - return false; - } - } + } + catch (TransformerException e) { + return false; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptor.java index 2bdf1ac7..4deecf52 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptor.java @@ -41,15 +41,15 @@ import org.springframework.ws.WebServiceMessage; */ public class PayloadValidatingInterceptor extends AbstractFaultCreatingValidatingInterceptor { - /** Returns the payload source of the given message. */ - @Override - protected Source getValidationRequestSource(WebServiceMessage request) { - return request.getPayloadSource(); - } + /** Returns the payload source of the given message. */ + @Override + protected Source getValidationRequestSource(WebServiceMessage request) { + return request.getPayloadSource(); + } - /** Returns the payload source of the given message. */ - @Override - protected Source getValidationResponseSource(WebServiceMessage response) { - return response.getPayloadSource(); - } + /** Returns the payload source of the given message. */ + @Override + protected Source getValidationResponseSource(WebServiceMessage response) { + return response.getPayloadSource(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptor.java index 846d8871..3d9bb23f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptor.java @@ -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,26 +31,26 @@ import org.springframework.ws.soap.SoapMessage; */ public class SoapActionSmartEndpointInterceptor extends DelegatingSmartSoapEndpointInterceptor { - private final String soapAction; + private final String soapAction; - public SoapActionSmartEndpointInterceptor(EndpointInterceptor delegate, String soapAction) { - super(delegate); - Assert.hasLength(soapAction, "soapAction can not be empty"); - this.soapAction = soapAction; - } + public SoapActionSmartEndpointInterceptor(EndpointInterceptor delegate, String soapAction) { + super(delegate); + Assert.hasLength(soapAction, "soapAction can not be empty"); + this.soapAction = soapAction; + } - @Override - protected boolean shouldIntercept(WebServiceMessage request, Object endpoint) { - if (request instanceof SoapMessage) { - String soapAction = ((SoapMessage) request).getSoapAction(); - if (StringUtils.hasLength(soapAction) && soapAction.charAt(0) == '"' && - soapAction.charAt(soapAction.length() - 1) == '"') { - soapAction = soapAction.substring(1, soapAction.length() - 1); - } - return this.soapAction.equals(soapAction); - } - else { - return false; - } - } + @Override + protected boolean shouldIntercept(WebServiceMessage request, Object endpoint) { + if (request instanceof SoapMessage) { + String soapAction = ((SoapMessage) request).getSoapAction(); + if (StringUtils.hasLength(soapAction) && soapAction.charAt(0) == '"' && + soapAction.charAt(soapAction.length() - 1) == '"') { + soapAction = soapAction.substring(1, soapAction.length() - 1); + } + return this.soapAction.equals(soapAction); + } + else { + return false; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptor.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptor.java index 9aaeb85e..34771018 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptor.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptor.java @@ -38,34 +38,34 @@ import org.springframework.ws.soap.server.SoapEndpointInterceptor; */ public class SoapEnvelopeLoggingInterceptor extends AbstractLoggingInterceptor implements SoapEndpointInterceptor { - private boolean logFault = true; + private boolean logFault = true; - /** Indicates whether a SOAP Fault should be logged. Default is {@code true}. */ - public void setLogFault(boolean logFault) { - this.logFault = logFault; - } + /** Indicates whether a SOAP Fault should be logged. Default is {@code true}. */ + public void setLogFault(boolean logFault) { + this.logFault = logFault; + } - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - if (logFault && logger.isDebugEnabled()) { - logMessageSource("Fault: ", getSource(messageContext.getResponse())); - } - return true; - } + @Override + public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { + if (logFault && logger.isDebugEnabled()) { + logMessageSource("Fault: ", getSource(messageContext.getResponse())); + } + return true; + } - @Override - public boolean understands(SoapHeaderElement header) { - return false; - } + @Override + public boolean understands(SoapHeaderElement header) { + return false; + } - @Override - protected Source getSource(WebServiceMessage message) { - if (message instanceof SoapMessage) { - SoapMessage soapMessage = (SoapMessage) message; - return soapMessage.getEnvelope().getSource(); - } - else { - return null; - } - } + @Override + protected Source getSource(WebServiceMessage message) { + if (message instanceof SoapMessage) { + SoapMessage soapMessage = (SoapMessage) message; + return soapMessage.getEnvelope().getSource(); + } + else { + return null; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMapping.java index 3d4765d6..c40d9808 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMapping.java @@ -43,54 +43,54 @@ import org.springframework.ws.soap.server.SoapEndpointMapping; */ public class DelegatingSoapEndpointMapping implements InitializingBean, SoapEndpointMapping { - private EndpointMapping delegate; + private EndpointMapping delegate; - private String[] actorsOrRoles; + private String[] actorsOrRoles; - private boolean isUltimateReceiver = true; + private boolean isUltimateReceiver = true; - /** Sets the delegate {@code EndpointMapping} to resolve the endpoint with. */ - public void setDelegate(EndpointMapping delegate) { - this.delegate = delegate; - } + /** Sets the delegate {@code EndpointMapping} to resolve the endpoint with. */ + public void setDelegate(EndpointMapping delegate) { + this.delegate = delegate; + } - @Override - public final void setActorOrRole(String actorOrRole) { - Assert.notNull(actorOrRole, "actorOrRole must not be null"); - actorsOrRoles = new String[]{actorOrRole}; - } + @Override + public final void setActorOrRole(String actorOrRole) { + Assert.notNull(actorOrRole, "actorOrRole must not be null"); + actorsOrRoles = new String[]{actorOrRole}; + } - @Override - public final void setActorsOrRoles(String[] actorsOrRoles) { - Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); - this.actorsOrRoles = actorsOrRoles; - } + @Override + public final void setActorsOrRoles(String[] actorsOrRoles) { + Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); + this.actorsOrRoles = actorsOrRoles; + } - @Override - public final void setUltimateReceiver(boolean ultimateReceiver) { - isUltimateReceiver = ultimateReceiver; - } + @Override + public final void setUltimateReceiver(boolean ultimateReceiver) { + isUltimateReceiver = ultimateReceiver; + } - /** - * Creates a new {@code SoapEndpointInvocationChain} based on the delegate endpoint, the delegate interceptors, - * and set actors/roles. - * - * @see #setActorsOrRoles(String[]) - */ - @Override - public EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception { - EndpointInvocationChain delegateChain = delegate.getEndpoint(messageContext); - if (delegateChain != null) { - return new SoapEndpointInvocationChain(delegateChain.getEndpoint(), delegateChain.getInterceptors(), - actorsOrRoles, isUltimateReceiver); - } - else { - return null; - } - } + /** + * Creates a new {@code SoapEndpointInvocationChain} based on the delegate endpoint, the delegate interceptors, + * and set actors/roles. + * + * @see #setActorsOrRoles(String[]) + */ + @Override + public EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception { + EndpointInvocationChain delegateChain = delegate.getEndpoint(messageContext); + if (delegateChain != null) { + return new SoapEndpointInvocationChain(delegateChain.getEndpoint(), delegateChain.getInterceptors(), + actorsOrRoles, isUltimateReceiver); + } + else { + return null; + } + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(delegate, "delegate is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(delegate, "delegate is required"); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMapping.java index da87eeb2..fae1ea88 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMapping.java @@ -41,10 +41,10 @@ import org.springframework.ws.soap.server.endpoint.annotation.SoapActions; *

  * @Endpoint
  * public class MyEndpoint{
- *    @SoapAction("http://springframework.org/spring-ws/SoapAction")
- *    public Source doSomethingWithRequest() {
- *       ...
- *    }
+ *	  @SoapAction("http://springframework.org/spring-ws/SoapAction")
+ *	  public Source doSomethingWithRequest() {
+ *		 ...
+ *	  }
  * }
  * 
* @@ -52,69 +52,69 @@ import org.springframework.ws.soap.server.endpoint.annotation.SoapActions; * @since 1.0.0 */ public class SoapActionAnnotationMethodEndpointMapping extends AbstractAnnotationMethodEndpointMapping - implements SoapEndpointMapping { + implements SoapEndpointMapping { - private String[] actorsOrRoles; + private String[] actorsOrRoles; - private boolean isUltimateReceiver = true; + private boolean isUltimateReceiver = true; - @Override - public final void setActorOrRole(String actorOrRole) { - Assert.notNull(actorOrRole, "actorOrRole must not be null"); - actorsOrRoles = new String[]{actorOrRole}; - } + @Override + public final void setActorOrRole(String actorOrRole) { + Assert.notNull(actorOrRole, "actorOrRole must not be null"); + actorsOrRoles = new String[]{actorOrRole}; + } - @Override - public final void setActorsOrRoles(String[] actorsOrRoles) { - Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); - this.actorsOrRoles = actorsOrRoles; - } + @Override + public final void setActorsOrRoles(String[] actorsOrRoles) { + Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); + this.actorsOrRoles = actorsOrRoles; + } - @Override - public final void setUltimateReceiver(boolean ultimateReceiver) { - isUltimateReceiver = ultimateReceiver; - } + @Override + public final void setUltimateReceiver(boolean ultimateReceiver) { + isUltimateReceiver = ultimateReceiver; + } - /** - * Creates a new {@code SoapEndpointInvocationChain} based on the given endpoint, and the set interceptors, and - * actors/roles. - * - * @param endpoint the endpoint - * @param interceptors the endpoint interceptors - * @return the created invocation chain - * @see #setInterceptors(org.springframework.ws.server.EndpointInterceptor[]) - * @see #setActorsOrRoles(String[]) - */ - @Override - protected final EndpointInvocationChain createEndpointInvocationChain(MessageContext messageContext, - Object endpoint, - EndpointInterceptor[] interceptors) { - return new SoapEndpointInvocationChain(endpoint, interceptors, actorsOrRoles, isUltimateReceiver); - } + /** + * Creates a new {@code SoapEndpointInvocationChain} based on the given endpoint, and the set interceptors, and + * actors/roles. + * + * @param endpoint the endpoint + * @param interceptors the endpoint interceptors + * @return the created invocation chain + * @see #setInterceptors(org.springframework.ws.server.EndpointInterceptor[]) + * @see #setActorsOrRoles(String[]) + */ + @Override + protected final EndpointInvocationChain createEndpointInvocationChain(MessageContext messageContext, + Object endpoint, + EndpointInterceptor[] interceptors) { + return new SoapEndpointInvocationChain(endpoint, interceptors, actorsOrRoles, isUltimateReceiver); + } - @Override - protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { - if (messageContext.getRequest() instanceof SoapMessage) { - SoapMessage request = (SoapMessage) messageContext.getRequest(); - String soapAction = request.getSoapAction(); - if (StringUtils.hasLength(soapAction) && soapAction.charAt(0) == '"' && - soapAction.charAt(soapAction.length() - 1) == '"') { - return soapAction.substring(1, soapAction.length() - 1); - } - else { - return soapAction; - } - } - else { - return null; - } - } + @Override + protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { + if (messageContext.getRequest() instanceof SoapMessage) { + SoapMessage request = (SoapMessage) messageContext.getRequest(); + String soapAction = request.getSoapAction(); + if (StringUtils.hasLength(soapAction) && soapAction.charAt(0) == '"' && + soapAction.charAt(soapAction.length() - 1) == '"') { + return soapAction.substring(1, soapAction.length() - 1); + } + else { + return soapAction; + } + } + else { + return null; + } + } - @Override - protected String getLookupKeyForMethod(Method method) { - SoapAction soapAction = AnnotationUtils.findAnnotation(method, SoapAction.class); - return soapAction != null ? soapAction.value() : null; - } + @Override + protected String getLookupKeyForMethod(Method method) { + SoapAction soapAction = AnnotationUtils.findAnnotation(method, SoapAction.class); + return soapAction != null ? soapAction.value() : null; + } @Override protected List getLookupKeysForMethod(Method method) { diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMapping.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMapping.java index 84a5bf3c..88db7a2c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMapping.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMapping.java @@ -54,64 +54,64 @@ import org.springframework.ws.soap.server.SoapEndpointMapping; @Deprecated public class SoapActionEndpointMapping extends AbstractMapBasedEndpointMapping implements SoapEndpointMapping { - private String[] actorsOrRoles; + private String[] actorsOrRoles; - private boolean isUltimateReceiver = true; + private boolean isUltimateReceiver = true; - @Override - public final void setActorOrRole(String actorOrRole) { - Assert.notNull(actorOrRole, "actorOrRole must not be null"); - actorsOrRoles = new String[]{actorOrRole}; - } + @Override + public final void setActorOrRole(String actorOrRole) { + Assert.notNull(actorOrRole, "actorOrRole must not be null"); + actorsOrRoles = new String[]{actorOrRole}; + } - @Override - public final void setActorsOrRoles(String[] actorsOrRoles) { - Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); - this.actorsOrRoles = actorsOrRoles; - } + @Override + public final void setActorsOrRoles(String[] actorsOrRoles) { + Assert.notEmpty(actorsOrRoles, "actorsOrRoles must not be empty"); + this.actorsOrRoles = actorsOrRoles; + } - @Override - public final void setUltimateReceiver(boolean ultimateReceiver) { - isUltimateReceiver = ultimateReceiver; - } + @Override + public final void setUltimateReceiver(boolean ultimateReceiver) { + isUltimateReceiver = ultimateReceiver; + } - /** - * Creates a new {@code SoapEndpointInvocationChain} based on the given endpoint, and the set interceptors, and - * actors/roles. - * - * @param endpoint the endpoint - * @param interceptors the endpoint interceptors - * @return the created invocation chain - * @see #setInterceptors(org.springframework.ws.server.EndpointInterceptor[]) - * @see #setActorsOrRoles(String[]) - */ - @Override - protected final EndpointInvocationChain createEndpointInvocationChain(MessageContext messageContext, - Object endpoint, - EndpointInterceptor[] interceptors) { - return new SoapEndpointInvocationChain(endpoint, interceptors, actorsOrRoles, isUltimateReceiver); - } + /** + * Creates a new {@code SoapEndpointInvocationChain} based on the given endpoint, and the set interceptors, and + * actors/roles. + * + * @param endpoint the endpoint + * @param interceptors the endpoint interceptors + * @return the created invocation chain + * @see #setInterceptors(org.springframework.ws.server.EndpointInterceptor[]) + * @see #setActorsOrRoles(String[]) + */ + @Override + protected final EndpointInvocationChain createEndpointInvocationChain(MessageContext messageContext, + Object endpoint, + EndpointInterceptor[] interceptors) { + return new SoapEndpointInvocationChain(endpoint, interceptors, actorsOrRoles, isUltimateReceiver); + } - @Override - protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { - if (messageContext.getRequest() instanceof SoapMessage) { - SoapMessage request = (SoapMessage) messageContext.getRequest(); - String soapAction = request.getSoapAction(); - if (StringUtils.hasLength(soapAction) && soapAction.charAt(0) == '"' && - soapAction.charAt(soapAction.length() - 1) == '"') { - return soapAction.substring(1, soapAction.length() - 1); - } - else { - return soapAction; - } - } - else { - return null; - } - } + @Override + protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { + if (messageContext.getRequest() instanceof SoapMessage) { + SoapMessage request = (SoapMessage) messageContext.getRequest(); + String soapAction = request.getSoapAction(); + if (StringUtils.hasLength(soapAction) && soapAction.charAt(0) == '"' && + soapAction.charAt(soapAction.length() - 1) == '"') { + return soapAction.substring(1, soapAction.length() - 1); + } + else { + return soapAction; + } + } + else { + return null; + } + } - @Override - protected boolean validateLookupKey(String key) { - return StringUtils.hasLength(key); - } + @Override + protected boolean validateLookupKey(String key) { + return StringUtils.hasLength(key); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Body.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Body.java index 157283dc..43f7bf3c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Body.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Body.java @@ -32,30 +32,30 @@ import org.springframework.ws.soap.SoapFaultException; */ public interface Soap11Body extends SoapBody { - /** - * Adds a SOAP 1.1 Fault to the body with a localized message. Adding a fault removes the - * current content of the body. - * - * @param faultCode the fully qualified fault faultCode - * @param faultString the faultString - * @param faultStringLocale the faultString locale. May be {@code null} - * @return the added Soap11Fault - * @throws IllegalArgumentException if the fault faultCode is not fully qualified - */ - Soap11Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) throws SoapFaultException; + /** + * Adds a SOAP 1.1 Fault to the body with a localized message. Adding a fault removes the + * current content of the body. + * + * @param faultCode the fully qualified fault faultCode + * @param faultString the faultString + * @param faultStringLocale the faultString locale. May be {@code null} + * @return the added Soap11Fault + * @throws IllegalArgumentException if the fault faultCode is not fully qualified + */ + Soap11Fault addFault(QName faultCode, String faultString, Locale faultStringLocale) throws SoapFaultException; - @Override - Soap11Fault getFault(); + @Override + Soap11Fault getFault(); - @Override - Soap11Fault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap11Fault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - @Override - Soap11Fault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap11Fault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - @Override - Soap11Fault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap11Fault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - @Override - Soap11Fault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap11Fault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Fault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Fault.java index 1f06d44c..901ec0f3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Fault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Fault.java @@ -29,7 +29,7 @@ import org.springframework.ws.soap.SoapFault; */ public interface Soap11Fault extends SoapFault { - /** Returns the locale of the fault string. */ - Locale getFaultStringLocale(); + /** Returns the locale of the fault string. */ + Locale getFaultStringLocale(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Header.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Header.java index 99bbbf82..92636006 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Header.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap11/Soap11Header.java @@ -30,16 +30,16 @@ import org.springframework.ws.soap.SoapHeaderException; */ public interface Soap11Header extends SoapHeader { - /** - * Returns an {@code Iterator} over all the {@link SoapHeaderElement header elements} that should be processed - * for the given actors. Headers target to the "next" actor or role will always be included. - * - * @param actors an array of actors to search for - * @return an iterator over all the header elements that contain the specified actors - * @throws SoapHeaderException if the headers cannot be returned - * @see SoapHeaderElement - */ - Iterator examineHeaderElementsToProcess(String[] actors) throws SoapHeaderException; + /** + * Returns an {@code Iterator} over all the {@link SoapHeaderElement header elements} that should be processed + * for the given actors. Headers target to the "next" actor or role will always be included. + * + * @param actors an array of actors to search for + * @return an iterator over all the header elements that contain the specified actors + * @throws SoapHeaderException if the headers cannot be returned + * @see SoapHeaderElement + */ + Iterator examineHeaderElementsToProcess(String[] actors) throws SoapHeaderException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Body.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Body.java index ced6225b..f7879408 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Body.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Body.java @@ -31,31 +31,31 @@ import org.springframework.ws.soap.SoapFaultException; */ public interface Soap12Body extends SoapBody { - /** - * Adds a {@code DataEncodingUnknown} fault to the body. - * - *

Adding a fault removes the current content of the body. - * - * @param subcodes the optional fully qualified fault subcodes - * @param reason the fault reason - * @param locale the language of the fault reason - * @return the created {@code SoapFault} - */ - Soap12Fault addDataEncodingUnknownFault(QName[] subcodes, String reason, Locale locale) throws SoapFaultException; - - @Override - Soap12Fault getFault(); + /** + * Adds a {@code DataEncodingUnknown} fault to the body. + * + *

Adding a fault removes the current content of the body. + * + * @param subcodes the optional fully qualified fault subcodes + * @param reason the fault reason + * @param locale the language of the fault reason + * @return the created {@code SoapFault} + */ + Soap12Fault addDataEncodingUnknownFault(QName[] subcodes, String reason, Locale locale) throws SoapFaultException; + + @Override + Soap12Fault getFault(); - @Override - Soap12Fault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap12Fault addMustUnderstandFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - @Override - Soap12Fault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap12Fault addClientOrSenderFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - @Override - Soap12Fault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + @Override + Soap12Fault addServerOrReceiverFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - @Override - Soap12Fault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException; - + @Override + Soap12Fault addVersionMismatchFault(String faultStringOrReason, Locale locale) throws SoapFaultException; + } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Fault.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Fault.java index a656f12e..5bdadff0 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Fault.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Fault.java @@ -31,30 +31,30 @@ import org.springframework.ws.soap.SoapFault; */ public interface Soap12Fault extends SoapFault { - /** - * Returns an iteration over the fault subcodes. The subcodes are returned in order: from top to bottom. - * - * @return an Iterator that contains {@code QNames} representing the fault subcodes - */ - Iterator getFaultSubcodes(); + /** + * Returns an iteration over the fault subcodes. The subcodes are returned in order: from top to bottom. + * + * @return an Iterator that contains {@code QNames} representing the fault subcodes + */ + Iterator getFaultSubcodes(); - /** - * Adds a fault subcode this fault. - * - * @param subcode the qualified name of the subcode - */ - void addFaultSubcode(QName subcode); + /** + * Adds a fault subcode this fault. + * + * @param subcode the qualified name of the subcode + */ + void addFaultSubcode(QName subcode); - /** Returns the fault node. Optional. */ - String getFaultNode(); + /** Returns the fault node. Optional. */ + String getFaultNode(); - /** Sets the fault node. */ - void setFaultNode(String uri); + /** Sets the fault node. */ + void setFaultNode(String uri); - /** Sets the specified fault reason text. */ - void setFaultReasonText(Locale locale, String text); + /** Sets the specified fault reason text. */ + void setFaultReasonText(Locale locale, String text); - /** Returns the reason associated with the given language. */ - String getFaultReasonText(Locale locale); + /** Returns the reason associated with the given language. */ + String getFaultReasonText(Locale locale); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Header.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Header.java index 5d2305aa..66b5020f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Header.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/soap12/Soap12Header.java @@ -31,38 +31,38 @@ import org.springframework.ws.soap.SoapHeaderException; */ public interface Soap12Header extends SoapHeader { - /** - * Adds a new NotUnderstood {@code SoapHeaderElement} this header. - * - * @param headerName the qualified name of the header that was not understood - * @return the created {@code SoapHeaderElement} - * @throws org.springframework.ws.soap.SoapHeaderException - * if the header cannot be created - */ - SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName); + /** + * Adds a new NotUnderstood {@code SoapHeaderElement} this header. + * + * @param headerName the qualified name of the header that was not understood + * @return the created {@code SoapHeaderElement} + * @throws org.springframework.ws.soap.SoapHeaderException + * if the header cannot be created + */ + SoapHeaderElement addNotUnderstoodHeaderElement(QName headerName); - /** - * Adds a new Upgrade {@code SoapHeaderElement} this header. - * - * @param supportedSoapUris an array of the URIs of SOAP versions supported - * @return the created {@code SoapHeaderElement} - * @throws org.springframework.ws.soap.SoapHeaderException - * if the header cannot be created - */ - SoapHeaderElement addUpgradeHeaderElement(java.lang.String[] supportedSoapUris); + /** + * Adds a new Upgrade {@code SoapHeaderElement} this header. + * + * @param supportedSoapUris an array of the URIs of SOAP versions supported + * @return the created {@code SoapHeaderElement} + * @throws org.springframework.ws.soap.SoapHeaderException + * if the header cannot be created + */ + SoapHeaderElement addUpgradeHeaderElement(java.lang.String[] supportedSoapUris); - /** - * Returns an {@code Iterator} over all the {@link SoapHeaderElement header elements} that should be processed - * for the given roles. Headers target to the "next" role will always be included, and those targeted to "none" will - * never be included. - * - * @param roles an array of roles to search for - * @param isUltimateReceiver whether to search for headers for the ultimate receiver - * @return an iterator over all the header elements that contain the specified roles - * @throws SoapHeaderException if the headers cannot be returned - * @see SoapHeaderElement - */ - Iterator examineHeaderElementsToProcess(String[] roles, boolean isUltimateReceiver) throws SoapHeaderException; + /** + * Returns an {@code Iterator} over all the {@link SoapHeaderElement header elements} that should be processed + * for the given roles. Headers target to the "next" role will always be included, and those targeted to "none" will + * never be included. + * + * @param roles an array of roles to search for + * @param isUltimateReceiver whether to search for headers for the ultimate receiver + * @return an iterator over all the header elements that contain the specified roles + * @throws SoapHeaderException if the headers cannot be returned + * @see SoapHeaderElement + */ + Iterator examineHeaderElementsToProcess(String[] roles, boolean isUltimateReceiver) throws SoapHeaderException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/soap/support/SoapUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/soap/support/SoapUtils.java index f6e26e30..7dca6991 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/soap/support/SoapUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/soap/support/SoapUtils.java @@ -31,66 +31,66 @@ import org.springframework.ws.transport.TransportConstants; */ public abstract class SoapUtils { - private static final Pattern ACTION_PATTERN = Pattern.compile("action\\s*=\\s*([^;]+)"); + private static final Pattern ACTION_PATTERN = Pattern.compile("action\\s*=\\s*([^;]+)"); - private SoapUtils() { - } + private SoapUtils() { + } - /** Escapes the given SOAP action to be surrounded by quotes. */ - public static String escapeAction(String soapAction) { - if (!StringUtils.hasLength(soapAction)) { - soapAction = "\"\""; - } - if (!soapAction.startsWith("\"")) { - soapAction = "\"" + soapAction; - } - if (!soapAction.endsWith("\"")) { - soapAction = soapAction + "\""; - } - return soapAction; - } + /** Escapes the given SOAP action to be surrounded by quotes. */ + public static String escapeAction(String soapAction) { + if (!StringUtils.hasLength(soapAction)) { + soapAction = "\"\""; + } + if (!soapAction.startsWith("\"")) { + soapAction = "\"" + soapAction; + } + if (!soapAction.endsWith("\"")) { + soapAction = soapAction + "\""; + } + return soapAction; + } - /** - * Returns the value of the action parameter in the given SOAP 1.2 content type. - * - * @param contentType the SOAP 1.2 content type - * @return the action - */ - public static String extractActionFromContentType(String contentType) { - if (contentType != null) { - Matcher matcher = ACTION_PATTERN.matcher(contentType); - if (matcher.find() && matcher.groupCount() == 1) { - return matcher.group(1).trim(); - } - } - return TransportConstants.EMPTY_SOAP_ACTION; - } + /** + * Returns the value of the action parameter in the given SOAP 1.2 content type. + * + * @param contentType the SOAP 1.2 content type + * @return the action + */ + public static String extractActionFromContentType(String contentType) { + if (contentType != null) { + Matcher matcher = ACTION_PATTERN.matcher(contentType); + if (matcher.find() && matcher.groupCount() == 1) { + return matcher.group(1).trim(); + } + } + return TransportConstants.EMPTY_SOAP_ACTION; + } - /** - * Replaces or adds the value of the action parameter in the given SOAP 1.2 content type. - * - * @param contentType the SOAP 1.2 content type - * @param action the action - * @return the new content type - */ - public static String setActionInContentType(String contentType, String action) { - Assert.hasLength(contentType, "'contentType' must not be empty"); - if (StringUtils.hasText(action)) { - Matcher matcher = ACTION_PATTERN.matcher(contentType); - if (matcher.find() && matcher.groupCount() == 1) { - StringBuffer buffer = new StringBuffer(); - matcher.appendReplacement(buffer, "action=" + action); - matcher.appendTail(buffer); - return buffer.toString(); - } - else { - return contentType + "; action=" + action; - } - } - else { - return contentType; - } - } + /** + * Replaces or adds the value of the action parameter in the given SOAP 1.2 content type. + * + * @param contentType the SOAP 1.2 content type + * @param action the action + * @return the new content type + */ + public static String setActionInContentType(String contentType, String action) { + Assert.hasLength(contentType, "'contentType' must not be empty"); + if (StringUtils.hasText(action)) { + Matcher matcher = ACTION_PATTERN.matcher(contentType); + if (matcher.find() && matcher.groupCount() == 1) { + StringBuffer buffer = new StringBuffer(); + matcher.appendReplacement(buffer, "action=" + action); + matcher.appendTail(buffer); + return buffer.toString(); + } + else { + return contentType + "; action=" + action; + } + } + else { + return contentType; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingPayload.java b/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingPayload.java index e77735d4..d0436966 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingPayload.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingPayload.java @@ -29,19 +29,19 @@ import javax.xml.stream.XMLStreamWriter; */ public interface StreamingPayload { - /** - * Returns the qualified name of the payload. - * - * @return the qualified name - */ - QName getName(); + /** + * Returns the qualified name of the payload. + * + * @return the qualified name + */ + QName getName(); - /** - * Writes this payload to the given {@link XMLStreamWriter}. - * - * @param streamWriter the stream writer to write to - * @throws XMLStreamException in case of errors - */ - void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException; + /** + * Writes this payload to the given {@link XMLStreamWriter}. + * + * @param streamWriter the stream writer to write to + * @throws XMLStreamException in case of errors + */ + void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingWebServiceMessage.java b/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingWebServiceMessage.java index 71d6d079..c5be5042 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingWebServiceMessage.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/stream/StreamingWebServiceMessage.java @@ -27,11 +27,11 @@ import org.springframework.ws.WebServiceMessage; */ public interface StreamingWebServiceMessage extends WebServiceMessage { - /** - * Sets the streaming payload for this message. - * - * @param payload the streaming payload - */ - void setStreamingPayload(StreamingPayload payload); + /** + * Sets the streaming payload for this message. + * + * @param payload the streaming payload + */ + void setStreamingPayload(StreamingPayload payload); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/support/DefaultStrategiesHelper.java b/spring-ws-core/src/main/java/org/springframework/ws/support/DefaultStrategiesHelper.java index bd8ea024..677d3fda 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/support/DefaultStrategiesHelper.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/support/DefaultStrategiesHelper.java @@ -60,168 +60,168 @@ import org.springframework.web.context.WebApplicationContext; */ public class DefaultStrategiesHelper { - /** Keys are strategy interface names, values are implementation class names. */ - private Properties defaultStrategies; + /** Keys are strategy interface names, values are implementation class names. */ + private Properties defaultStrategies; - /** Initializes a new instance of the {@code DefaultStrategiesHelper} based on the given set of properties. */ - public DefaultStrategiesHelper(Properties defaultStrategies) { - Assert.notNull(defaultStrategies, "defaultStrategies must not be null"); - this.defaultStrategies = defaultStrategies; - } + /** Initializes a new instance of the {@code DefaultStrategiesHelper} based on the given set of properties. */ + public DefaultStrategiesHelper(Properties defaultStrategies) { + Assert.notNull(defaultStrategies, "defaultStrategies must not be null"); + this.defaultStrategies = defaultStrategies; + } - /** Initializes a new instance of the {@code DefaultStrategiesHelper} based on the given resource. */ - public DefaultStrategiesHelper(Resource resource) throws IllegalStateException { - try { - defaultStrategies = PropertiesLoaderUtils.loadProperties(resource); - } - catch (IOException ex) { - throw new IllegalStateException("Could not load '" + resource + "': " + ex.getMessage()); - } - } + /** Initializes a new instance of the {@code DefaultStrategiesHelper} based on the given resource. */ + public DefaultStrategiesHelper(Resource resource) throws IllegalStateException { + try { + defaultStrategies = PropertiesLoaderUtils.loadProperties(resource); + } + catch (IOException ex) { + throw new IllegalStateException("Could not load '" + resource + "': " + ex.getMessage()); + } + } - /** - * Initializes a new instance of the {@code DefaultStrategiesHelper} based on the given type. - * - *

This constructor will attempt to load a 'typeName'.properties file in the same package as the given type. - */ - public DefaultStrategiesHelper(Class type) { - this(new ClassPathResource(ClassUtils.getShortName(type) + ".properties", type)); - } + /** + * Initializes a new instance of the {@code DefaultStrategiesHelper} based on the given type. + * + *

This constructor will attempt to load a 'typeName'.properties file in the same package as the given type. + */ + public DefaultStrategiesHelper(Class type) { + this(new ClassPathResource(ClassUtils.getShortName(type) + ".properties", type)); + } - /** - * Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the - * {@code Properties} object given at construction-time. - * - * @param strategyInterface the strategy interface - * @return a list of corresponding strategy objects - * @throws BeansException if initialization failed - */ - public List getDefaultStrategies(Class strategyInterface) throws BeanInitializationException { - return getDefaultStrategies(strategyInterface, null); - } + /** + * Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the + * {@code Properties} object given at construction-time. + * + * @param strategyInterface the strategy interface + * @return a list of corresponding strategy objects + * @throws BeansException if initialization failed + */ + public List getDefaultStrategies(Class strategyInterface) throws BeanInitializationException { + return getDefaultStrategies(strategyInterface, null); + } - /** - * Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the - * {@code Properties} object given at construction-time. It instantiates the strategy objects and satisfies - * {@code ApplicationContextAware} with the supplied context if necessary. - * - * @param strategyInterface the strategy interface - * @param applicationContext used to satisfy strategies that are application context aware, may be - * {@code null} - * @return a list of corresponding strategy objects - * @throws BeansException if initialization failed - */ - @SuppressWarnings("unchecked") - public List getDefaultStrategies(Class strategyInterface, ApplicationContext applicationContext) - throws BeanInitializationException { - String key = strategyInterface.getName(); - try { - List result; - String value = defaultStrategies.getProperty(key); - if (value != null) { - String[] classNames = StringUtils.commaDelimitedListToStringArray(value); - result = new ArrayList(classNames.length); - ClassLoader classLoader = null; - if (applicationContext != null) { - classLoader = applicationContext.getClassLoader(); - } - if (classLoader == null) { - classLoader = DefaultStrategiesHelper.class.getClassLoader(); - } - for (String className : classNames) { - Class clazz = (Class) ClassUtils.forName(className, classLoader); - Assert.isTrue(strategyInterface.isAssignableFrom(clazz), clazz.getName() + " is not a " + strategyInterface.getName()); - T strategy = instantiateBean(clazz, applicationContext); - result.add(strategy); - } - } - else { - result = Collections.emptyList(); - } - Collections.sort(result, new OrderComparator()); - return result; - } - catch (ClassNotFoundException ex) { - throw new BeanInitializationException("Could not find default strategy class for interface [" + key + "]", - ex); - } - } + /** + * Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the + * {@code Properties} object given at construction-time. It instantiates the strategy objects and satisfies + * {@code ApplicationContextAware} with the supplied context if necessary. + * + * @param strategyInterface the strategy interface + * @param applicationContext used to satisfy strategies that are application context aware, may be + * {@code null} + * @return a list of corresponding strategy objects + * @throws BeansException if initialization failed + */ + @SuppressWarnings("unchecked") + public List getDefaultStrategies(Class strategyInterface, ApplicationContext applicationContext) + throws BeanInitializationException { + String key = strategyInterface.getName(); + try { + List result; + String value = defaultStrategies.getProperty(key); + if (value != null) { + String[] classNames = StringUtils.commaDelimitedListToStringArray(value); + result = new ArrayList(classNames.length); + ClassLoader classLoader = null; + if (applicationContext != null) { + classLoader = applicationContext.getClassLoader(); + } + if (classLoader == null) { + classLoader = DefaultStrategiesHelper.class.getClassLoader(); + } + for (String className : classNames) { + Class clazz = (Class) ClassUtils.forName(className, classLoader); + Assert.isTrue(strategyInterface.isAssignableFrom(clazz), clazz.getName() + " is not a " + strategyInterface.getName()); + T strategy = instantiateBean(clazz, applicationContext); + result.add(strategy); + } + } + else { + result = Collections.emptyList(); + } + Collections.sort(result, new OrderComparator()); + return result; + } + catch (ClassNotFoundException ex) { + throw new BeanInitializationException("Could not find default strategy class for interface [" + key + "]", + ex); + } + } - /** Instantiates the given bean, simulating the standard bean life cycle. */ - private T instantiateBean(Class clazz, ApplicationContext applicationContext) { - T strategy = BeanUtils.instantiateClass(clazz); - if (strategy instanceof BeanNameAware) { - BeanNameAware beanNameAware = (BeanNameAware) strategy; - beanNameAware.setBeanName(clazz.getName()); - } - if (applicationContext != null) { - if (strategy instanceof BeanClassLoaderAware) { - ((BeanClassLoaderAware) strategy).setBeanClassLoader(applicationContext.getClassLoader()); - } - if (strategy instanceof BeanFactoryAware) { - ((BeanFactoryAware) strategy).setBeanFactory(applicationContext); - } - if (strategy instanceof ResourceLoaderAware) { - ((ResourceLoaderAware) strategy).setResourceLoader(applicationContext); - } - if (strategy instanceof ApplicationEventPublisherAware) { - ((ApplicationEventPublisherAware) strategy).setApplicationEventPublisher(applicationContext); - } - if (strategy instanceof MessageSourceAware) { - ((MessageSourceAware) strategy).setMessageSource(applicationContext); - } - if (strategy instanceof ApplicationContextAware) { - ApplicationContextAware applicationContextAware = (ApplicationContextAware) strategy; - applicationContextAware.setApplicationContext(applicationContext); - } - if (applicationContext instanceof WebApplicationContext && strategy instanceof ServletContextAware) { - ServletContext servletContext = ((WebApplicationContext) applicationContext).getServletContext(); - ((ServletContextAware) strategy).setServletContext(servletContext); - } - } - if (strategy instanceof InitializingBean) { - InitializingBean initializingBean = (InitializingBean) strategy; - try { - initializingBean.afterPropertiesSet(); - } - catch (Throwable ex) { - throw new BeanCreationException("Invocation of init method failed", ex); - } - } - return strategy; - } + /** Instantiates the given bean, simulating the standard bean life cycle. */ + private T instantiateBean(Class clazz, ApplicationContext applicationContext) { + T strategy = BeanUtils.instantiateClass(clazz); + if (strategy instanceof BeanNameAware) { + BeanNameAware beanNameAware = (BeanNameAware) strategy; + beanNameAware.setBeanName(clazz.getName()); + } + if (applicationContext != null) { + if (strategy instanceof BeanClassLoaderAware) { + ((BeanClassLoaderAware) strategy).setBeanClassLoader(applicationContext.getClassLoader()); + } + if (strategy instanceof BeanFactoryAware) { + ((BeanFactoryAware) strategy).setBeanFactory(applicationContext); + } + if (strategy instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) strategy).setResourceLoader(applicationContext); + } + if (strategy instanceof ApplicationEventPublisherAware) { + ((ApplicationEventPublisherAware) strategy).setApplicationEventPublisher(applicationContext); + } + if (strategy instanceof MessageSourceAware) { + ((MessageSourceAware) strategy).setMessageSource(applicationContext); + } + if (strategy instanceof ApplicationContextAware) { + ApplicationContextAware applicationContextAware = (ApplicationContextAware) strategy; + applicationContextAware.setApplicationContext(applicationContext); + } + if (applicationContext instanceof WebApplicationContext && strategy instanceof ServletContextAware) { + ServletContext servletContext = ((WebApplicationContext) applicationContext).getServletContext(); + ((ServletContextAware) strategy).setServletContext(servletContext); + } + } + if (strategy instanceof InitializingBean) { + InitializingBean initializingBean = (InitializingBean) strategy; + try { + initializingBean.afterPropertiesSet(); + } + catch (Throwable ex) { + throw new BeanCreationException("Invocation of init method failed", ex); + } + } + return strategy; + } - /** - * Return the default strategy object for the given strategy interface. - * - * @param strategyInterface the strategy interface - * @return the corresponding strategy object - * @throws BeansException if initialization failed - * @see #getDefaultStrategies - */ - public T getDefaultStrategy(Class strategyInterface) throws BeanInitializationException { - return getDefaultStrategy(strategyInterface, null); - } + /** + * Return the default strategy object for the given strategy interface. + * + * @param strategyInterface the strategy interface + * @return the corresponding strategy object + * @throws BeansException if initialization failed + * @see #getDefaultStrategies + */ + public T getDefaultStrategy(Class strategyInterface) throws BeanInitializationException { + return getDefaultStrategy(strategyInterface, null); + } - /** - * Return the default strategy object for the given strategy interface. - * - *

Delegates to {@link #getDefaultStrategies(Class,ApplicationContext)}, expecting a single object in the list. - * - * @param strategyInterface the strategy interface - * @param applicationContext used to satisfy strategies that are application context aware, may be - * {@code null} - * @return the corresponding strategy object - * @throws BeansException if initialization failed - */ - public T getDefaultStrategy(Class strategyInterface, ApplicationContext applicationContext) - throws BeanInitializationException { - List result = getDefaultStrategies(strategyInterface, applicationContext); - if (result.size() != 1) { - throw new BeanInitializationException( - "Could not find exactly 1 strategy for interface [" + strategyInterface.getName() + "]"); - } - return result.get(0); - } + /** + * Return the default strategy object for the given strategy interface. + * + *

Delegates to {@link #getDefaultStrategies(Class,ApplicationContext)}, expecting a single object in the list. + * + * @param strategyInterface the strategy interface + * @param applicationContext used to satisfy strategies that are application context aware, may be + * {@code null} + * @return the corresponding strategy object + * @throws BeansException if initialization failed + */ + public T getDefaultStrategy(Class strategyInterface, ApplicationContext applicationContext) + throws BeanInitializationException { + List result = getDefaultStrategies(strategyInterface, applicationContext); + if (result.size() != 1) { + throw new BeanInitializationException( + "Could not find exactly 1 strategy for interface [" + strategyInterface.getName() + "]"); + } + return result.get(0); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/support/MarshallingUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/support/MarshallingUtils.java index 7cbf6d17..bce31c8b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/support/MarshallingUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/support/MarshallingUtils.java @@ -37,82 +37,82 @@ import org.springframework.ws.mime.MimeMessage; */ public abstract class MarshallingUtils { - private MarshallingUtils() { - } + private MarshallingUtils() { + } - /** - * Unmarshals the payload of the given message using the provided {@link Unmarshaller}. - * - *

If the request message has no payload (i.e. {@link WebServiceMessage#getPayloadSource()} returns - * {@code null}), this method will return {@code null}. - * - * @param unmarshaller the unmarshaller - * @param message the message of which the payload is to be unmarshalled - * @return the unmarshalled object - * @throws IOException in case of I/O errors - */ - public static Object unmarshal(Unmarshaller unmarshaller, WebServiceMessage message) throws IOException { - Source payload = message.getPayloadSource(); - if (payload == null) { - return null; - } - else if (unmarshaller instanceof MimeUnmarshaller && message instanceof MimeMessage) { - MimeUnmarshaller mimeUnmarshaller = (MimeUnmarshaller) unmarshaller; - MimeMessageContainer container = new MimeMessageContainer((MimeMessage) message); - return mimeUnmarshaller.unmarshal(payload, container); - } - else { - return unmarshaller.unmarshal(payload); - } - } + /** + * Unmarshals the payload of the given message using the provided {@link Unmarshaller}. + * + *

If the request message has no payload (i.e. {@link WebServiceMessage#getPayloadSource()} returns + * {@code null}), this method will return {@code null}. + * + * @param unmarshaller the unmarshaller + * @param message the message of which the payload is to be unmarshalled + * @return the unmarshalled object + * @throws IOException in case of I/O errors + */ + public static Object unmarshal(Unmarshaller unmarshaller, WebServiceMessage message) throws IOException { + Source payload = message.getPayloadSource(); + if (payload == null) { + return null; + } + else if (unmarshaller instanceof MimeUnmarshaller && message instanceof MimeMessage) { + MimeUnmarshaller mimeUnmarshaller = (MimeUnmarshaller) unmarshaller; + MimeMessageContainer container = new MimeMessageContainer((MimeMessage) message); + return mimeUnmarshaller.unmarshal(payload, container); + } + else { + return unmarshaller.unmarshal(payload); + } + } - /** - * Marshals the given object to the payload of the given message using the provided {@link Marshaller}. - * - * @param marshaller the marshaller - * @param graph the root of the object graph to marshal - * @param message the message of which the payload is to be unmarshalled - * @throws IOException in case of I/O errors - */ - public static void marshal(Marshaller marshaller, Object graph, WebServiceMessage message) throws IOException { - if (marshaller instanceof MimeMarshaller && message instanceof MimeMessage) { - MimeMarshaller mimeMarshaller = (MimeMarshaller) marshaller; - MimeMessageContainer container = new MimeMessageContainer((MimeMessage) message); - mimeMarshaller.marshal(graph, message.getPayloadResult(), container); - } - else { - marshaller.marshal(graph, message.getPayloadResult()); - } - } + /** + * Marshals the given object to the payload of the given message using the provided {@link Marshaller}. + * + * @param marshaller the marshaller + * @param graph the root of the object graph to marshal + * @param message the message of which the payload is to be unmarshalled + * @throws IOException in case of I/O errors + */ + public static void marshal(Marshaller marshaller, Object graph, WebServiceMessage message) throws IOException { + if (marshaller instanceof MimeMarshaller && message instanceof MimeMessage) { + MimeMarshaller mimeMarshaller = (MimeMarshaller) marshaller; + MimeMessageContainer container = new MimeMessageContainer((MimeMessage) message); + mimeMarshaller.marshal(graph, message.getPayloadResult(), container); + } + else { + marshaller.marshal(graph, message.getPayloadResult()); + } + } - private static class MimeMessageContainer implements MimeContainer { + private static class MimeMessageContainer implements MimeContainer { - private final MimeMessage mimeMessage; + private final MimeMessage mimeMessage; - public MimeMessageContainer(MimeMessage mimeMessage) { - this.mimeMessage = mimeMessage; - } + public MimeMessageContainer(MimeMessage mimeMessage) { + this.mimeMessage = mimeMessage; + } - @Override - public boolean isXopPackage() { - return mimeMessage.isXopPackage(); - } + @Override + public boolean isXopPackage() { + return mimeMessage.isXopPackage(); + } - @Override - public boolean convertToXopPackage() { - return mimeMessage.convertToXopPackage(); - } + @Override + public boolean convertToXopPackage() { + return mimeMessage.convertToXopPackage(); + } - @Override - public void addAttachment(String contentId, DataHandler dataHandler) { - mimeMessage.addAttachment(contentId, dataHandler); - } + @Override + public void addAttachment(String contentId, DataHandler dataHandler) { + mimeMessage.addAttachment(contentId, dataHandler); + } - @Override - public DataHandler getAttachment(String contentId) { - Attachment attachment = mimeMessage.getAttachment(contentId); - return attachment != null ? attachment.getDataHandler() : null; - } - } + @Override + public DataHandler getAttachment(String contentId) { + Attachment attachment = mimeMessage.getAttachment(contentId); + return attachment != null ? attachment.getDataHandler() : null; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractReceiverConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractReceiverConnection.java index eccc6659..d66c478d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractReceiverConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractReceiverConnection.java @@ -29,96 +29,96 @@ import java.util.Iterator; */ public abstract class AbstractReceiverConnection extends AbstractWebServiceConnection { - private TransportInputStream requestInputStream; + private TransportInputStream requestInputStream; - private TransportOutputStream responseOutputStream; + private TransportOutputStream responseOutputStream; - @Override - protected final TransportInputStream createTransportInputStream() throws IOException { - if (requestInputStream == null) { - requestInputStream = new RequestTransportInputStream(); - } - return requestInputStream; - } + @Override + protected final TransportInputStream createTransportInputStream() throws IOException { + if (requestInputStream == null) { + requestInputStream = new RequestTransportInputStream(); + } + return requestInputStream; + } - @Override - protected final TransportOutputStream createTransportOutputStream() throws IOException { - if (responseOutputStream == null) { - responseOutputStream = new ResponseTransportOutputStream(); - } - return responseOutputStream; - } + @Override + protected final TransportOutputStream createTransportOutputStream() throws IOException { + if (responseOutputStream == null) { + responseOutputStream = new ResponseTransportOutputStream(); + } + return responseOutputStream; + } - /** - * Template method invoked from {@link #close()}. Default implementation is empty. - * - * @throws IOException if an I/O error occurs when closing this connection - */ - @Override - protected void onClose() throws IOException { - } + /** + * Template method invoked from {@link #close()}. Default implementation is empty. + * + * @throws IOException if an I/O error occurs when closing this connection + */ + @Override + protected void onClose() throws IOException { + } - /** - * Returns an iteration over all the header names this request contains. Returns an empty {@code Iterator} if - * there are no headers. - */ - protected abstract Iterator getRequestHeaderNames() throws IOException; + /** + * Returns an iteration over all the header names this request contains. Returns an empty {@code Iterator} if + * there are no headers. + */ + protected abstract Iterator getRequestHeaderNames() throws IOException; - /** - * Returns an iteration over all the string values of the specified header. Returns an empty {@code Iterator} - * if there are no headers of the specified name. - */ - protected abstract Iterator getRequestHeaders(String name) throws IOException; + /** + * Returns an iteration over all the string values of the specified header. Returns an empty {@code Iterator} + * if there are no headers of the specified name. + */ + protected abstract Iterator getRequestHeaders(String name) throws IOException; - /** Returns the input stream to read the response from. */ - protected abstract InputStream getRequestInputStream() throws IOException; + /** Returns the input stream to read the response from. */ + protected abstract InputStream getRequestInputStream() throws IOException; - /** - * Adds a response header with the given name and value. This method can be called multiple times, to allow for - * headers with multiple values. - * - * @param name the name of the header - * @param value the value of the header - */ - protected abstract void addResponseHeader(String name, String value) throws IOException; + /** + * Adds a response header with the given name and value. This method can be called multiple times, to allow for + * headers with multiple values. + * + * @param name the name of the header + * @param value the value of the header + */ + protected abstract void addResponseHeader(String name, String value) throws IOException; - /** Returns the output stream to write the request to. */ - protected abstract OutputStream getResponseOutputStream() throws IOException; + /** Returns the output stream to write the request to. */ + protected abstract OutputStream getResponseOutputStream() throws IOException; - /** Implementation of {@code TransportInputStream} for receiving-side connections. */ - private class RequestTransportInputStream extends TransportInputStream { + /** Implementation of {@code TransportInputStream} for receiving-side connections. */ + private class RequestTransportInputStream extends TransportInputStream { - @Override - protected InputStream createInputStream() throws IOException { - return getRequestInputStream(); - } + @Override + protected InputStream createInputStream() throws IOException { + return getRequestInputStream(); + } - @Override - public Iterator getHeaderNames() throws IOException { - return getRequestHeaderNames(); - } + @Override + public Iterator getHeaderNames() throws IOException { + return getRequestHeaderNames(); + } - @Override - public Iterator getHeaders(String name) throws IOException { - return getRequestHeaders(name); - } + @Override + public Iterator getHeaders(String name) throws IOException { + return getRequestHeaders(name); + } - } + } - /** Implementation of {@code TransportOutputStream} for sending-side connections. */ - private class ResponseTransportOutputStream extends TransportOutputStream { + /** Implementation of {@code TransportOutputStream} for sending-side connections. */ + private class ResponseTransportOutputStream extends TransportOutputStream { - @Override - public void addHeader(String name, String value) throws IOException { - addResponseHeader(name, value); - } + @Override + public void addHeader(String name, String value) throws IOException { + addResponseHeader(name, value); + } - @Override - protected OutputStream createOutputStream() throws IOException { - return getResponseOutputStream(); - } + @Override + protected OutputStream createOutputStream() throws IOException { + return getResponseOutputStream(); + } - } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractSenderConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractSenderConnection.java index bb6b51e9..0bcc7f83 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractSenderConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractSenderConnection.java @@ -29,102 +29,102 @@ import java.util.Iterator; */ public abstract class AbstractSenderConnection extends AbstractWebServiceConnection { - private TransportOutputStream requestOutputStream; + private TransportOutputStream requestOutputStream; - private TransportInputStream responseInputStream; + private TransportInputStream responseInputStream; - @Override - protected final TransportOutputStream createTransportOutputStream() throws IOException { - if (requestOutputStream == null) { - requestOutputStream = new RequestTransportOutputStream(); - } - return requestOutputStream; - } + @Override + protected final TransportOutputStream createTransportOutputStream() throws IOException { + if (requestOutputStream == null) { + requestOutputStream = new RequestTransportOutputStream(); + } + return requestOutputStream; + } - @Override - protected final TransportInputStream createTransportInputStream() throws IOException { - if (hasResponse()) { - if (responseInputStream == null) { - responseInputStream = new ResponseTransportInputStream(); - } - return responseInputStream; - } - else { - return null; - } - } + @Override + protected final TransportInputStream createTransportInputStream() throws IOException { + if (hasResponse()) { + if (responseInputStream == null) { + responseInputStream = new ResponseTransportInputStream(); + } + return responseInputStream; + } + else { + return null; + } + } - /** - * Template method invoked from {@link #close()}. Default implementation is empty. - * - * @throws IOException if an I/O error occurs when closing this connection - */ - @Override - protected void onClose() throws IOException { - } + /** + * Template method invoked from {@link #close()}. Default implementation is empty. + * + * @throws IOException if an I/O error occurs when closing this connection + */ + @Override + protected void onClose() throws IOException { + } - /** Indicates whether this connection has a response. */ - protected abstract boolean hasResponse() throws IOException; + /** Indicates whether this connection has a response. */ + protected abstract boolean hasResponse() throws IOException; - /** - * Adds a request header with the given name and value. This method can be called multiple times, to allow for - * headers with multiple values. - * - * @param name the name of the header - * @param value the value of the header - */ - protected abstract void addRequestHeader(String name, String value) throws IOException; + /** + * Adds a request header with the given name and value. This method can be called multiple times, to allow for + * headers with multiple values. + * + * @param name the name of the header + * @param value the value of the header + */ + protected abstract void addRequestHeader(String name, String value) throws IOException; - /** Returns the output stream to write the request to. */ - protected abstract OutputStream getRequestOutputStream() throws IOException; + /** Returns the output stream to write the request to. */ + protected abstract OutputStream getRequestOutputStream() throws IOException; - /** - * Returns an iteration over all the header names this request contains. Returns an empty {@code Iterator} if - * there are no headers. - */ - protected abstract Iterator getResponseHeaderNames() throws IOException; + /** + * Returns an iteration over all the header names this request contains. Returns an empty {@code Iterator} if + * there are no headers. + */ + protected abstract Iterator getResponseHeaderNames() throws IOException; - /** - * Returns an iteration over all the string values of the specified header. Returns an empty {@code Iterator} - * if there are no headers of the specified name. - */ - protected abstract Iterator getResponseHeaders(String name) throws IOException; + /** + * Returns an iteration over all the string values of the specified header. Returns an empty {@code Iterator} + * if there are no headers of the specified name. + */ + protected abstract Iterator getResponseHeaders(String name) throws IOException; - /** Returns the input stream to read the response from. */ - protected abstract InputStream getResponseInputStream() throws IOException; + /** Returns the input stream to read the response from. */ + protected abstract InputStream getResponseInputStream() throws IOException; - /** Implementation of {@code TransportInputStream} for receiving-side connections. */ - class RequestTransportOutputStream extends TransportOutputStream { + /** Implementation of {@code TransportInputStream} for receiving-side connections. */ + class RequestTransportOutputStream extends TransportOutputStream { - @Override - public void addHeader(String name, String value) throws IOException { - addRequestHeader(name, value); - } + @Override + public void addHeader(String name, String value) throws IOException { + addRequestHeader(name, value); + } - @Override - protected OutputStream createOutputStream() throws IOException { - return getRequestOutputStream(); - } - } + @Override + protected OutputStream createOutputStream() throws IOException { + return getRequestOutputStream(); + } + } - /** Implementation of {@link TransportInputStream} for client-side HTTP. */ - class ResponseTransportInputStream extends TransportInputStream { + /** Implementation of {@link TransportInputStream} for client-side HTTP. */ + class ResponseTransportInputStream extends TransportInputStream { - @Override - protected InputStream createInputStream() throws IOException { - return getResponseInputStream(); - } + @Override + protected InputStream createInputStream() throws IOException { + return getResponseInputStream(); + } - @Override - public Iterator getHeaderNames() throws IOException { - return getResponseHeaderNames(); - } + @Override + public Iterator getHeaderNames() throws IOException { + return getResponseHeaderNames(); + } - @Override - public Iterator getHeaders(String name) throws IOException { - return getResponseHeaders(name); - } + @Override + public Iterator getHeaders(String name) throws IOException { + return getResponseHeaders(name); + } - } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractWebServiceConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractWebServiceConnection.java index ecee1b49..9685999a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractWebServiceConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/AbstractWebServiceConnection.java @@ -29,140 +29,140 @@ import org.springframework.ws.WebServiceMessageFactory; */ public abstract class AbstractWebServiceConnection implements WebServiceConnection { - private TransportInputStream tis; + private TransportInputStream tis; - private TransportOutputStream tos; + private TransportOutputStream tos; - private boolean closed = false; + private boolean closed = false; - @Override - public final void send(WebServiceMessage message) throws IOException { - checkClosed(); - onSendBeforeWrite(message); - tos = createTransportOutputStream(); - if (tos == null) { - return; - } - message.writeTo(tos); - tos.flush(); - onSendAfterWrite(message); - } + @Override + public final void send(WebServiceMessage message) throws IOException { + checkClosed(); + onSendBeforeWrite(message); + tos = createTransportOutputStream(); + if (tos == null) { + return; + } + message.writeTo(tos); + tos.flush(); + onSendAfterWrite(message); + } - /** - * Called before the given message has been written to the {@code TransportOutputStream}. Called from {@link - * #send(WebServiceMessage)}. - * - *

Default implementation does nothing. - * - * @param message the message - * @throws IOException when an I/O exception occurs - */ - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - } + /** + * Called before the given message has been written to the {@code TransportOutputStream}. Called from {@link + * #send(WebServiceMessage)}. + * + *

Default implementation does nothing. + * + * @param message the message + * @throws IOException when an I/O exception occurs + */ + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + } - /** - * Returns a {@code TransportOutputStream} for the given message. Called from {@link - * #send(WebServiceMessage)}. - * - * @return the output stream - * @throws IOException when an I/O exception occurs - */ - protected abstract TransportOutputStream createTransportOutputStream() throws IOException; + /** + * Returns a {@code TransportOutputStream} for the given message. Called from {@link + * #send(WebServiceMessage)}. + * + * @return the output stream + * @throws IOException when an I/O exception occurs + */ + protected abstract TransportOutputStream createTransportOutputStream() throws IOException; - /** - * Called after the given message has been written to the {@code TransportOutputStream}. Called from {@link - * #send(WebServiceMessage)}. - * - *

Default implementation does nothing. - * - * @param message the message - * @throws IOException when an I/O exception occurs - */ - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - } + /** + * Called after the given message has been written to the {@code TransportOutputStream}. Called from {@link + * #send(WebServiceMessage)}. + * + *

Default implementation does nothing. + * + * @param message the message + * @throws IOException when an I/O exception occurs + */ + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + } - @Override - public final WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException { - checkClosed(); - onReceiveBeforeRead(); - tis = createTransportInputStream(); - if (tis == null) { - return null; - } - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - onReceiveAfterRead(message); - return message; - } + @Override + public final WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException { + checkClosed(); + onReceiveBeforeRead(); + tis = createTransportInputStream(); + if (tis == null) { + return null; + } + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + onReceiveAfterRead(message); + return message; + } - /** - * Called before a message has been read from the {@code TransportInputStream}. Called from {@link - * #receive(WebServiceMessageFactory)}. - * - *

Default implementation does nothing. - * - * @throws IOException when an I/O exception occurs - */ - protected void onReceiveBeforeRead() throws IOException { - } + /** + * Called before a message has been read from the {@code TransportInputStream}. Called from {@link + * #receive(WebServiceMessageFactory)}. + * + *

Default implementation does nothing. + * + * @throws IOException when an I/O exception occurs + */ + protected void onReceiveBeforeRead() throws IOException { + } - /** - * Returns a {@code TransportInputStream}. Called from {@link #receive(WebServiceMessageFactory)}. - * - * @return the input stream, or {@code null} if no response can be read - * @throws IOException when an I/O exception occurs - */ - protected abstract TransportInputStream createTransportInputStream() throws IOException; + /** + * Returns a {@code TransportInputStream}. Called from {@link #receive(WebServiceMessageFactory)}. + * + * @return the input stream, or {@code null} if no response can be read + * @throws IOException when an I/O exception occurs + */ + protected abstract TransportInputStream createTransportInputStream() throws IOException; - /** - * Called when the given message has been read from the {@code TransportInputStream}. Called from {@link - * #receive(WebServiceMessageFactory)}. - * - *

Default implementation does nothing. - * - * @param message the message - * @throws IOException when an I/O exception occurs - */ - protected void onReceiveAfterRead(WebServiceMessage message) throws IOException { - } + /** + * Called when the given message has been read from the {@code TransportInputStream}. Called from {@link + * #receive(WebServiceMessageFactory)}. + * + *

Default implementation does nothing. + * + * @param message the message + * @throws IOException when an I/O exception occurs + */ + protected void onReceiveAfterRead(WebServiceMessage message) throws IOException { + } - @Override - public final void close() throws IOException { - IOException ioex = null; - if (tis != null) { - try { - tis.close(); - } - catch (IOException ex) { - ioex = ex; - } - } - if (tos != null) { - try { - tos.close(); - } - catch (IOException ex) { - ioex = ex; - } - } - onClose(); - closed = true; - if (ioex != null) { - throw ioex; - } - } + @Override + public final void close() throws IOException { + IOException ioex = null; + if (tis != null) { + try { + tis.close(); + } + catch (IOException ex) { + ioex = ex; + } + } + if (tos != null) { + try { + tos.close(); + } + catch (IOException ex) { + ioex = ex; + } + } + onClose(); + closed = true; + if (ioex != null) { + throw ioex; + } + } - private void checkClosed() { - if (closed) { - throw new IllegalStateException("Connection has been closed and cannot be reused."); - } - } + private void checkClosed() { + if (closed) { + throw new IllegalStateException("Connection has been closed and cannot be reused."); + } + } - /** - * Template method invoked from {@link #close()}. Default implementation is empty. - * - * @throws IOException if an I/O error occurs when closing this connection - */ - protected void onClose() throws IOException { - } + /** + * Template method invoked from {@link #close()}. Default implementation is empty. + * + * @throws IOException if an I/O error occurs when closing this connection + */ + protected void onClose() throws IOException { + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/EndpointAwareWebServiceConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/EndpointAwareWebServiceConnection.java index 0c61cc01..316c534a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/EndpointAwareWebServiceConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/EndpointAwareWebServiceConnection.java @@ -28,7 +28,7 @@ import org.springframework.ws.NoEndpointFoundException; */ public interface EndpointAwareWebServiceConnection extends WebServiceConnection { - /** Called when an endpoint is not found. */ - void endpointNotFound(); + /** Called when an endpoint is not found. */ + void endpointNotFound(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/FaultAwareWebServiceConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/FaultAwareWebServiceConnection.java index b83546d1..138033a7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/FaultAwareWebServiceConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/FaultAwareWebServiceConnection.java @@ -31,35 +31,35 @@ import org.springframework.ws.soap.SoapFault; */ public interface FaultAwareWebServiceConnection extends WebServiceConnection { - /** - * Indicates whether this connection received a fault. - * - *

Typically implemented by looking at an HTTP status code. - * - * @return {@code true} if this connection received a fault; {@code false} otherwise. - * @throws IOException in case of I/O errors - */ - boolean hasFault() throws IOException; + /** + * Indicates whether this connection received a fault. + * + *

Typically implemented by looking at an HTTP status code. + * + * @return {@code true} if this connection received a fault; {@code false} otherwise. + * @throws IOException in case of I/O errors + */ + boolean hasFault() throws IOException; - /** - * Sets whether this connection will send a fault. - * - *

Typically implemented by setting an HTTP status code. - * - * @param fault {@code true} if this will send a fault; {@code false} otherwise. - * @throws IOException in case of I/O errors - * @deprecated In favor of {@link #setFaultCode(QName)} - */ - @Deprecated - void setFault(boolean fault) throws IOException; + /** + * Sets whether this connection will send a fault. + * + *

Typically implemented by setting an HTTP status code. + * + * @param fault {@code true} if this will send a fault; {@code false} otherwise. + * @throws IOException in case of I/O errors + * @deprecated In favor of {@link #setFaultCode(QName)} + */ + @Deprecated + void setFault(boolean fault) throws IOException; - /** - * Sets a specific fault code. - * - *

Typically implemented by setting an HTTP status code. - * - * @param faultCode the fault code to be set on the connection, or {@code null} for no fault. - * @throws IOException in case of I/O errors - */ - void setFaultCode(QName faultCode) throws IOException; + /** + * Sets a specific fault code. + * + *

Typically implemented by setting an HTTP status code. + * + * @param faultCode the fault code to be set on the connection, or {@code null} for no fault. + * @throws IOException in case of I/O errors + */ + void setFaultCode(QName faultCode) throws IOException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportConstants.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportConstants.java index 32404cb0..0546a546 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportConstants.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportConstants.java @@ -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, @@ -24,30 +24,30 @@ package org.springframework.ws.transport; */ public interface TransportConstants { - /** The "Accept" header. */ - String HEADER_ACCEPT = "Accept"; + /** The "Accept" header. */ + String HEADER_ACCEPT = "Accept"; - /** The "Accept-Encoding" header. */ - String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; + /** The "Accept-Encoding" header. */ + String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; - /** The "Content-Id" header. */ - String HEADER_CONTENT_ID = "Content-Id"; + /** The "Content-Id" header. */ + String HEADER_CONTENT_ID = "Content-Id"; - /** The "Content-Length" header. */ - String HEADER_CONTENT_LENGTH = "Content-Length"; + /** The "Content-Length" header. */ + String HEADER_CONTENT_LENGTH = "Content-Length"; - /** The "Content-Transfer-Encoding" header. */ - String HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; + /** The "Content-Transfer-Encoding" header. */ + String HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; - /** The "Content-Type" header. */ - String HEADER_CONTENT_TYPE = "Content-Type"; + /** The "Content-Type" header. */ + String HEADER_CONTENT_TYPE = "Content-Type"; - /** The "SOAPAction" header, used in SOAP 1.1. */ - String HEADER_SOAP_ACTION = "SOAPAction"; + /** The "SOAPAction" header, used in SOAP 1.1. */ + String HEADER_SOAP_ACTION = "SOAPAction"; - /** The "action" parameter, used to set SOAP Actions in SOAP 1.2. */ - String PARAMETER_ACTION = "action"; + /** The "action" parameter, used to set SOAP Actions in SOAP 1.2. */ + String PARAMETER_ACTION = "action"; - /** The empty SOAP action value. */ - String EMPTY_SOAP_ACTION = "\"\""; + /** The empty SOAP action value. */ + String EMPTY_SOAP_ACTION = "\"\""; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportException.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportException.java index f280806c..db6d74a2 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportException.java @@ -27,13 +27,13 @@ import java.io.IOException; @SuppressWarnings("serial") public abstract class TransportException extends IOException { - protected TransportException(String msg) { - super(msg); - } + protected TransportException(String msg) { + super(msg); + } - protected TransportException(String msg, Throwable cause) { - super(msg); - initCause(cause); - } + protected TransportException(String msg, Throwable cause) { + super(msg); + initCause(cause); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportInputStream.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportInputStream.java index 87b666c7..bd49f100 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportInputStream.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportInputStream.java @@ -33,86 +33,86 @@ import org.springframework.util.Assert; */ public abstract class TransportInputStream extends InputStream { - private InputStream inputStream; + private InputStream inputStream; - protected TransportInputStream() { - } + protected TransportInputStream() { + } - private InputStream getInputStream() throws IOException { - if (inputStream == null) { - inputStream = createInputStream(); - Assert.notNull(inputStream, "inputStream must not be null"); - } - return inputStream; - } + private InputStream getInputStream() throws IOException { + if (inputStream == null) { + inputStream = createInputStream(); + Assert.notNull(inputStream, "inputStream must not be null"); + } + return inputStream; + } - @Override - public void close() throws IOException { - getInputStream().close(); - } + @Override + public void close() throws IOException { + getInputStream().close(); + } - @Override - public int available() throws IOException { - return getInputStream().available(); - } + @Override + public int available() throws IOException { + return getInputStream().available(); + } - @Override - public synchronized void mark(int readlimit) { - try { - getInputStream().mark(readlimit); - } - catch (IOException e) { - // ignored - } - } + @Override + public synchronized void mark(int readlimit) { + try { + getInputStream().mark(readlimit); + } + catch (IOException e) { + // ignored + } + } - @Override - public boolean markSupported() { - try { - return getInputStream().markSupported(); - } - catch (IOException e) { - return false; - } - } + @Override + public boolean markSupported() { + try { + return getInputStream().markSupported(); + } + catch (IOException e) { + return false; + } + } - @Override - public int read(byte b[]) throws IOException { - return getInputStream().read(b); - } + @Override + public int read(byte b[]) throws IOException { + return getInputStream().read(b); + } - @Override - public int read(byte b[], int off, int len) throws IOException { - return getInputStream().read(b, off, len); - } + @Override + public int read(byte b[], int off, int len) throws IOException { + return getInputStream().read(b, off, len); + } - @Override - public synchronized void reset() throws IOException { - getInputStream().reset(); - } + @Override + public synchronized void reset() throws IOException { + getInputStream().reset(); + } - @Override - public long skip(long n) throws IOException { - return getInputStream().skip(n); - } + @Override + public long skip(long n) throws IOException { + return getInputStream().skip(n); + } - @Override - public int read() throws IOException { - return getInputStream().read(); - } + @Override + public int read() throws IOException { + return getInputStream().read(); + } - /** Returns the input stream to read from. */ - protected abstract InputStream createInputStream() throws IOException; + /** Returns the input stream to read from. */ + protected abstract InputStream createInputStream() throws IOException; - /** - * Returns an iteration over all the header names this stream contains. Returns an empty {@code Iterator} if - * there are no headers. - */ - public abstract Iterator getHeaderNames() throws IOException; + /** + * Returns an iteration over all the header names this stream contains. Returns an empty {@code Iterator} if + * there are no headers. + */ + public abstract Iterator getHeaderNames() throws IOException; - /** - * Returns an iteration over all the string values of the specified header. Returns an empty {@code Iterator} - * if there are no headers of the specified name. - */ - public abstract Iterator getHeaders(String name) throws IOException; + /** + * Returns an iteration over all the string values of the specified header. Returns an empty {@code Iterator} + * if there are no headers of the specified name. + */ + public abstract Iterator getHeaders(String name) throws IOException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportOutputStream.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportOutputStream.java index 9b2709c2..c00d55e7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportOutputStream.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/TransportOutputStream.java @@ -31,53 +31,53 @@ import org.springframework.util.Assert; */ public abstract class TransportOutputStream extends OutputStream { - private OutputStream outputStream; + private OutputStream outputStream; - protected TransportOutputStream() { - } + protected TransportOutputStream() { + } - private OutputStream getOutputStream() throws IOException { - if (outputStream == null) { - outputStream = createOutputStream(); - Assert.notNull(outputStream, "outputStream must not be null"); - } - return outputStream; - } + private OutputStream getOutputStream() throws IOException { + if (outputStream == null) { + outputStream = createOutputStream(); + Assert.notNull(outputStream, "outputStream must not be null"); + } + return outputStream; + } - @Override - public void close() throws IOException { - getOutputStream().close(); - } + @Override + public void close() throws IOException { + getOutputStream().close(); + } - @Override - public void flush() throws IOException { - getOutputStream().flush(); - } + @Override + public void flush() throws IOException { + getOutputStream().flush(); + } - @Override - public void write(byte b[]) throws IOException { - getOutputStream().write(b); - } + @Override + public void write(byte b[]) throws IOException { + getOutputStream().write(b); + } - @Override - public void write(byte b[], int off, int len) throws IOException { - getOutputStream().write(b, off, len); - } + @Override + public void write(byte b[], int off, int len) throws IOException { + getOutputStream().write(b, off, len); + } - @Override - public void write(int b) throws IOException { - getOutputStream().write(b); - } + @Override + public void write(int b) throws IOException { + getOutputStream().write(b); + } - /** - * Adds a header with the given name and value. This method can be called multiple times, to allow for headers with - * multiple values. - * - * @param name the name of the header - * @param value the value of the header - */ - public abstract void addHeader(String name, String value) throws IOException; + /** + * Adds a header with the given name and value. This method can be called multiple times, to allow for headers with + * multiple values. + * + * @param name the name of the header + * @param value the value of the header + */ + public abstract void addHeader(String name, String value) throws IOException; - /** Returns the output stream to write to. */ - protected abstract OutputStream createOutputStream() throws IOException; + /** Returns the output stream to write to. */ + protected abstract OutputStream createOutputStream() throws IOException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceConnection.java index 9e55e48b..e2c62143 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceConnection.java @@ -35,50 +35,50 @@ import org.springframework.ws.WebServiceMessageFactory; */ public interface WebServiceConnection { - /** - * Sends the given message using this connection. - * - * @param message the message to be sent - * @throws IOException in case of I/O errors - */ - void send(WebServiceMessage message) throws IOException; + /** + * Sends the given message using this connection. + * + * @param message the message to be sent + * @throws IOException in case of I/O errors + */ + void send(WebServiceMessage message) throws IOException; - /** - * Receives a message using the given {@link WebServiceMessageFactory}. This method blocks until it receives, or - * returns {@code null} when no message is received. - * - * @param messageFactory the message factory used for reading messages - * @return the read message, or {@code null} if no message received - * @throws IOException in case of I/O errors - */ - WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException; + /** + * Receives a message using the given {@link WebServiceMessageFactory}. This method blocks until it receives, or + * returns {@code null} when no message is received. + * + * @param messageFactory the message factory used for reading messages + * @return the read message, or {@code null} if no message received + * @throws IOException in case of I/O errors + */ + WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException; - /** Returns the URI for this connection. */ - URI getUri() throws URISyntaxException; + /** Returns the URI for this connection. */ + URI getUri() throws URISyntaxException; - /** - * Indicates whether this connection has an error. Typically, error detection is done by inspecting connection error - * codes, etc. - * - * @return {@code true} if this connection has an error; {@code false} otherwise. - */ - boolean hasError() throws IOException; + /** + * Indicates whether this connection has an error. Typically, error detection is done by inspecting connection error + * codes, etc. + * + * @return {@code true} if this connection has an error; {@code false} otherwise. + */ + boolean hasError() throws IOException; - /** - * Returns the error message. - * - * @return the connection error message, if any; returns {@code null} when no error is present - * @see #hasError() - */ - String getErrorMessage() throws IOException; + /** + * Returns the error message. + * + * @return the connection error message, if any; returns {@code null} when no error is present + * @see #hasError() + */ + String getErrorMessage() throws IOException; - /** - * Closes this connection. - * - *

Once a connection has been closed, it is not available for further use. A new connection needs to be created. - * - * @throws IOException if an I/O error occurs when closing this connection - */ - void close() throws IOException; + /** + * Closes this connection. + * + *

Once a connection has been closed, it is not available for further use. A new connection needs to be created. + * + * @throws IOException if an I/O error occurs when closing this connection + */ + void close() throws IOException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageReceiver.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageReceiver.java index 3b693aa2..11818259 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageReceiver.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageReceiver.java @@ -27,11 +27,11 @@ import org.springframework.ws.context.MessageContext; */ public interface WebServiceMessageReceiver { - /** - * Receives the given message context. The given message context can be used to create a response. - * - * @param messageContext the message context to be received - */ - void receive(MessageContext messageContext) throws Exception; + /** + * Receives the given message context. The given message context can be used to create a response. + * + * @param messageContext the message context to be received + */ + void receive(MessageContext messageContext) throws Exception; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageSender.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageSender.java index 35335a89..8114610b 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageSender.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/WebServiceMessageSender.java @@ -33,21 +33,21 @@ import org.springframework.ws.WebServiceMessage; */ public interface WebServiceMessageSender { - /** - * Create a new {@link WebServiceConnection} to the specified URI. - * - * @param uri the URI to open a connection to - * @return the new connection - * @throws IOException in case of I/O errors - */ - WebServiceConnection createConnection(URI uri) throws IOException; + /** + * Create a new {@link WebServiceConnection} to the specified URI. + * + * @param uri the URI to open a connection to + * @return the new connection + * @throws IOException in case of I/O errors + */ + WebServiceConnection createConnection(URI uri) throws IOException; - /** - * Does this {@link WebServiceMessageSender} support the supplied URI? - * - * @param uri the URI to be checked - * @return {@code true} if this {@code WebServiceMessageSender} supports the supplied URI - */ - boolean supports(URI uri); + /** + * Does this {@link WebServiceMessageSender} support the supplied URI? + * + * @param uri the URI to be checked + * @return {@code true} if this {@code WebServiceMessageSender} supports the supplied URI + */ + boolean supports(URI uri); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/context/DefaultTransportContext.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/context/DefaultTransportContext.java index 1de51800..ec78a2dc 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/context/DefaultTransportContext.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/context/DefaultTransportContext.java @@ -27,20 +27,20 @@ import org.springframework.ws.transport.WebServiceConnection; */ public class DefaultTransportContext implements TransportContext { - private final WebServiceConnection connection; + private final WebServiceConnection connection; - /** Creates a new {@code DefaultTransportContext} that exposes the given connection. */ - public DefaultTransportContext(WebServiceConnection connection) { - Assert.notNull(connection, "'connection' must not be null"); - this.connection = connection; - } + /** Creates a new {@code DefaultTransportContext} that exposes the given connection. */ + public DefaultTransportContext(WebServiceConnection connection) { + Assert.notNull(connection, "'connection' must not be null"); + this.connection = connection; + } - @Override - public WebServiceConnection getConnection() { - return connection; - } + @Override + public WebServiceConnection getConnection() { + return connection; + } - public String toString() { - return connection.toString(); - } + public String toString() { + return connection.toString(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContext.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContext.java index a54deca6..c7fe1b6f 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContext.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContext.java @@ -12,6 +12,6 @@ import org.springframework.ws.transport.WebServiceConnection; */ public interface TransportContext { - /** Returns the current {@code WebServiceConnection}. */ - WebServiceConnection getConnection(); + /** Returns the current {@code WebServiceConnection}. */ + WebServiceConnection getConnection(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContextHolder.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContextHolder.java index 39fa7e66..3f4c266a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContextHolder.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/context/TransportContextHolder.java @@ -26,30 +26,30 @@ package org.springframework.ws.transport.context; */ public abstract class TransportContextHolder { - private static final ThreadLocal transportContextHolder = new TransportThreadLocal(); + private static final ThreadLocal transportContextHolder = new TransportThreadLocal(); - /** - * Associate the given {@code TransportContext} with the current thread. - * - * @param transportContext the current transport context, or {@code null} to reset the thread-bound context - */ - public static void setTransportContext(TransportContext transportContext) { - transportContextHolder.set(transportContext); - } + /** + * Associate the given {@code TransportContext} with the current thread. + * + * @param transportContext the current transport context, or {@code null} to reset the thread-bound context + */ + public static void setTransportContext(TransportContext transportContext) { + transportContextHolder.set(transportContext); + } - /** - * Return the {@code TransportContext} associated with the current thread, if any. - * - * @return the current transport context, or {@code null} if none - */ - public static TransportContext getTransportContext() { - return transportContextHolder.get(); - } + /** + * Return the {@code TransportContext} associated with the current thread, if any. + * + * @return the current transport context, or {@code null} if none + */ + public static TransportContext getTransportContext() { + return transportContextHolder.get(); + } - private static class TransportThreadLocal extends ThreadLocal { + private static class TransportThreadLocal extends ThreadLocal { - public String toString() { - return "Transport State"; - } - } + public String toString() { + return "Transport State"; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpSenderConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpSenderConnection.java index 4ea3e234..8cfa03c5 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpSenderConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpSenderConnection.java @@ -36,126 +36,126 @@ import org.springframework.ws.transport.WebServiceConnection; * @since 1.0.0 */ public abstract class AbstractHttpSenderConnection extends AbstractSenderConnection - implements FaultAwareWebServiceConnection { + implements FaultAwareWebServiceConnection { - /** Buffer used for reading the response, when the content length is invalid. */ - private byte[] responseBuffer; + /** Buffer used for reading the response, when the content length is invalid. */ + private byte[] responseBuffer; - @Override - public final boolean hasError() throws IOException { - return getResponseCode() / 100 != 2; - } + @Override + public final boolean hasError() throws IOException { + return getResponseCode() / 100 != 2; + } - @Override - public final String getErrorMessage() throws IOException { - StringBuilder builder = new StringBuilder(); - String responseMessage = getResponseMessage(); - if (StringUtils.hasLength(responseMessage)) { - builder.append(responseMessage); - } - builder.append(" ["); - builder.append(getResponseCode()); - builder.append(']'); - return builder.toString(); - } + @Override + public final String getErrorMessage() throws IOException { + StringBuilder builder = new StringBuilder(); + String responseMessage = getResponseMessage(); + if (StringUtils.hasLength(responseMessage)) { + builder.append(responseMessage); + } + builder.append(" ["); + builder.append(getResponseCode()); + builder.append(']'); + return builder.toString(); + } - /* - * Receiving response - */ - @Override - protected final boolean hasResponse() throws IOException { - int responseCode = getResponseCode(); - if (HttpTransportConstants.STATUS_ACCEPTED == responseCode || - HttpTransportConstants.STATUS_NO_CONTENT == responseCode) { - return false; - } - long contentLength = getResponseContentLength(); - if (contentLength < 0) { - if (responseBuffer == null) { - responseBuffer = FileCopyUtils.copyToByteArray(getRawResponseInputStream()); - } - contentLength = responseBuffer.length; - } - return contentLength > 0; - } + /* + * Receiving response + */ + @Override + protected final boolean hasResponse() throws IOException { + int responseCode = getResponseCode(); + if (HttpTransportConstants.STATUS_ACCEPTED == responseCode || + HttpTransportConstants.STATUS_NO_CONTENT == responseCode) { + return false; + } + long contentLength = getResponseContentLength(); + if (contentLength < 0) { + if (responseBuffer == null) { + responseBuffer = FileCopyUtils.copyToByteArray(getRawResponseInputStream()); + } + contentLength = responseBuffer.length; + } + return contentLength > 0; + } - @Override - protected final InputStream getResponseInputStream() throws IOException { - InputStream inputStream; - if (responseBuffer != null) { - inputStream = new ByteArrayInputStream(responseBuffer); - } - else { - inputStream = getRawResponseInputStream(); - } - return isGzipResponse() ? new GZIPInputStream(inputStream) : inputStream; - } + @Override + protected final InputStream getResponseInputStream() throws IOException { + InputStream inputStream; + if (responseBuffer != null) { + inputStream = new ByteArrayInputStream(responseBuffer); + } + else { + inputStream = getRawResponseInputStream(); + } + return isGzipResponse() ? new GZIPInputStream(inputStream) : inputStream; + } - /** Determine whether the response is a GZIP response. */ - private boolean isGzipResponse() throws IOException { - Iterator iterator = getResponseHeaders(HttpTransportConstants.HEADER_CONTENT_ENCODING); - if (iterator.hasNext()) { - String encodingHeader = iterator.next(); - return encodingHeader.toLowerCase() - .contains(HttpTransportConstants.CONTENT_ENCODING_GZIP); - } - return false; - } + /** Determine whether the response is a GZIP response. */ + private boolean isGzipResponse() throws IOException { + Iterator iterator = getResponseHeaders(HttpTransportConstants.HEADER_CONTENT_ENCODING); + if (iterator.hasNext()) { + String encodingHeader = iterator.next(); + return encodingHeader.toLowerCase() + .contains(HttpTransportConstants.CONTENT_ENCODING_GZIP); + } + return false; + } - /** Returns the HTTP status code of the response. */ - protected abstract int getResponseCode() throws IOException; + /** Returns the HTTP status code of the response. */ + protected abstract int getResponseCode() throws IOException; - /** Returns the HTTP status message of the response. */ - protected abstract String getResponseMessage() throws IOException; + /** Returns the HTTP status message of the response. */ + protected abstract String getResponseMessage() throws IOException; - /** Returns the length of the response. */ - protected abstract long getResponseContentLength() throws IOException; + /** Returns the length of the response. */ + protected abstract long getResponseContentLength() throws IOException; - /** Returns the raw, possibly compressed input stream to read the response from. */ - protected abstract InputStream getRawResponseInputStream() throws IOException; + /** Returns the raw, possibly compressed input stream to read the response from. */ + protected abstract InputStream getRawResponseInputStream() throws IOException; - /* - * Faults - */ + /* + * Faults + */ - @Override - public final boolean hasFault() throws IOException { - // SOAP 1.1 specifies a 500 status code for faults - // SOAP 1.2 specifies a 400 status code for sender faults, and 500 for all other faults - switch (getResponseCode()) { - case HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR: - return isSoap11Response() || isSoap12Response(); - case HttpTransportConstants.STATUS_BAD_REQUEST: - return isSoap12Response(); - default: - return false; - } - } + @Override + public final boolean hasFault() throws IOException { + // SOAP 1.1 specifies a 500 status code for faults + // SOAP 1.2 specifies a 400 status code for sender faults, and 500 for all other faults + switch (getResponseCode()) { + case HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR: + return isSoap11Response() || isSoap12Response(); + case HttpTransportConstants.STATUS_BAD_REQUEST: + return isSoap12Response(); + default: + return false; + } + } - /** Determine whether the response is a SOAP 1.1 message. */ - private boolean isSoap11Response() throws IOException { - Iterator iterator = getResponseHeaders(HttpTransportConstants.HEADER_CONTENT_TYPE); - if (iterator.hasNext()) { - String contentType = iterator.next().toLowerCase(); - return contentType.contains("text/xml"); - } - return false; - } + /** Determine whether the response is a SOAP 1.1 message. */ + private boolean isSoap11Response() throws IOException { + Iterator iterator = getResponseHeaders(HttpTransportConstants.HEADER_CONTENT_TYPE); + if (iterator.hasNext()) { + String contentType = iterator.next().toLowerCase(); + return contentType.contains("text/xml"); + } + return false; + } - /** Determine whether the response is a SOAP 1.1 message. */ - private boolean isSoap12Response() throws IOException { - Iterator iterator = getResponseHeaders(HttpTransportConstants.HEADER_CONTENT_TYPE); - if (iterator.hasNext()) { - String contentType = iterator.next().toLowerCase(); - return contentType.contains("application/soap+xml"); - } - return false; - } + /** Determine whether the response is a SOAP 1.1 message. */ + private boolean isSoap12Response() throws IOException { + Iterator iterator = getResponseHeaders(HttpTransportConstants.HEADER_CONTENT_TYPE); + if (iterator.hasNext()) { + String contentType = iterator.next().toLowerCase(); + return contentType.contains("application/soap+xml"); + } + return false; + } - @Override - @Deprecated - public final void setFault(boolean fault) { - } + @Override + @Deprecated + public final void setFault(boolean fault) { + } @Override public final void setFaultCode(QName faultCode) throws IOException { diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSender.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSender.java index b5da3545..ce068908 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSender.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSender.java @@ -32,35 +32,35 @@ import org.springframework.ws.transport.WebServiceMessageSender; */ public abstract class AbstractHttpWebServiceMessageSender implements WebServiceMessageSender { - /** - * Logger available to subclasses. - */ - protected final Log logger = LogFactory.getLog(getClass()); + /** + * Logger available to subclasses. + */ + protected final Log logger = LogFactory.getLog(getClass()); - private boolean acceptGzipEncoding = true; + private boolean acceptGzipEncoding = true; - /** - * Return whether to accept GZIP encoding, that is, whether to send the HTTP {@code Accept-Encoding} header - * with {@code gzip} as value. - */ - public boolean isAcceptGzipEncoding() { - return acceptGzipEncoding; - } + /** + * Return whether to accept GZIP encoding, that is, whether to send the HTTP {@code Accept-Encoding} header + * with {@code gzip} as value. + */ + public boolean isAcceptGzipEncoding() { + return acceptGzipEncoding; + } - /** - * Set whether to accept GZIP encoding, that is, whether to send the HTTP {@code Accept-Encoding} header with - * {@code gzip} as value. - * - *

Default is {@code true}. Turn this flag off if you do not want GZIP response compression even if enabled on - * the HTTP server. - */ - public void setAcceptGzipEncoding(boolean acceptGzipEncoding) { - this.acceptGzipEncoding = acceptGzipEncoding; - } + /** + * Set whether to accept GZIP encoding, that is, whether to send the HTTP {@code Accept-Encoding} header with + * {@code gzip} as value. + * + *

Default is {@code true}. Turn this flag off if you do not want GZIP response compression even if enabled on + * the HTTP server. + */ + public void setAcceptGzipEncoding(boolean acceptGzipEncoding) { + this.acceptGzipEncoding = acceptGzipEncoding; + } - @Override - public boolean supports(URI uri) { - return uri.getScheme().equals(HttpTransportConstants.HTTP_URI_SCHEME) || - uri.getScheme().equals(HttpTransportConstants.HTTPS_URI_SCHEME); - } + @Override + public boolean supports(URI uri) { + return uri.getScheme().equals(HttpTransportConstants.HTTP_URI_SCHEME) || + uri.getScheme().equals(HttpTransportConstants.HTTPS_URI_SCHEME); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpConnection.java index 2fbbc5a7..e44fcc8c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpConnection.java @@ -47,127 +47,127 @@ import org.springframework.ws.transport.WebServiceConnection; @Deprecated public class CommonsHttpConnection extends AbstractHttpSenderConnection { - private final HttpClient httpClient; + private final HttpClient httpClient; - private final PostMethod postMethod; + private final PostMethod postMethod; - private ByteArrayOutputStream requestBuffer; + private ByteArrayOutputStream requestBuffer; - private MultiThreadedHttpConnectionManager connectionManager; + private MultiThreadedHttpConnectionManager connectionManager; - protected CommonsHttpConnection(HttpClient httpClient, PostMethod postMethod) { - Assert.notNull(httpClient, "httpClient must not be null"); - Assert.notNull(postMethod, "postMethod must not be null"); - this.httpClient = httpClient; - this.postMethod = postMethod; - } + protected CommonsHttpConnection(HttpClient httpClient, PostMethod postMethod) { + Assert.notNull(httpClient, "httpClient must not be null"); + Assert.notNull(postMethod, "postMethod must not be null"); + this.httpClient = httpClient; + this.postMethod = postMethod; + } - public PostMethod getPostMethod() { - return postMethod; - } + public PostMethod getPostMethod() { + return postMethod; + } - @Override - public void onClose() throws IOException { - postMethod.releaseConnection(); - if (connectionManager != null) { - connectionManager.shutdown(); - } - } + @Override + public void onClose() throws IOException { + postMethod.releaseConnection(); + if (connectionManager != null) { + connectionManager.shutdown(); + } + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - try { - return new URI(postMethod.getURI().toString()); - } - catch (URIException ex) { - throw new URISyntaxException("", ex.getMessage()); - } - } + @Override + public URI getUri() throws URISyntaxException { + try { + return new URI(postMethod.getURI().toString()); + } + catch (URIException ex) { + throw new URISyntaxException("", ex.getMessage()); + } + } - /* - * Sending request - */ + /* + * Sending request + */ - @Override - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - requestBuffer = new ByteArrayOutputStream(); - } + @Override + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + requestBuffer = new ByteArrayOutputStream(); + } - @Override - protected void addRequestHeader(String name, String value) throws IOException { - postMethod.addRequestHeader(name, value); - } + @Override + protected void addRequestHeader(String name, String value) throws IOException { + postMethod.addRequestHeader(name, value); + } - @Override - protected OutputStream getRequestOutputStream() throws IOException { - return requestBuffer; - } + @Override + protected OutputStream getRequestOutputStream() throws IOException { + return requestBuffer; + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - postMethod.setRequestEntity(new ByteArrayRequestEntity(requestBuffer.toByteArray())); - requestBuffer = null; - try { - httpClient.executeMethod(postMethod); - } catch (IllegalStateException ex) { - if ("Connection factory has been shutdown.".equals(ex.getMessage())) { - // The application context has been closed, resulting in a connection factory shutdown and an ISE. - // Let's create a new connection factory for this connection only. - connectionManager = new MultiThreadedHttpConnectionManager(); - httpClient.setHttpConnectionManager(connectionManager); - httpClient.executeMethod(postMethod); - } else { - throw ex; - } - } - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + postMethod.setRequestEntity(new ByteArrayRequestEntity(requestBuffer.toByteArray())); + requestBuffer = null; + try { + httpClient.executeMethod(postMethod); + } catch (IllegalStateException ex) { + if ("Connection factory has been shutdown.".equals(ex.getMessage())) { + // The application context has been closed, resulting in a connection factory shutdown and an ISE. + // Let's create a new connection factory for this connection only. + connectionManager = new MultiThreadedHttpConnectionManager(); + httpClient.setHttpConnectionManager(connectionManager); + httpClient.executeMethod(postMethod); + } else { + throw ex; + } + } + } - /* - * Receiving response - */ + /* + * Receiving response + */ - @Override - protected int getResponseCode() throws IOException { - return postMethod.getStatusCode(); - } + @Override + protected int getResponseCode() throws IOException { + return postMethod.getStatusCode(); + } - @Override - protected String getResponseMessage() throws IOException { - return postMethod.getStatusText(); - } + @Override + protected String getResponseMessage() throws IOException { + return postMethod.getStatusText(); + } - @Override - protected long getResponseContentLength() throws IOException { - return postMethod.getResponseContentLength(); - } + @Override + protected long getResponseContentLength() throws IOException { + return postMethod.getResponseContentLength(); + } - @Override - protected InputStream getRawResponseInputStream() throws IOException { - return postMethod.getResponseBodyAsStream(); - } + @Override + protected InputStream getRawResponseInputStream() throws IOException { + return postMethod.getResponseBodyAsStream(); + } - @Override - protected Iterator getResponseHeaderNames() throws IOException { - Header[] headers = postMethod.getResponseHeaders(); - String[] names = new String[headers.length]; - for (int i = 0; i < headers.length; i++) { - names[i] = headers[i].getName(); - } - return Arrays.asList(names).iterator(); - } + @Override + protected Iterator getResponseHeaderNames() throws IOException { + Header[] headers = postMethod.getResponseHeaders(); + String[] names = new String[headers.length]; + for (int i = 0; i < headers.length; i++) { + names[i] = headers[i].getName(); + } + return Arrays.asList(names).iterator(); + } - @Override - protected Iterator getResponseHeaders(String name) throws IOException { - Header[] headers = postMethod.getResponseHeaders(name); - String[] values = new String[headers.length]; - for (int i = 0; i < headers.length; i++) { - values[i] = headers[i].getValue(); - } - return Arrays.asList(values).iterator(); - } + @Override + protected Iterator getResponseHeaders(String name) throws IOException { + Header[] headers = postMethod.getResponseHeaders(name); + String[] values = new String[headers.length]; + for (int i = 0; i < headers.length; i++) { + values[i] = headers[i].getValue(); + } + return Arrays.asList(values).iterator(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpMessageSender.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpMessageSender.java index 6347822a..0920ead1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpMessageSender.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/CommonsHttpMessageSender.java @@ -55,186 +55,186 @@ import org.springframework.ws.transport.WebServiceConnection; */ @Deprecated public class CommonsHttpMessageSender extends AbstractHttpWebServiceMessageSender - implements InitializingBean, DisposableBean { + implements InitializingBean, DisposableBean { - private static final int DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = (60 * 1000); + private static final int DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = (60 * 1000); - private static final int DEFAULT_READ_TIMEOUT_MILLISECONDS = (60 * 1000); + private static final int DEFAULT_READ_TIMEOUT_MILLISECONDS = (60 * 1000); - private HttpClient httpClient; + private HttpClient httpClient; - private Credentials credentials; + private Credentials credentials; - private AuthScope authScope; + private AuthScope authScope; - /** - * Create a new instance of the {@code CommonsHttpMessageSender} with a default {@link HttpClient} that uses a - * default {@link MultiThreadedHttpConnectionManager}. - */ - public CommonsHttpMessageSender() { - httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); - setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS); - setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); - } + /** + * Create a new instance of the {@code CommonsHttpMessageSender} with a default {@link HttpClient} that uses a + * default {@link MultiThreadedHttpConnectionManager}. + */ + public CommonsHttpMessageSender() { + httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); + setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS); + setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); + } - /** - * Create a new instance of the {@code CommonsHttpMessageSender} with the given {@link HttpClient} instance. - * - * @param httpClient the HttpClient instance to use for this sender - */ - public CommonsHttpMessageSender(HttpClient httpClient) { - Assert.notNull(httpClient, "httpClient must not be null"); - this.httpClient = httpClient; - } + /** + * Create a new instance of the {@code CommonsHttpMessageSender} with the given {@link HttpClient} instance. + * + * @param httpClient the HttpClient instance to use for this sender + */ + public CommonsHttpMessageSender(HttpClient httpClient) { + Assert.notNull(httpClient, "httpClient must not be null"); + this.httpClient = httpClient; + } - /** Returns the {@code HttpClient} used by this message sender. */ - public HttpClient getHttpClient() { - return httpClient; - } + /** Returns the {@code HttpClient} used by this message sender. */ + public HttpClient getHttpClient() { + return httpClient; + } - /** Set the {@code HttpClient} used by this message sender. */ - public void setHttpClient(HttpClient httpClient) { - this.httpClient = httpClient; - } + /** Set the {@code HttpClient} used by this message sender. */ + public void setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } - /** Returns the credentials to be used. */ - public Credentials getCredentials() { - return credentials; - } + /** Returns the credentials to be used. */ + public Credentials getCredentials() { + return credentials; + } - /** - * Sets the credentials to be used. If not set, no authentication is done. - * - * @see UsernamePasswordCredentials - * @see NTCredentials - */ - public void setCredentials(Credentials credentials) { - this.credentials = credentials; - } + /** + * Sets the credentials to be used. If not set, no authentication is done. + * + * @see UsernamePasswordCredentials + * @see NTCredentials + */ + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } - /** - * Sets the timeout until a connection is etablished. A value of 0 means never timeout. - * - * @param timeout the timeout value in milliseconds - * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setConnectionTimeout(int) - */ - public void setConnectionTimeout(int timeout) { - if (timeout < 0) { - throw new IllegalArgumentException("timeout must be a non-negative value"); - } - getHttpClient().getHttpConnectionManager().getParams().setConnectionTimeout(timeout); - } + /** + * Sets the timeout until a connection is etablished. A value of 0 means never timeout. + * + * @param timeout the timeout value in milliseconds + * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setConnectionTimeout(int) + */ + public void setConnectionTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout must be a non-negative value"); + } + getHttpClient().getHttpConnectionManager().getParams().setConnectionTimeout(timeout); + } - /** - * Set the socket read timeout for the underlying HttpClient. A value of 0 means never timeout. - * - * @param timeout the timeout value in milliseconds - * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setSoTimeout(int) - */ - public void setReadTimeout(int timeout) { - if (timeout < 0) { - throw new IllegalArgumentException("timeout must be a non-negative value"); - } - getHttpClient().getHttpConnectionManager().getParams().setSoTimeout(timeout); - } + /** + * Set the socket read timeout for the underlying HttpClient. A value of 0 means never timeout. + * + * @param timeout the timeout value in milliseconds + * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setSoTimeout(int) + */ + public void setReadTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout must be a non-negative value"); + } + getHttpClient().getHttpConnectionManager().getParams().setSoTimeout(timeout); + } - /** - * Sets the maximum number of connections allowed for the underlying HttpClient. - * - * @param maxTotalConnections the maximum number of connections allowed - * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setMaxTotalConnections(int) - */ - public void setMaxTotalConnections(int maxTotalConnections) { - if (maxTotalConnections <= 0) { - throw new IllegalArgumentException("maxTotalConnections must be a positive value"); - } - getHttpClient().getHttpConnectionManager().getParams().setMaxTotalConnections(maxTotalConnections); - } + /** + * Sets the maximum number of connections allowed for the underlying HttpClient. + * + * @param maxTotalConnections the maximum number of connections allowed + * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setMaxTotalConnections(int) + */ + public void setMaxTotalConnections(int maxTotalConnections) { + if (maxTotalConnections <= 0) { + throw new IllegalArgumentException("maxTotalConnections must be a positive value"); + } + getHttpClient().getHttpConnectionManager().getParams().setMaxTotalConnections(maxTotalConnections); + } - /** - * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections - * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows: - *

-     * https://www.example.com=1
-     * http://www.example.com:8080=7
-     * www.springframework.org=10
-     * *=5
-     * 
- * The host can be specified as hostname, or as URI (with scheme and port). The special host name {@code *} can be - * used to specify {@link org.apache.commons.httpclient.HostConfiguration#ANY_HOST_CONFIGURATION}. - * - * @param maxConnectionsPerHost a properties object specifying the maximum number of connection - * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setMaxConnectionsPerHost(org.apache.commons.httpclient.HostConfiguration, - * int) - */ - public void setMaxConnectionsPerHost(Map maxConnectionsPerHost) throws URIException { - for (String host : maxConnectionsPerHost.keySet()) { - HostConfiguration hostConfiguration = new HostConfiguration(); - if ("*".equals(host)) { - hostConfiguration = HostConfiguration.ANY_HOST_CONFIGURATION; - } - else if (host.startsWith("http://")) { - HttpURL httpURL = new HttpURL(host); - hostConfiguration.setHost(httpURL); - } - else if (host.startsWith("https://")) { - HttpsURL httpsURL = new HttpsURL(host); - hostConfiguration.setHost(httpsURL); - } - else { - hostConfiguration.setHost(host); - } - int maxHostConnections = Integer.parseInt(maxConnectionsPerHost.get(host)); - getHttpClient().getHttpConnectionManager().getParams() - .setMaxConnectionsPerHost(hostConfiguration, maxHostConnections); - } - } + /** + * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections + * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows: + *
+	 * https://www.example.com=1
+	 * http://www.example.com:8080=7
+	 * www.springframework.org=10
+	 * *=5
+	 * 
+ * The host can be specified as hostname, or as URI (with scheme and port). The special host name {@code *} can be + * used to specify {@link org.apache.commons.httpclient.HostConfiguration#ANY_HOST_CONFIGURATION}. + * + * @param maxConnectionsPerHost a properties object specifying the maximum number of connection + * @see org.apache.commons.httpclient.params.HttpConnectionManagerParams#setMaxConnectionsPerHost(org.apache.commons.httpclient.HostConfiguration, + * int) + */ + public void setMaxConnectionsPerHost(Map maxConnectionsPerHost) throws URIException { + for (String host : maxConnectionsPerHost.keySet()) { + HostConfiguration hostConfiguration = new HostConfiguration(); + if ("*".equals(host)) { + hostConfiguration = HostConfiguration.ANY_HOST_CONFIGURATION; + } + else if (host.startsWith("http://")) { + HttpURL httpURL = new HttpURL(host); + hostConfiguration.setHost(httpURL); + } + else if (host.startsWith("https://")) { + HttpsURL httpsURL = new HttpsURL(host); + hostConfiguration.setHost(httpsURL); + } + else { + hostConfiguration.setHost(host); + } + int maxHostConnections = Integer.parseInt(maxConnectionsPerHost.get(host)); + getHttpClient().getHttpConnectionManager().getParams() + .setMaxConnectionsPerHost(hostConfiguration, maxHostConnections); + } + } - /** - * Returns the authentication scope to be used. Only used when the {@code credentials} property has been set. - * - *

By default, the {@link AuthScope#ANY} is returned. - */ - public AuthScope getAuthScope() { - return authScope != null ? authScope : AuthScope.ANY; - } + /** + * Returns the authentication scope to be used. Only used when the {@code credentials} property has been set. + * + *

By default, the {@link AuthScope#ANY} is returned. + */ + public AuthScope getAuthScope() { + return authScope != null ? authScope : AuthScope.ANY; + } - /** - * Sets the authentication scope to be used. Only used when the {@code credentials} property has been set. - * - *

By default, the {@link AuthScope#ANY} is used. - * - * @see #setCredentials(Credentials) - */ - public void setAuthScope(AuthScope authScope) { - this.authScope = authScope; - } + /** + * Sets the authentication scope to be used. Only used when the {@code credentials} property has been set. + * + *

By default, the {@link AuthScope#ANY} is used. + * + * @see #setCredentials(Credentials) + */ + public void setAuthScope(AuthScope authScope) { + this.authScope = authScope; + } - @Override - public void afterPropertiesSet() throws Exception { - if (getCredentials() != null) { - getHttpClient().getState().setCredentials(getAuthScope(), getCredentials()); - getHttpClient().getParams().setAuthenticationPreemptive(true); - } - } + @Override + public void afterPropertiesSet() throws Exception { + if (getCredentials() != null) { + getHttpClient().getState().setCredentials(getAuthScope(), getCredentials()); + getHttpClient().getParams().setAuthenticationPreemptive(true); + } + } - @Override - public void destroy() throws Exception { - HttpConnectionManager connectionManager = getHttpClient().getHttpConnectionManager(); - if (connectionManager instanceof MultiThreadedHttpConnectionManager) { - ((MultiThreadedHttpConnectionManager) connectionManager).shutdown(); - } - } + @Override + public void destroy() throws Exception { + HttpConnectionManager connectionManager = getHttpClient().getHttpConnectionManager(); + if (connectionManager instanceof MultiThreadedHttpConnectionManager) { + ((MultiThreadedHttpConnectionManager) connectionManager).shutdown(); + } + } - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - PostMethod postMethod = new PostMethod(uri.toString()); - if (isAcceptGzipEncoding()) { - postMethod.addRequestHeader(HttpTransportConstants.HEADER_ACCEPT_ENCODING, - HttpTransportConstants.CONTENT_ENCODING_GZIP); - } - return new CommonsHttpConnection(getHttpClient(), postMethod); - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + PostMethod postMethod = new PostMethod(uri.toString()); + if (isAcceptGzipEncoding()) { + postMethod.addRequestHeader(HttpTransportConstants.HEADER_ACCEPT_ENCODING, + HttpTransportConstants.CONTENT_ENCODING_GZIP); + } + return new CommonsHttpConnection(getHttpClient(), postMethod); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsConnection.java index 70a8f920..053d6f02 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsConnection.java @@ -49,127 +49,127 @@ import org.springframework.ws.transport.WebServiceConnection; */ public class HttpComponentsConnection extends AbstractHttpSenderConnection { - private final HttpClient httpClient; + private final HttpClient httpClient; - private final HttpPost httpPost; + private final HttpPost httpPost; - private final HttpContext httpContext; + private final HttpContext httpContext; - private HttpResponse httpResponse; + private HttpResponse httpResponse; - private ByteArrayOutputStream requestBuffer; + private ByteArrayOutputStream requestBuffer; - protected HttpComponentsConnection(HttpClient httpClient, HttpPost httpPost, HttpContext httpContext) { - Assert.notNull(httpClient, "httpClient must not be null"); - Assert.notNull(httpPost, "httpPost must not be null"); - this.httpClient = httpClient; - this.httpPost = httpPost; - this.httpContext = httpContext; - } + protected HttpComponentsConnection(HttpClient httpClient, HttpPost httpPost, HttpContext httpContext) { + Assert.notNull(httpClient, "httpClient must not be null"); + Assert.notNull(httpPost, "httpPost must not be null"); + this.httpClient = httpClient; + this.httpPost = httpPost; + this.httpContext = httpContext; + } - public HttpPost getHttpPost() { - return httpPost; - } + public HttpPost getHttpPost() { + return httpPost; + } - public HttpResponse getHttpResponse() { - return httpResponse; - } + public HttpResponse getHttpResponse() { + return httpResponse; + } - @Override - public void onClose() throws IOException { - if (httpResponse != null && httpResponse.getEntity() != null) { - EntityUtils.consume(httpResponse.getEntity()); - } - } + @Override + public void onClose() throws IOException { + if (httpResponse != null && httpResponse.getEntity() != null) { + EntityUtils.consume(httpResponse.getEntity()); + } + } - /* - * URI - */ - @Override - public URI getUri() throws URISyntaxException { - return new URI(httpPost.getURI().toString()); - } + /* + * URI + */ + @Override + public URI getUri() throws URISyntaxException { + return new URI(httpPost.getURI().toString()); + } - /* - * Sending request - */ + /* + * Sending request + */ - @Override - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - requestBuffer = new ByteArrayOutputStream(); - } + @Override + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + requestBuffer = new ByteArrayOutputStream(); + } - @Override - protected void addRequestHeader(String name, String value) throws IOException { - httpPost.addHeader(name, value); - } + @Override + protected void addRequestHeader(String name, String value) throws IOException { + httpPost.addHeader(name, value); + } - @Override - protected OutputStream getRequestOutputStream() throws IOException { - return requestBuffer; - } + @Override + protected OutputStream getRequestOutputStream() throws IOException { + return requestBuffer; + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - httpPost.setEntity(new ByteArrayEntity(requestBuffer.toByteArray())); - requestBuffer = null; - if (httpContext != null) { - httpResponse = httpClient.execute(httpPost, httpContext); - } - else { - httpResponse = httpClient.execute(httpPost); - } - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + httpPost.setEntity(new ByteArrayEntity(requestBuffer.toByteArray())); + requestBuffer = null; + if (httpContext != null) { + httpResponse = httpClient.execute(httpPost, httpContext); + } + else { + httpResponse = httpClient.execute(httpPost); + } + } - /* - * Receiving response - */ + /* + * Receiving response + */ - @Override - protected int getResponseCode() throws IOException { - return httpResponse.getStatusLine().getStatusCode(); - } + @Override + protected int getResponseCode() throws IOException { + return httpResponse.getStatusLine().getStatusCode(); + } - @Override - protected String getResponseMessage() throws IOException { - return httpResponse.getStatusLine().getReasonPhrase(); - } + @Override + protected String getResponseMessage() throws IOException { + return httpResponse.getStatusLine().getReasonPhrase(); + } - @Override - protected long getResponseContentLength() throws IOException { - HttpEntity entity = httpResponse.getEntity(); - if (entity != null) { - return entity.getContentLength(); - } - return 0; - } + @Override + protected long getResponseContentLength() throws IOException { + HttpEntity entity = httpResponse.getEntity(); + if (entity != null) { + return entity.getContentLength(); + } + return 0; + } - @Override - protected InputStream getRawResponseInputStream() throws IOException { - HttpEntity entity = httpResponse.getEntity(); - if (entity != null) { - return entity.getContent(); - } - throw new IllegalStateException("Response has no enclosing response entity, cannot create input stream"); - } + @Override + protected InputStream getRawResponseInputStream() throws IOException { + HttpEntity entity = httpResponse.getEntity(); + if (entity != null) { + return entity.getContent(); + } + throw new IllegalStateException("Response has no enclosing response entity, cannot create input stream"); + } - @Override - protected Iterator getResponseHeaderNames() throws IOException { - Header[] headers = httpResponse.getAllHeaders(); - String[] names = new String[headers.length]; - for (int i = 0; i < headers.length; i++) { - names[i] = headers[i].getName(); - } - return Arrays.asList(names).iterator(); - } + @Override + protected Iterator getResponseHeaderNames() throws IOException { + Header[] headers = httpResponse.getAllHeaders(); + String[] names = new String[headers.length]; + for (int i = 0; i < headers.length; i++) { + names[i] = headers[i].getName(); + } + return Arrays.asList(names).iterator(); + } - @Override - protected Iterator getResponseHeaders(String name) throws IOException { - Header[] headers = httpResponse.getHeaders(name); - String[] values = new String[headers.length]; - for (int i = 0; i < headers.length; i++) { - values[i] = headers[i].getValue(); - } - return Arrays.asList(values).iterator(); - } + @Override + protected Iterator getResponseHeaders(String name) throws IOException { + Header[] headers = httpResponse.getHeaders(name); + String[] values = new String[headers.length]; + for (int i = 0; i < headers.length; i++) { + values[i] = headers[i].getValue(); + } + return Arrays.asList(values).iterator(); + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsMessageSender.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsMessageSender.java index cfe50d4b..1e3075ba 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsMessageSender.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpComponentsMessageSender.java @@ -56,217 +56,217 @@ import org.springframework.ws.transport.WebServiceConnection; */ @SuppressWarnings("deprecation") public class HttpComponentsMessageSender extends AbstractHttpWebServiceMessageSender - implements InitializingBean, DisposableBean { + implements InitializingBean, DisposableBean { - private static final int DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = (60 * 1000); + private static final int DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = (60 * 1000); - private static final int DEFAULT_READ_TIMEOUT_MILLISECONDS = (60 * 1000); + private static final int DEFAULT_READ_TIMEOUT_MILLISECONDS = (60 * 1000); - private HttpClient httpClient; + private HttpClient httpClient; - private Credentials credentials; + private Credentials credentials; - private AuthScope authScope = AuthScope.ANY; + private AuthScope authScope = AuthScope.ANY; - /** - * Create a new instance of the {@code HttpClientMessageSender} with a default {@link HttpClient} that uses a - * default {@link org.apache.http.impl.conn.PoolingClientConnectionManager}. - */ - public HttpComponentsMessageSender() { - org.apache.http.impl.client.DefaultHttpClient defaultClient = - new org.apache.http.impl.client.DefaultHttpClient(new org.apache.http.impl.conn.PoolingClientConnectionManager()); - defaultClient.addRequestInterceptor(new RemoveSoapHeadersInterceptor(), 0); + /** + * Create a new instance of the {@code HttpClientMessageSender} with a default {@link HttpClient} that uses a + * default {@link org.apache.http.impl.conn.PoolingClientConnectionManager}. + */ + public HttpComponentsMessageSender() { + org.apache.http.impl.client.DefaultHttpClient defaultClient = + new org.apache.http.impl.client.DefaultHttpClient(new org.apache.http.impl.conn.PoolingClientConnectionManager()); + defaultClient.addRequestInterceptor(new RemoveSoapHeadersInterceptor(), 0); - this.httpClient = defaultClient; - setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS); - setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); - } + this.httpClient = defaultClient; + setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS); + setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); + } - /** - * Create a new instance of the {@code HttpClientMessageSender} with the given - * {@link HttpClient} instance. - *

- * This constructor does not change the given {@code HttpClient} in any way. As such, - * it does not set timeouts, nor does it - * {@linkplain org.apache.http.impl.client.DefaultHttpClient#addRequestInterceptor(org.apache.http.HttpRequestInterceptor) add} - * the {@link RemoveSoapHeadersInterceptor}. - * - * @param httpClient the HttpClient instance to use for this sender - */ - public HttpComponentsMessageSender(HttpClient httpClient) { - Assert.notNull(httpClient, "httpClient must not be null"); - this.httpClient = httpClient; - } + /** + * Create a new instance of the {@code HttpClientMessageSender} with the given + * {@link HttpClient} instance. + *

+ * This constructor does not change the given {@code HttpClient} in any way. As such, + * it does not set timeouts, nor does it + * {@linkplain org.apache.http.impl.client.DefaultHttpClient#addRequestInterceptor(org.apache.http.HttpRequestInterceptor) add} + * the {@link RemoveSoapHeadersInterceptor}. + * + * @param httpClient the HttpClient instance to use for this sender + */ + public HttpComponentsMessageSender(HttpClient httpClient) { + Assert.notNull(httpClient, "httpClient must not be null"); + this.httpClient = httpClient; + } - /** - * Sets the credentials to be used. If not set, no authentication is done. - * - * @see UsernamePasswordCredentials - * @see org.apache.http.auth.NTCredentials - */ - public void setCredentials(Credentials credentials) { - this.credentials = credentials; - } + /** + * Sets the credentials to be used. If not set, no authentication is done. + * + * @see UsernamePasswordCredentials + * @see org.apache.http.auth.NTCredentials + */ + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } - /** - * Returns the {@code HttpClient} used by this message sender. - */ - public HttpClient getHttpClient() { - return httpClient; - } + /** + * Returns the {@code HttpClient} used by this message sender. + */ + public HttpClient getHttpClient() { + return httpClient; + } - /** - * Set the {@code HttpClient} used by this message sender. - */ - public void setHttpClient(HttpClient httpClient) { - this.httpClient = httpClient; - } + /** + * Set the {@code HttpClient} used by this message sender. + */ + public void setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } - /** - * Sets the timeout until a connection is established. A value of 0 means never timeout. - * - * @param timeout the timeout value in milliseconds - * @see org.apache.http.params.HttpConnectionParams#setConnectionTimeout(org.apache.http.params.HttpParams, int) - */ - public void setConnectionTimeout(int timeout) { - if (timeout < 0) { - throw new IllegalArgumentException("timeout must be a non-negative value"); - } - org.apache.http.params.HttpConnectionParams.setConnectionTimeout(getHttpClient().getParams(), timeout); - } + /** + * Sets the timeout until a connection is established. A value of 0 means never timeout. + * + * @param timeout the timeout value in milliseconds + * @see org.apache.http.params.HttpConnectionParams#setConnectionTimeout(org.apache.http.params.HttpParams, int) + */ + public void setConnectionTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout must be a non-negative value"); + } + org.apache.http.params.HttpConnectionParams.setConnectionTimeout(getHttpClient().getParams(), timeout); + } - /** - * Set the socket read timeout for the underlying HttpClient. A value of 0 means never timeout. - * - * @param timeout the timeout value in milliseconds - * @see org.apache.http.params.HttpConnectionParams#setSoTimeout(org.apache.http.params.HttpParams, int) - */ - public void setReadTimeout(int timeout) { - if (timeout < 0) { - throw new IllegalArgumentException("timeout must be a non-negative value"); - } - org.apache.http.params.HttpConnectionParams.setSoTimeout(getHttpClient().getParams(), timeout); - } + /** + * Set the socket read timeout for the underlying HttpClient. A value of 0 means never timeout. + * + * @param timeout the timeout value in milliseconds + * @see org.apache.http.params.HttpConnectionParams#setSoTimeout(org.apache.http.params.HttpParams, int) + */ + public void setReadTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout must be a non-negative value"); + } + org.apache.http.params.HttpConnectionParams.setSoTimeout(getHttpClient().getParams(), timeout); + } - /** - * Sets the maximum number of connections allowed for the underlying HttpClient. - * - * @param maxTotalConnections the maximum number of connections allowed - * @see org.apache.http.impl.conn.PoolingClientConnectionManager#setMaxTotal(int) - */ - public void setMaxTotalConnections(int maxTotalConnections) { - if (maxTotalConnections <= 0) { - throw new IllegalArgumentException("maxTotalConnections must be a positive value"); - } - org.apache.http.conn.ClientConnectionManager connectionManager = getHttpClient().getConnectionManager(); - if (!(connectionManager instanceof org.apache.http.impl.conn.PoolingClientConnectionManager)) { - throw new IllegalArgumentException("maxTotalConnections is not supported on " + - connectionManager.getClass().getName() + ". Use " + org.apache.http.impl.conn.PoolingClientConnectionManager.class.getName() + - " instead"); - } - ((org.apache.http.impl.conn.PoolingClientConnectionManager) connectionManager).setMaxTotal(maxTotalConnections); - } + /** + * Sets the maximum number of connections allowed for the underlying HttpClient. + * + * @param maxTotalConnections the maximum number of connections allowed + * @see org.apache.http.impl.conn.PoolingClientConnectionManager#setMaxTotal(int) + */ + public void setMaxTotalConnections(int maxTotalConnections) { + if (maxTotalConnections <= 0) { + throw new IllegalArgumentException("maxTotalConnections must be a positive value"); + } + org.apache.http.conn.ClientConnectionManager connectionManager = getHttpClient().getConnectionManager(); + if (!(connectionManager instanceof org.apache.http.impl.conn.PoolingClientConnectionManager)) { + throw new IllegalArgumentException("maxTotalConnections is not supported on " + + connectionManager.getClass().getName() + ". Use " + org.apache.http.impl.conn.PoolingClientConnectionManager.class.getName() + + " instead"); + } + ((org.apache.http.impl.conn.PoolingClientConnectionManager) connectionManager).setMaxTotal(maxTotalConnections); + } - /** - * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections - * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows: - * - *

-     * https://www.example.com=1
-     * http://www.example.com:8080=7
-     * http://www.springframework.org=10
-     * 
- * - *

The host can be specified as a URI (with scheme and port). - * - * @param maxConnectionsPerHost a properties object specifying the maximum number of connection - * @see org.apache.http.impl.conn.PoolingClientConnectionManager#setMaxPerRoute(HttpRoute, int) - */ - public void setMaxConnectionsPerHost(Map maxConnectionsPerHost) throws URISyntaxException { - org.apache.http.conn.ClientConnectionManager connectionManager = getHttpClient().getConnectionManager(); - if (!(connectionManager instanceof org.apache.http.impl.conn.PoolingClientConnectionManager)) { - throw new IllegalArgumentException("maxConnectionsPerHost is not supported on " + - connectionManager.getClass().getName() + ". Use " + org.apache.http.impl.conn.PoolingClientConnectionManager.class.getName() + - " instead"); - } - org.apache.http.impl.conn.PoolingClientConnectionManager poolingConnectionManager = - (org.apache.http.impl.conn.PoolingClientConnectionManager) connectionManager; + /** + * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections + * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows: + * + *

+	 * https://www.example.com=1
+	 * http://www.example.com:8080=7
+	 * http://www.springframework.org=10
+	 * 
+ * + *

The host can be specified as a URI (with scheme and port). + * + * @param maxConnectionsPerHost a properties object specifying the maximum number of connection + * @see org.apache.http.impl.conn.PoolingClientConnectionManager#setMaxPerRoute(HttpRoute, int) + */ + public void setMaxConnectionsPerHost(Map maxConnectionsPerHost) throws URISyntaxException { + org.apache.http.conn.ClientConnectionManager connectionManager = getHttpClient().getConnectionManager(); + if (!(connectionManager instanceof org.apache.http.impl.conn.PoolingClientConnectionManager)) { + throw new IllegalArgumentException("maxConnectionsPerHost is not supported on " + + connectionManager.getClass().getName() + ". Use " + org.apache.http.impl.conn.PoolingClientConnectionManager.class.getName() + + " instead"); + } + org.apache.http.impl.conn.PoolingClientConnectionManager poolingConnectionManager = + (org.apache.http.impl.conn.PoolingClientConnectionManager) connectionManager; - for (Map.Entry entry : maxConnectionsPerHost.entrySet()) { - URI uri = new URI(entry.getKey()); - HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); - HttpRoute route = new HttpRoute(host); + for (Map.Entry entry : maxConnectionsPerHost.entrySet()) { + URI uri = new URI(entry.getKey()); + HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); + HttpRoute route = new HttpRoute(host); - int max = Integer.parseInt(entry.getValue()); + int max = Integer.parseInt(entry.getValue()); - poolingConnectionManager.setMaxPerRoute(route, max); - } - } + poolingConnectionManager.setMaxPerRoute(route, max); + } + } - /** - * Sets the authentication scope to be used. Only used when the {@code credentials} property has been set. - * - *

By default, the {@link AuthScope#ANY} is used. - * - * @see #setCredentials(Credentials) - */ - public void setAuthScope(AuthScope authScope) { - this.authScope = authScope; - } + /** + * Sets the authentication scope to be used. Only used when the {@code credentials} property has been set. + * + *

By default, the {@link AuthScope#ANY} is used. + * + * @see #setCredentials(Credentials) + */ + public void setAuthScope(AuthScope authScope) { + this.authScope = authScope; + } - @Override - public void afterPropertiesSet() throws Exception { - if (credentials != null && - getHttpClient() instanceof org.apache.http.impl.client.DefaultHttpClient) { - ((org.apache.http.impl.client.DefaultHttpClient) getHttpClient()) - .getCredentialsProvider().setCredentials(authScope, credentials); - } - } + @Override + public void afterPropertiesSet() throws Exception { + if (credentials != null && + getHttpClient() instanceof org.apache.http.impl.client.DefaultHttpClient) { + ((org.apache.http.impl.client.DefaultHttpClient) getHttpClient()) + .getCredentialsProvider().setCredentials(authScope, credentials); + } + } - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - HttpPost httpPost = new HttpPost(uri); - if (isAcceptGzipEncoding()) { - httpPost.addHeader(HttpTransportConstants.HEADER_ACCEPT_ENCODING, - HttpTransportConstants.CONTENT_ENCODING_GZIP); - } - HttpContext httpContext = createContext(uri); - return new HttpComponentsConnection(getHttpClient(), httpPost, httpContext); - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + HttpPost httpPost = new HttpPost(uri); + if (isAcceptGzipEncoding()) { + httpPost.addHeader(HttpTransportConstants.HEADER_ACCEPT_ENCODING, + HttpTransportConstants.CONTENT_ENCODING_GZIP); + } + HttpContext httpContext = createContext(uri); + return new HttpComponentsConnection(getHttpClient(), httpPost, httpContext); + } - /** - * Template method that allows for creation of a {@link HttpContext} for the given uri. Default implementation - * returns {@code null}. - * - * @param uri the URI to create the context for - * @return the context, or {@code null} - */ - protected HttpContext createContext(URI uri) { - return null; - } + /** + * Template method that allows for creation of a {@link HttpContext} for the given uri. Default implementation + * returns {@code null}. + * + * @param uri the URI to create the context for + * @return the context, or {@code null} + */ + protected HttpContext createContext(URI uri) { + return null; + } - @Override - public void destroy() throws Exception { - getHttpClient().getConnectionManager().shutdown(); - } + @Override + public void destroy() throws Exception { + getHttpClient().getConnectionManager().shutdown(); + } - /** - * HttpClient {@link org.apache.http.HttpRequestInterceptor} implementation that removes {@code Content-Length} and - * {@code Transfer-Encoding} headers from the request. Necessary, because some SAAJ and other SOAP implementations set these - * headers themselves, and HttpClient throws an exception if they have been set. - */ - public static class RemoveSoapHeadersInterceptor implements HttpRequestInterceptor { + /** + * HttpClient {@link org.apache.http.HttpRequestInterceptor} implementation that removes {@code Content-Length} and + * {@code Transfer-Encoding} headers from the request. Necessary, because some SAAJ and other SOAP implementations set these + * headers themselves, and HttpClient throws an exception if they have been set. + */ + public static class RemoveSoapHeadersInterceptor implements HttpRequestInterceptor { - @Override - public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { - if (request instanceof HttpEntityEnclosingRequest) { - if (request.containsHeader(HTTP.TRANSFER_ENCODING)) { - request.removeHeaders(HTTP.TRANSFER_ENCODING); - } - if (request.containsHeader(HTTP.CONTENT_LEN)) { - request.removeHeaders(HTTP.CONTENT_LEN); - } - } - } - } + @Override + public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { + if (request instanceof HttpEntityEnclosingRequest) { + if (request.containsHeader(HTTP.TRANSFER_ENCODING)) { + request.removeHeaders(HTTP.TRANSFER_ENCODING); + } + if (request.containsHeader(HTTP.CONTENT_LEN)) { + request.removeHeaders(HTTP.CONTENT_LEN); + } + } + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpServletConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpServletConnection.java index df7edc96..b75a7e82 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpServletConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpServletConnection.java @@ -41,131 +41,131 @@ import org.springframework.ws.transport.support.EnumerationIterator; * @since 1.0.0 */ public class HttpServletConnection extends AbstractReceiverConnection - implements EndpointAwareWebServiceConnection, FaultAwareWebServiceConnection { + implements EndpointAwareWebServiceConnection, FaultAwareWebServiceConnection { - private final HttpServletRequest httpServletRequest; + private final HttpServletRequest httpServletRequest; - private final HttpServletResponse httpServletResponse; + private final HttpServletResponse httpServletResponse; - private boolean statusCodeSet = false; + private boolean statusCodeSet = false; - /** - * Constructs a new servlet connection with the given {@code HttpServletRequest} and - * {@code HttpServletResponse}. - */ - protected HttpServletConnection(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { - this.httpServletRequest = httpServletRequest; - this.httpServletResponse = httpServletResponse; - } + /** + * Constructs a new servlet connection with the given {@code HttpServletRequest} and + * {@code HttpServletResponse}. + */ + protected HttpServletConnection(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { + this.httpServletRequest = httpServletRequest; + this.httpServletResponse = httpServletResponse; + } - /** Returns the {@code HttpServletRequest} for this connection. */ - public HttpServletRequest getHttpServletRequest() { - return httpServletRequest; - } + /** Returns the {@code HttpServletRequest} for this connection. */ + public HttpServletRequest getHttpServletRequest() { + return httpServletRequest; + } - /** Returns the {@code HttpServletResponse} for this connection. */ - public HttpServletResponse getHttpServletResponse() { - return httpServletResponse; - } + /** Returns the {@code HttpServletResponse} for this connection. */ + public HttpServletResponse getHttpServletResponse() { + return httpServletResponse; + } - @Override - public void endpointNotFound() { - getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_NOT_FOUND); - statusCodeSet = true; - } + @Override + public void endpointNotFound() { + getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_NOT_FOUND); + statusCodeSet = true; + } - /* - * Errors - */ + /* + * Errors + */ - @Override - public boolean hasError() throws IOException { - return false; - } + @Override + public boolean hasError() throws IOException { + return false; + } - @Override - public String getErrorMessage() throws IOException { - return null; - } + @Override + public String getErrorMessage() throws IOException { + return null; + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - return new URI(httpServletRequest.getScheme(), null, httpServletRequest.getServerName(), - httpServletRequest.getServerPort(), httpServletRequest.getRequestURI(), - httpServletRequest.getQueryString(), null); - } + @Override + public URI getUri() throws URISyntaxException { + return new URI(httpServletRequest.getScheme(), null, httpServletRequest.getServerName(), + httpServletRequest.getServerPort(), httpServletRequest.getRequestURI(), + httpServletRequest.getQueryString(), null); + } - /* - * Receiving request - */ + /* + * Receiving request + */ - @Override - @SuppressWarnings("unchecked") - protected Iterator getRequestHeaderNames() throws IOException { - return new EnumerationIterator(getHttpServletRequest().getHeaderNames()); - } + @Override + @SuppressWarnings("unchecked") + protected Iterator getRequestHeaderNames() throws IOException { + return new EnumerationIterator(getHttpServletRequest().getHeaderNames()); + } - @Override - @SuppressWarnings("unchecked") - protected Iterator getRequestHeaders(String name) throws IOException { - return new EnumerationIterator(getHttpServletRequest().getHeaders(name)); - } + @Override + @SuppressWarnings("unchecked") + protected Iterator getRequestHeaders(String name) throws IOException { + return new EnumerationIterator(getHttpServletRequest().getHeaders(name)); + } - @Override - protected InputStream getRequestInputStream() throws IOException { - return getHttpServletRequest().getInputStream(); - } + @Override + protected InputStream getRequestInputStream() throws IOException { + return getHttpServletRequest().getInputStream(); + } - /* - * Sending response - */ + /* + * Sending response + */ - @Override - protected void addResponseHeader(String name, String value) throws IOException { - getHttpServletResponse().addHeader(name, value); - } + @Override + protected void addResponseHeader(String name, String value) throws IOException { + getHttpServletResponse().addHeader(name, value); + } - @Override - protected OutputStream getResponseOutputStream() throws IOException { - return getHttpServletResponse().getOutputStream(); - } + @Override + protected OutputStream getResponseOutputStream() throws IOException { + return getHttpServletResponse().getOutputStream(); + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - statusCodeSet = true; - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + statusCodeSet = true; + } - @Override - public void onClose() throws IOException { - if (!statusCodeSet) { - getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_ACCEPTED); - } - } + @Override + public void onClose() throws IOException { + if (!statusCodeSet) { + getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_ACCEPTED); + } + } - /* - * Faults - */ + /* + * Faults + */ - @Override - public boolean hasFault() throws IOException { - return false; - } + @Override + public boolean hasFault() throws IOException { + return false; + } - @Override - @Deprecated - public void setFault(boolean fault) throws IOException { - if (fault) { - getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR); - } - else { - getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_OK); - } - statusCodeSet = true; - } + @Override + @Deprecated + public void setFault(boolean fault) throws IOException { + if (fault) { + getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR); + } + else { + getHttpServletResponse().setStatus(HttpTransportConstants.STATUS_OK); + } + statusCodeSet = true; + } @Override public void setFaultCode(QName faultCode) throws IOException { diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportConstants.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportConstants.java index 22edf8d5..2ab71dae 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportConstants.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportConstants.java @@ -26,45 +26,45 @@ import org.springframework.ws.transport.TransportConstants; */ public interface HttpTransportConstants extends TransportConstants { - /** The "Content-Encoding" header. */ - String HEADER_CONTENT_ENCODING = "Content-Encoding"; + /** The "Content-Encoding" header. */ + String HEADER_CONTENT_ENCODING = "Content-Encoding"; - /** The "Accept-Encoding" header. */ - String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; + /** The "Accept-Encoding" header. */ + String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; - /** Header value that indicates a compressed "Content-Encoding". */ - String CONTENT_ENCODING_GZIP = "gzip"; + /** Header value that indicates a compressed "Content-Encoding". */ + String CONTENT_ENCODING_GZIP = "gzip"; - /** The "200 OK" status code. */ - int STATUS_OK = 200; + /** The "200 OK" status code. */ + int STATUS_OK = 200; - /** The "202 Accepted" status code. */ - int STATUS_ACCEPTED = 202; + /** The "202 Accepted" status code. */ + int STATUS_ACCEPTED = 202; - /** The "204 No Content" status code. */ - int STATUS_NO_CONTENT = 204; + /** The "204 No Content" status code. */ + int STATUS_NO_CONTENT = 204; - /** The "400 Bad Request" status code. */ - int STATUS_BAD_REQUEST = 400; + /** The "400 Bad Request" status code. */ + int STATUS_BAD_REQUEST = 400; - /** The "404 Not Found" status code. */ - int STATUS_NOT_FOUND = 404; + /** The "404 Not Found" status code. */ + int STATUS_NOT_FOUND = 404; - /** The "405 Method Not Allowed" status code. */ - int STATUS_METHOD_NOT_ALLOWED = 405; + /** The "405 Method Not Allowed" status code. */ + int STATUS_METHOD_NOT_ALLOWED = 405; - /** The "500 Server Error" status code. */ - int STATUS_INTERNAL_SERVER_ERROR = 500; + /** The "500 Server Error" status code. */ + int STATUS_INTERNAL_SERVER_ERROR = 500; - /** The "http" URI scheme. */ - String HTTP_URI_SCHEME = "http"; + /** The "http" URI scheme. */ + String HTTP_URI_SCHEME = "http"; - /** The "https" URI scheme. */ - String HTTPS_URI_SCHEME = "https"; + /** The "https" URI scheme. */ + String HTTPS_URI_SCHEME = "https"; - /** The "GET" HTTP method */ - String METHOD_GET = "GET"; + /** The "GET" HTTP method */ + String METHOD_GET = "GET"; - /** The "POST" HTTP method */ - String METHOD_POST = "POST"; + /** The "POST" HTTP method */ + String METHOD_POST = "POST"; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportException.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportException.java index daf647a9..d0680061 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpTransportException.java @@ -27,13 +27,13 @@ import org.springframework.ws.transport.TransportException; @SuppressWarnings("serial") public class HttpTransportException extends TransportException { - public HttpTransportException(String msg) { - super(msg); - } + public HttpTransportException(String msg) { + super(msg); + } - protected HttpTransportException(String msg, Throwable cause) { - super(msg); - initCause(cause); - } + protected HttpTransportException(String msg, Throwable cause) { + super(msg); + initCause(cause); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnection.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnection.java index a8436c8c..1962ca6c 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnection.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnection.java @@ -41,109 +41,109 @@ import org.springframework.ws.transport.WebServiceConnection; */ public class HttpUrlConnection extends AbstractHttpSenderConnection { - private final HttpURLConnection connection; + private final HttpURLConnection connection; - /** - * Creates a new instance of the {@code HttpUrlConnection} with the given {@code HttpURLConnection}. - * - * @param connection the {@code HttpURLConnection} - */ - protected HttpUrlConnection(HttpURLConnection connection) { - Assert.notNull(connection, "connection must not be null"); - this.connection = connection; - } + /** + * Creates a new instance of the {@code HttpUrlConnection} with the given {@code HttpURLConnection}. + * + * @param connection the {@code HttpURLConnection} + */ + protected HttpUrlConnection(HttpURLConnection connection) { + Assert.notNull(connection, "connection must not be null"); + this.connection = connection; + } - public HttpURLConnection getConnection() { - return connection; - } + public HttpURLConnection getConnection() { + return connection; + } - @Override - public void onClose() { - connection.disconnect(); - } + @Override + public void onClose() { + connection.disconnect(); + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - return new URI(StringUtils.replace(connection.getURL().toString(), " ", "%20")); - } + @Override + public URI getUri() throws URISyntaxException { + return new URI(StringUtils.replace(connection.getURL().toString(), " ", "%20")); + } - /* - * Sending request - */ + /* + * Sending request + */ - @Override - protected void addRequestHeader(String name, String value) throws IOException { - connection.addRequestProperty(name, value); - } + @Override + protected void addRequestHeader(String name, String value) throws IOException { + connection.addRequestProperty(name, value); + } - @Override - protected OutputStream getRequestOutputStream() throws IOException { - return connection.getOutputStream(); - } + @Override + protected OutputStream getRequestOutputStream() throws IOException { + return connection.getOutputStream(); + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - connection.connect(); - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + connection.connect(); + } - /* - * Receiving response - */ + /* + * Receiving response + */ - @Override - protected long getResponseContentLength() throws IOException { - return connection.getContentLength(); - } + @Override + protected long getResponseContentLength() throws IOException { + return connection.getContentLength(); + } - @Override - protected Iterator getResponseHeaderNames() throws IOException { - List headerNames = new ArrayList(); - // Header field 0 is the status line, so we start at 1 - int i = 1; - while (true) { - String headerName = connection.getHeaderFieldKey(i); - if (!StringUtils.hasLength(headerName)) { - break; - } - headerNames.add(headerName); - i++; - } - return headerNames.iterator(); - } + @Override + protected Iterator getResponseHeaderNames() throws IOException { + List headerNames = new ArrayList(); + // Header field 0 is the status line, so we start at 1 + int i = 1; + while (true) { + String headerName = connection.getHeaderFieldKey(i); + if (!StringUtils.hasLength(headerName)) { + break; + } + headerNames.add(headerName); + i++; + } + return headerNames.iterator(); + } - @Override - protected Iterator getResponseHeaders(String name) throws IOException { - String headerField = connection.getHeaderField(name); - if (headerField == null) { - return Collections.emptyList().iterator(); - } - else { - Set tokens = StringUtils.commaDelimitedListToSet(headerField); - return tokens.iterator(); - } - } + @Override + protected Iterator getResponseHeaders(String name) throws IOException { + String headerField = connection.getHeaderField(name); + if (headerField == null) { + return Collections.emptyList().iterator(); + } + else { + Set tokens = StringUtils.commaDelimitedListToSet(headerField); + return tokens.iterator(); + } + } - @Override - protected int getResponseCode() throws IOException { - return connection.getResponseCode(); - } + @Override + protected int getResponseCode() throws IOException { + return connection.getResponseCode(); + } - @Override - protected String getResponseMessage() throws IOException { - return connection.getResponseMessage(); - } + @Override + protected String getResponseMessage() throws IOException { + return connection.getResponseMessage(); + } - @Override - protected InputStream getRawResponseInputStream() throws IOException { - if (connection.getResponseCode() / 100 != 2) { - return connection.getErrorStream(); - } - else { - return connection.getInputStream(); - } - } + @Override + protected InputStream getRawResponseInputStream() throws IOException { + if (connection.getResponseCode() / 100 != 2) { + return connection.getErrorStream(); + } + else { + return connection.getInputStream(); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSender.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSender.java index fca8ecfe..3b3d0417 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSender.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSender.java @@ -38,40 +38,40 @@ import org.springframework.ws.transport.WebServiceConnection; */ public class HttpUrlConnectionMessageSender extends AbstractHttpWebServiceMessageSender { - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - URL url = uri.toURL(); - URLConnection connection = url.openConnection(); - if (!(connection instanceof HttpURLConnection)) { - throw new HttpTransportException("URI [" + uri + "] is not an HTTP URL"); - } - else { - HttpURLConnection httpURLConnection = (HttpURLConnection) connection; - prepareConnection(httpURLConnection); - return new HttpUrlConnection(httpURLConnection); - } - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + URL url = uri.toURL(); + URLConnection connection = url.openConnection(); + if (!(connection instanceof HttpURLConnection)) { + throw new HttpTransportException("URI [" + uri + "] is not an HTTP URL"); + } + else { + HttpURLConnection httpURLConnection = (HttpURLConnection) connection; + prepareConnection(httpURLConnection); + return new HttpUrlConnection(httpURLConnection); + } + } - /** - * Template method for preparing the given {@link java.net.HttpURLConnection}. - * - *

The default implementation prepares the connection for input and output, sets the HTTP method to POST, disables - * caching, and sets the {@code Accept-Encoding} header to gzip, if {@linkplain #setAcceptGzipEncoding(boolean) - * applicable}. - * - * @param connection the connection to prepare - * @throws IOException in case of I/O errors - */ - protected void prepareConnection(HttpURLConnection connection) throws IOException { - connection.setRequestMethod(HttpTransportConstants.METHOD_POST); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - if (isAcceptGzipEncoding()) { - connection.setRequestProperty(HttpTransportConstants.HEADER_ACCEPT_ENCODING, - HttpTransportConstants.CONTENT_ENCODING_GZIP); - } - } + /** + * Template method for preparing the given {@link java.net.HttpURLConnection}. + * + *

The default implementation prepares the connection for input and output, sets the HTTP method to POST, disables + * caching, and sets the {@code Accept-Encoding} header to gzip, if {@linkplain #setAcceptGzipEncoding(boolean) + * applicable}. + * + * @param connection the connection to prepare + * @throws IOException in case of I/O errors + */ + protected void prepareConnection(HttpURLConnection connection) throws IOException { + connection.setRequestMethod(HttpTransportConstants.METHOD_POST); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + if (isAcceptGzipEncoding()) { + connection.setRequestProperty(HttpTransportConstants.HEADER_ACCEPT_ENCODING, + HttpTransportConstants.CONTENT_ENCODING_GZIP); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LastModifiedHelper.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LastModifiedHelper.java index 7079cfb4..2ddf962e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LastModifiedHelper.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LastModifiedHelper.java @@ -35,41 +35,41 @@ import org.springframework.xml.transform.TraxUtils; */ class LastModifiedHelper { - private LastModifiedHelper() { - } + private LastModifiedHelper() { + } - /** - * Returns the last modified date of the given {@link Source}. - * - * @param source the source - * @return the last modified date, as a long - */ - static long getLastModified(Source source) { - if (source instanceof DOMSource) { - Document document = TraxUtils.getDocument((DOMSource) source); - return document != null ? getLastModified(document.getDocumentURI()) : -1; - } - else { - return getLastModified(source.getSystemId()); - } - } + /** + * Returns the last modified date of the given {@link Source}. + * + * @param source the source + * @return the last modified date, as a long + */ + static long getLastModified(Source source) { + if (source instanceof DOMSource) { + Document document = TraxUtils.getDocument((DOMSource) source); + return document != null ? getLastModified(document.getDocumentURI()) : -1; + } + else { + return getLastModified(source.getSystemId()); + } + } - private static long getLastModified(String systemId) { - if (StringUtils.hasText(systemId)) { - try { - URI systemIdUri = new URI(systemId); - if ("file".equals(systemIdUri.getScheme())) { - File documentFile = new File(systemIdUri); - if (documentFile.exists()) { - return documentFile.lastModified(); - } - } - } - catch (URISyntaxException e) { - // ignore - } - } - return -1; - } + private static long getLastModified(String systemId) { + if (StringUtils.hasText(systemId)) { + try { + URI systemIdUri = new URI(systemId); + if ("file".equals(systemIdUri.getScheme())) { + File documentFile = new File(systemIdUri); + if (documentFile.exists()) { + return documentFile.lastModified(); + } + } + } + catch (URISyntaxException e) { + // ignore + } + } + return -1; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LocationTransformerObjectSupport.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LocationTransformerObjectSupport.java index 31478df2..f62e2f42 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LocationTransformerObjectSupport.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/LocationTransformerObjectSupport.java @@ -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,73 +39,73 @@ import org.w3c.dom.Node; */ public abstract class LocationTransformerObjectSupport extends TransformerObjectSupport { - /** Logger available to subclasses. */ - private final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + private final Log logger = LogFactory.getLog(getClass()); - /** - * Transforms the locations of the given definition document using the given XPath expression. - * @param xPathExpression the XPath expression - * @param definitionDocument the definition document - * @param request the request, used to determine the location to transform to - */ - protected void transformLocations(XPathExpression xPathExpression, - Document definitionDocument, - HttpServletRequest request) { - Assert.notNull(xPathExpression, "'xPathExpression' must not be null"); - Assert.notNull(definitionDocument, "'definitionDocument' must not be null"); - Assert.notNull(request, "'request' must not be null"); + /** + * Transforms the locations of the given definition document using the given XPath expression. + * @param xPathExpression the XPath expression + * @param definitionDocument the definition document + * @param request the request, used to determine the location to transform to + */ + protected void transformLocations(XPathExpression xPathExpression, + Document definitionDocument, + HttpServletRequest request) { + Assert.notNull(xPathExpression, "'xPathExpression' must not be null"); + Assert.notNull(definitionDocument, "'definitionDocument' must not be null"); + Assert.notNull(request, "'request' must not be null"); - List locationNodes = xPathExpression.evaluateAsNodeList(definitionDocument); - for (Node locationNode : locationNodes) { - if (locationNode instanceof Attr) { - Attr location = (Attr) locationNode; - if (StringUtils.hasLength(location.getValue())) { - String newLocation = transformLocation(location.getValue(), request); - if (logger.isDebugEnabled()) { - logger.debug("Transforming [" + location.getValue() + "] to [" + newLocation + "]"); - } - location.setValue(newLocation); - } - } - } - } + List locationNodes = xPathExpression.evaluateAsNodeList(definitionDocument); + for (Node locationNode : locationNodes) { + if (locationNode instanceof Attr) { + Attr location = (Attr) locationNode; + if (StringUtils.hasLength(location.getValue())) { + String newLocation = transformLocation(location.getValue(), request); + if (logger.isDebugEnabled()) { + logger.debug("Transforming [" + location.getValue() + "] to [" + newLocation + "]"); + } + location.setValue(newLocation); + } + } + } + } - /** - * Transform the given location string to reflect the given request. If the given location is a full url, the - * scheme, server name, and port are changed. If it is a relative url, the scheme, server name, and port are - * prepended. Can be overridden in subclasses to change this behavior. - * - *

For instance, if the location attribute defined in the WSDL is {@code http://localhost:8080/context/services/myService}, - * and the request URI for the WSDL is {@code http://example.com:80/context/myService.wsdl}, the location - * will be changed to {@code http://example.com:80/context/services/myService}. - * - *

If the location attribute defined in the WSDL is {@code /services/myService}, and the request URI for the - * WSDL is {@code http://example.com:8080/context/myService.wsdl}, the location will be changed to - * {@code http://example.com:8080/context/services/myService}. - * - *

This method is only called when the {@code transformLocations} property is true. - */ - protected String transformLocation(String location, HttpServletRequest request) { - StringBuilder url = new StringBuilder(request.getScheme()); - url.append("://").append(request.getServerName()).append(':').append(request.getServerPort()); - if (location.startsWith("/")) { - // a relative path, prepend the context path - url.append(request.getContextPath()).append(location); - return url.toString(); - } - else { - int idx = location.indexOf("://"); - if (idx != -1) { - // a full url - idx = location.indexOf('/', idx + 3); - if (idx != -1) { - String path = location.substring(idx); - url.append(path); - return url.toString(); - } - } - } - // unknown location, return the original - return location; - } + /** + * Transform the given location string to reflect the given request. If the given location is a full url, the + * scheme, server name, and port are changed. If it is a relative url, the scheme, server name, and port are + * prepended. Can be overridden in subclasses to change this behavior. + * + *

For instance, if the location attribute defined in the WSDL is {@code http://localhost:8080/context/services/myService}, + * and the request URI for the WSDL is {@code http://example.com:80/context/myService.wsdl}, the location + * will be changed to {@code http://example.com:80/context/services/myService}. + * + *

If the location attribute defined in the WSDL is {@code /services/myService}, and the request URI for the + * WSDL is {@code http://example.com:8080/context/myService.wsdl}, the location will be changed to + * {@code http://example.com:8080/context/services/myService}. + * + *

This method is only called when the {@code transformLocations} property is true. + */ + protected String transformLocation(String location, HttpServletRequest request) { + StringBuilder url = new StringBuilder(request.getScheme()); + url.append("://").append(request.getServerName()).append(':').append(request.getServerPort()); + if (location.startsWith("/")) { + // a relative path, prepend the context path + url.append(request.getContextPath()).append(location); + return url.toString(); + } + else { + int idx = location.indexOf("://"); + if (idx != -1) { + // a full url + idx = location.indexOf('/', idx + 3); + if (idx != -1) { + String path = location.substring(idx); + url.append(path); + return url.toString(); + } + } + } + // unknown location, return the original + return location; + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/MessageDispatcherServlet.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/MessageDispatcherServlet.java index 76596a78..15b000f1 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/MessageDispatcherServlet.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/MessageDispatcherServlet.java @@ -65,422 +65,422 @@ import org.springframework.xml.xsd.XsdSchema; @SuppressWarnings("serial") public class MessageDispatcherServlet extends FrameworkServlet { - /** Well-known name for the {@link WebServiceMessageFactory} bean in the bean factory for this namespace. */ - public static final String DEFAULT_MESSAGE_FACTORY_BEAN_NAME = "messageFactory"; + /** Well-known name for the {@link WebServiceMessageFactory} bean in the bean factory for this namespace. */ + public static final String DEFAULT_MESSAGE_FACTORY_BEAN_NAME = "messageFactory"; - /** Well-known name for the {@link WebServiceMessageReceiver} object in the bean factory for this namespace. */ - public static final String DEFAULT_MESSAGE_RECEIVER_BEAN_NAME = "messageReceiver"; + /** Well-known name for the {@link WebServiceMessageReceiver} object in the bean factory for this namespace. */ + public static final String DEFAULT_MESSAGE_RECEIVER_BEAN_NAME = "messageReceiver"; - /** - * Well-known name for the {@link WebServiceMessageReceiverHandlerAdapter} object in the bean factory for this - * namespace. - */ - public static final String DEFAULT_MESSAGE_RECEIVER_HANDLER_ADAPTER_BEAN_NAME = "messageReceiverHandlerAdapter"; + /** + * Well-known name for the {@link WebServiceMessageReceiverHandlerAdapter} object in the bean factory for this + * namespace. + */ + public static final String DEFAULT_MESSAGE_RECEIVER_HANDLER_ADAPTER_BEAN_NAME = "messageReceiverHandlerAdapter"; - /** Well-known name for the {@link WsdlDefinitionHandlerAdapter} object in the bean factory for this namespace. */ - public static final String DEFAULT_WSDL_DEFINITION_HANDLER_ADAPTER_BEAN_NAME = "wsdlDefinitionHandlerAdapter"; + /** Well-known name for the {@link WsdlDefinitionHandlerAdapter} object in the bean factory for this namespace. */ + public static final String DEFAULT_WSDL_DEFINITION_HANDLER_ADAPTER_BEAN_NAME = "wsdlDefinitionHandlerAdapter"; - /** Well-known name for the {@link XsdSchemaHandlerAdapter} object in the bean factory for this namespace. */ - public static final String DEFAULT_XSD_SCHEMA_HANDLER_ADAPTER_BEAN_NAME = "xsdSchemaHandlerAdapter"; + /** Well-known name for the {@link XsdSchemaHandlerAdapter} object in the bean factory for this namespace. */ + public static final String DEFAULT_XSD_SCHEMA_HANDLER_ADAPTER_BEAN_NAME = "xsdSchemaHandlerAdapter"; - /** Suffix of a WSDL request uri. */ - private static final String WSDL_SUFFIX_NAME = ".wsdl"; + /** Suffix of a WSDL request uri. */ + private static final String WSDL_SUFFIX_NAME = ".wsdl"; - /** Suffix of a XSD request uri. */ - private static final String XSD_SUFFIX_NAME = ".xsd"; + /** Suffix of a XSD request uri. */ + private static final String XSD_SUFFIX_NAME = ".xsd"; - private final DefaultStrategiesHelper defaultStrategiesHelper; + private final DefaultStrategiesHelper defaultStrategiesHelper; - private String messageFactoryBeanName = DEFAULT_MESSAGE_FACTORY_BEAN_NAME; + private String messageFactoryBeanName = DEFAULT_MESSAGE_FACTORY_BEAN_NAME; - private String messageReceiverHandlerAdapterBeanName = DEFAULT_MESSAGE_RECEIVER_HANDLER_ADAPTER_BEAN_NAME; + private String messageReceiverHandlerAdapterBeanName = DEFAULT_MESSAGE_RECEIVER_HANDLER_ADAPTER_BEAN_NAME; - /** The {@link WebServiceMessageReceiverHandlerAdapter} used by this servlet. */ - private WebServiceMessageReceiverHandlerAdapter messageReceiverHandlerAdapter; + /** The {@link WebServiceMessageReceiverHandlerAdapter} used by this servlet. */ + private WebServiceMessageReceiverHandlerAdapter messageReceiverHandlerAdapter; - private String wsdlDefinitionHandlerAdapterBeanName = DEFAULT_WSDL_DEFINITION_HANDLER_ADAPTER_BEAN_NAME; + private String wsdlDefinitionHandlerAdapterBeanName = DEFAULT_WSDL_DEFINITION_HANDLER_ADAPTER_BEAN_NAME; - /** The {@link WsdlDefinitionHandlerAdapter} used by this servlet. */ - private WsdlDefinitionHandlerAdapter wsdlDefinitionHandlerAdapter; + /** The {@link WsdlDefinitionHandlerAdapter} used by this servlet. */ + private WsdlDefinitionHandlerAdapter wsdlDefinitionHandlerAdapter; - private String xsdSchemaHandlerAdapterBeanName = DEFAULT_XSD_SCHEMA_HANDLER_ADAPTER_BEAN_NAME; + private String xsdSchemaHandlerAdapterBeanName = DEFAULT_XSD_SCHEMA_HANDLER_ADAPTER_BEAN_NAME; - /** The {@link XsdSchemaHandlerAdapter} used by this servlet. */ - private XsdSchemaHandlerAdapter xsdSchemaHandlerAdapter; + /** The {@link XsdSchemaHandlerAdapter} used by this servlet. */ + private XsdSchemaHandlerAdapter xsdSchemaHandlerAdapter; - private String messageReceiverBeanName = DEFAULT_MESSAGE_RECEIVER_BEAN_NAME; + private String messageReceiverBeanName = DEFAULT_MESSAGE_RECEIVER_BEAN_NAME; - /** The {@link WebServiceMessageReceiver} used by this servlet. */ - private WebServiceMessageReceiver messageReceiver; + /** The {@link WebServiceMessageReceiver} used by this servlet. */ + private WebServiceMessageReceiver messageReceiver; - /** Keys are bean names, values are {@link WsdlDefinition WsdlDefinitions}. */ - private Map wsdlDefinitions; + /** Keys are bean names, values are {@link WsdlDefinition WsdlDefinitions}. */ + private Map wsdlDefinitions; - private Map xsdSchemas; + private Map xsdSchemas; - private boolean transformWsdlLocations = false; + private boolean transformWsdlLocations = false; - private boolean transformSchemaLocations = false; + private boolean transformSchemaLocations = false; - /** - * Public constructor, necessary for some Web application servers. - */ - public MessageDispatcherServlet() { - this(null); - } + /** + * Public constructor, necessary for some Web application servers. + */ + public MessageDispatcherServlet() { + this(null); + } - /** - * Constructor to support programmatic configuration of the Servlet with the specified - * web application context. This constructor is useful in Servlet 3.0+ environments - * where instance-based registration of servlets is possible through the - * {@code ServletContext#addServlet} API. - *

Using this constructor indicates that the following properties / init-params - * will be ignored: - *

    - *
  • {@link #setContextClass(Class)} / 'contextClass'
  • - *
  • {@link #setContextConfigLocation(String)} / 'contextConfigLocation'
  • - *
  • {@link #setContextAttribute(String)} / 'contextAttribute'
  • - *
  • {@link #setNamespace(String)} / 'namespace'
  • - *
- *

The given web application context may or may not yet be {@linkplain - * org.springframework.web.context.ConfigurableWebApplicationContext#refresh() refreshed}. - * If it has not already been refreshed (the recommended approach), then - * the following will occur: - *

    - *
  • If the given context does not already have a {@linkplain - * org.springframework.web.context.ConfigurableWebApplicationContext#setParent parent}, - * the root application context will be set as the parent.
  • - *
  • If the given context has not already been assigned an {@linkplain - * org.springframework.web.context.ConfigurableWebApplicationContext#setId id}, one - * will be assigned to it
  • - *
  • {@code ServletContext} and {@code ServletConfig} objects will be delegated to - * the application context
  • - *
  • {@link #postProcessWebApplicationContext} will be called
  • - *
  • Any {@code ApplicationContextInitializer}s specified through the - * "contextInitializerClasses" init-param or through the {@link - * #setContextInitializers} property will be applied.
  • - *
  • {@link org.springframework.web.context.ConfigurableWebApplicationContext#refresh refresh()} - * will be called if the context implements - * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
  • - *
- * If the context has already been refreshed, none of the above will occur, under the - * assumption that the user has performed these actions (or not) per their specific - * needs. - *

See {@link org.springframework.web.WebApplicationInitializer} for usage examples. - * - * @param webApplicationContext the context to use - * @see FrameworkServlet#FrameworkServlet(WebApplicationContext) - * @see org.springframework.web.WebApplicationInitializer - * @see #initWebApplicationContext() - * @see #configureAndRefreshWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext) - */ - public MessageDispatcherServlet(WebApplicationContext webApplicationContext) { - super(webApplicationContext); - defaultStrategiesHelper = new DefaultStrategiesHelper(MessageDispatcherServlet.class); - } + /** + * Constructor to support programmatic configuration of the Servlet with the specified + * web application context. This constructor is useful in Servlet 3.0+ environments + * where instance-based registration of servlets is possible through the + * {@code ServletContext#addServlet} API. + *

Using this constructor indicates that the following properties / init-params + * will be ignored: + *

    + *
  • {@link #setContextClass(Class)} / 'contextClass'
  • + *
  • {@link #setContextConfigLocation(String)} / 'contextConfigLocation'
  • + *
  • {@link #setContextAttribute(String)} / 'contextAttribute'
  • + *
  • {@link #setNamespace(String)} / 'namespace'
  • + *
+ *

The given web application context may or may not yet be {@linkplain + * org.springframework.web.context.ConfigurableWebApplicationContext#refresh() refreshed}. + * If it has not already been refreshed (the recommended approach), then + * the following will occur: + *

    + *
  • If the given context does not already have a {@linkplain + * org.springframework.web.context.ConfigurableWebApplicationContext#setParent parent}, + * the root application context will be set as the parent.
  • + *
  • If the given context has not already been assigned an {@linkplain + * org.springframework.web.context.ConfigurableWebApplicationContext#setId id}, one + * will be assigned to it
  • + *
  • {@code ServletContext} and {@code ServletConfig} objects will be delegated to + * the application context
  • + *
  • {@link #postProcessWebApplicationContext} will be called
  • + *
  • Any {@code ApplicationContextInitializer}s specified through the + * "contextInitializerClasses" init-param or through the {@link + * #setContextInitializers} property will be applied.
  • + *
  • {@link org.springframework.web.context.ConfigurableWebApplicationContext#refresh refresh()} + * will be called if the context implements + * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
  • + *
+ * If the context has already been refreshed, none of the above will occur, under the + * assumption that the user has performed these actions (or not) per their specific + * needs. + *

See {@link org.springframework.web.WebApplicationInitializer} for usage examples. + * + * @param webApplicationContext the context to use + * @see FrameworkServlet#FrameworkServlet(WebApplicationContext) + * @see org.springframework.web.WebApplicationInitializer + * @see #initWebApplicationContext() + * @see #configureAndRefreshWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext) + */ + public MessageDispatcherServlet(WebApplicationContext webApplicationContext) { + super(webApplicationContext); + defaultStrategiesHelper = new DefaultStrategiesHelper(MessageDispatcherServlet.class); + } - /** Returns the bean name used to lookup a {@link WebServiceMessageFactory}. */ - public String getMessageFactoryBeanName() { - return messageFactoryBeanName; - } + /** Returns the bean name used to lookup a {@link WebServiceMessageFactory}. */ + public String getMessageFactoryBeanName() { + return messageFactoryBeanName; + } - /** - * Sets the bean name used to lookup a {@link WebServiceMessageFactory}. Defaults to {@link - * #DEFAULT_MESSAGE_FACTORY_BEAN_NAME}. - */ - public void setMessageFactoryBeanName(String messageFactoryBeanName) { - this.messageFactoryBeanName = messageFactoryBeanName; - } + /** + * Sets the bean name used to lookup a {@link WebServiceMessageFactory}. Defaults to {@link + * #DEFAULT_MESSAGE_FACTORY_BEAN_NAME}. + */ + public void setMessageFactoryBeanName(String messageFactoryBeanName) { + this.messageFactoryBeanName = messageFactoryBeanName; + } - /** Returns the bean name used to lookup a {@link WebServiceMessageReceiver}. */ - public String getMessageReceiverBeanName() { - return messageReceiverBeanName; - } + /** Returns the bean name used to lookup a {@link WebServiceMessageReceiver}. */ + public String getMessageReceiverBeanName() { + return messageReceiverBeanName; + } - /** - * Sets the bean name used to lookup a {@link WebServiceMessageReceiver}. Defaults to {@link - * #DEFAULT_MESSAGE_RECEIVER_BEAN_NAME}. - */ - public void setMessageReceiverBeanName(String messageReceiverBeanName) { - this.messageReceiverBeanName = messageReceiverBeanName; - } + /** + * Sets the bean name used to lookup a {@link WebServiceMessageReceiver}. Defaults to {@link + * #DEFAULT_MESSAGE_RECEIVER_BEAN_NAME}. + */ + public void setMessageReceiverBeanName(String messageReceiverBeanName) { + this.messageReceiverBeanName = messageReceiverBeanName; + } - /** - * Indicates whether relative address locations in the WSDL are to be transformed using the request URI of the - * incoming {@link HttpServletRequest}. - */ - public boolean isTransformWsdlLocations() { - return transformWsdlLocations; - } + /** + * Indicates whether relative address locations in the WSDL are to be transformed using the request URI of the + * incoming {@link HttpServletRequest}. + */ + public boolean isTransformWsdlLocations() { + return transformWsdlLocations; + } - /** - * Sets whether relative address locations in the WSDL are to be transformed using the request URI of the incoming - * {@link HttpServletRequest}. Defaults to {@code false}. - */ - public void setTransformWsdlLocations(boolean transformWsdlLocations) { - this.transformWsdlLocations = transformWsdlLocations; - } + /** + * Sets whether relative address locations in the WSDL are to be transformed using the request URI of the incoming + * {@link HttpServletRequest}. Defaults to {@code false}. + */ + public void setTransformWsdlLocations(boolean transformWsdlLocations) { + this.transformWsdlLocations = transformWsdlLocations; + } - /** - * Indicates whether relative address locations in the XSD are to be transformed using the request URI of the - * incoming {@link HttpServletRequest}. - */ - public boolean isTransformSchemaLocations() { - return transformSchemaLocations; - } + /** + * Indicates whether relative address locations in the XSD are to be transformed using the request URI of the + * incoming {@link HttpServletRequest}. + */ + public boolean isTransformSchemaLocations() { + return transformSchemaLocations; + } - /** - * Sets whether relative address locations in the XSD are to be transformed using the request URI of the incoming - * {@link HttpServletRequest}. Defaults to {@code false}. - */ - public void setTransformSchemaLocations(boolean transformSchemaLocations) { - this.transformSchemaLocations = transformSchemaLocations; - } + /** + * Sets whether relative address locations in the XSD are to be transformed using the request URI of the incoming + * {@link HttpServletRequest}. Defaults to {@code false}. + */ + public void setTransformSchemaLocations(boolean transformSchemaLocations) { + this.transformSchemaLocations = transformSchemaLocations; + } - /** Returns the bean name used to lookup a {@link WebServiceMessageReceiverHandlerAdapter}. */ - public String getMessageReceiverHandlerAdapterBeanName() { - return messageReceiverHandlerAdapterBeanName; - } + /** Returns the bean name used to lookup a {@link WebServiceMessageReceiverHandlerAdapter}. */ + public String getMessageReceiverHandlerAdapterBeanName() { + return messageReceiverHandlerAdapterBeanName; + } - /** - * Sets the bean name used to lookup a {@link WebServiceMessageReceiverHandlerAdapter}. Defaults to {@link - * #DEFAULT_MESSAGE_RECEIVER_HANDLER_ADAPTER_BEAN_NAME}. - */ - public void setMessageReceiverHandlerAdapterBeanName(String messageReceiverHandlerAdapterBeanName) { - this.messageReceiverHandlerAdapterBeanName = messageReceiverHandlerAdapterBeanName; - } + /** + * Sets the bean name used to lookup a {@link WebServiceMessageReceiverHandlerAdapter}. Defaults to {@link + * #DEFAULT_MESSAGE_RECEIVER_HANDLER_ADAPTER_BEAN_NAME}. + */ + public void setMessageReceiverHandlerAdapterBeanName(String messageReceiverHandlerAdapterBeanName) { + this.messageReceiverHandlerAdapterBeanName = messageReceiverHandlerAdapterBeanName; + } - /** Returns the bean name used to lookup a {@link WsdlDefinitionHandlerAdapter}. */ - public String getWsdlDefinitionHandlerAdapterBeanName() { - return wsdlDefinitionHandlerAdapterBeanName; - } + /** Returns the bean name used to lookup a {@link WsdlDefinitionHandlerAdapter}. */ + public String getWsdlDefinitionHandlerAdapterBeanName() { + return wsdlDefinitionHandlerAdapterBeanName; + } - /** - * Sets the bean name used to lookup a {@link WsdlDefinitionHandlerAdapter}. Defaults to {@link - * #DEFAULT_WSDL_DEFINITION_HANDLER_ADAPTER_BEAN_NAME}. - */ - public void setWsdlDefinitionHandlerAdapterBeanName(String wsdlDefinitionHandlerAdapterBeanName) { - this.wsdlDefinitionHandlerAdapterBeanName = wsdlDefinitionHandlerAdapterBeanName; - } + /** + * Sets the bean name used to lookup a {@link WsdlDefinitionHandlerAdapter}. Defaults to {@link + * #DEFAULT_WSDL_DEFINITION_HANDLER_ADAPTER_BEAN_NAME}. + */ + public void setWsdlDefinitionHandlerAdapterBeanName(String wsdlDefinitionHandlerAdapterBeanName) { + this.wsdlDefinitionHandlerAdapterBeanName = wsdlDefinitionHandlerAdapterBeanName; + } - /** Returns the bean name used to lookup a {@link XsdSchemaHandlerAdapter}. */ - public String getXsdSchemaHandlerAdapterBeanName() { - return xsdSchemaHandlerAdapterBeanName; - } + /** Returns the bean name used to lookup a {@link XsdSchemaHandlerAdapter}. */ + public String getXsdSchemaHandlerAdapterBeanName() { + return xsdSchemaHandlerAdapterBeanName; + } - /** - * Sets the bean name used to lookup a {@link XsdSchemaHandlerAdapter}. Defaults to {@link - * #DEFAULT_XSD_SCHEMA_HANDLER_ADAPTER_BEAN_NAME}. - */ - public void setXsdSchemaHandlerAdapterBeanName(String xsdSchemaHandlerAdapterBeanName) { - this.xsdSchemaHandlerAdapterBeanName = xsdSchemaHandlerAdapterBeanName; - } + /** + * Sets the bean name used to lookup a {@link XsdSchemaHandlerAdapter}. Defaults to {@link + * #DEFAULT_XSD_SCHEMA_HANDLER_ADAPTER_BEAN_NAME}. + */ + public void setXsdSchemaHandlerAdapterBeanName(String xsdSchemaHandlerAdapterBeanName) { + this.xsdSchemaHandlerAdapterBeanName = xsdSchemaHandlerAdapterBeanName; + } - @Override - protected void doService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) - throws Exception { - WsdlDefinition definition = getWsdlDefinition(httpServletRequest); - if (definition != null) { - wsdlDefinitionHandlerAdapter.handle(httpServletRequest, httpServletResponse, definition); - return; - } - XsdSchema schema = getXsdSchema(httpServletRequest); - if (schema != null) { - xsdSchemaHandlerAdapter.handle(httpServletRequest, httpServletResponse, schema); - return; - } - messageReceiverHandlerAdapter.handle(httpServletRequest, httpServletResponse, messageReceiver); - } + @Override + protected void doService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) + throws Exception { + WsdlDefinition definition = getWsdlDefinition(httpServletRequest); + if (definition != null) { + wsdlDefinitionHandlerAdapter.handle(httpServletRequest, httpServletResponse, definition); + return; + } + XsdSchema schema = getXsdSchema(httpServletRequest); + if (schema != null) { + xsdSchemaHandlerAdapter.handle(httpServletRequest, httpServletResponse, schema); + return; + } + messageReceiverHandlerAdapter.handle(httpServletRequest, httpServletResponse, messageReceiver); + } - /** - * This implementation calls {@link #initStrategies}. - */ - @Override - protected void onRefresh(ApplicationContext context) { - initStrategies(context); - } + /** + * This implementation calls {@link #initStrategies}. + */ + @Override + protected void onRefresh(ApplicationContext context) { + initStrategies(context); + } - @Override - protected long getLastModified(HttpServletRequest httpServletRequest) { - WsdlDefinition definition = getWsdlDefinition(httpServletRequest); - if (definition != null) { - return wsdlDefinitionHandlerAdapter.getLastModified(httpServletRequest, definition); - } - XsdSchema schema = getXsdSchema(httpServletRequest); - if (schema != null) { - return xsdSchemaHandlerAdapter.getLastModified(httpServletRequest, schema); - } - return messageReceiverHandlerAdapter.getLastModified(httpServletRequest, messageReceiver); - } + @Override + protected long getLastModified(HttpServletRequest httpServletRequest) { + WsdlDefinition definition = getWsdlDefinition(httpServletRequest); + if (definition != null) { + return wsdlDefinitionHandlerAdapter.getLastModified(httpServletRequest, definition); + } + XsdSchema schema = getXsdSchema(httpServletRequest); + if (schema != null) { + return xsdSchemaHandlerAdapter.getLastModified(httpServletRequest, schema); + } + return messageReceiverHandlerAdapter.getLastModified(httpServletRequest, messageReceiver); + } - /** Returns the {@link WebServiceMessageReceiver} used by this servlet. */ - protected WebServiceMessageReceiver getMessageReceiver() { - return messageReceiver; - } + /** Returns the {@link WebServiceMessageReceiver} used by this servlet. */ + protected WebServiceMessageReceiver getMessageReceiver() { + return messageReceiver; + } - /** - * Determines the {@link WsdlDefinition} for a given request, or {@code null} if none is found. - * - *

Default implementation checks whether the request method is {@code GET}, whether the request uri ends with - * {@code ".wsdl"}, and if there is a {@code WsdlDefinition} with the same name as the filename in the - * request uri. - * - * @param request the {@code HttpServletRequest} - * @return a definition, or {@code null} - */ - protected WsdlDefinition getWsdlDefinition(HttpServletRequest request) { - if (HttpTransportConstants.METHOD_GET.equals(request.getMethod()) && - request.getRequestURI().endsWith(WSDL_SUFFIX_NAME)) { - String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI()); - return wsdlDefinitions.get(fileName); - } - else { - return null; - } - } + /** + * Determines the {@link WsdlDefinition} for a given request, or {@code null} if none is found. + * + *

Default implementation checks whether the request method is {@code GET}, whether the request uri ends with + * {@code ".wsdl"}, and if there is a {@code WsdlDefinition} with the same name as the filename in the + * request uri. + * + * @param request the {@code HttpServletRequest} + * @return a definition, or {@code null} + */ + protected WsdlDefinition getWsdlDefinition(HttpServletRequest request) { + if (HttpTransportConstants.METHOD_GET.equals(request.getMethod()) && + request.getRequestURI().endsWith(WSDL_SUFFIX_NAME)) { + String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI()); + return wsdlDefinitions.get(fileName); + } + else { + return null; + } + } - /** - * Determines the {@link XsdSchema} for a given request, or {@code null} if none is found. - * - *

Default implementation checks whether the request method is {@code GET}, whether the request uri ends with - * {@code ".xsd"}, and if there is a {@code XsdSchema} with the same name as the filename in the request - * uri. - * - * @param request the {@code HttpServletRequest} - * @return a schema, or {@code null} - */ - protected XsdSchema getXsdSchema(HttpServletRequest request) { - if (HttpTransportConstants.METHOD_GET.equals(request.getMethod()) && - request.getRequestURI().endsWith(XSD_SUFFIX_NAME)) { - String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI()); - return xsdSchemas.get(fileName); - } - else { - return null; - } - } + /** + * Determines the {@link XsdSchema} for a given request, or {@code null} if none is found. + * + *

Default implementation checks whether the request method is {@code GET}, whether the request uri ends with + * {@code ".xsd"}, and if there is a {@code XsdSchema} with the same name as the filename in the request + * uri. + * + * @param request the {@code HttpServletRequest} + * @return a schema, or {@code null} + */ + protected XsdSchema getXsdSchema(HttpServletRequest request) { + if (HttpTransportConstants.METHOD_GET.equals(request.getMethod()) && + request.getRequestURI().endsWith(XSD_SUFFIX_NAME)) { + String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI()); + return xsdSchemas.get(fileName); + } + else { + return null; + } + } - /** - * Initialize the strategy objects that this servlet uses. - *

May be overridden in subclasses in order to initialize further strategy objects. - */ - protected void initStrategies(ApplicationContext context) { - initMessageReceiverHandlerAdapter(context); - initWsdlDefinitionHandlerAdapter(context); - initXsdSchemaHandlerAdapter(context); - initMessageReceiver(context); - initWsdlDefinitions(context); - initXsdSchemas(context); - } + /** + * Initialize the strategy objects that this servlet uses. + *

May be overridden in subclasses in order to initialize further strategy objects. + */ + protected void initStrategies(ApplicationContext context) { + initMessageReceiverHandlerAdapter(context); + initWsdlDefinitionHandlerAdapter(context); + initXsdSchemaHandlerAdapter(context); + initMessageReceiver(context); + initWsdlDefinitions(context); + initXsdSchemas(context); + } - private void initMessageReceiverHandlerAdapter(ApplicationContext context) { - try { - try { - messageReceiverHandlerAdapter = context.getBean(getMessageReceiverHandlerAdapterBeanName(), - WebServiceMessageReceiverHandlerAdapter.class); - } - catch (NoSuchBeanDefinitionException ignored) { - messageReceiverHandlerAdapter = new WebServiceMessageReceiverHandlerAdapter(); - } - initWebServiceMessageFactory(context); - messageReceiverHandlerAdapter.afterPropertiesSet(); - } - catch (Exception ex) { - throw new BeanInitializationException("Could not initialize WebServiceMessageReceiverHandlerAdapter", ex); - } - } + private void initMessageReceiverHandlerAdapter(ApplicationContext context) { + try { + try { + messageReceiverHandlerAdapter = context.getBean(getMessageReceiverHandlerAdapterBeanName(), + WebServiceMessageReceiverHandlerAdapter.class); + } + catch (NoSuchBeanDefinitionException ignored) { + messageReceiverHandlerAdapter = new WebServiceMessageReceiverHandlerAdapter(); + } + initWebServiceMessageFactory(context); + messageReceiverHandlerAdapter.afterPropertiesSet(); + } + catch (Exception ex) { + throw new BeanInitializationException("Could not initialize WebServiceMessageReceiverHandlerAdapter", ex); + } + } - private void initWebServiceMessageFactory(ApplicationContext context) { - WebServiceMessageFactory messageFactory; - try { - messageFactory = context.getBean(getMessageFactoryBeanName(), WebServiceMessageFactory.class); - } - catch (NoSuchBeanDefinitionException ignored) { - messageFactory = defaultStrategiesHelper - .getDefaultStrategy(WebServiceMessageFactory.class, context); - if (logger.isDebugEnabled()) { - logger.debug("No WebServiceMessageFactory found in servlet '" + getServletName() + "': using default"); - } - } - messageReceiverHandlerAdapter.setMessageFactory(messageFactory); - } + private void initWebServiceMessageFactory(ApplicationContext context) { + WebServiceMessageFactory messageFactory; + try { + messageFactory = context.getBean(getMessageFactoryBeanName(), WebServiceMessageFactory.class); + } + catch (NoSuchBeanDefinitionException ignored) { + messageFactory = defaultStrategiesHelper + .getDefaultStrategy(WebServiceMessageFactory.class, context); + if (logger.isDebugEnabled()) { + logger.debug("No WebServiceMessageFactory found in servlet '" + getServletName() + "': using default"); + } + } + messageReceiverHandlerAdapter.setMessageFactory(messageFactory); + } - private void initWsdlDefinitionHandlerAdapter(ApplicationContext context) { - try { - try { - wsdlDefinitionHandlerAdapter = - context.getBean(getWsdlDefinitionHandlerAdapterBeanName(), WsdlDefinitionHandlerAdapter.class); + private void initWsdlDefinitionHandlerAdapter(ApplicationContext context) { + try { + try { + wsdlDefinitionHandlerAdapter = + context.getBean(getWsdlDefinitionHandlerAdapterBeanName(), WsdlDefinitionHandlerAdapter.class); - } - catch (NoSuchBeanDefinitionException ignored) { - wsdlDefinitionHandlerAdapter = new WsdlDefinitionHandlerAdapter(); - } - wsdlDefinitionHandlerAdapter.setTransformLocations(isTransformWsdlLocations()); - wsdlDefinitionHandlerAdapter.setTransformSchemaLocations(isTransformSchemaLocations()); - wsdlDefinitionHandlerAdapter.afterPropertiesSet(); - } - catch (Exception ex) { - throw new BeanInitializationException("Could not initialize WsdlDefinitionHandlerAdapter", ex); - } - } + } + catch (NoSuchBeanDefinitionException ignored) { + wsdlDefinitionHandlerAdapter = new WsdlDefinitionHandlerAdapter(); + } + wsdlDefinitionHandlerAdapter.setTransformLocations(isTransformWsdlLocations()); + wsdlDefinitionHandlerAdapter.setTransformSchemaLocations(isTransformSchemaLocations()); + wsdlDefinitionHandlerAdapter.afterPropertiesSet(); + } + catch (Exception ex) { + throw new BeanInitializationException("Could not initialize WsdlDefinitionHandlerAdapter", ex); + } + } - private void initXsdSchemaHandlerAdapter(ApplicationContext context) { - try { - try { - xsdSchemaHandlerAdapter = context - .getBean(getXsdSchemaHandlerAdapterBeanName(), XsdSchemaHandlerAdapter.class); + private void initXsdSchemaHandlerAdapter(ApplicationContext context) { + try { + try { + xsdSchemaHandlerAdapter = context + .getBean(getXsdSchemaHandlerAdapterBeanName(), XsdSchemaHandlerAdapter.class); - } - catch (NoSuchBeanDefinitionException ignored) { - xsdSchemaHandlerAdapter = new XsdSchemaHandlerAdapter(); - } - xsdSchemaHandlerAdapter.setTransformSchemaLocations(isTransformSchemaLocations()); - xsdSchemaHandlerAdapter.afterPropertiesSet(); - } - catch (Exception ex) { - throw new BeanInitializationException("Could not initialize XsdSchemaHandlerAdapter", ex); - } - } + } + catch (NoSuchBeanDefinitionException ignored) { + xsdSchemaHandlerAdapter = new XsdSchemaHandlerAdapter(); + } + xsdSchemaHandlerAdapter.setTransformSchemaLocations(isTransformSchemaLocations()); + xsdSchemaHandlerAdapter.afterPropertiesSet(); + } + catch (Exception ex) { + throw new BeanInitializationException("Could not initialize XsdSchemaHandlerAdapter", ex); + } + } - private void initMessageReceiver(ApplicationContext context) { - try { - messageReceiver = context.getBean(getMessageReceiverBeanName(), WebServiceMessageReceiver.class); - } - catch (NoSuchBeanDefinitionException ex) { - messageReceiver = defaultStrategiesHelper - .getDefaultStrategy(WebServiceMessageReceiver.class, context); - if (messageReceiver instanceof BeanNameAware) { - ((BeanNameAware) messageReceiver).setBeanName(getServletName()); - } - if (logger.isDebugEnabled()) { - logger.debug("No MessageDispatcher found in servlet '" + getServletName() + "': using default"); - } - } - } + private void initMessageReceiver(ApplicationContext context) { + try { + messageReceiver = context.getBean(getMessageReceiverBeanName(), WebServiceMessageReceiver.class); + } + catch (NoSuchBeanDefinitionException ex) { + messageReceiver = defaultStrategiesHelper + .getDefaultStrategy(WebServiceMessageReceiver.class, context); + if (messageReceiver instanceof BeanNameAware) { + ((BeanNameAware) messageReceiver).setBeanName(getServletName()); + } + if (logger.isDebugEnabled()) { + logger.debug("No MessageDispatcher found in servlet '" + getServletName() + "': using default"); + } + } + } - private void initWsdlDefinitions(ApplicationContext context) { - wsdlDefinitions = BeanFactoryUtils - .beansOfTypeIncludingAncestors(context, WsdlDefinition.class, true, false); - if (logger.isDebugEnabled()) { - for (Map.Entry entry : wsdlDefinitions.entrySet()) { - String beanName = entry.getKey(); - WsdlDefinition definition = entry.getValue(); - logger.debug("Published [" + definition + "] as " + beanName + WSDL_SUFFIX_NAME); - } - } - } + private void initWsdlDefinitions(ApplicationContext context) { + wsdlDefinitions = BeanFactoryUtils + .beansOfTypeIncludingAncestors(context, WsdlDefinition.class, true, false); + if (logger.isDebugEnabled()) { + for (Map.Entry entry : wsdlDefinitions.entrySet()) { + String beanName = entry.getKey(); + WsdlDefinition definition = entry.getValue(); + logger.debug("Published [" + definition + "] as " + beanName + WSDL_SUFFIX_NAME); + } + } + } - private void initXsdSchemas(ApplicationContext context) { - xsdSchemas = BeanFactoryUtils - .beansOfTypeIncludingAncestors(context, XsdSchema.class, true, false); - if (logger.isDebugEnabled()) { - for (Map.Entry entry : xsdSchemas.entrySet()) { - String beanName = entry.getKey(); - XsdSchema schema = entry.getValue(); - logger.debug("Published [" + schema + "] as " + beanName + XSD_SUFFIX_NAME); - } - } - } + private void initXsdSchemas(ApplicationContext context) { + xsdSchemas = BeanFactoryUtils + .beansOfTypeIncludingAncestors(context, XsdSchema.class, true, false); + if (logger.isDebugEnabled()) { + for (Map.Entry entry : xsdSchemas.entrySet()) { + String beanName = entry.getKey(); + XsdSchema schema = entry.getValue(); + logger.debug("Published [" + schema + "] as " + beanName + XSD_SUFFIX_NAME); + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapter.java index dde213a5..8ac53a3d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapter.java @@ -44,69 +44,69 @@ import org.springframework.ws.transport.support.WebServiceMessageReceiverObjectS * @since 1.0.0 */ public class WebServiceMessageReceiverHandlerAdapter extends WebServiceMessageReceiverObjectSupport - implements HandlerAdapter { + implements HandlerAdapter { - @Override - public long getLastModified(HttpServletRequest request, Object handler) { - return -1L; - } + @Override + public long getLastModified(HttpServletRequest request, Object handler) { + return -1L; + } - @Override - public ModelAndView handle(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, - Object handler) throws Exception { - if (HttpTransportConstants.METHOD_POST.equals(httpServletRequest.getMethod())) { - WebServiceConnection connection = new HttpServletConnection(httpServletRequest, httpServletResponse); - try { - handleConnection(connection, (WebServiceMessageReceiver) handler); - } - catch (InvalidXmlException ex) { - handleInvalidXmlException(httpServletRequest, httpServletResponse, handler, ex); - } - } - else { - handleNonPostMethod(httpServletRequest, httpServletResponse, handler); - } - return null; - } + @Override + public ModelAndView handle(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + Object handler) throws Exception { + if (HttpTransportConstants.METHOD_POST.equals(httpServletRequest.getMethod())) { + WebServiceConnection connection = new HttpServletConnection(httpServletRequest, httpServletResponse); + try { + handleConnection(connection, (WebServiceMessageReceiver) handler); + } + catch (InvalidXmlException ex) { + handleInvalidXmlException(httpServletRequest, httpServletResponse, handler, ex); + } + } + else { + handleNonPostMethod(httpServletRequest, httpServletResponse, handler); + } + return null; + } - @Override - public boolean supports(Object handler) { - return handler instanceof WebServiceMessageReceiver; - } + @Override + public boolean supports(Object handler) { + return handler instanceof WebServiceMessageReceiver; + } - /** - * Template method that is invoked when the request method is not {@code POST}. Called from {@link - * #handle(HttpServletRequest, HttpServletResponse, Object)}. - * - *

Default implementation set the response status to 405: Method Not Allowed. Can be overridden in subclasses. - * - * @param httpServletRequest current HTTP request - * @param httpServletResponse current HTTP response - * @param handler current handler - */ - protected void handleNonPostMethod(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, - Object handler) throws Exception { - httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - } + /** + * Template method that is invoked when the request method is not {@code POST}. Called from {@link + * #handle(HttpServletRequest, HttpServletResponse, Object)}. + * + *

Default implementation set the response status to 405: Method Not Allowed. Can be overridden in subclasses. + * + * @param httpServletRequest current HTTP request + * @param httpServletResponse current HTTP response + * @param handler current handler + */ + protected void handleNonPostMethod(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + Object handler) throws Exception { + httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } - /** - * Template method that is invoked when parsing the request results in a {@link InvalidXmlException}. Called from - * {@link #handle(HttpServletRequest, HttpServletResponse, Object)}. - * - *

Default implementation set the response status to 400: Bad Request. Can be overridden in subclasses. - * - * @param httpServletRequest current HTTP request - * @param httpServletResponse current HTTP response - * @param handler current handler - * @param ex the invalid XML exception that resulted in this method being called - */ - protected void handleInvalidXmlException(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, - Object handler, - InvalidXmlException ex) throws Exception { - httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); - } + /** + * Template method that is invoked when parsing the request results in a {@link InvalidXmlException}. Called from + * {@link #handle(HttpServletRequest, HttpServletResponse, Object)}. + * + *

Default implementation set the response status to 400: Bad Request. Can be overridden in subclasses. + * + * @param httpServletRequest current HTTP request + * @param httpServletResponse current HTTP response + * @param handler current handler + * @param ex the invalid XML exception that resulted in this method being called + */ + protected void handleInvalidXmlException(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + Object handler, + InvalidXmlException ex) throws Exception { + httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapter.java index b936b7b2..be6ee092 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapter.java @@ -68,141 +68,141 @@ import org.springframework.xml.xpath.XPathExpressionFactory; */ public class WsdlDefinitionHandlerAdapter extends LocationTransformerObjectSupport implements HandlerAdapter, InitializingBean { - /** Default XPath expression used for extracting all {@code location} attributes from the WSDL definition. */ - public static final String DEFAULT_LOCATION_EXPRESSION = "//@location"; + /** Default XPath expression used for extracting all {@code location} attributes from the WSDL definition. */ + public static final String DEFAULT_LOCATION_EXPRESSION = "//@location"; - /** Default XPath expression used for extracting all {@code schemaLocation} attributes from the WSDL definition. */ - public static final String DEFAULT_SCHEMA_LOCATION_EXPRESSION = "//@schemaLocation"; + /** Default XPath expression used for extracting all {@code schemaLocation} attributes from the WSDL definition. */ + public static final String DEFAULT_SCHEMA_LOCATION_EXPRESSION = "//@schemaLocation"; - private static final String CONTENT_TYPE = "text/xml"; + private static final String CONTENT_TYPE = "text/xml"; - private Map expressionNamespaces = new HashMap(); + private Map expressionNamespaces = new HashMap(); - private String locationExpression = DEFAULT_LOCATION_EXPRESSION; + private String locationExpression = DEFAULT_LOCATION_EXPRESSION; - private String schemaLocationExpression = DEFAULT_SCHEMA_LOCATION_EXPRESSION; + private String schemaLocationExpression = DEFAULT_SCHEMA_LOCATION_EXPRESSION; - private XPathExpression locationXPathExpression; + private XPathExpression locationXPathExpression; - private XPathExpression schemaLocationXPathExpression; + private XPathExpression schemaLocationXPathExpression; - private boolean transformLocations = false; + private boolean transformLocations = false; - private boolean transformSchemaLocations = false; + private boolean transformSchemaLocations = false; - /** - * Sets the XPath expression used for extracting the {@code location} attributes from the WSDL 1.1 definition. - * - *

Defaults to {@code DEFAULT_LOCATION_EXPRESSION}. - */ - public void setLocationExpression(String locationExpression) { - this.locationExpression = locationExpression; - } + /** + * Sets the XPath expression used for extracting the {@code location} attributes from the WSDL 1.1 definition. + * + *

Defaults to {@code DEFAULT_LOCATION_EXPRESSION}. + */ + public void setLocationExpression(String locationExpression) { + this.locationExpression = locationExpression; + } - /** - * Sets the XPath expression used for extracting the {@code schemaLocation} attributes from the WSDL 1.1 definition. - * - *

Defaults to {@code DEFAULT_SCHEMA_LOCATION_EXPRESSION}. - */ - public void setSchemaLocationExpression(String schemaLocationExpression) { - this.schemaLocationExpression = schemaLocationExpression; - } + /** + * Sets the XPath expression used for extracting the {@code schemaLocation} attributes from the WSDL 1.1 definition. + * + *

Defaults to {@code DEFAULT_SCHEMA_LOCATION_EXPRESSION}. + */ + public void setSchemaLocationExpression(String schemaLocationExpression) { + this.schemaLocationExpression = schemaLocationExpression; + } - /** - * Sets whether relative address locations in the WSDL are to be transformed using the request URI of the incoming - * {@code HttpServletRequest}. Defaults to {@code false}. - */ - public void setTransformLocations(boolean transformLocations) { - this.transformLocations = transformLocations; - } + /** + * Sets whether relative address locations in the WSDL are to be transformed using the request URI of the incoming + * {@code HttpServletRequest}. Defaults to {@code false}. + */ + public void setTransformLocations(boolean transformLocations) { + this.transformLocations = transformLocations; + } - /** - * Sets whether relative address schema locations in the WSDL are to be transformed using the request URI of the - * incoming {@code HttpServletRequest}. Defaults to {@code false}. - */ - public void setTransformSchemaLocations(boolean transformSchemaLocations) { - this.transformSchemaLocations = transformSchemaLocations; - } + /** + * Sets whether relative address schema locations in the WSDL are to be transformed using the request URI of the + * incoming {@code HttpServletRequest}. Defaults to {@code false}. + */ + public void setTransformSchemaLocations(boolean transformSchemaLocations) { + this.transformSchemaLocations = transformSchemaLocations; + } - @Override - public long getLastModified(HttpServletRequest request, Object handler) { - Source definitionSource = ((WsdlDefinition) handler).getSource(); - return LastModifiedHelper.getLastModified(definitionSource); - } + @Override + public long getLastModified(HttpServletRequest request, Object handler) { + Source definitionSource = ((WsdlDefinition) handler).getSource(); + return LastModifiedHelper.getLastModified(definitionSource); + } - @Override - public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - if (HttpTransportConstants.METHOD_GET.equals(request.getMethod())) { - WsdlDefinition definition = (WsdlDefinition) handler; + @Override + public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (HttpTransportConstants.METHOD_GET.equals(request.getMethod())) { + WsdlDefinition definition = (WsdlDefinition) handler; - Transformer transformer = createTransformer(); - Source definitionSource = definition.getSource(); + Transformer transformer = createTransformer(); + Source definitionSource = definition.getSource(); - if (transformLocations || transformSchemaLocations) { - DOMResult domResult = new DOMResult(); - transformer.transform(definitionSource, domResult); - Document definitionDocument = (Document) domResult.getNode(); - if (transformLocations) { - transformLocations(definitionDocument, request); - } - if (transformSchemaLocations) { - transformSchemaLocations(definitionDocument, request); - } - definitionSource = new DOMSource(definitionDocument); - } + if (transformLocations || transformSchemaLocations) { + DOMResult domResult = new DOMResult(); + transformer.transform(definitionSource, domResult); + Document definitionDocument = (Document) domResult.getNode(); + if (transformLocations) { + transformLocations(definitionDocument, request); + } + if (transformSchemaLocations) { + transformSchemaLocations(definitionDocument, request); + } + definitionSource = new DOMSource(definitionDocument); + } - response.setContentType(CONTENT_TYPE); - StreamResult responseResult = new StreamResult(response.getOutputStream()); - transformer.transform(definitionSource, responseResult); - } - else { - response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - } - return null; - } + response.setContentType(CONTENT_TYPE); + StreamResult responseResult = new StreamResult(response.getOutputStream()); + transformer.transform(definitionSource, responseResult); + } + else { + response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } + return null; + } - @Override - public boolean supports(Object handler) { - return handler instanceof WsdlDefinition; - } + @Override + public boolean supports(Object handler) { + return handler instanceof WsdlDefinition; + } - @Override - public void afterPropertiesSet() throws Exception { - locationXPathExpression = - XPathExpressionFactory.createXPathExpression(locationExpression, expressionNamespaces); - schemaLocationXPathExpression = - XPathExpressionFactory.createXPathExpression(schemaLocationExpression, expressionNamespaces); - } + @Override + public void afterPropertiesSet() throws Exception { + locationXPathExpression = + XPathExpressionFactory.createXPathExpression(locationExpression, expressionNamespaces); + schemaLocationXPathExpression = + XPathExpressionFactory.createXPathExpression(schemaLocationExpression, expressionNamespaces); + } - /** - * Transforms all {@code location} attributes to reflect the server name given {@code HttpServletRequest}. - * Determines the suitable attributes by evaluating the defined XPath expression, and delegates to - * {@code transformLocation} to do the transformation for all attributes that match. - * - *

This method is only called when the {@code transformLocations} property is true. - * - * @see #setLocationExpression(String) - * @see #setTransformLocations(boolean) - * @see #transformLocation(String,javax.servlet.http.HttpServletRequest) - */ - protected void transformLocations(Document definitionDocument, HttpServletRequest request) throws Exception { - transformLocations(locationXPathExpression, definitionDocument, request); - } + /** + * Transforms all {@code location} attributes to reflect the server name given {@code HttpServletRequest}. + * Determines the suitable attributes by evaluating the defined XPath expression, and delegates to + * {@code transformLocation} to do the transformation for all attributes that match. + * + *

This method is only called when the {@code transformLocations} property is true. + * + * @see #setLocationExpression(String) + * @see #setTransformLocations(boolean) + * @see #transformLocation(String,javax.servlet.http.HttpServletRequest) + */ + protected void transformLocations(Document definitionDocument, HttpServletRequest request) throws Exception { + transformLocations(locationXPathExpression, definitionDocument, request); + } - /** - * Transforms all {@code schemaLocation} attributes to reflect the server name given {@code HttpServletRequest}. - * Determines the suitable attributes by evaluating the defined XPath expression, and delegates to - * {@code transformLocation} to do the transformation for all attributes that match. - * - *

This method is only called when the {@code transformSchemaLocations} property is true. - * - * @see #setSchemaLocationExpression(String) - * @see #setTransformSchemaLocations(boolean) - * @see #transformLocation(String,javax.servlet.http.HttpServletRequest) - */ - protected void transformSchemaLocations(Document definitionDocument, HttpServletRequest request) throws Exception { - transformLocations(schemaLocationXPathExpression, definitionDocument, request); - } + /** + * Transforms all {@code schemaLocation} attributes to reflect the server name given {@code HttpServletRequest}. + * Determines the suitable attributes by evaluating the defined XPath expression, and delegates to + * {@code transformLocation} to do the transformation for all attributes that match. + * + *

This method is only called when the {@code transformSchemaLocations} property is true. + * + * @see #setSchemaLocationExpression(String) + * @see #setTransformSchemaLocations(boolean) + * @see #transformLocation(String,javax.servlet.http.HttpServletRequest) + */ + protected void transformSchemaLocations(Document definitionDocument, HttpServletRequest request) throws Exception { + transformLocations(schemaLocationXPathExpression, definitionDocument, request); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapter.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapter.java index 5858c8e4..490b3c94 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapter.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapter.java @@ -47,109 +47,109 @@ import org.springframework.xml.xsd.XsdSchema; * @since 1.5.3 */ public class XsdSchemaHandlerAdapter extends LocationTransformerObjectSupport - implements HandlerAdapter, InitializingBean { + implements HandlerAdapter, InitializingBean { - /** - * Default XPath expression used for extracting all {@code schemaLocation} attributes from the WSDL definition. - */ - public static final String DEFAULT_SCHEMA_LOCATION_EXPRESSION = "//@schemaLocation"; + /** + * Default XPath expression used for extracting all {@code schemaLocation} attributes from the WSDL definition. + */ + public static final String DEFAULT_SCHEMA_LOCATION_EXPRESSION = "//@schemaLocation"; - private static final String CONTENT_TYPE = "text/xml"; + private static final String CONTENT_TYPE = "text/xml"; - private Map expressionNamespaces = new HashMap(); + private Map expressionNamespaces = new HashMap(); - private String schemaLocationExpression = DEFAULT_SCHEMA_LOCATION_EXPRESSION; + private String schemaLocationExpression = DEFAULT_SCHEMA_LOCATION_EXPRESSION; - private XPathExpression schemaLocationXPathExpression; + private XPathExpression schemaLocationXPathExpression; - private boolean transformSchemaLocations = false; + private boolean transformSchemaLocations = false; - /** - * Sets the XPath expression used for extracting the {@code schemaLocation} attributes from the WSDL 1.1 definition. - * - *

Defaults to {@code DEFAULT_SCHEMA_LOCATION_EXPRESSION}. - */ - public void setSchemaLocationExpression(String schemaLocationExpression) { - this.schemaLocationExpression = schemaLocationExpression; - } + /** + * Sets the XPath expression used for extracting the {@code schemaLocation} attributes from the WSDL 1.1 definition. + * + *

Defaults to {@code DEFAULT_SCHEMA_LOCATION_EXPRESSION}. + */ + public void setSchemaLocationExpression(String schemaLocationExpression) { + this.schemaLocationExpression = schemaLocationExpression; + } - /** - * Sets whether relative address schema locations in the WSDL are to be transformed using the request URI of the - * incoming {@code HttpServletRequest}. Defaults to {@code false}. - */ - public void setTransformSchemaLocations(boolean transformSchemaLocations) { - this.transformSchemaLocations = transformSchemaLocations; - } + /** + * Sets whether relative address schema locations in the WSDL are to be transformed using the request URI of the + * incoming {@code HttpServletRequest}. Defaults to {@code false}. + */ + public void setTransformSchemaLocations(boolean transformSchemaLocations) { + this.transformSchemaLocations = transformSchemaLocations; + } - @Override - public long getLastModified(HttpServletRequest request, Object handler) { - Source schemaSource = ((XsdSchema) handler).getSource(); - return LastModifiedHelper.getLastModified(schemaSource); - } + @Override + public long getLastModified(HttpServletRequest request, Object handler) { + Source schemaSource = ((XsdSchema) handler).getSource(); + return LastModifiedHelper.getLastModified(schemaSource); + } - @Override - public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - if (HttpTransportConstants.METHOD_GET.equals(request.getMethod())) { - Transformer transformer = createTransformer(); - Source schemaSource = getSchemaSource((XsdSchema) handler); + @Override + public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (HttpTransportConstants.METHOD_GET.equals(request.getMethod())) { + Transformer transformer = createTransformer(); + Source schemaSource = getSchemaSource((XsdSchema) handler); - if (transformSchemaLocations) { - DOMResult domResult = new DOMResult(); - transformer.transform(schemaSource, domResult); - Document schemaDocument = (Document) domResult.getNode(); - transformSchemaLocations(schemaDocument, request); - schemaSource = new DOMSource(schemaDocument); - } + if (transformSchemaLocations) { + DOMResult domResult = new DOMResult(); + transformer.transform(schemaSource, domResult); + Document schemaDocument = (Document) domResult.getNode(); + transformSchemaLocations(schemaDocument, request); + schemaSource = new DOMSource(schemaDocument); + } - response.setContentType(CONTENT_TYPE); - StreamResult responseResult = new StreamResult(response.getOutputStream()); - transformer.transform(schemaSource, responseResult); - } - else { - response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - } - return null; - } + response.setContentType(CONTENT_TYPE); + StreamResult responseResult = new StreamResult(response.getOutputStream()); + transformer.transform(schemaSource, responseResult); + } + else { + response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } + return null; + } - @Override - public boolean supports(Object handler) { - return handler instanceof XsdSchema; - } + @Override + public boolean supports(Object handler) { + return handler instanceof XsdSchema; + } - @Override - public void afterPropertiesSet() throws Exception { - schemaLocationXPathExpression = - XPathExpressionFactory.createXPathExpression(schemaLocationExpression, expressionNamespaces); - } + @Override + public void afterPropertiesSet() throws Exception { + schemaLocationXPathExpression = + XPathExpressionFactory.createXPathExpression(schemaLocationExpression, expressionNamespaces); + } - /** - * Returns the {@link Source} of the given schema. Allows for post-processing and transformation of the schema in - * sub-classes. - * - *

Default implementation simply returns {@link XsdSchema#getSource()}. - * - * @param schema the schema - * @return the source of the given schema - * @throws Exception in case of errors - */ - protected Source getSchemaSource(XsdSchema schema) throws Exception { - return schema.getSource(); - } + /** + * Returns the {@link Source} of the given schema. Allows for post-processing and transformation of the schema in + * sub-classes. + * + *

Default implementation simply returns {@link XsdSchema#getSource()}. + * + * @param schema the schema + * @return the source of the given schema + * @throws Exception in case of errors + */ + protected Source getSchemaSource(XsdSchema schema) throws Exception { + return schema.getSource(); + } - /** - * Transforms all {@code schemaLocation} attributes to reflect the server name given {@code HttpServletRequest}. - * Determines the suitable attributes by evaluating the defined XPath expression, and delegates to {@code - * transformLocation} to do the transformation for all attributes that match. - * - *

This method is only called when the {@code transformSchemaLocations} property is true. - * - * @see #setSchemaLocationExpression(String) - * @see #transformLocation(String, javax.servlet.http.HttpServletRequest) - */ - protected void transformSchemaLocations(Document definitionDocument, HttpServletRequest request) throws Exception { - transformLocations(schemaLocationXPathExpression, definitionDocument, request); - } + /** + * Transforms all {@code schemaLocation} attributes to reflect the server name given {@code HttpServletRequest}. + * Determines the suitable attributes by evaluating the defined XPath expression, and delegates to {@code + * transformLocation} to do the transformation for all attributes that match. + * + *

This method is only called when the {@code transformSchemaLocations} property is true. + * + * @see #setSchemaLocationExpression(String) + * @see #transformLocation(String, javax.servlet.http.HttpServletRequest) + */ + protected void transformSchemaLocations(Document definitionDocument, HttpServletRequest request) throws Exception { + transformLocations(schemaLocationXPathExpression, definitionDocument, request); + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractAnnotationConfigMessageDispatcherServletInitializer.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractAnnotationConfigMessageDispatcherServletInitializer.java index a691b9d9..e8cec1a4 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractAnnotationConfigMessageDispatcherServletInitializer.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractAnnotationConfigMessageDispatcherServletInitializer.java @@ -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, diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractMessageDispatcherServletInitializer.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractMessageDispatcherServletInitializer.java index 52d51486..aa7aad9a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractMessageDispatcherServletInitializer.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/http/support/AbstractMessageDispatcherServletInitializer.java @@ -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, @@ -143,7 +143,7 @@ public abstract class AbstractMessageDispatcherServletInitializer extends */ protected boolean isTransformSchemaLocations() { return false; - } + } /** diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/support/EnumerationIterator.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/support/EnumerationIterator.java index 1b758251..0b06d250 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/support/EnumerationIterator.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/support/EnumerationIterator.java @@ -27,24 +27,24 @@ import java.util.Iterator; */ public class EnumerationIterator implements Iterator { - private final Enumeration enumeration; + private final Enumeration enumeration; - public EnumerationIterator(Enumeration enumeration) { - this.enumeration = enumeration; - } + public EnumerationIterator(Enumeration enumeration) { + this.enumeration = enumeration; + } - @Override - public boolean hasNext() { - return enumeration.hasMoreElements(); - } + @Override + public boolean hasNext() { + return enumeration.hasMoreElements(); + } - @Override - public T next() { - return enumeration.nextElement(); - } + @Override + public T next() { + return enumeration.nextElement(); + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/support/TransportUtils.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/support/TransportUtils.java index 831a70a7..5083c306 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/support/TransportUtils.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/support/TransportUtils.java @@ -31,26 +31,26 @@ import org.springframework.ws.transport.WebServiceConnection; */ public abstract class TransportUtils { - private static final Log logger = LogFactory.getLog(TransportUtils.class); + private static final Log logger = LogFactory.getLog(TransportUtils.class); - /** - * Close the given {@link WebServiceConnection} and ignore any thrown exception. This is useful for typical - * {@code finally} blocks. - * - * @param connection the web service connection to close (may be {@code null}) - */ - public static void closeConnection(WebServiceConnection connection) { - if (connection != null) { - try { - connection.close(); - } - catch (IOException ex) { - logger.debug("Could not close WebServiceConnection", ex); - } - catch (Throwable ex) { - logger.debug("Unexpected exception on closing WebServiceConnection", ex); - } - } - } + /** + * Close the given {@link WebServiceConnection} and ignore any thrown exception. This is useful for typical + * {@code finally} blocks. + * + * @param connection the web service connection to close (may be {@code null}) + */ + public static void closeConnection(WebServiceConnection connection) { + if (connection != null) { + try { + connection.close(); + } + catch (IOException ex) { + logger.debug("Could not close WebServiceConnection", ex); + } + catch (Throwable ex) { + logger.debug("Unexpected exception on closing WebServiceConnection", ex); + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupport.java b/spring-ws-core/src/main/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupport.java index 31471cd5..d3227503 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupport.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupport.java @@ -47,65 +47,65 @@ import org.springframework.ws.transport.context.TransportContextHolder; */ public abstract class WebServiceMessageReceiverObjectSupport 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 WebServiceMessageFactory messageFactory; + private WebServiceMessageFactory messageFactory; - /** Returns the {@code WebServiceMessageFactory}. */ - public WebServiceMessageFactory getMessageFactory() { - return messageFactory; - } + /** Returns the {@code WebServiceMessageFactory}. */ + public WebServiceMessageFactory getMessageFactory() { + return messageFactory; + } - /** Sets the {@code WebServiceMessageFactory}. */ - public void setMessageFactory(WebServiceMessageFactory messageFactory) { - this.messageFactory = messageFactory; - } + /** Sets the {@code WebServiceMessageFactory}. */ + public void setMessageFactory(WebServiceMessageFactory messageFactory) { + this.messageFactory = messageFactory; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(messageFactory, "messageFactory is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(messageFactory, "messageFactory is required"); + } - /** - * Handles an incoming connection by {@link WebServiceConnection#receive(WebServiceMessageFactory) receving} a - * message from it, passing it to the {@link WebServiceMessageReceiver#receive(MessageContext) receiver}, and {@link - * WebServiceConnection#send(WebServiceMessage) sending} the response (if any). - * - *

Stores the given connection in the {@link TransportContext}. - * - * @param connection the incoming connection - * @param receiver the handler of the message, typically a {@link org.springframework.ws.server.MessageDispatcher} - */ - protected final void handleConnection(WebServiceConnection connection, WebServiceMessageReceiver receiver) - throws Exception { - logUri(connection); - TransportContext previousTransportContext = TransportContextHolder.getTransportContext(); - TransportContextHolder.setTransportContext(new DefaultTransportContext(connection)); + /** + * Handles an incoming connection by {@link WebServiceConnection#receive(WebServiceMessageFactory) receving} a + * message from it, passing it to the {@link WebServiceMessageReceiver#receive(MessageContext) receiver}, and {@link + * WebServiceConnection#send(WebServiceMessage) sending} the response (if any). + * + *

Stores the given connection in the {@link TransportContext}. + * + * @param connection the incoming connection + * @param receiver the handler of the message, typically a {@link org.springframework.ws.server.MessageDispatcher} + */ + protected final void handleConnection(WebServiceConnection connection, WebServiceMessageReceiver receiver) + throws Exception { + logUri(connection); + TransportContext previousTransportContext = TransportContextHolder.getTransportContext(); + TransportContextHolder.setTransportContext(new DefaultTransportContext(connection)); - try { - WebServiceMessage request = connection.receive(getMessageFactory()); - MessageContext messageContext = new DefaultMessageContext(request, getMessageFactory()); - receiver.receive(messageContext); - if (messageContext.hasResponse()) { - WebServiceMessage response = messageContext.getResponse(); - if (response instanceof FaultAwareWebServiceMessage && - connection instanceof FaultAwareWebServiceConnection) { - FaultAwareWebServiceMessage faultResponse = (FaultAwareWebServiceMessage) response; - FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection; - faultConnection.setFaultCode(faultResponse.getFaultCode()); - } - connection.send(messageContext.getResponse()); - } - } - catch (NoEndpointFoundException ex) { - handleNoEndpointFoundException(ex, connection, receiver); - } - finally { - TransportUtils.closeConnection(connection); - TransportContextHolder.setTransportContext(previousTransportContext); - } - } + try { + WebServiceMessage request = connection.receive(getMessageFactory()); + MessageContext messageContext = new DefaultMessageContext(request, getMessageFactory()); + receiver.receive(messageContext); + if (messageContext.hasResponse()) { + WebServiceMessage response = messageContext.getResponse(); + if (response instanceof FaultAwareWebServiceMessage && + connection instanceof FaultAwareWebServiceConnection) { + FaultAwareWebServiceMessage faultResponse = (FaultAwareWebServiceMessage) response; + FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection) connection; + faultConnection.setFaultCode(faultResponse.getFaultCode()); + } + connection.send(messageContext.getResponse()); + } + } + catch (NoEndpointFoundException ex) { + handleNoEndpointFoundException(ex, connection, receiver); + } + finally { + TransportUtils.closeConnection(connection); + TransportContextHolder.setTransportContext(previousTransportContext); + } + } /** * Template method for handling {@code NoEndpointFoundException}s. @@ -128,14 +128,14 @@ public abstract class WebServiceMessageReceiverObjectSupport implements Initiali } private void logUri(WebServiceConnection connection) { - if (logger.isDebugEnabled()) { - try { - logger.debug("Accepting incoming [" + connection + "] at [" + connection.getUri() + "]"); - } - catch (URISyntaxException e) { - // ignore - } - } - } + if (logger.isDebugEnabled()) { + try { + logger.debug("Accepting incoming [" + connection + "] at [" + connection.getUri() + "]"); + } + catch (URISyntaxException e) { + // ignore + } + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinition.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinition.java index 4aac4ab5..765f7b72 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinition.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinition.java @@ -26,11 +26,11 @@ import javax.xml.transform.Source; */ public interface WsdlDefinition { - /** - * Returns the {@code Source} of the definition. - * - * @return the {@code Source} of this WSDL definition - */ - Source getSource(); + /** + * Returns the {@code Source} of the definition. + * + * @return the {@code Source} of this WSDL definition + */ + Source getSource(); } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinitionException.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinitionException.java index 3584fefa..18952f0e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinitionException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/WsdlDefinitionException.java @@ -27,11 +27,11 @@ import org.springframework.ws.WebServiceException; @SuppressWarnings("serial") public class WsdlDefinitionException extends WebServiceException { - public WsdlDefinitionException(String reason) { - super(reason); - } + public WsdlDefinitionException(String reason) { + super(reason); + } - public WsdlDefinitionException(String reason, Throwable throwable) { - super(reason, throwable); - } + public WsdlDefinitionException(String reason, Throwable throwable) { + super(reason, throwable); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11Definition.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11Definition.java index c953f38f..a73cca61 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11Definition.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11Definition.java @@ -38,13 +38,13 @@ import org.springframework.xml.xsd.XsdSchemaCollection; *

Example configuration: *

  * <bean id="airline" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
- *   <property name="schema">
- *     <bean class="org.springframework.xml.xsd.SimpleXsdSchema">
- *       <property name="xsd" value="/WEB-INF/airline.xsd"/>
- *     </bean>
- *   </property>
- *   <property name="portTypeName" value="Airline"/>
- *   <property name="locationUri" value="http://localhost:8080/airline/services"/>
+ *	 <property name="schema">
+ *	   <bean class="org.springframework.xml.xsd.SimpleXsdSchema">
+ *		 <property name="xsd" value="/WEB-INF/airline.xsd"/>
+ *	   </bean>
+ *	 </property>
+ *	 <property name="portTypeName" value="Airline"/>
+ *	 <property name="locationUri" value="http://localhost:8080/airline/services"/>
  * </bean>
  * 
* @@ -53,138 +53,138 @@ import org.springframework.xml.xsd.XsdSchemaCollection; */ public class DefaultWsdl11Definition implements Wsdl11Definition, InitializingBean { - private final InliningXsdSchemaTypesProvider typesProvider = new InliningXsdSchemaTypesProvider(); + private final InliningXsdSchemaTypesProvider typesProvider = new InliningXsdSchemaTypesProvider(); - private final SuffixBasedMessagesProvider messagesProvider = new SuffixBasedMessagesProvider(); + private final SuffixBasedMessagesProvider messagesProvider = new SuffixBasedMessagesProvider(); - private final SuffixBasedPortTypesProvider portTypesProvider = new SuffixBasedPortTypesProvider(); + private final SuffixBasedPortTypesProvider portTypesProvider = new SuffixBasedPortTypesProvider(); - private final SoapProvider soapProvider = new SoapProvider(); + private final SoapProvider soapProvider = new SoapProvider(); - private final ProviderBasedWsdl4jDefinition delegate = new ProviderBasedWsdl4jDefinition(); + private final ProviderBasedWsdl4jDefinition delegate = new ProviderBasedWsdl4jDefinition(); - private String serviceName; + private String serviceName; - /** Creates a new instance of the {@link DefaultWsdl11Definition}. */ - public DefaultWsdl11Definition() { - delegate.setTypesProvider(typesProvider); - delegate.setMessagesProvider(messagesProvider); - delegate.setPortTypesProvider(portTypesProvider); - delegate.setBindingsProvider(soapProvider); - delegate.setServicesProvider(soapProvider); - } + /** Creates a new instance of the {@link DefaultWsdl11Definition}. */ + public DefaultWsdl11Definition() { + delegate.setTypesProvider(typesProvider); + delegate.setMessagesProvider(messagesProvider); + delegate.setPortTypesProvider(portTypesProvider); + delegate.setBindingsProvider(soapProvider); + delegate.setServicesProvider(soapProvider); + } - /** - * Sets the target namespace used for this definition. - * - *

Defaults to the target namespace of the defined schema. - */ - public void setTargetNamespace(String targetNamespace) { - delegate.setTargetNamespace(targetNamespace); - } + /** + * Sets the target namespace used for this definition. + * + *

Defaults to the target namespace of the defined schema. + */ + public void setTargetNamespace(String targetNamespace) { + delegate.setTargetNamespace(targetNamespace); + } - /** - * Sets the single XSD schema to inline. Either this property, or {@link #setSchemaCollection(XsdSchemaCollection) - * schemaCollection} must be set. - */ - public void setSchema(XsdSchema schema) { - typesProvider.setSchema(schema); - } + /** + * Sets the single XSD schema to inline. Either this property, or {@link #setSchemaCollection(XsdSchemaCollection) + * schemaCollection} must be set. + */ + public void setSchema(XsdSchema schema) { + typesProvider.setSchema(schema); + } - /** - * Sets the XSD schema collection to inline. Either this property, or {@link #setSchema(XsdSchema) schema} must be - * set. - */ - public void setSchemaCollection(XsdSchemaCollection schemaCollection) { - typesProvider.setSchemaCollection(schemaCollection); - } + /** + * Sets the XSD schema collection to inline. Either this property, or {@link #setSchema(XsdSchema) schema} must be + * set. + */ + public void setSchemaCollection(XsdSchemaCollection schemaCollection) { + typesProvider.setSchemaCollection(schemaCollection); + } - /** Sets the port type name used for this definition. Required. */ - public void setPortTypeName(String portTypeName) { - portTypesProvider.setPortTypeName(portTypeName); - } + /** Sets the port type name used for this definition. Required. */ + public void setPortTypeName(String portTypeName) { + portTypesProvider.setPortTypeName(portTypeName); + } - /** Sets the suffix used to detect request elements in the schema. */ - public void setRequestSuffix(String requestSuffix) { - portTypesProvider.setRequestSuffix(requestSuffix); - messagesProvider.setRequestSuffix(requestSuffix); - } + /** Sets the suffix used to detect request elements in the schema. */ + public void setRequestSuffix(String requestSuffix) { + portTypesProvider.setRequestSuffix(requestSuffix); + messagesProvider.setRequestSuffix(requestSuffix); + } - /** Sets the suffix used to detect response elements in the schema. */ - public void setResponseSuffix(String responseSuffix) { - portTypesProvider.setResponseSuffix(responseSuffix); - messagesProvider.setResponseSuffix(responseSuffix); - } + /** Sets the suffix used to detect response elements in the schema. */ + public void setResponseSuffix(String responseSuffix) { + portTypesProvider.setResponseSuffix(responseSuffix); + messagesProvider.setResponseSuffix(responseSuffix); + } - /** Sets the suffix used to detect fault elements in the schema. */ - public void setFaultSuffix(String faultSuffix) { - portTypesProvider.setFaultSuffix(faultSuffix); - messagesProvider.setFaultSuffix(faultSuffix); - } + /** Sets the suffix used to detect fault elements in the schema. */ + public void setFaultSuffix(String faultSuffix) { + portTypesProvider.setFaultSuffix(faultSuffix); + messagesProvider.setFaultSuffix(faultSuffix); + } - /** - * Indicates whether a SOAP 1.1 binding should be created. - * - *

Defaults to {@code true}. - */ - public void setCreateSoap11Binding(boolean createSoap11Binding) { - soapProvider.setCreateSoap11Binding(createSoap11Binding); - } + /** + * Indicates whether a SOAP 1.1 binding should be created. + * + *

Defaults to {@code true}. + */ + public void setCreateSoap11Binding(boolean createSoap11Binding) { + soapProvider.setCreateSoap11Binding(createSoap11Binding); + } - /** - * Indicates whether a SOAP 1.2 binding should be created. - * - *

Defaults to {@code false}. - */ - public void setCreateSoap12Binding(boolean createSoap12Binding) { - soapProvider.setCreateSoap12Binding(createSoap12Binding); - } + /** + * Indicates whether a SOAP 1.2 binding should be created. + * + *

Defaults to {@code false}. + */ + public void setCreateSoap12Binding(boolean createSoap12Binding) { + soapProvider.setCreateSoap12Binding(createSoap12Binding); + } - /** - * Sets the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding operation - * names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. - * - * @param soapActions the soap - */ - public void setSoapActions(Properties soapActions) { - soapProvider.setSoapActions(soapActions); - } + /** + * Sets the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding operation + * names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. + * + * @param soapActions the soap + */ + public void setSoapActions(Properties soapActions) { + soapProvider.setSoapActions(soapActions); + } - /** Sets the value used for the binding transport attribute value. Defaults to HTTP. */ - public void setTransportUri(String transportUri) { - soapProvider.setTransportUri(transportUri); - } + /** Sets the value used for the binding transport attribute value. Defaults to HTTP. */ + public void setTransportUri(String transportUri) { + soapProvider.setTransportUri(transportUri); + } - /** Sets the value used for the SOAP Address location attribute value. */ - public void setLocationUri(String locationUri) { - soapProvider.setLocationUri(locationUri); - } + /** Sets the value used for the SOAP Address location attribute value. */ + public void setLocationUri(String locationUri) { + soapProvider.setLocationUri(locationUri); + } - /** - * Sets the service name. - * - *

Defaults to the port type name, with the suffix {@code Service} appended to it. - */ - public void setServiceName(String serviceName) { - soapProvider.setServiceName(serviceName); - this.serviceName = serviceName; - } + /** + * Sets the service name. + * + *

Defaults to the port type name, with the suffix {@code Service} appended to it. + */ + public void setServiceName(String serviceName) { + soapProvider.setServiceName(serviceName); + this.serviceName = serviceName; + } - @Override - public void afterPropertiesSet() throws Exception { - if (!StringUtils.hasText(delegate.getTargetNamespace()) && typesProvider.getSchemaCollection() != null && - typesProvider.getSchemaCollection().getXsdSchemas().length > 0) { - XsdSchema schema = typesProvider.getSchemaCollection().getXsdSchemas()[0]; - setTargetNamespace(schema.getTargetNamespace()); - } - if (!StringUtils.hasText(serviceName) && StringUtils.hasText(portTypesProvider.getPortTypeName())) { - soapProvider.setServiceName(portTypesProvider.getPortTypeName() + "Service"); - } - delegate.afterPropertiesSet(); - } + @Override + public void afterPropertiesSet() throws Exception { + if (!StringUtils.hasText(delegate.getTargetNamespace()) && typesProvider.getSchemaCollection() != null && + typesProvider.getSchemaCollection().getXsdSchemas().length > 0) { + XsdSchema schema = typesProvider.getSchemaCollection().getXsdSchemas()[0]; + setTargetNamespace(schema.getTargetNamespace()); + } + if (!StringUtils.hasText(serviceName) && StringUtils.hasText(portTypesProvider.getPortTypeName())) { + soapProvider.setServiceName(portTypesProvider.getPortTypeName() + "Service"); + } + delegate.afterPropertiesSet(); + } - @Override - public Source getSource() { - return delegate.getSource(); - } + @Override + public Source getSource() { + return delegate.getSource(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/ProviderBasedWsdl4jDefinition.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/ProviderBasedWsdl4jDefinition.java index 2e374adf..510bf1be 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/ProviderBasedWsdl4jDefinition.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/ProviderBasedWsdl4jDefinition.java @@ -51,200 +51,200 @@ import org.springframework.ws.wsdl.wsdl11.provider.TypesProvider; */ public class ProviderBasedWsdl4jDefinition extends Wsdl4jDefinition implements InitializingBean { - /** The prefix used to register the target namespace in the WSDL. */ - public static final String TARGET_NAMESPACE_PREFIX = "tns"; + /** The prefix used to register the target namespace in the WSDL. */ + public static final String TARGET_NAMESPACE_PREFIX = "tns"; - private ImportsProvider importsProvider; + private ImportsProvider importsProvider; - private TypesProvider typesProvider; + private TypesProvider typesProvider; - private MessagesProvider messagesProvider; + private MessagesProvider messagesProvider; - private PortTypesProvider portTypesProvider; + private PortTypesProvider portTypesProvider; - private BindingsProvider bindingsProvider; + private BindingsProvider bindingsProvider; - private ServicesProvider servicesProvider; + private ServicesProvider servicesProvider; - private String targetNamespace; + private String targetNamespace; - /** - * Returns the {@link ImportsProvider} for this definition. - * - *

Default is {@code null}, indicating that no {@code <import>} will be created - * - * @return the import provider; or {@code null} - */ - public ImportsProvider getImportsProvider() { - return importsProvider; - } + /** + * Returns the {@link ImportsProvider} for this definition. + * + *

Default is {@code null}, indicating that no {@code <import>} will be created + * + * @return the import provider; or {@code null} + */ + public ImportsProvider getImportsProvider() { + return importsProvider; + } - /** - * Sets the {@link ImportsProvider} for this definition. - * - *

Default is {@code null}, indicating that no {@code <import>} will be created - * - * @param importsProvider the import provider - */ - public void setImportsProvider(ImportsProvider importsProvider) { - this.importsProvider = importsProvider; - } + /** + * Sets the {@link ImportsProvider} for this definition. + * + *

Default is {@code null}, indicating that no {@code <import>} will be created + * + * @param importsProvider the import provider + */ + public void setImportsProvider(ImportsProvider importsProvider) { + this.importsProvider = importsProvider; + } - /** - * Returns the {@link TypesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <types>} will be created - * - * @return the types provider; or {@code null} - */ - public TypesProvider getTypesProvider() { - return typesProvider; - } + /** + * Returns the {@link TypesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <types>} will be created + * + * @return the types provider; or {@code null} + */ + public TypesProvider getTypesProvider() { + return typesProvider; + } - /** - * Sets the {@link TypesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <types>} will be created - * - * @param typesProvider the types provider; or {@code null} - */ - public void setTypesProvider(TypesProvider typesProvider) { - this.typesProvider = typesProvider; - } + /** + * Sets the {@link TypesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <types>} will be created + * + * @param typesProvider the types provider; or {@code null} + */ + public void setTypesProvider(TypesProvider typesProvider) { + this.typesProvider = typesProvider; + } - /** - * Returns the {@link MessagesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <message>} will be created - * - * @return the messages provider; or {@code null} - */ - public MessagesProvider getMessagesProvider() { - return messagesProvider; - } + /** + * Returns the {@link MessagesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <message>} will be created + * + * @return the messages provider; or {@code null} + */ + public MessagesProvider getMessagesProvider() { + return messagesProvider; + } - /** - * Sets the {@link MessagesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <message>} will be created - * - * @param messagesProvider the messages provider; or {@code null} - */ - public void setMessagesProvider(MessagesProvider messagesProvider) { - this.messagesProvider = messagesProvider; - } + /** + * Sets the {@link MessagesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <message>} will be created + * + * @param messagesProvider the messages provider; or {@code null} + */ + public void setMessagesProvider(MessagesProvider messagesProvider) { + this.messagesProvider = messagesProvider; + } - /** - * Returns the {@link PortTypesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <portType>} will be created - * - * @return the port types provider; or {@code null} - */ - public PortTypesProvider getPortTypesProvider() { - return portTypesProvider; - } + /** + * Returns the {@link PortTypesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <portType>} will be created + * + * @return the port types provider; or {@code null} + */ + public PortTypesProvider getPortTypesProvider() { + return portTypesProvider; + } - /** - * Sets the {@link PortTypesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <portType>} will be created - * - * @param portTypesProvider the port types provider; or {@code null} - */ - public void setPortTypesProvider(PortTypesProvider portTypesProvider) { - this.portTypesProvider = portTypesProvider; - } + /** + * Sets the {@link PortTypesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <portType>} will be created + * + * @param portTypesProvider the port types provider; or {@code null} + */ + public void setPortTypesProvider(PortTypesProvider portTypesProvider) { + this.portTypesProvider = portTypesProvider; + } - /** - * Returns the {@link BindingsProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <binding>} will be created - * - * @return the binding provider; or {@code null} - */ - public BindingsProvider getBindingsProvider() { - return bindingsProvider; - } + /** + * Returns the {@link BindingsProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <binding>} will be created + * + * @return the binding provider; or {@code null} + */ + public BindingsProvider getBindingsProvider() { + return bindingsProvider; + } - /** - * Sets the {@link BindingsProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <binding>} will be created - * - * @param bindingsProvider the bindings provider; or {@code null} - */ - public void setBindingsProvider(BindingsProvider bindingsProvider) { - this.bindingsProvider = bindingsProvider; - } + /** + * Sets the {@link BindingsProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <binding>} will be created + * + * @param bindingsProvider the bindings provider; or {@code null} + */ + public void setBindingsProvider(BindingsProvider bindingsProvider) { + this.bindingsProvider = bindingsProvider; + } - /** - * Returns the {@link ServicesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <service>} will be created - * - * @return the services provider; or {@code null} - */ - public ServicesProvider getServicesProvider() { - return servicesProvider; - } + /** + * Returns the {@link ServicesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <service>} will be created + * + * @return the services provider; or {@code null} + */ + public ServicesProvider getServicesProvider() { + return servicesProvider; + } - /** - * Sets the {@link ServicesProvider} for this definition. - * - *

Defaults to {@code null}, indicating that no {@code <service>} will be created - * - * @param servicesProvider the services provider; or {@code null} - */ - public void setServicesProvider(ServicesProvider servicesProvider) { - this.servicesProvider = servicesProvider; - } + /** + * Sets the {@link ServicesProvider} for this definition. + * + *

Defaults to {@code null}, indicating that no {@code <service>} will be created + * + * @param servicesProvider the services provider; or {@code null} + */ + public void setServicesProvider(ServicesProvider servicesProvider) { + this.servicesProvider = servicesProvider; + } - /** - * Returns the target namespace for the WSDL definition. - * - * @return the target namespace - * @see javax.wsdl.Definition#getTargetNamespace() - */ - public String getTargetNamespace() { - return targetNamespace; - } + /** + * Returns the target namespace for the WSDL definition. + * + * @return the target namespace + * @see javax.wsdl.Definition#getTargetNamespace() + */ + public String getTargetNamespace() { + return targetNamespace; + } - /** - * Sets the target namespace used for this definition. Required. - * - * @param targetNamespace the target namespace - * @see javax.wsdl.Definition#setTargetNamespace(String) - */ - public void setTargetNamespace(String targetNamespace) { - this.targetNamespace = targetNamespace; - } + /** + * Sets the target namespace used for this definition. Required. + * + * @param targetNamespace the target namespace + * @see javax.wsdl.Definition#setTargetNamespace(String) + */ + public void setTargetNamespace(String targetNamespace) { + this.targetNamespace = targetNamespace; + } - @Override - public void afterPropertiesSet() throws WSDLException { - Assert.notNull(getTargetNamespace(), "'targetNamespace' is required"); - WSDLFactory wsdlFactory = WSDLFactory.newInstance(); - Definition definition = wsdlFactory.newDefinition(); - definition.setTargetNamespace(getTargetNamespace()); - definition.addNamespace(TARGET_NAMESPACE_PREFIX, getTargetNamespace()); - if (importsProvider != null) { - importsProvider.addImports(definition); - } - if (typesProvider != null) { - typesProvider.addTypes(definition); - } - if (messagesProvider != null) { - messagesProvider.addMessages(definition); - } - if (portTypesProvider != null) { - portTypesProvider.addPortTypes(definition); - } - if (bindingsProvider != null) { - bindingsProvider.addBindings(definition); - } - if (servicesProvider != null) { - servicesProvider.addServices(definition); - } - setDefinition(definition); - } + @Override + public void afterPropertiesSet() throws WSDLException { + Assert.notNull(getTargetNamespace(), "'targetNamespace' is required"); + WSDLFactory wsdlFactory = WSDLFactory.newInstance(); + Definition definition = wsdlFactory.newDefinition(); + definition.setTargetNamespace(getTargetNamespace()); + definition.addNamespace(TARGET_NAMESPACE_PREFIX, getTargetNamespace()); + if (importsProvider != null) { + importsProvider.addImports(definition); + } + if (typesProvider != null) { + typesProvider.addTypes(definition); + } + if (messagesProvider != null) { + messagesProvider.addMessages(definition); + } + if (portTypesProvider != null) { + portTypesProvider.addPortTypes(definition); + } + if (bindingsProvider != null) { + bindingsProvider.addBindings(definition); + } + if (servicesProvider != null) { + servicesProvider.addServices(definition); + } + setDefinition(definition); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11Definition.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11Definition.java index 156e9312..b742efe9 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11Definition.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11Definition.java @@ -40,60 +40,60 @@ import org.springframework.xml.transform.ResourceSource; */ public class SimpleWsdl11Definition implements Wsdl11Definition, InitializingBean { - private Resource wsdlResource; + private Resource wsdlResource; - /** - * Create a new instance of the {@link SimpleWsdl11Definition} class. - * - *

A subsequent call to the {@link #setWsdl(Resource)} method is required. - */ - public SimpleWsdl11Definition() { - } + /** + * Create a new instance of the {@link SimpleWsdl11Definition} class. + * + *

A subsequent call to the {@link #setWsdl(Resource)} method is required. + */ + public SimpleWsdl11Definition() { + } - /** - * Create a new instance of the {@link SimpleWsdl11Definition} class with the specified resource. - * - * @param wsdlResource the WSDL resource; must not be {@code null} - * @throws IllegalArgumentException if the supplied {@code wsdlResource} is {@code null} - */ - public SimpleWsdl11Definition(Resource wsdlResource) { - Assert.notNull(wsdlResource, "wsdlResource must not be null"); - this.wsdlResource = wsdlResource; - } + /** + * Create a new instance of the {@link SimpleWsdl11Definition} class with the specified resource. + * + * @param wsdlResource the WSDL resource; must not be {@code null} + * @throws IllegalArgumentException if the supplied {@code wsdlResource} is {@code null} + */ + public SimpleWsdl11Definition(Resource wsdlResource) { + Assert.notNull(wsdlResource, "wsdlResource must not be null"); + this.wsdlResource = wsdlResource; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(this.wsdlResource, "wsdl is required"); - Assert.isTrue(this.wsdlResource.exists(), "wsdl '" + this.wsdlResource + "' does not exist"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(this.wsdlResource, "wsdl is required"); + Assert.isTrue(this.wsdlResource.exists(), "wsdl '" + this.wsdlResource + "' does not exist"); + } - @Override - public Source getSource() { - try { - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); - xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); - return new ResourceSource(xmlReader, wsdlResource); - } - catch (SAXException ex) { - throw new WsdlDefinitionException("Could not create XMLReader", ex); - } - catch (IOException ex) { - throw new WsdlDefinitionException("Could not create source from " + this.wsdlResource, ex); - } - } + @Override + public Source getSource() { + try { + XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + return new ResourceSource(xmlReader, wsdlResource); + } + catch (SAXException ex) { + throw new WsdlDefinitionException("Could not create XMLReader", ex); + } + catch (IOException ex) { + throw new WsdlDefinitionException("Could not create source from " + this.wsdlResource, ex); + } + } - /** - * Set the WSDL resource to be exposed by calls to this instances' {@link #getSource()} method. - * - * @param wsdlResource the WSDL resource - */ - public void setWsdl(Resource wsdlResource) { - this.wsdlResource = wsdlResource; - } + /** + * Set the WSDL resource to be exposed by calls to this instances' {@link #getSource()} method. + * + * @param wsdlResource the WSDL resource + */ + public void setWsdl(Resource wsdlResource) { + this.wsdlResource = wsdlResource; + } - public String toString() { - return "SimpleWsdl11Definition " + wsdlResource; - } + public String toString() { + return "SimpleWsdl11Definition " + wsdlResource; + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinition.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinition.java index 3f91d839..866ba725 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinition.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinition.java @@ -40,71 +40,71 @@ import org.springframework.ws.wsdl.WsdlDefinitionException; */ public class Wsdl4jDefinition implements Wsdl11Definition { - private Definition definition; + private Definition definition; - /** Cached DOM version of the definition */ - private Document document; + /** Cached DOM version of the definition */ + private Document document; - /** WSDL4J is not thread safe, hence the need for a monitor. */ - private final Object monitor = new Object(); + /** WSDL4J is not thread safe, hence the need for a monitor. */ + private final Object monitor = new Object(); - /** - * Constructs a new, empty {@code Wsdl4jDefinition}. - * - * @see #setDefinition(javax.wsdl.Definition) - */ - public Wsdl4jDefinition() { - } + /** + * Constructs a new, empty {@code Wsdl4jDefinition}. + * + * @see #setDefinition(javax.wsdl.Definition) + */ + public Wsdl4jDefinition() { + } - /** - * Constructs a new {@code Wsdl4jDefinition} based on the given {@code Definition}. - * - * @param definition the WSDL4J definition - */ - public Wsdl4jDefinition(Definition definition) { - setDefinition(definition); - } + /** + * Constructs a new {@code Wsdl4jDefinition} based on the given {@code Definition}. + * + * @param definition the WSDL4J definition + */ + public Wsdl4jDefinition(Definition definition) { + setDefinition(definition); + } - /** Returns the WSDL4J {@code Definition}. */ - public Definition getDefinition() { - synchronized (monitor) { - return definition; - } - } + /** Returns the WSDL4J {@code Definition}. */ + public Definition getDefinition() { + synchronized (monitor) { + return definition; + } + } - /** Set the WSDL4J {@code Definition}. */ - public void setDefinition(Definition definition) { - synchronized (monitor) { - this.definition = definition; - this.document = null; - } - } + /** Set the WSDL4J {@code Definition}. */ + public void setDefinition(Definition definition) { + synchronized (monitor) { + this.definition = definition; + this.document = null; + } + } - @Override - public Source getSource() { - synchronized (monitor) { - Assert.notNull(definition, "definition must not be null"); - if (document == null) { - try { - WSDLFactory wsdlFactory = WSDLFactory.newInstance(); - WSDLWriter wsdlWriter = wsdlFactory.newWSDLWriter(); - document = wsdlWriter.getDocument(definition); - } - catch (WSDLException ex) { - throw new WsdlDefinitionException(ex.getMessage(), ex); - } - } - } - return new DOMSource(document); - } + @Override + public Source getSource() { + synchronized (monitor) { + Assert.notNull(definition, "definition must not be null"); + if (document == null) { + try { + WSDLFactory wsdlFactory = WSDLFactory.newInstance(); + WSDLWriter wsdlWriter = wsdlFactory.newWSDLWriter(); + document = wsdlWriter.getDocument(definition); + } + catch (WSDLException ex) { + throw new WsdlDefinitionException(ex.getMessage(), ex); + } + } + } + return new DOMSource(document); + } - public String toString() { - StringBuilder builder = new StringBuilder("Wsdl4jDefinition"); - if (definition != null && StringUtils.hasLength(definition.getTargetNamespace())) { - builder.append('{'); - builder.append(definition.getTargetNamespace()); - builder.append('}'); - } - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("Wsdl4jDefinition"); + if (definition != null && StringUtils.hasLength(definition.getTargetNamespace())) { + builder.append('{'); + builder.append(definition.getTargetNamespace()); + builder.append('}'); + } + return builder.toString(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionException.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionException.java index b0be6612..2535e552 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionException.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionException.java @@ -29,8 +29,8 @@ import org.springframework.ws.wsdl.WsdlDefinitionException; @SuppressWarnings("serial") public class Wsdl4jDefinitionException extends WsdlDefinitionException { - public Wsdl4jDefinitionException(WSDLException ex) { - super(ex.getMessage(), ex); - } + public Wsdl4jDefinitionException(WSDLException ex) { + super(ex.getMessage(), ex); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/AbstractPortTypesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/AbstractPortTypesProvider.java index 0486ebb6..0c8cd779 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/AbstractPortTypesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/AbstractPortTypesProvider.java @@ -45,195 +45,195 @@ import org.springframework.util.StringUtils; */ public abstract class AbstractPortTypesProvider implements PortTypesProvider { - /** Logger available to subclasses. */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); - private String portTypeName; + private String portTypeName; - /** Returns the port type name used for this definition. */ - public String getPortTypeName() { - return portTypeName; - } + /** Returns the port type name used for this definition. */ + public String getPortTypeName() { + return portTypeName; + } - /** Sets the port type name used for this definition. Required. */ - public void setPortTypeName(String portTypeName) { - this.portTypeName = portTypeName; - } + /** Sets the port type name used for this definition. Required. */ + public void setPortTypeName(String portTypeName) { + this.portTypeName = portTypeName; + } - /** - * Creates a single {@link PortType}, and calls {@link #populatePortType(Definition, PortType)} with it. - * - * @param definition the WSDL4J {@code Definition} - * @throws WSDLException in case of errors - */ - @Override - public void addPortTypes(Definition definition) throws WSDLException { - Assert.notNull(getPortTypeName(), "'portTypeName' is required"); - PortType portType = definition.createPortType(); - populatePortType(definition, portType); - createOperations(definition, portType); - portType.setUndefined(false); - definition.addPortType(portType); - } + /** + * Creates a single {@link PortType}, and calls {@link #populatePortType(Definition, PortType)} with it. + * + * @param definition the WSDL4J {@code Definition} + * @throws WSDLException in case of errors + */ + @Override + public void addPortTypes(Definition definition) throws WSDLException { + Assert.notNull(getPortTypeName(), "'portTypeName' is required"); + PortType portType = definition.createPortType(); + populatePortType(definition, portType); + createOperations(definition, portType); + portType.setUndefined(false); + definition.addPortType(portType); + } - /** - * Called after the {@link PortType} has been created. - * - *

Default implementation sets the name of the port type to the defined value. - * - * @param portType the WSDL4J {@code PortType} - * @throws WSDLException in case of errors - * @see #setPortTypeName(String) - */ - protected void populatePortType(Definition definition, PortType portType) throws WSDLException { - QName portTypeName = new QName(definition.getTargetNamespace(), getPortTypeName()); - if (logger.isDebugEnabled()) { - logger.debug("Creating port type [" + portTypeName + "]"); - } - portType.setQName(portTypeName); - } + /** + * Called after the {@link PortType} has been created. + * + *

Default implementation sets the name of the port type to the defined value. + * + * @param portType the WSDL4J {@code PortType} + * @throws WSDLException in case of errors + * @see #setPortTypeName(String) + */ + protected void populatePortType(Definition definition, PortType portType) throws WSDLException { + QName portTypeName = new QName(definition.getTargetNamespace(), getPortTypeName()); + if (logger.isDebugEnabled()) { + logger.debug("Creating port type [" + portTypeName + "]"); + } + portType.setQName(portTypeName); + } - private void createOperations(Definition definition, PortType portType) throws WSDLException { - MultiValueMap operations = new LinkedMultiValueMap(); - for (Iterator iterator = definition.getMessages().values().iterator(); iterator.hasNext();) { - Message message = (Message) iterator.next(); - String operationName = getOperationName(message); - if (StringUtils.hasText(operationName)) { - operations.add(operationName,message); - } - } - if (operations.isEmpty() && logger.isWarnEnabled()) { - logger.warn("No operations were created, make sure the WSDL contains messages"); - } - for (String operationName : operations.keySet()) { - Operation operation = definition.createOperation(); - operation.setName(operationName); - List messages = operations.get(operationName); - for (Message message : messages) { - if (isInputMessage(message)) { - Input input = definition.createInput(); - input.setMessage(message); - populateInput(definition, input); - operation.setInput(input); - } - else if (isOutputMessage(message)) { - Output output = definition.createOutput(); - output.setMessage(message); - populateOutput(definition, output); - operation.setOutput(output); - } - else if (isFaultMessage(message)) { - Fault fault = definition.createFault(); - fault.setMessage(message); - populateFault(definition, fault); - operation.addFault(fault); - } - } - operation.setStyle(getOperationType(operation)); - operation.setUndefined(false); - if (logger.isDebugEnabled()) { - logger.debug( - "Adding operation [" + operation.getName() + "] to port type [" + portType.getQName() + "]"); - } - portType.addOperation(operation); - } - } + private void createOperations(Definition definition, PortType portType) throws WSDLException { + MultiValueMap operations = new LinkedMultiValueMap(); + for (Iterator iterator = definition.getMessages().values().iterator(); iterator.hasNext();) { + Message message = (Message) iterator.next(); + String operationName = getOperationName(message); + if (StringUtils.hasText(operationName)) { + operations.add(operationName,message); + } + } + if (operations.isEmpty() && logger.isWarnEnabled()) { + logger.warn("No operations were created, make sure the WSDL contains messages"); + } + for (String operationName : operations.keySet()) { + Operation operation = definition.createOperation(); + operation.setName(operationName); + List messages = operations.get(operationName); + for (Message message : messages) { + if (isInputMessage(message)) { + Input input = definition.createInput(); + input.setMessage(message); + populateInput(definition, input); + operation.setInput(input); + } + else if (isOutputMessage(message)) { + Output output = definition.createOutput(); + output.setMessage(message); + populateOutput(definition, output); + operation.setOutput(output); + } + else if (isFaultMessage(message)) { + Fault fault = definition.createFault(); + fault.setMessage(message); + populateFault(definition, fault); + operation.addFault(fault); + } + } + operation.setStyle(getOperationType(operation)); + operation.setUndefined(false); + if (logger.isDebugEnabled()) { + logger.debug( + "Adding operation [" + operation.getName() + "] to port type [" + portType.getQName() + "]"); + } + portType.addOperation(operation); + } + } - /** - * Template method that returns the name of the operation coupled to the given {@link Message}. Subclasses can - * return {@code null} to indicate that a message should not be coupled to an operation. - * - * @param message the WSDL4J {@code Message} - * @return the operation name; or {@code null} - */ - protected abstract String getOperationName(Message message); + /** + * Template method that returns the name of the operation coupled to the given {@link Message}. Subclasses can + * return {@code null} to indicate that a message should not be coupled to an operation. + * + * @param message the WSDL4J {@code Message} + * @return the operation name; or {@code null} + */ + protected abstract String getOperationName(Message message); - /** - * Indicates whether the given name name should be included as {@link Input} message in the definition. - * - * @param message the message - * @return {@code true} if to be included as input; {@code false} otherwise - */ - protected abstract boolean isInputMessage(Message message); + /** + * Indicates whether the given name name should be included as {@link Input} message in the definition. + * + * @param message the message + * @return {@code true} if to be included as input; {@code false} otherwise + */ + protected abstract boolean isInputMessage(Message message); - /** - * Called after the {@link javax.wsdl.Input} has been created, but it's added to the operation. Subclasses can - * override this method to define the input name. - * - *

Default implementation sets the input name to the message name. - * - * @param definition the WSDL4J {@code Definition} - * @param input the WSDL4J {@code Input} - */ - protected void populateInput(Definition definition, Input input) { - input.setName(input.getMessage().getQName().getLocalPart()); - } + /** + * Called after the {@link javax.wsdl.Input} has been created, but it's added to the operation. Subclasses can + * override this method to define the input name. + * + *

Default implementation sets the input name to the message name. + * + * @param definition the WSDL4J {@code Definition} + * @param input the WSDL4J {@code Input} + */ + protected void populateInput(Definition definition, Input input) { + input.setName(input.getMessage().getQName().getLocalPart()); + } - /** - * Indicates whether the given name name should be included as {@link Output} message in the definition. - * - * @param message the message - * @return {@code true} if to be included as output; {@code false} otherwise - */ - protected abstract boolean isOutputMessage(Message message); + /** + * Indicates whether the given name name should be included as {@link Output} message in the definition. + * + * @param message the message + * @return {@code true} if to be included as output; {@code false} otherwise + */ + protected abstract boolean isOutputMessage(Message message); - /** - * Called after the {@link javax.wsdl.Output} has been created, but it's added to the operation. Subclasses can - * override this method to define the output name. - * - *

Default implementation sets the output name to the message name. - * - * @param definition the WSDL4J {@code Definition} - * @param output the WSDL4J {@code Output} - */ - protected void populateOutput(Definition definition, Output output) { - output.setName(output.getMessage().getQName().getLocalPart()); - } + /** + * Called after the {@link javax.wsdl.Output} has been created, but it's added to the operation. Subclasses can + * override this method to define the output name. + * + *

Default implementation sets the output name to the message name. + * + * @param definition the WSDL4J {@code Definition} + * @param output the WSDL4J {@code Output} + */ + protected void populateOutput(Definition definition, Output output) { + output.setName(output.getMessage().getQName().getLocalPart()); + } - /** - * Indicates whether the given name name should be included as {@link Fault} message in the definition. - * - * @param message the message - * @return {@code true} if to be included as fault; {@code false} otherwise - */ - protected abstract boolean isFaultMessage(Message message); + /** + * Indicates whether the given name name should be included as {@link Fault} message in the definition. + * + * @param message the message + * @return {@code true} if to be included as fault; {@code false} otherwise + */ + protected abstract boolean isFaultMessage(Message message); - /** - * Called after the {@link javax.wsdl.Fault} has been created, but it's added to the operation. Subclasses can - * override this method to define the fault name. - * - *

Default implementation sets the fault name to the message name. - * - * @param definition the WSDL4J {@code Definition} - * @param fault the WSDL4J {@code Fault} - */ - protected void populateFault(Definition definition, Fault fault) { - fault.setName(fault.getMessage().getQName().getLocalPart()); - } + /** + * Called after the {@link javax.wsdl.Fault} has been created, but it's added to the operation. Subclasses can + * override this method to define the fault name. + * + *

Default implementation sets the fault name to the message name. + * + * @param definition the WSDL4J {@code Definition} + * @param fault the WSDL4J {@code Fault} + */ + protected void populateFault(Definition definition, Fault fault) { + fault.setName(fault.getMessage().getQName().getLocalPart()); + } - /** - * Returns the {@link OperationType} for the given operation. - * - *

Default implementation returns {@link OperationType#REQUEST_RESPONSE} if both input and output are set; {@link - * OperationType#ONE_WAY} if only input is set, or {@link OperationType#NOTIFICATION} if only output is set. - * - * @param operation the WSDL4J {@code Operation} - * @return the operation type for the operation - */ - protected OperationType getOperationType(Operation operation) { - if (operation.getInput() != null && operation.getOutput() != null) { - return OperationType.REQUEST_RESPONSE; - } - else if (operation.getInput() != null && operation.getOutput() == null) { - return OperationType.ONE_WAY; - } - else if (operation.getInput() == null && operation.getOutput() != null) { - return OperationType.NOTIFICATION; - } - else { - return null; - } - } + /** + * Returns the {@link OperationType} for the given operation. + * + *

Default implementation returns {@link OperationType#REQUEST_RESPONSE} if both input and output are set; {@link + * OperationType#ONE_WAY} if only input is set, or {@link OperationType#NOTIFICATION} if only output is set. + * + * @param operation the WSDL4J {@code Operation} + * @return the operation type for the operation + */ + protected OperationType getOperationType(Operation operation) { + if (operation.getInput() != null && operation.getOutput() != null) { + return OperationType.REQUEST_RESPONSE; + } + else if (operation.getInput() != null && operation.getOutput() == null) { + return OperationType.ONE_WAY; + } + else if (operation.getInput() == null && operation.getOutput() != null) { + return OperationType.NOTIFICATION; + } + else { + return null; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/BindingsProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/BindingsProvider.java index 236e3230..754ff43d 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/BindingsProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/BindingsProvider.java @@ -29,6 +29,6 @@ import javax.wsdl.WSDLException; */ public interface BindingsProvider { - void addBindings(Definition definition) throws WSDLException; + void addBindings(Definition definition) throws WSDLException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultConcretePartProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultConcretePartProvider.java index 96b5c550..399dd718 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultConcretePartProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultConcretePartProvider.java @@ -51,280 +51,280 @@ import org.springframework.util.StringUtils; */ public class DefaultConcretePartProvider implements BindingsProvider, ServicesProvider { - /** Logger available to subclasses. */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); - private String bindingSuffix; + private String bindingSuffix; - private String serviceName; + private String serviceName; - /** Returns the service name. */ - public String getServiceName() { - return serviceName; - } + /** Returns the service name. */ + public String getServiceName() { + return serviceName; + } - /** Sets the service name. */ - public void setServiceName(String serviceName) { - Assert.hasText(serviceName, "'serviceName' must not be null"); - this.serviceName = serviceName; - } + /** Sets the service name. */ + public void setServiceName(String serviceName) { + Assert.hasText(serviceName, "'serviceName' must not be null"); + this.serviceName = serviceName; + } - /** Returns the suffix to append to the port type name to obtain the binding name. */ - public String getBindingSuffix() { - return bindingSuffix; - } + /** Returns the suffix to append to the port type name to obtain the binding name. */ + public String getBindingSuffix() { + return bindingSuffix; + } - /** Sets the suffix to append to the port type name to obtain the binding name. */ - public void setBindingSuffix(String bindingSuffix) { - Assert.notNull(bindingSuffix, "'bindingSuffix' must not be null"); - this.bindingSuffix = bindingSuffix; - } + /** Sets the suffix to append to the port type name to obtain the binding name. */ + public void setBindingSuffix(String bindingSuffix) { + Assert.notNull(bindingSuffix, "'bindingSuffix' must not be null"); + this.bindingSuffix = bindingSuffix; + } - /** - * Creates a {@link Binding} for each {@link PortType} in the definition, and calls {@link - * #populateBinding(Definition,javax.wsdl.Binding)} with it. Creates a {@link BindingOperation} for each {@link - * Operation} in the port type, a {@link BindingInput} for each {@link Input} in the operation, etc. - * - *

Calls the various {@code populate} methods with the created WSDL4J objects. - * - * @param definition the WSDL4J {@code Definition} - * @throws WSDLException in case of errors - * @see #populateBinding(Definition,javax.wsdl.Binding) - * @see #populateBindingOperation(Definition,javax.wsdl.BindingOperation) - * @see #populateBindingInput(Definition,javax.wsdl.BindingInput,javax.wsdl.Input) - * @see #populateBindingOutput(Definition,javax.wsdl.BindingOutput,javax.wsdl.Output) - * @see #populateBindingFault(Definition,javax.wsdl.BindingFault,javax.wsdl.Fault) - */ - @Override - public void addBindings(Definition definition) throws WSDLException { - for (Iterator iterator = definition.getPortTypes().values().iterator(); iterator.hasNext();) { - PortType portType = (PortType) iterator.next(); - Binding binding = definition.createBinding(); - binding.setPortType(portType); - populateBinding(definition, binding); - createBindingOperations(definition, binding); - binding.setUndefined(false); - if (binding.getQName() != null) { - definition.addBinding(binding); - } - } - if (definition.getBindings().isEmpty() && logger.isWarnEnabled()) { - logger.warn("No bindings were created, make sure the WSDL contains port types"); - } - } + /** + * Creates a {@link Binding} for each {@link PortType} in the definition, and calls {@link + * #populateBinding(Definition,javax.wsdl.Binding)} with it. Creates a {@link BindingOperation} for each {@link + * Operation} in the port type, a {@link BindingInput} for each {@link Input} in the operation, etc. + * + *

Calls the various {@code populate} methods with the created WSDL4J objects. + * + * @param definition the WSDL4J {@code Definition} + * @throws WSDLException in case of errors + * @see #populateBinding(Definition,javax.wsdl.Binding) + * @see #populateBindingOperation(Definition,javax.wsdl.BindingOperation) + * @see #populateBindingInput(Definition,javax.wsdl.BindingInput,javax.wsdl.Input) + * @see #populateBindingOutput(Definition,javax.wsdl.BindingOutput,javax.wsdl.Output) + * @see #populateBindingFault(Definition,javax.wsdl.BindingFault,javax.wsdl.Fault) + */ + @Override + public void addBindings(Definition definition) throws WSDLException { + for (Iterator iterator = definition.getPortTypes().values().iterator(); iterator.hasNext();) { + PortType portType = (PortType) iterator.next(); + Binding binding = definition.createBinding(); + binding.setPortType(portType); + populateBinding(definition, binding); + createBindingOperations(definition, binding); + binding.setUndefined(false); + if (binding.getQName() != null) { + definition.addBinding(binding); + } + } + if (definition.getBindings().isEmpty() && logger.isWarnEnabled()) { + logger.warn("No bindings were created, make sure the WSDL contains port types"); + } + } - /** - * Called after the {@link Binding} has been created, but before any sub-elements are added. Subclasses can override - * this method to define the binding name, or add extensions to it. - * - *

Default implementation sets the binding name to the port type name with the {@link #getBindingSuffix() suffix} - * appended to it. - * - * @param definition the WSDL4J {@code Definition} - * @param binding the WSDL4J {@code Binding} - */ - protected void populateBinding(Definition definition, Binding binding) throws WSDLException { - QName portTypeName = binding.getPortType().getQName(); - if (portTypeName != null) { - QName bindingName = - new QName(portTypeName.getNamespaceURI(), portTypeName.getLocalPart() + getBindingSuffix()); - if (logger.isDebugEnabled()) { - logger.debug("Creating binding [" + bindingName + "]"); - } - binding.setQName(bindingName); - } - } + /** + * Called after the {@link Binding} has been created, but before any sub-elements are added. Subclasses can override + * this method to define the binding name, or add extensions to it. + * + *

Default implementation sets the binding name to the port type name with the {@link #getBindingSuffix() suffix} + * appended to it. + * + * @param definition the WSDL4J {@code Definition} + * @param binding the WSDL4J {@code Binding} + */ + protected void populateBinding(Definition definition, Binding binding) throws WSDLException { + QName portTypeName = binding.getPortType().getQName(); + if (portTypeName != null) { + QName bindingName = + new QName(portTypeName.getNamespaceURI(), portTypeName.getLocalPart() + getBindingSuffix()); + if (logger.isDebugEnabled()) { + logger.debug("Creating binding [" + bindingName + "]"); + } + binding.setQName(bindingName); + } + } - private void createBindingOperations(Definition definition, Binding binding) throws WSDLException { - PortType portType = binding.getPortType(); - for (Iterator operationIterator = portType.getOperations().iterator(); operationIterator.hasNext();) { - Operation operation = (Operation) operationIterator.next(); - BindingOperation bindingOperation = definition.createBindingOperation(); - bindingOperation.setOperation(operation); - populateBindingOperation(definition, bindingOperation); - if (OperationType.REQUEST_RESPONSE.equals(operation.getStyle())) { - createBindingInput(definition, operation, bindingOperation); - createBindingOutput(definition, operation, bindingOperation); - } - else if (OperationType.ONE_WAY.equals(operation.getStyle())) { - createBindingInput(definition, operation, bindingOperation); - } - else if (OperationType.NOTIFICATION.equals(operation.getStyle())) { - createBindingOutput(definition, operation, bindingOperation); - } - else if (OperationType.SOLICIT_RESPONSE.equals(operation.getStyle())) { - createBindingOutput(definition, operation, bindingOperation); - createBindingInput(definition, operation, bindingOperation); - } - for (Iterator faultIterator = operation.getFaults().values().iterator(); faultIterator.hasNext();) { - Fault fault = (Fault) faultIterator.next(); - BindingFault bindingFault = definition.createBindingFault(); - populateBindingFault(definition, bindingFault, fault); - if (StringUtils.hasText(bindingFault.getName())) { - bindingOperation.addBindingFault(bindingFault); - } - } - binding.addBindingOperation(bindingOperation); - } - } + private void createBindingOperations(Definition definition, Binding binding) throws WSDLException { + PortType portType = binding.getPortType(); + for (Iterator operationIterator = portType.getOperations().iterator(); operationIterator.hasNext();) { + Operation operation = (Operation) operationIterator.next(); + BindingOperation bindingOperation = definition.createBindingOperation(); + bindingOperation.setOperation(operation); + populateBindingOperation(definition, bindingOperation); + if (OperationType.REQUEST_RESPONSE.equals(operation.getStyle())) { + createBindingInput(definition, operation, bindingOperation); + createBindingOutput(definition, operation, bindingOperation); + } + else if (OperationType.ONE_WAY.equals(operation.getStyle())) { + createBindingInput(definition, operation, bindingOperation); + } + else if (OperationType.NOTIFICATION.equals(operation.getStyle())) { + createBindingOutput(definition, operation, bindingOperation); + } + else if (OperationType.SOLICIT_RESPONSE.equals(operation.getStyle())) { + createBindingOutput(definition, operation, bindingOperation); + createBindingInput(definition, operation, bindingOperation); + } + for (Iterator faultIterator = operation.getFaults().values().iterator(); faultIterator.hasNext();) { + Fault fault = (Fault) faultIterator.next(); + BindingFault bindingFault = definition.createBindingFault(); + populateBindingFault(definition, bindingFault, fault); + if (StringUtils.hasText(bindingFault.getName())) { + bindingOperation.addBindingFault(bindingFault); + } + } + binding.addBindingOperation(bindingOperation); + } + } - /** - * Called after the {@link BindingOperation} has been created, but before any sub-elements are added. Subclasses can - * override this method to define the binding name, or add extensions to it. - * - *

Default implementation sets the name of the binding operation to the name of the operation. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingOperation the WSDL4J {@code BindingOperation} - * @throws WSDLException in case of errors - */ - protected void populateBindingOperation(Definition definition, BindingOperation bindingOperation) - throws WSDLException { - bindingOperation.setName(bindingOperation.getOperation().getName()); - } + /** + * Called after the {@link BindingOperation} has been created, but before any sub-elements are added. Subclasses can + * override this method to define the binding name, or add extensions to it. + * + *

Default implementation sets the name of the binding operation to the name of the operation. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingOperation the WSDL4J {@code BindingOperation} + * @throws WSDLException in case of errors + */ + protected void populateBindingOperation(Definition definition, BindingOperation bindingOperation) + throws WSDLException { + bindingOperation.setName(bindingOperation.getOperation().getName()); + } - private void createBindingInput(Definition definition, Operation operation, BindingOperation bindingOperation) - throws WSDLException { - BindingInput bindingInput = definition.createBindingInput(); - populateBindingInput(definition, bindingInput, operation.getInput()); - bindingOperation.setBindingInput(bindingInput); - } + private void createBindingInput(Definition definition, Operation operation, BindingOperation bindingOperation) + throws WSDLException { + BindingInput bindingInput = definition.createBindingInput(); + populateBindingInput(definition, bindingInput, operation.getInput()); + bindingOperation.setBindingInput(bindingInput); + } - private void createBindingOutput(Definition definition, Operation operation, BindingOperation bindingOperation) - throws WSDLException { - BindingOutput bindingOutput = definition.createBindingOutput(); - populateBindingOutput(definition, bindingOutput, operation.getOutput()); - bindingOperation.setBindingOutput(bindingOutput); - } + private void createBindingOutput(Definition definition, Operation operation, BindingOperation bindingOperation) + throws WSDLException { + BindingOutput bindingOutput = definition.createBindingOutput(); + populateBindingOutput(definition, bindingOutput, operation.getOutput()); + bindingOperation.setBindingOutput(bindingOutput); + } - /** - * Called after the {@link BindingInput} has been created. Subclasses can override this method to define the name, - * or add extensions to it. - * - *

Default implementation set the name of the binding input to the name of the input. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingInput the WSDL4J {@code BindingInput} - * @param input the corresponding WSDL4J {@code Input} @throws WSDLException in case of errors - */ - protected void populateBindingInput(Definition definition, BindingInput bindingInput, Input input) - throws WSDLException { - bindingInput.setName(input.getName()); - } + /** + * Called after the {@link BindingInput} has been created. Subclasses can override this method to define the name, + * or add extensions to it. + * + *

Default implementation set the name of the binding input to the name of the input. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingInput the WSDL4J {@code BindingInput} + * @param input the corresponding WSDL4J {@code Input} @throws WSDLException in case of errors + */ + protected void populateBindingInput(Definition definition, BindingInput bindingInput, Input input) + throws WSDLException { + bindingInput.setName(input.getName()); + } - /** - * Called after the {@link BindingOutput} has been created. Subclasses can override this method to define the name, - * or add extensions to it. - * - *

Default implementation sets the name of the binding output to the name of the output. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingOutput the WSDL4J {@code BindingOutput} - * @param output the corresponding WSDL4J {@code Output} @throws WSDLException in case of errors - */ - protected void populateBindingOutput(Definition definition, BindingOutput bindingOutput, Output output) - throws WSDLException { - bindingOutput.setName(output.getName()); - } + /** + * Called after the {@link BindingOutput} has been created. Subclasses can override this method to define the name, + * or add extensions to it. + * + *

Default implementation sets the name of the binding output to the name of the output. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingOutput the WSDL4J {@code BindingOutput} + * @param output the corresponding WSDL4J {@code Output} @throws WSDLException in case of errors + */ + protected void populateBindingOutput(Definition definition, BindingOutput bindingOutput, Output output) + throws WSDLException { + bindingOutput.setName(output.getName()); + } - /** - * Called after the {@link BindingFault} has been created. Subclasses can implement this method to define the name, - * or add extensions to it. - * - *

Default implementation set the name of the binding fault to the name of the fault. - * - * @param bindingFault the WSDL4J {@code BindingFault} - * @param fault the corresponding WSDL4J {@code Fault} @throws WSDLException in case of errors - */ - protected void populateBindingFault(Definition definition, BindingFault bindingFault, Fault fault) - throws WSDLException { - bindingFault.setName(fault.getName()); - } + /** + * Called after the {@link BindingFault} has been created. Subclasses can implement this method to define the name, + * or add extensions to it. + * + *

Default implementation set the name of the binding fault to the name of the fault. + * + * @param bindingFault the WSDL4J {@code BindingFault} + * @param fault the corresponding WSDL4J {@code Fault} @throws WSDLException in case of errors + */ + protected void populateBindingFault(Definition definition, BindingFault bindingFault, Fault fault) + throws WSDLException { + bindingFault.setName(fault.getName()); + } - /** - * Creates a single {@link Service} if not present, and calls {@link #populateService(Definition, Service)} with it. - * Creates a corresponding {@link Port} for each {@link Binding}, which is passed to {@link - * #populatePort(javax.wsdl.Definition,javax.wsdl.Port)}. - * - * @param definition the WSDL4J {@code Definition} - * @throws WSDLException in case of errors - */ - @Override - public void addServices(Definition definition) throws WSDLException { - Assert.notNull(getServiceName(), "'serviceName' is required"); - Service service; - if (definition.getServices().isEmpty()) { - service = definition.createService(); - } - else { - service = (Service) definition.getServices().values().iterator().next(); - } - populateService(definition, service); - createPorts(definition, service); - if (service.getQName() != null) { - definition.addService(service); - } - } + /** + * Creates a single {@link Service} if not present, and calls {@link #populateService(Definition, Service)} with it. + * Creates a corresponding {@link Port} for each {@link Binding}, which is passed to {@link + * #populatePort(javax.wsdl.Definition,javax.wsdl.Port)}. + * + * @param definition the WSDL4J {@code Definition} + * @throws WSDLException in case of errors + */ + @Override + public void addServices(Definition definition) throws WSDLException { + Assert.notNull(getServiceName(), "'serviceName' is required"); + Service service; + if (definition.getServices().isEmpty()) { + service = definition.createService(); + } + else { + service = (Service) definition.getServices().values().iterator().next(); + } + populateService(definition, service); + createPorts(definition, service); + if (service.getQName() != null) { + definition.addService(service); + } + } - /** - * Called after the {@link Service} has been created, but before any sub-elements are added. Subclasses can - * implement this method to define the service name, or add extensions to it. - * - *

Default implementation sets the name to the {@link #setServiceName(String) serviceName} property. - * - * @param service the WSDL4J {@code Service} - * @throws WSDLException in case of errors - */ - protected void populateService(Definition definition, Service service) throws WSDLException { - if (StringUtils.hasText(definition.getTargetNamespace()) && StringUtils.hasText(getServiceName())) { - QName serviceName = new QName(definition.getTargetNamespace(), getServiceName()); - if (logger.isDebugEnabled()) { - logger.debug("Creating service [" + serviceName + "]"); - } - service.setQName(serviceName); - } - } + /** + * Called after the {@link Service} has been created, but before any sub-elements are added. Subclasses can + * implement this method to define the service name, or add extensions to it. + * + *

Default implementation sets the name to the {@link #setServiceName(String) serviceName} property. + * + * @param service the WSDL4J {@code Service} + * @throws WSDLException in case of errors + */ + protected void populateService(Definition definition, Service service) throws WSDLException { + if (StringUtils.hasText(definition.getTargetNamespace()) && StringUtils.hasText(getServiceName())) { + QName serviceName = new QName(definition.getTargetNamespace(), getServiceName()); + if (logger.isDebugEnabled()) { + logger.debug("Creating service [" + serviceName + "]"); + } + service.setQName(serviceName); + } + } - private void createPorts(Definition definition, Service service) throws WSDLException { - for (Iterator iterator = definition.getBindings().values().iterator(); iterator.hasNext();) { - Binding binding = (Binding) iterator.next(); - Port port = null; - for (Iterator iterator1 = service.getPorts().values().iterator(); iterator1.hasNext();) { - Port existingPort = (Port) iterator1.next(); - if (binding.equals(existingPort.getBinding())) { - port = existingPort; - } - } - if (port == null) { - port = definition.createPort(); - port.setBinding(binding); - } - populatePort(definition, port); - if (StringUtils.hasText(port.getName())) { - if (logger.isDebugEnabled()) { - logger.debug("Adding port [" + port.getName() + "] to service [" + service.getQName() + "]"); - } - service.addPort(port); - } - } - if (service.getPorts().isEmpty() && logger.isWarnEnabled()) { - logger.warn("No ports were created, make sure the WSDL contains bindings"); - } - } + private void createPorts(Definition definition, Service service) throws WSDLException { + for (Iterator iterator = definition.getBindings().values().iterator(); iterator.hasNext();) { + Binding binding = (Binding) iterator.next(); + Port port = null; + for (Iterator iterator1 = service.getPorts().values().iterator(); iterator1.hasNext();) { + Port existingPort = (Port) iterator1.next(); + if (binding.equals(existingPort.getBinding())) { + port = existingPort; + } + } + if (port == null) { + port = definition.createPort(); + port.setBinding(binding); + } + populatePort(definition, port); + if (StringUtils.hasText(port.getName())) { + if (logger.isDebugEnabled()) { + logger.debug("Adding port [" + port.getName() + "] to service [" + service.getQName() + "]"); + } + service.addPort(port); + } + } + if (service.getPorts().isEmpty() && logger.isWarnEnabled()) { + logger.warn("No ports were created, make sure the WSDL contains bindings"); + } + } - /** - * Called after the {@link Port} has been created, but before any sub-elements are added. Subclasses can implement - * this method to define the port name, or add extensions to it. - * - *

Default implementation sets the port name to the binding name. - * - * @param definition the WSDL4J {@code Definition} - * @param port the WSDL4J {@code Port} - * @throws WSDLException in case of errors - */ - protected void populatePort(Definition definition, Port port) throws WSDLException { - String portName = port.getBinding().getQName().getLocalPart(); - port.setName(portName); - } + /** + * Called after the {@link Port} has been created, but before any sub-elements are added. Subclasses can implement + * this method to define the port name, or add extensions to it. + * + *

Default implementation sets the port name to the binding name. + * + * @param definition the WSDL4J {@code Definition} + * @param port the WSDL4J {@code Port} + * @throws WSDLException in case of errors + */ + protected void populatePort(Definition definition, Port port) throws WSDLException { + String portName = port.getBinding().getQName().getLocalPart(); + port.setName(portName); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProvider.java index f3efadb9..da68fa29 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProvider.java @@ -44,106 +44,106 @@ import org.springframework.util.Assert; */ public class DefaultMessagesProvider implements MessagesProvider { - private static final Log logger = LogFactory.getLog(DefaultMessagesProvider.class); + private static final Log logger = LogFactory.getLog(DefaultMessagesProvider.class); - @Override - public void addMessages(Definition definition) throws WSDLException { - Types types = definition.getTypes(); - Assert.notNull(types, "No types element present in definition"); - for (Iterator iterator = types.getExtensibilityElements().iterator(); iterator.hasNext();) { - ExtensibilityElement extensibilityElement = (ExtensibilityElement) iterator.next(); - if (extensibilityElement instanceof Schema) { - Schema schema = (Schema) extensibilityElement; - if (schema.getElement() != null) { - createMessages(definition, schema.getElement()); - } - } - } - if (definition.getMessages().isEmpty() && logger.isWarnEnabled()) { - logger.warn("No messages were created, make sure the referenced schema(s) contain elements"); - } - } + @Override + public void addMessages(Definition definition) throws WSDLException { + Types types = definition.getTypes(); + Assert.notNull(types, "No types element present in definition"); + for (Iterator iterator = types.getExtensibilityElements().iterator(); iterator.hasNext();) { + ExtensibilityElement extensibilityElement = (ExtensibilityElement) iterator.next(); + if (extensibilityElement instanceof Schema) { + Schema schema = (Schema) extensibilityElement; + if (schema.getElement() != null) { + createMessages(definition, schema.getElement()); + } + } + } + if (definition.getMessages().isEmpty() && logger.isWarnEnabled()) { + logger.warn("No messages were created, make sure the referenced schema(s) contain elements"); + } + } - private void createMessages(Definition definition, Element schemaElement) throws WSDLException { - String schemaTargetNamespace = schemaElement.getAttribute("targetNamespace"); - Assert.hasText(schemaTargetNamespace, "No targetNamespace defined on schema"); - if (logger.isDebugEnabled()) { - logger.debug("Looking for elements in schema with target namespace [" + schemaTargetNamespace + "]"); - } - NodeList children = schemaElement.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElement = (Element) child; - if (isMessageElement(childElement)) { - QName elementName = new QName(schemaTargetNamespace, getElementName(childElement)); - Message message = definition.createMessage(); - populateMessage(definition, message, elementName); - Part part = definition.createPart(); - populatePart(definition, part, elementName); - message.addPart(part); - message.setUndefined(false); - definition.addMessage(message); - } - } - } - } + private void createMessages(Definition definition, Element schemaElement) throws WSDLException { + String schemaTargetNamespace = schemaElement.getAttribute("targetNamespace"); + Assert.hasText(schemaTargetNamespace, "No targetNamespace defined on schema"); + if (logger.isDebugEnabled()) { + logger.debug("Looking for elements in schema with target namespace [" + schemaTargetNamespace + "]"); + } + NodeList children = schemaElement.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + Element childElement = (Element) child; + if (isMessageElement(childElement)) { + QName elementName = new QName(schemaTargetNamespace, getElementName(childElement)); + Message message = definition.createMessage(); + populateMessage(definition, message, elementName); + Part part = definition.createPart(); + populatePart(definition, part, elementName); + message.addPart(part); + message.setUndefined(false); + definition.addMessage(message); + } + } + } + } - /** - * Returns the name attribute of the given element. - * - * @param element the element whose name to return - * @return the name of the element - */ - protected String getElementName(Element element) { - return element.getAttribute("name"); - } + /** + * Returns the name attribute of the given element. + * + * @param element the element whose name to return + * @return the name of the element + */ + protected String getElementName(Element element) { + return element.getAttribute("name"); + } - /** - * Indicates whether the given element should be includes as {@link Message} in the definition. - * - *

Default implementation checks whether the element has the XML Schema namespace, and if it has the local name - * "element". - * - * @param element the element elligable for being a message - * @return {@code true} if to be included as message; {@code false} otherwise - */ - protected boolean isMessageElement(Element element) { - return "element".equals(element.getLocalName()) && - "http://www.w3.org/2001/XMLSchema".equals(element.getNamespaceURI()); - } + /** + * Indicates whether the given element should be includes as {@link Message} in the definition. + * + *

Default implementation checks whether the element has the XML Schema namespace, and if it has the local name + * "element". + * + * @param element the element elligable for being a message + * @return {@code true} if to be included as message; {@code false} otherwise + */ + protected boolean isMessageElement(Element element) { + return "element".equals(element.getLocalName()) && + "http://www.w3.org/2001/XMLSchema".equals(element.getNamespaceURI()); + } - /** - * Called after the {@link Message} has been created. - * - *

Default implementation sets the name of the message to the element name. - * - * @param definition the WSDL4J {@code Definition} - * @param message the WSDL4J {@code Message} - * @param elementName the element name - * @throws WSDLException in case of errors - */ - protected void populateMessage(Definition definition, Message message, QName elementName) throws WSDLException { - QName messageName = new QName(definition.getTargetNamespace(), elementName.getLocalPart()); - if (logger.isDebugEnabled()) { - logger.debug("Creating message [" + messageName + "]"); - } - message.setQName(messageName); - } + /** + * Called after the {@link Message} has been created. + * + *

Default implementation sets the name of the message to the element name. + * + * @param definition the WSDL4J {@code Definition} + * @param message the WSDL4J {@code Message} + * @param elementName the element name + * @throws WSDLException in case of errors + */ + protected void populateMessage(Definition definition, Message message, QName elementName) throws WSDLException { + QName messageName = new QName(definition.getTargetNamespace(), elementName.getLocalPart()); + if (logger.isDebugEnabled()) { + logger.debug("Creating message [" + messageName + "]"); + } + message.setQName(messageName); + } - /** - * Called after the {@link Part} has been created. - * - *

Default implementation sets the element name of the part. - * - * @param definition the WSDL4J {@code Definition} - * @param part the WSDL4J {@code Part} - * @param elementName the elementName @throws WSDLException in case of errors - * @see Part#setElementName(javax.xml.namespace.QName) - */ - protected void populatePart(Definition definition, Part part, QName elementName) throws WSDLException { - part.setElementName(elementName); - part.setName(elementName.getLocalPart()); - } + /** + * Called after the {@link Part} has been created. + * + *

Default implementation sets the element name of the part. + * + * @param definition the WSDL4J {@code Definition} + * @param part the WSDL4J {@code Part} + * @param elementName the elementName @throws WSDLException in case of errors + * @see Part#setElementName(javax.xml.namespace.QName) + */ + protected void populatePart(Definition definition, Part part, QName elementName) throws WSDLException { + part.setElementName(elementName); + part.setName(elementName.getLocalPart()); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ImportsProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ImportsProvider.java index 6f127d46..dd0e4437 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ImportsProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ImportsProvider.java @@ -29,6 +29,6 @@ import javax.wsdl.WSDLException; */ public interface ImportsProvider { - void addImports(Definition definition) throws WSDLException; + void addImports(Definition definition) throws WSDLException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProvider.java index d5204408..0889eedd 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProvider.java @@ -45,78 +45,78 @@ import org.springframework.xml.xsd.XsdSchemaCollection; */ public class InliningXsdSchemaTypesProvider extends TransformerObjectSupport implements TypesProvider { - private static final Log logger = LogFactory.getLog(InliningXsdSchemaTypesProvider.class); + private static final Log logger = LogFactory.getLog(InliningXsdSchemaTypesProvider.class); - /** The prefix used to register the schema namespace in the WSDL. */ - public static final String SCHEMA_PREFIX = "sch"; + /** The prefix used to register the schema namespace in the WSDL. */ + public static final String SCHEMA_PREFIX = "sch"; - private XsdSchemaCollection schemaCollection; + private XsdSchemaCollection schemaCollection; - /** - * Sets the single XSD schema to inline. Either this property, or {@link #setSchemaCollection(XsdSchemaCollection) - * schemaCollection} must be set. - */ - public void setSchema(final XsdSchema schema) { - this.schemaCollection = new XsdSchemaCollection() { + /** + * Sets the single XSD schema to inline. Either this property, or {@link #setSchemaCollection(XsdSchemaCollection) + * schemaCollection} must be set. + */ + public void setSchema(final XsdSchema schema) { + this.schemaCollection = new XsdSchemaCollection() { - public XsdSchema[] getXsdSchemas() { - return new XsdSchema[]{schema}; - } + public XsdSchema[] getXsdSchemas() { + return new XsdSchema[]{schema}; + } - public XmlValidator createValidator() { - throw new UnsupportedOperationException(); - } - }; - } + public XmlValidator createValidator() { + throw new UnsupportedOperationException(); + } + }; + } - /** Returns the XSD schema collection to inline. */ - public XsdSchemaCollection getSchemaCollection() { - return schemaCollection; - } + /** Returns the XSD schema collection to inline. */ + public XsdSchemaCollection getSchemaCollection() { + return schemaCollection; + } - /** - * Sets the XSD schema collection to inline. Either this property, or {@link #setSchema(XsdSchema) schema} must be - * set. - */ - public void setSchemaCollection(XsdSchemaCollection schemaCollection) { - this.schemaCollection = schemaCollection; - } + /** + * Sets the XSD schema collection to inline. Either this property, or {@link #setSchema(XsdSchema) schema} must be + * set. + */ + public void setSchemaCollection(XsdSchemaCollection schemaCollection) { + this.schemaCollection = schemaCollection; + } - @Override - public void addTypes(Definition definition) throws WSDLException { - Assert.notNull(getSchemaCollection(), "setting 'schema' or 'schemaCollection' is required"); - Types types = definition.createTypes(); - XsdSchema[] schemas = schemaCollection.getXsdSchemas(); - for (int i = 0; i < schemas.length; i++) { - if (logger.isDebugEnabled()) { - logger.debug("Inlining " + schemas[i]); - } - if (schemas.length == 1) { - definition.addNamespace(SCHEMA_PREFIX, schemas[i].getTargetNamespace()); - } - else { - String prefix = SCHEMA_PREFIX + i; - definition.addNamespace(prefix, schemas[i].getTargetNamespace()); - } - Element schemaElement = getSchemaElement(schemas[i]); - Schema schema = (Schema) definition.getExtensionRegistry() - .createExtension(Types.class, new QName("http://www.w3.org/2001/XMLSchema", "schema")); - types.addExtensibilityElement(schema); - schema.setElement(schemaElement); - } - definition.setTypes(types); - } + @Override + public void addTypes(Definition definition) throws WSDLException { + Assert.notNull(getSchemaCollection(), "setting 'schema' or 'schemaCollection' is required"); + Types types = definition.createTypes(); + XsdSchema[] schemas = schemaCollection.getXsdSchemas(); + for (int i = 0; i < schemas.length; i++) { + if (logger.isDebugEnabled()) { + logger.debug("Inlining " + schemas[i]); + } + if (schemas.length == 1) { + definition.addNamespace(SCHEMA_PREFIX, schemas[i].getTargetNamespace()); + } + else { + String prefix = SCHEMA_PREFIX + i; + definition.addNamespace(prefix, schemas[i].getTargetNamespace()); + } + Element schemaElement = getSchemaElement(schemas[i]); + Schema schema = (Schema) definition.getExtensionRegistry() + .createExtension(Types.class, new QName("http://www.w3.org/2001/XMLSchema", "schema")); + types.addExtensibilityElement(schema); + schema.setElement(schemaElement); + } + definition.setTypes(types); + } - private Element getSchemaElement(XsdSchema schema) { - try { - DOMResult result = new DOMResult(); - transform(schema.getSource(), result); - Document schemaDocument = (Document) result.getNode(); - return schemaDocument.getDocumentElement(); - } - catch (TransformerException e) { - throw new WsdlDefinitionException("Could not transform schema source to Document"); - } - } + private Element getSchemaElement(XsdSchema schema) { + try { + DOMResult result = new DOMResult(); + transform(schema.getSource(), result); + Document schemaDocument = (Document) result.getNode(); + return schemaDocument.getDocumentElement(); + } + catch (TransformerException e) { + throw new WsdlDefinitionException("Could not transform schema source to Document"); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/MessagesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/MessagesProvider.java index c195dbd6..af05e52a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/MessagesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/MessagesProvider.java @@ -29,6 +29,6 @@ import javax.wsdl.WSDLException; */ public interface MessagesProvider { - void addMessages(Definition definition) throws WSDLException; + void addMessages(Definition definition) throws WSDLException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/PortTypesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/PortTypesProvider.java index 40b5c90f..794682e3 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/PortTypesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/PortTypesProvider.java @@ -29,6 +29,6 @@ import javax.wsdl.WSDLException; */ public interface PortTypesProvider { - void addPortTypes(Definition definition) throws WSDLException; + void addPortTypes(Definition definition) throws WSDLException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ServicesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ServicesProvider.java index 69453154..da3c139e 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ServicesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/ServicesProvider.java @@ -29,6 +29,6 @@ import javax.wsdl.WSDLException; */ public interface ServicesProvider { - void addServices(Definition definition) throws WSDLException; + void addServices(Definition definition) throws WSDLException; } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11Provider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11Provider.java index 166db53d..54e69073 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11Provider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11Provider.java @@ -52,300 +52,300 @@ import org.springframework.util.Assert; */ public class Soap11Provider extends DefaultConcretePartProvider { - /** The default transport URI, which indicates an HTTP transport. */ - public static final String DEFAULT_TRANSPORT_URI = "http://schemas.xmlsoap.org/soap/http"; + /** The default transport URI, which indicates an HTTP transport. */ + public static final String DEFAULT_TRANSPORT_URI = "http://schemas.xmlsoap.org/soap/http"; - /** The prefix of the WSDL SOAP 1.1 namespace. */ - public static final String SOAP_11_NAMESPACE_PREFIX = "soap"; + /** The prefix of the WSDL SOAP 1.1 namespace. */ + public static final String SOAP_11_NAMESPACE_PREFIX = "soap"; - /** The WSDL SOAP 1.1 namespace. */ - public static final String SOAP_11_NAMESPACE_URI = "http://schemas.xmlsoap.org/wsdl/soap/"; + /** The WSDL SOAP 1.1 namespace. */ + public static final String SOAP_11_NAMESPACE_URI = "http://schemas.xmlsoap.org/wsdl/soap/"; - private String transportUri = DEFAULT_TRANSPORT_URI; + private String transportUri = DEFAULT_TRANSPORT_URI; - private Properties soapActions = new Properties(); + private Properties soapActions = new Properties(); - private String locationUri; + private String locationUri; - /** - * Constructs a new version of the {@link Soap11Provider}. - * - *

Sets the {@link #setBindingSuffix(String) binding suffix} to {@code Soap11}. - */ - public Soap11Provider() { - setBindingSuffix("Soap11"); - } + /** + * Constructs a new version of the {@link Soap11Provider}. + * + *

Sets the {@link #setBindingSuffix(String) binding suffix} to {@code Soap11}. + */ + public Soap11Provider() { + setBindingSuffix("Soap11"); + } - /** - * Returns the SOAP Actions for this binding. Keys are {@link BindingOperation#getName() binding operation names}; - * values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. - * - * @return the soap actions - */ - public Properties getSoapActions() { - return soapActions; - } + /** + * Returns the SOAP Actions for this binding. Keys are {@link BindingOperation#getName() binding operation names}; + * values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. + * + * @return the soap actions + */ + public Properties getSoapActions() { + return soapActions; + } - /** - * Sets the SOAP Actions for this binding. Keys are {@link BindingOperation#getName() binding operation names}; - * values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. - * - * @param soapActions the soap - */ - public void setSoapActions(Properties soapActions) { - Assert.notNull(soapActions, "'soapActions' must not be null"); - this.soapActions = soapActions; - } + /** + * Sets the SOAP Actions for this binding. Keys are {@link BindingOperation#getName() binding operation names}; + * values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. + * + * @param soapActions the soap + */ + public void setSoapActions(Properties soapActions) { + Assert.notNull(soapActions, "'soapActions' must not be null"); + this.soapActions = soapActions; + } - /** - * Returns the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. - * - * @return the binding transport value - */ - public String getTransportUri() { - return transportUri; - } + /** + * Returns the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. + * + * @return the binding transport value + */ + public String getTransportUri() { + return transportUri; + } - /** - * Sets the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. - * - * @param transportUri the binding transport value - */ - public void setTransportUri(String transportUri) { - Assert.notNull(transportUri, "'transportUri' must not be null"); - this.transportUri = transportUri; - } + /** + * Sets the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. + * + * @param transportUri the binding transport value + */ + public void setTransportUri(String transportUri) { + Assert.notNull(transportUri, "'transportUri' must not be null"); + this.transportUri = transportUri; + } - /** Returns the value used for the SOAP Address location attribute value. */ - public String getLocationUri() { - return locationUri; - } + /** Returns the value used for the SOAP Address location attribute value. */ + public String getLocationUri() { + return locationUri; + } - /** Sets the value used for the SOAP Address location attribute value. */ - public void setLocationUri(String locationUri) { - this.locationUri = locationUri; - } + /** Sets the value used for the SOAP Address location attribute value. */ + public void setLocationUri(String locationUri) { + this.locationUri = locationUri; + } - /** - * Called after the {@link Binding} has been created, but before any sub-elements are added. Subclasses can override - * this method to define the binding name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBinding(Definition, Binding)}, adds the - * SOAP 1.1 namespace, creates a {@link SOAPBinding}, and calls {@link #populateSoapBinding(SOAPBinding, Binding)} - * sets the binding name to the port type name with the {@link #getBindingSuffix() suffix} appended to it. - * - * @param definition the WSDL4J {@code Definition} - * @param binding the WSDL4J {@code Binding} - */ - @Override - protected void populateBinding(Definition definition, Binding binding) throws WSDLException { - definition.addNamespace(SOAP_11_NAMESPACE_PREFIX, SOAP_11_NAMESPACE_URI); - super.populateBinding(definition, binding); - SOAPBinding soapBinding = (SOAPBinding) createSoapExtension(definition, Binding.class, "binding"); - populateSoapBinding(soapBinding, binding); - binding.addExtensibilityElement(soapBinding); - } + /** + * Called after the {@link Binding} has been created, but before any sub-elements are added. Subclasses can override + * this method to define the binding name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBinding(Definition, Binding)}, adds the + * SOAP 1.1 namespace, creates a {@link SOAPBinding}, and calls {@link #populateSoapBinding(SOAPBinding, Binding)} + * sets the binding name to the port type name with the {@link #getBindingSuffix() suffix} appended to it. + * + * @param definition the WSDL4J {@code Definition} + * @param binding the WSDL4J {@code Binding} + */ + @Override + protected void populateBinding(Definition definition, Binding binding) throws WSDLException { + definition.addNamespace(SOAP_11_NAMESPACE_PREFIX, SOAP_11_NAMESPACE_URI); + super.populateBinding(definition, binding); + SOAPBinding soapBinding = (SOAPBinding) createSoapExtension(definition, Binding.class, "binding"); + populateSoapBinding(soapBinding, binding); + binding.addExtensibilityElement(soapBinding); + } - /** - * Called after the {@link SOAPBinding} has been created. - * - *

Default implementation sets the binding style to {@code "document"}, and set the transport URI to the {@link - * #setTransportUri(String) transportUri} property value. Subclasses can override this behavior. - * - * @param soapBinding the WSDL4J {@code SOAPBinding} - * @throws WSDLException in case of errors - * @see SOAPBinding#setStyle(String) - * @see SOAPBinding#setTransportURI(String) - * @see #setTransportUri(String) - * @see #DEFAULT_TRANSPORT_URI - */ - protected void populateSoapBinding(SOAPBinding soapBinding, Binding binding) throws WSDLException { - soapBinding.setStyle("document"); - soapBinding.setTransportURI(getTransportUri()); - } + /** + * Called after the {@link SOAPBinding} has been created. + * + *

Default implementation sets the binding style to {@code "document"}, and set the transport URI to the {@link + * #setTransportUri(String) transportUri} property value. Subclasses can override this behavior. + * + * @param soapBinding the WSDL4J {@code SOAPBinding} + * @throws WSDLException in case of errors + * @see SOAPBinding#setStyle(String) + * @see SOAPBinding#setTransportURI(String) + * @see #setTransportUri(String) + * @see #DEFAULT_TRANSPORT_URI + */ + protected void populateSoapBinding(SOAPBinding soapBinding, Binding binding) throws WSDLException { + soapBinding.setStyle("document"); + soapBinding.setTransportURI(getTransportUri()); + } - /** - * Called after the {@link BindingFault} has been created. Subclasses can override this method to define the name, - * or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingFault(Definition, BindingFault, - * Fault)}, creates a {@link SOAPFault}, and calls {@link #populateSoapFault(BindingFault, SOAPFault)}. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingFault the WSDL4J {@code BindingFault} - * @param fault the corresponding WSDL4J {@code Fault} @throws WSDLException in case of errors - */ - @Override - protected void populateBindingFault(Definition definition, BindingFault bindingFault, Fault fault) - throws WSDLException { - super.populateBindingFault(definition, bindingFault, fault); - SOAPFault soapFault = (SOAPFault) createSoapExtension(definition, BindingFault.class, "fault"); - populateSoapFault(bindingFault, soapFault); - bindingFault.addExtensibilityElement(soapFault); - } + /** + * Called after the {@link BindingFault} has been created. Subclasses can override this method to define the name, + * or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingFault(Definition, BindingFault, + * Fault)}, creates a {@link SOAPFault}, and calls {@link #populateSoapFault(BindingFault, SOAPFault)}. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingFault the WSDL4J {@code BindingFault} + * @param fault the corresponding WSDL4J {@code Fault} @throws WSDLException in case of errors + */ + @Override + protected void populateBindingFault(Definition definition, BindingFault bindingFault, Fault fault) + throws WSDLException { + super.populateBindingFault(definition, bindingFault, fault); + SOAPFault soapFault = (SOAPFault) createSoapExtension(definition, BindingFault.class, "fault"); + populateSoapFault(bindingFault, soapFault); + bindingFault.addExtensibilityElement(soapFault); + } - /** - * Called after the {@link SOAPFault} has been created. - * - *

Default implementation sets the use style to {@code "literal"}, and sets the name equal to the binding - * fault. Subclasses can override this behavior. - * - * @param bindingFault the WSDL4J {@code BindingFault} - * @param soapFault the WSDL4J {@code SOAPFault} - * @throws WSDLException in case of errors - * @see SOAPFault#setUse(String) - */ - protected void populateSoapFault(BindingFault bindingFault, SOAPFault soapFault) throws WSDLException { - soapFault.setName(bindingFault.getName()); - soapFault.setUse("literal"); - } + /** + * Called after the {@link SOAPFault} has been created. + * + *

Default implementation sets the use style to {@code "literal"}, and sets the name equal to the binding + * fault. Subclasses can override this behavior. + * + * @param bindingFault the WSDL4J {@code BindingFault} + * @param soapFault the WSDL4J {@code SOAPFault} + * @throws WSDLException in case of errors + * @see SOAPFault#setUse(String) + */ + protected void populateSoapFault(BindingFault bindingFault, SOAPFault soapFault) throws WSDLException { + soapFault.setName(bindingFault.getName()); + soapFault.setUse("literal"); + } - /** - * Called after the {@link BindingInput} has been created. Subclasses can implement this method to define the name, - * or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingInput(Definition, - * javax.wsdl.BindingInput, javax.wsdl.Input)}, creates a {@link SOAPBody}, and calls {@link - * #populateSoapBody(SOAPBody)}. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingInput the WSDL4J {@code BindingInput} - * @param input the corresponding WSDL4J {@code Input} @throws WSDLException in case of errors - */ - @Override - protected void populateBindingInput(Definition definition, BindingInput bindingInput, Input input) - throws WSDLException { - super.populateBindingInput(definition, bindingInput, input); - SOAPBody soapBody = (SOAPBody) createSoapExtension(definition, BindingInput.class, "body"); - populateSoapBody(soapBody); - bindingInput.addExtensibilityElement(soapBody); - } + /** + * Called after the {@link BindingInput} has been created. Subclasses can implement this method to define the name, + * or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingInput(Definition, + * javax.wsdl.BindingInput, javax.wsdl.Input)}, creates a {@link SOAPBody}, and calls {@link + * #populateSoapBody(SOAPBody)}. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingInput the WSDL4J {@code BindingInput} + * @param input the corresponding WSDL4J {@code Input} @throws WSDLException in case of errors + */ + @Override + protected void populateBindingInput(Definition definition, BindingInput bindingInput, Input input) + throws WSDLException { + super.populateBindingInput(definition, bindingInput, input); + SOAPBody soapBody = (SOAPBody) createSoapExtension(definition, BindingInput.class, "body"); + populateSoapBody(soapBody); + bindingInput.addExtensibilityElement(soapBody); + } - /** - * Called after the {@link SOAPBody} has been created. - * - *

Default implementation sets the use style to {@code "literal"}. Subclasses can override this behavior. - * - * @param soapBody the WSDL4J {@code SOAPBody} - * @throws WSDLException in case of errors - * @see SOAPBody#setUse(String) - */ - protected void populateSoapBody(SOAPBody soapBody) throws WSDLException { - soapBody.setUse("literal"); - } + /** + * Called after the {@link SOAPBody} has been created. + * + *

Default implementation sets the use style to {@code "literal"}. Subclasses can override this behavior. + * + * @param soapBody the WSDL4J {@code SOAPBody} + * @throws WSDLException in case of errors + * @see SOAPBody#setUse(String) + */ + protected void populateSoapBody(SOAPBody soapBody) throws WSDLException { + soapBody.setUse("literal"); + } - /** - * Called after the {@link BindingOperation} has been created, but before any sub-elements are added. Subclasses can - * implement this method to define the binding name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOperation(Definition, - * BindingOperation)}, creates a {@link SOAPOperation}, and calls {@link #populateSoapOperation} sets the name of - * the binding operation to the name of the operation. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingOperation the WSDL4J {@code BindingOperation} - * @throws WSDLException in case of errors - */ - @Override - protected void populateBindingOperation(Definition definition, BindingOperation bindingOperation) - throws WSDLException { - super.populateBindingOperation(definition, bindingOperation); - SOAPOperation soapOperation = - (SOAPOperation) createSoapExtension(definition, BindingOperation.class, "operation"); - populateSoapOperation(soapOperation, bindingOperation); - bindingOperation.addExtensibilityElement(soapOperation); - } + /** + * Called after the {@link BindingOperation} has been created, but before any sub-elements are added. Subclasses can + * implement this method to define the binding name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOperation(Definition, + * BindingOperation)}, creates a {@link SOAPOperation}, and calls {@link #populateSoapOperation} sets the name of + * the binding operation to the name of the operation. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingOperation the WSDL4J {@code BindingOperation} + * @throws WSDLException in case of errors + */ + @Override + protected void populateBindingOperation(Definition definition, BindingOperation bindingOperation) + throws WSDLException { + super.populateBindingOperation(definition, bindingOperation); + SOAPOperation soapOperation = + (SOAPOperation) createSoapExtension(definition, BindingOperation.class, "operation"); + populateSoapOperation(soapOperation, bindingOperation); + bindingOperation.addExtensibilityElement(soapOperation); + } - /** - * Called after the {@link SOAPOperation} has been created. - * - *

Default implementation sets {@code SOAPAction} to the corresponding {@link - * #setSoapActions(java.util.Properties) soapActions} property, and defaults to "". - * - * @param soapOperation the WSDL4J {@code SOAPOperation} - * @param bindingOperation the WSDL4J {@code BindingOperation} - * @throws WSDLException in case of errors - * @see SOAPOperation#setSoapActionURI(String) - * @see #setSoapActions(java.util.Properties) - */ - protected void populateSoapOperation(SOAPOperation soapOperation, BindingOperation bindingOperation) - throws WSDLException { - String bindingOperationName = bindingOperation.getName(); - String soapAction = getSoapActions().getProperty(bindingOperationName, ""); - soapOperation.setSoapActionURI(soapAction); - } + /** + * Called after the {@link SOAPOperation} has been created. + * + *

Default implementation sets {@code SOAPAction} to the corresponding {@link + * #setSoapActions(java.util.Properties) soapActions} property, and defaults to "". + * + * @param soapOperation the WSDL4J {@code SOAPOperation} + * @param bindingOperation the WSDL4J {@code BindingOperation} + * @throws WSDLException in case of errors + * @see SOAPOperation#setSoapActionURI(String) + * @see #setSoapActions(java.util.Properties) + */ + protected void populateSoapOperation(SOAPOperation soapOperation, BindingOperation bindingOperation) + throws WSDLException { + String bindingOperationName = bindingOperation.getName(); + String soapAction = getSoapActions().getProperty(bindingOperationName, ""); + soapOperation.setSoapActionURI(soapAction); + } - /** - * Called after the {@link BindingInput} has been created. Subclasses can implement this method to define the name, - * or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOutput(Definition, BindingOutput, - * Output)}, creates a {@link SOAPBody}, and calls {@link #populateSoapBody(SOAPBody)}. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingOutput the WSDL4J {@code BindingOutput} - * @param output the corresponding WSDL4J {@code Output} @throws WSDLException in case of errors - */ - @Override - protected void populateBindingOutput(Definition definition, BindingOutput bindingOutput, Output output) - throws WSDLException { - super.populateBindingOutput(definition, bindingOutput, output); - SOAPBody soapBody = (SOAPBody) createSoapExtension(definition, BindingOutput.class, "body"); - populateSoapBody(soapBody); - bindingOutput.addExtensibilityElement(soapBody); - } + /** + * Called after the {@link BindingInput} has been created. Subclasses can implement this method to define the name, + * or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOutput(Definition, BindingOutput, + * Output)}, creates a {@link SOAPBody}, and calls {@link #populateSoapBody(SOAPBody)}. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingOutput the WSDL4J {@code BindingOutput} + * @param output the corresponding WSDL4J {@code Output} @throws WSDLException in case of errors + */ + @Override + protected void populateBindingOutput(Definition definition, BindingOutput bindingOutput, Output output) + throws WSDLException { + super.populateBindingOutput(definition, bindingOutput, output); + SOAPBody soapBody = (SOAPBody) createSoapExtension(definition, BindingOutput.class, "body"); + populateSoapBody(soapBody); + bindingOutput.addExtensibilityElement(soapBody); + } - /** - * Called after the {@link Port} has been created, but before any sub-elements are added. Subclasses can implement - * this method to define the port name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populatePort(javax.wsdl.Definition,javax.wsdl.Port)}, - * creates a {@link SOAPAddress}, and calls {@link #populateSoapAddress(SOAPAddress)}. - * - * @param port the WSDL4J {@code Port} - * @throws WSDLException in case of errors - */ - @Override - protected void populatePort(Definition definition, Port port) throws WSDLException { - for (Iterator iterator = port.getBinding().getExtensibilityElements().iterator(); iterator.hasNext();) { - if (iterator.next() instanceof SOAPBinding) { - // this is a SOAP 1.1 binding, create a SOAP Address for it - super.populatePort(definition, port); - SOAPAddress soapAddress = (SOAPAddress) createSoapExtension(definition, Port.class, "address"); - populateSoapAddress(soapAddress); - port.addExtensibilityElement(soapAddress); - return; - } - } - } + /** + * Called after the {@link Port} has been created, but before any sub-elements are added. Subclasses can implement + * this method to define the port name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populatePort(javax.wsdl.Definition,javax.wsdl.Port)}, + * creates a {@link SOAPAddress}, and calls {@link #populateSoapAddress(SOAPAddress)}. + * + * @param port the WSDL4J {@code Port} + * @throws WSDLException in case of errors + */ + @Override + protected void populatePort(Definition definition, Port port) throws WSDLException { + for (Iterator iterator = port.getBinding().getExtensibilityElements().iterator(); iterator.hasNext();) { + if (iterator.next() instanceof SOAPBinding) { + // this is a SOAP 1.1 binding, create a SOAP Address for it + super.populatePort(definition, port); + SOAPAddress soapAddress = (SOAPAddress) createSoapExtension(definition, Port.class, "address"); + populateSoapAddress(soapAddress); + port.addExtensibilityElement(soapAddress); + return; + } + } + } - /** - * Called after the {@link SOAPAddress} has been created. Default implementation sets the location URI to the value - * set on this builder. Subclasses can override this behavior. - * - * @param soapAddress the WSDL4J {@code SOAPAddress} - * @throws WSDLException in case of errors - * @see SOAPAddress#setLocationURI(String) - * @see #setLocationUri(String) - */ - protected void populateSoapAddress(SOAPAddress soapAddress) throws WSDLException { - soapAddress.setLocationURI(getLocationUri()); - } + /** + * Called after the {@link SOAPAddress} has been created. Default implementation sets the location URI to the value + * set on this builder. Subclasses can override this behavior. + * + * @param soapAddress the WSDL4J {@code SOAPAddress} + * @throws WSDLException in case of errors + * @see SOAPAddress#setLocationURI(String) + * @see #setLocationUri(String) + */ + protected void populateSoapAddress(SOAPAddress soapAddress) throws WSDLException { + soapAddress.setLocationURI(getLocationUri()); + } - /** - * Creates a SOAP extensibility element. - * - * @param definition the WSDL4J {@code Definition} - * @param parentType a class object indicating where in the WSDL definition this extension will exist - * @param localName the local name of the extensibility element - * @return the extensibility element - * @throws WSDLException in case of errors - * @see ExtensionRegistry#createExtension(Class, QName) - */ - private ExtensibilityElement createSoapExtension(Definition definition, Class parentType, String localName) - throws WSDLException { - return definition.getExtensionRegistry() - .createExtension(parentType, new QName(SOAP_11_NAMESPACE_URI, localName)); - } + /** + * Creates a SOAP extensibility element. + * + * @param definition the WSDL4J {@code Definition} + * @param parentType a class object indicating where in the WSDL definition this extension will exist + * @param localName the local name of the extensibility element + * @return the extensibility element + * @throws WSDLException in case of errors + * @see ExtensionRegistry#createExtension(Class, QName) + */ + private ExtensibilityElement createSoapExtension(Definition definition, Class parentType, String localName) + throws WSDLException { + return definition.getExtensionRegistry() + .createExtension(parentType, new QName(SOAP_11_NAMESPACE_URI, localName)); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12Provider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12Provider.java index 60bfc2e6..250d72ea 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12Provider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12Provider.java @@ -51,304 +51,304 @@ import org.springframework.util.Assert; */ public class Soap12Provider extends DefaultConcretePartProvider { - /** The default transport URI, which indicates an HTTP transport. */ - public static final String DEFAULT_TRANSPORT_URI = "http://schemas.xmlsoap.org/soap/http"; + /** The default transport URI, which indicates an HTTP transport. */ + public static final String DEFAULT_TRANSPORT_URI = "http://schemas.xmlsoap.org/soap/http"; - /** The prefix of the WSDL SOAP 1.2 namespace. */ - public static final String SOAP_12_NAMESPACE_PREFIX = "soap12"; + /** The prefix of the WSDL SOAP 1.2 namespace. */ + public static final String SOAP_12_NAMESPACE_PREFIX = "soap12"; - /** The WSDL SOAP 1.1 namespace. */ - public static final String SOAP_12_NAMESPACE_URI = "http://schemas.xmlsoap.org/wsdl/soap12/"; + /** The WSDL SOAP 1.1 namespace. */ + public static final String SOAP_12_NAMESPACE_URI = "http://schemas.xmlsoap.org/wsdl/soap12/"; - private String transportUri = DEFAULT_TRANSPORT_URI; + private String transportUri = DEFAULT_TRANSPORT_URI; - private Properties soapActions = new Properties(); + private Properties soapActions = new Properties(); - private String locationUri; + private String locationUri; - /** - * Constructs a new version of the {@link Soap12Provider}. - * - *

Sets the {@link #setBindingSuffix(String) binding suffix} to {@code Soap12}. - */ - public Soap12Provider() { - setBindingSuffix("Soap12"); - } + /** + * Constructs a new version of the {@link Soap12Provider}. + * + *

Sets the {@link #setBindingSuffix(String) binding suffix} to {@code Soap12}. + */ + public Soap12Provider() { + setBindingSuffix("Soap12"); + } - /** - * Returns the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding - * operation names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action - * URIs}. - * - * @return the soap actions - */ - public Properties getSoapActions() { - return soapActions; - } + /** + * Returns the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding + * operation names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action + * URIs}. + * + * @return the soap actions + */ + public Properties getSoapActions() { + return soapActions; + } - /** - * Sets the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding operation - * names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. - * - * @param soapActions the soap - */ - public void setSoapActions(Properties soapActions) { - Assert.notNull(soapActions, "'soapActions' must not be null"); - this.soapActions = soapActions; - } + /** + * Sets the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding operation + * names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. + * + * @param soapActions the soap + */ + public void setSoapActions(Properties soapActions) { + Assert.notNull(soapActions, "'soapActions' must not be null"); + this.soapActions = soapActions; + } - /** - * Returns the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. - * - * @return the binding transport value - */ - public String getTransportUri() { - return transportUri; - } + /** + * Returns the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. + * + * @return the binding transport value + */ + public String getTransportUri() { + return transportUri; + } - /** - * Sets the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. - * - * @param transportUri the binding transport value - */ - public void setTransportUri(String transportUri) { - Assert.notNull(transportUri, "'transportUri' must not be null"); - this.transportUri = transportUri; - } + /** + * Sets the value used for the binding transport attribute value. Defaults to {@link #DEFAULT_TRANSPORT_URI}. + * + * @param transportUri the binding transport value + */ + public void setTransportUri(String transportUri) { + Assert.notNull(transportUri, "'transportUri' must not be null"); + this.transportUri = transportUri; + } - /** Returns the value used for the SOAP Address location attribute value. */ - public String getLocationUri() { - return locationUri; - } + /** Returns the value used for the SOAP Address location attribute value. */ + public String getLocationUri() { + return locationUri; + } - /** Sets the value used for the SOAP Address location attribute value. */ - public void setLocationUri(String locationUri) { - this.locationUri = locationUri; - } + /** Sets the value used for the SOAP Address location attribute value. */ + public void setLocationUri(String locationUri) { + this.locationUri = locationUri; + } - /** - * Called after the {@link javax.wsdl.Binding} has been created, but before any sub-elements are added. Subclasses - * can override this method to define the binding name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBinding(javax.wsdl.Definition, - * javax.wsdl.Binding)}, adds the SOAP 1.1 namespace, creates a {@link javax.wsdl.extensions.soap.SOAPBinding}, and - * calls {@link #populateSoapBinding(javax.wsdl.extensions.soap12.SOAP12Binding, javax.wsdl.Binding)} sets the - * binding name to the port type name with the {@link #getBindingSuffix() suffix} appended to it. - * - * @param definition the WSDL4J {@code Definition} - * @param binding the WSDL4J {@code Binding} - */ - @Override - protected void populateBinding(Definition definition, Binding binding) throws WSDLException { - definition.addNamespace(SOAP_12_NAMESPACE_PREFIX, SOAP_12_NAMESPACE_URI); - super.populateBinding(definition, binding); - SOAP12Binding soapBinding = (SOAP12Binding) createSoapExtension(definition, Binding.class, "binding"); - populateSoapBinding(soapBinding, binding); - binding.addExtensibilityElement(soapBinding); - } + /** + * Called after the {@link javax.wsdl.Binding} has been created, but before any sub-elements are added. Subclasses + * can override this method to define the binding name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBinding(javax.wsdl.Definition, + * javax.wsdl.Binding)}, adds the SOAP 1.1 namespace, creates a {@link javax.wsdl.extensions.soap.SOAPBinding}, and + * calls {@link #populateSoapBinding(javax.wsdl.extensions.soap12.SOAP12Binding, javax.wsdl.Binding)} sets the + * binding name to the port type name with the {@link #getBindingSuffix() suffix} appended to it. + * + * @param definition the WSDL4J {@code Definition} + * @param binding the WSDL4J {@code Binding} + */ + @Override + protected void populateBinding(Definition definition, Binding binding) throws WSDLException { + definition.addNamespace(SOAP_12_NAMESPACE_PREFIX, SOAP_12_NAMESPACE_URI); + super.populateBinding(definition, binding); + SOAP12Binding soapBinding = (SOAP12Binding) createSoapExtension(definition, Binding.class, "binding"); + populateSoapBinding(soapBinding, binding); + binding.addExtensibilityElement(soapBinding); + } - /** - * Called after the {@link javax.wsdl.extensions.soap.SOAPBinding} has been created. - * - *

Default implementation sets the binding style to {@code "document"}, and set the transport URI to the {@link - * #setTransportUri(String) transportUri} property value. Subclasses can override this behavior. - * - * @param soapBinding the WSDL4J {@code SOAPBinding} - * @throws javax.wsdl.WSDLException in case of errors - * @see javax.wsdl.extensions.soap.SOAPBinding#setStyle(String) - * @see javax.wsdl.extensions.soap.SOAPBinding#setTransportURI(String) - * @see #setTransportUri(String) - * @see #DEFAULT_TRANSPORT_URI - */ - protected void populateSoapBinding(SOAP12Binding soapBinding, Binding binding) throws WSDLException { - soapBinding.setStyle("document"); - soapBinding.setTransportURI(getTransportUri()); - } + /** + * Called after the {@link javax.wsdl.extensions.soap.SOAPBinding} has been created. + * + *

Default implementation sets the binding style to {@code "document"}, and set the transport URI to the {@link + * #setTransportUri(String) transportUri} property value. Subclasses can override this behavior. + * + * @param soapBinding the WSDL4J {@code SOAPBinding} + * @throws javax.wsdl.WSDLException in case of errors + * @see javax.wsdl.extensions.soap.SOAPBinding#setStyle(String) + * @see javax.wsdl.extensions.soap.SOAPBinding#setTransportURI(String) + * @see #setTransportUri(String) + * @see #DEFAULT_TRANSPORT_URI + */ + protected void populateSoapBinding(SOAP12Binding soapBinding, Binding binding) throws WSDLException { + soapBinding.setStyle("document"); + soapBinding.setTransportURI(getTransportUri()); + } - /** - * Called after the {@link javax.wsdl.BindingFault} has been created. Subclasses can override this method to define - * the name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingFault(javax.wsdl.Definition, - * javax.wsdl.BindingFault, javax.wsdl.Fault)}, creates a {@link javax.wsdl.extensions.soap.SOAPFault}, and calls - * {@link #populateSoapFault(javax.wsdl.BindingFault, javax.wsdl.extensions.soap12.SOAP12Fault)}. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingFault the WSDL4J {@code BindingFault} - * @param fault the corresponding WSDL4J {@code Fault} @throws WSDLException in case of errors - */ - @Override - protected void populateBindingFault(Definition definition, BindingFault bindingFault, Fault fault) - throws WSDLException { - super.populateBindingFault(definition, bindingFault, fault); - SOAP12Fault soapFault = (SOAP12Fault) createSoapExtension(definition, BindingFault.class, "fault"); - populateSoapFault(bindingFault, soapFault); - bindingFault.addExtensibilityElement(soapFault); - } + /** + * Called after the {@link javax.wsdl.BindingFault} has been created. Subclasses can override this method to define + * the name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingFault(javax.wsdl.Definition, + * javax.wsdl.BindingFault, javax.wsdl.Fault)}, creates a {@link javax.wsdl.extensions.soap.SOAPFault}, and calls + * {@link #populateSoapFault(javax.wsdl.BindingFault, javax.wsdl.extensions.soap12.SOAP12Fault)}. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingFault the WSDL4J {@code BindingFault} + * @param fault the corresponding WSDL4J {@code Fault} @throws WSDLException in case of errors + */ + @Override + protected void populateBindingFault(Definition definition, BindingFault bindingFault, Fault fault) + throws WSDLException { + super.populateBindingFault(definition, bindingFault, fault); + SOAP12Fault soapFault = (SOAP12Fault) createSoapExtension(definition, BindingFault.class, "fault"); + populateSoapFault(bindingFault, soapFault); + bindingFault.addExtensibilityElement(soapFault); + } - /** - * Called after the {@link javax.wsdl.extensions.soap.SOAPFault} has been created. - * - *

Default implementation sets the use style to {@code "literal"}, and sets the name equal to the binding - * fault. Subclasses can override this behavior. - * - * @param bindingFault the WSDL4J {@code BindingFault} - * @param soapFault the WSDL4J {@code SOAPFault} - * @throws javax.wsdl.WSDLException in case of errors - * @see javax.wsdl.extensions.soap.SOAPFault#setUse(String) - */ - protected void populateSoapFault(BindingFault bindingFault, SOAP12Fault soapFault) throws WSDLException { - soapFault.setName(bindingFault.getName()); - soapFault.setUse("literal"); - } + /** + * Called after the {@link javax.wsdl.extensions.soap.SOAPFault} has been created. + * + *

Default implementation sets the use style to {@code "literal"}, and sets the name equal to the binding + * fault. Subclasses can override this behavior. + * + * @param bindingFault the WSDL4J {@code BindingFault} + * @param soapFault the WSDL4J {@code SOAPFault} + * @throws javax.wsdl.WSDLException in case of errors + * @see javax.wsdl.extensions.soap.SOAPFault#setUse(String) + */ + protected void populateSoapFault(BindingFault bindingFault, SOAP12Fault soapFault) throws WSDLException { + soapFault.setName(bindingFault.getName()); + soapFault.setUse("literal"); + } - /** - * Called after the {@link javax.wsdl.BindingInput} has been created. Subclasses can implement this method to define - * the name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingInput(javax.wsdl.Definition, - * javax.wsdl.BindingInput, javax.wsdl.Input)}, creates a {@link javax.wsdl.extensions.soap.SOAPBody}, and calls - * {@link #populateSoapBody(javax.wsdl.extensions.soap12.SOAP12Body)}. 2 - * - * @param definition the WSDL4J {@code Definition} - * @param bindingInput the WSDL4J {@code BindingInput} - * @param input the corresponding WSDL4J {@code Input} @throws WSDLException in case of errors - */ - @Override - protected void populateBindingInput(Definition definition, BindingInput bindingInput, Input input) - throws WSDLException { - super.populateBindingInput(definition, bindingInput, input); - SOAP12Body soapBody = (SOAP12Body) createSoapExtension(definition, BindingInput.class, "body"); - populateSoapBody(soapBody); - bindingInput.addExtensibilityElement(soapBody); - } + /** + * Called after the {@link javax.wsdl.BindingInput} has been created. Subclasses can implement this method to define + * the name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingInput(javax.wsdl.Definition, + * javax.wsdl.BindingInput, javax.wsdl.Input)}, creates a {@link javax.wsdl.extensions.soap.SOAPBody}, and calls + * {@link #populateSoapBody(javax.wsdl.extensions.soap12.SOAP12Body)}. 2 + * + * @param definition the WSDL4J {@code Definition} + * @param bindingInput the WSDL4J {@code BindingInput} + * @param input the corresponding WSDL4J {@code Input} @throws WSDLException in case of errors + */ + @Override + protected void populateBindingInput(Definition definition, BindingInput bindingInput, Input input) + throws WSDLException { + super.populateBindingInput(definition, bindingInput, input); + SOAP12Body soapBody = (SOAP12Body) createSoapExtension(definition, BindingInput.class, "body"); + populateSoapBody(soapBody); + bindingInput.addExtensibilityElement(soapBody); + } - /** - * Called after the {@link javax.wsdl.extensions.soap.SOAPBody} has been created. - * - *

Default implementation sets the use style to {@code "literal"}. Subclasses can override this behavior. - * - * @param soapBody the WSDL4J {@code SOAPBody} - * @throws javax.wsdl.WSDLException in case of errors - * @see javax.wsdl.extensions.soap.SOAPBody#setUse(String) - */ - protected void populateSoapBody(SOAP12Body soapBody) throws WSDLException { - soapBody.setUse("literal"); - } + /** + * Called after the {@link javax.wsdl.extensions.soap.SOAPBody} has been created. + * + *

Default implementation sets the use style to {@code "literal"}. Subclasses can override this behavior. + * + * @param soapBody the WSDL4J {@code SOAPBody} + * @throws javax.wsdl.WSDLException in case of errors + * @see javax.wsdl.extensions.soap.SOAPBody#setUse(String) + */ + protected void populateSoapBody(SOAP12Body soapBody) throws WSDLException { + soapBody.setUse("literal"); + } - /** - * Called after the {@link javax.wsdl.BindingOperation} has been created, but before any sub-elements are added. - * Subclasses can implement this method to define the binding name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOperation(javax.wsdl.Definition, - * javax.wsdl.BindingOperation)}, creates a {@link javax.wsdl.extensions.soap.SOAPOperation}, and calls {@link - * #populateSoapOperation} sets the name of the binding operation to the name of the operation. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingOperation the WSDL4J {@code BindingOperation} - * @throws javax.wsdl.WSDLException in case of errors - */ - @Override - protected void populateBindingOperation(Definition definition, BindingOperation bindingOperation) - throws WSDLException { - super.populateBindingOperation(definition, bindingOperation); - SOAP12Operation soapOperation = - (SOAP12Operation) createSoapExtension(definition, BindingOperation.class, "operation"); - populateSoapOperation(soapOperation, bindingOperation); - bindingOperation.addExtensibilityElement(soapOperation); - } + /** + * Called after the {@link javax.wsdl.BindingOperation} has been created, but before any sub-elements are added. + * Subclasses can implement this method to define the binding name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOperation(javax.wsdl.Definition, + * javax.wsdl.BindingOperation)}, creates a {@link javax.wsdl.extensions.soap.SOAPOperation}, and calls {@link + * #populateSoapOperation} sets the name of the binding operation to the name of the operation. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingOperation the WSDL4J {@code BindingOperation} + * @throws javax.wsdl.WSDLException in case of errors + */ + @Override + protected void populateBindingOperation(Definition definition, BindingOperation bindingOperation) + throws WSDLException { + super.populateBindingOperation(definition, bindingOperation); + SOAP12Operation soapOperation = + (SOAP12Operation) createSoapExtension(definition, BindingOperation.class, "operation"); + populateSoapOperation(soapOperation, bindingOperation); + bindingOperation.addExtensibilityElement(soapOperation); + } - /** - * Called after the {@link javax.wsdl.extensions.soap.SOAPOperation} has been created. - * - *

Default implementation sets {@code SOAPAction} to the corresponding {@link - * #setSoapActions(java.util.Properties) soapActions} property, and defaults to "". - * - * @param soapOperation the WSDL4J {@code SOAPOperation} - * @param bindingOperation the WSDL4J {@code BindingOperation} - * @throws javax.wsdl.WSDLException in case of errors - * @see javax.wsdl.extensions.soap.SOAPOperation#setSoapActionURI(String) - * @see #setSoapActions(java.util.Properties) - */ - protected void populateSoapOperation(SOAP12Operation soapOperation, BindingOperation bindingOperation) - throws WSDLException { - String bindingOperationName = bindingOperation.getName(); - String soapAction = getSoapActions().getProperty(bindingOperationName, ""); - soapOperation.setSoapActionURI(soapAction); - } + /** + * Called after the {@link javax.wsdl.extensions.soap.SOAPOperation} has been created. + * + *

Default implementation sets {@code SOAPAction} to the corresponding {@link + * #setSoapActions(java.util.Properties) soapActions} property, and defaults to "". + * + * @param soapOperation the WSDL4J {@code SOAPOperation} + * @param bindingOperation the WSDL4J {@code BindingOperation} + * @throws javax.wsdl.WSDLException in case of errors + * @see javax.wsdl.extensions.soap.SOAPOperation#setSoapActionURI(String) + * @see #setSoapActions(java.util.Properties) + */ + protected void populateSoapOperation(SOAP12Operation soapOperation, BindingOperation bindingOperation) + throws WSDLException { + String bindingOperationName = bindingOperation.getName(); + String soapAction = getSoapActions().getProperty(bindingOperationName, ""); + soapOperation.setSoapActionURI(soapAction); + } - /** - * Called after the {@link javax.wsdl.BindingInput} has been created. Subclasses can implement this method to define - * the name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOutput(javax.wsdl.Definition, - * javax.wsdl.BindingOutput, javax.wsdl.Output)}, creates a {@link javax.wsdl.extensions.soap.SOAPBody}, and calls - * {@link #populateSoapBody(javax.wsdl.extensions.soap12.SOAP12Body)}. - * - * @param definition the WSDL4J {@code Definition} - * @param bindingOutput the WSDL4J {@code BindingOutput} - * @param output the corresponding WSDL4J {@code Output} @throws WSDLException in case of errors - */ - @Override - protected void populateBindingOutput(Definition definition, BindingOutput bindingOutput, Output output) - throws WSDLException { - super.populateBindingOutput(definition, bindingOutput, output); - SOAP12Body soapBody = (SOAP12Body) createSoapExtension(definition, BindingOutput.class, "body"); - populateSoapBody(soapBody); - bindingOutput.addExtensibilityElement(soapBody); - } + /** + * Called after the {@link javax.wsdl.BindingInput} has been created. Subclasses can implement this method to define + * the name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populateBindingOutput(javax.wsdl.Definition, + * javax.wsdl.BindingOutput, javax.wsdl.Output)}, creates a {@link javax.wsdl.extensions.soap.SOAPBody}, and calls + * {@link #populateSoapBody(javax.wsdl.extensions.soap12.SOAP12Body)}. + * + * @param definition the WSDL4J {@code Definition} + * @param bindingOutput the WSDL4J {@code BindingOutput} + * @param output the corresponding WSDL4J {@code Output} @throws WSDLException in case of errors + */ + @Override + protected void populateBindingOutput(Definition definition, BindingOutput bindingOutput, Output output) + throws WSDLException { + super.populateBindingOutput(definition, bindingOutput, output); + SOAP12Body soapBody = (SOAP12Body) createSoapExtension(definition, BindingOutput.class, "body"); + populateSoapBody(soapBody); + bindingOutput.addExtensibilityElement(soapBody); + } - /** - * Called after the {@link javax.wsdl.Port} has been created, but before any sub-elements are added. Subclasses can - * implement this method to define the port name, or add extensions to it. - * - *

Default implementation calls {@link DefaultConcretePartProvider#populatePort(javax.wsdl.Definition,javax.wsdl.Port)}, - * creates a {@link javax.wsdl.extensions.soap.SOAPAddress}, and calls {@link #populateSoapAddress(SOAP12Address)}. - * - * @param port the WSDL4J {@code Port} - * @throws WSDLException in case of errors - */ - @Override - protected void populatePort(Definition definition, Port port) throws WSDLException { - for (Iterator iterator = port.getBinding().getExtensibilityElements().iterator(); iterator.hasNext();) { - if (iterator.next() instanceof SOAP12Binding) { - // this is a SOAP 1.2 binding, create a SOAP Address for it - super.populatePort(definition, port); - SOAP12Address soapAddress = (SOAP12Address) createSoapExtension(definition, Port.class, "address"); - populateSoapAddress(soapAddress); - port.addExtensibilityElement(soapAddress); - return; - } - } - } + /** + * Called after the {@link javax.wsdl.Port} has been created, but before any sub-elements are added. Subclasses can + * implement this method to define the port name, or add extensions to it. + * + *

Default implementation calls {@link DefaultConcretePartProvider#populatePort(javax.wsdl.Definition,javax.wsdl.Port)}, + * creates a {@link javax.wsdl.extensions.soap.SOAPAddress}, and calls {@link #populateSoapAddress(SOAP12Address)}. + * + * @param port the WSDL4J {@code Port} + * @throws WSDLException in case of errors + */ + @Override + protected void populatePort(Definition definition, Port port) throws WSDLException { + for (Iterator iterator = port.getBinding().getExtensibilityElements().iterator(); iterator.hasNext();) { + if (iterator.next() instanceof SOAP12Binding) { + // this is a SOAP 1.2 binding, create a SOAP Address for it + super.populatePort(definition, port); + SOAP12Address soapAddress = (SOAP12Address) createSoapExtension(definition, Port.class, "address"); + populateSoapAddress(soapAddress); + port.addExtensibilityElement(soapAddress); + return; + } + } + } - /** - * Called after the {@link SOAP12Address} has been created. Default implementation sets the location URI to the - * value set on this builder. Subclasses can override this behavior. - * - * @param soapAddress the WSDL4J {@code SOAPAddress} - * @throws WSDLException in case of errors - * @see SOAP12Address#setLocationURI(String) - * @see #setLocationUri(String) - */ - protected void populateSoapAddress(SOAP12Address soapAddress) throws WSDLException { - soapAddress.setLocationURI(getLocationUri()); - } + /** + * Called after the {@link SOAP12Address} has been created. Default implementation sets the location URI to the + * value set on this builder. Subclasses can override this behavior. + * + * @param soapAddress the WSDL4J {@code SOAPAddress} + * @throws WSDLException in case of errors + * @see SOAP12Address#setLocationURI(String) + * @see #setLocationUri(String) + */ + protected void populateSoapAddress(SOAP12Address soapAddress) throws WSDLException { + soapAddress.setLocationURI(getLocationUri()); + } - /** - * Creates a SOAP extensibility element. - * - * @param definition the WSDL4J {@code Definition} - * @param parentType a class object indicating where in the WSDL definition this extension will exist - * @param localName the local name of the extensibility element - * @return the extensibility element - * @throws WSDLException in case of errors - * @see javax.wsdl.extensions.ExtensionRegistry#createExtension(Class, QName) - */ - private ExtensibilityElement createSoapExtension(Definition definition, Class parentType, String localName) - throws WSDLException { - return definition.getExtensionRegistry() - .createExtension(parentType, new QName(SOAP_12_NAMESPACE_URI, localName)); - } + /** + * Creates a SOAP extensibility element. + * + * @param definition the WSDL4J {@code Definition} + * @param parentType a class object indicating where in the WSDL definition this extension will exist + * @param localName the local name of the extensibility element + * @return the extensibility element + * @throws WSDLException in case of errors + * @see javax.wsdl.extensions.ExtensionRegistry#createExtension(Class, QName) + */ + private ExtensibilityElement createSoapExtension(Definition definition, Class parentType, String localName) + throws WSDLException { + return definition.getExtensionRegistry() + .createExtension(parentType, new QName(SOAP_12_NAMESPACE_URI, localName)); + } } \ No newline at end of file diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProvider.java index f7b8955b..ee7eaf34 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProvider.java @@ -37,78 +37,78 @@ import javax.wsdl.WSDLException; */ public class SoapProvider implements BindingsProvider, ServicesProvider { - private final Soap11Provider soap11BindingProvider = new Soap11Provider(); + private final Soap11Provider soap11BindingProvider = new Soap11Provider(); - private final Soap12Provider soap12BindingProvider = new Soap12Provider(); + private final Soap12Provider soap12BindingProvider = new Soap12Provider(); - private boolean createSoap11Binding = true; + private boolean createSoap11Binding = true; - private boolean createSoap12Binding = false; + private boolean createSoap12Binding = false; - /** - * Indicates whether a SOAP 1.1 binding should be created. - * - *

Defaults to {@code true}. - */ - public void setCreateSoap11Binding(boolean createSoap11Binding) { - this.createSoap11Binding = createSoap11Binding; - } + /** + * Indicates whether a SOAP 1.1 binding should be created. + * + *

Defaults to {@code true}. + */ + public void setCreateSoap11Binding(boolean createSoap11Binding) { + this.createSoap11Binding = createSoap11Binding; + } - /** - * Indicates whether a SOAP 1.2 binding should be created. - * - *

Defaults to {@code false}. - */ - public void setCreateSoap12Binding(boolean createSoap12Binding) { - this.createSoap12Binding = createSoap12Binding; - } + /** + * Indicates whether a SOAP 1.2 binding should be created. + * + *

Defaults to {@code false}. + */ + public void setCreateSoap12Binding(boolean createSoap12Binding) { + this.createSoap12Binding = createSoap12Binding; + } - /** - * Sets the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding operation - * names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. - * - * @param soapActions the soap - */ - public void setSoapActions(Properties soapActions) { - soap11BindingProvider.setSoapActions(soapActions); - soap12BindingProvider.setSoapActions(soapActions); - } + /** + * Sets the SOAP Actions for this binding. Keys are {@link javax.wsdl.BindingOperation#getName() binding operation + * names}; values are {@link javax.wsdl.extensions.soap.SOAPOperation#getSoapActionURI() SOAP Action URIs}. + * + * @param soapActions the soap + */ + public void setSoapActions(Properties soapActions) { + soap11BindingProvider.setSoapActions(soapActions); + soap12BindingProvider.setSoapActions(soapActions); + } - /** Sets the value used for the binding transport attribute value. Defaults to HTTP. */ - public void setTransportUri(String transportUri) { - soap11BindingProvider.setTransportUri(transportUri); - soap12BindingProvider.setTransportUri(transportUri); - } + /** Sets the value used for the binding transport attribute value. Defaults to HTTP. */ + public void setTransportUri(String transportUri) { + soap11BindingProvider.setTransportUri(transportUri); + soap12BindingProvider.setTransportUri(transportUri); + } - /** Sets the value used for the SOAP Address location attribute value. */ - public void setLocationUri(String locationUri) { - soap11BindingProvider.setLocationUri(locationUri); - soap12BindingProvider.setLocationUri(locationUri); - } + /** Sets the value used for the SOAP Address location attribute value. */ + public void setLocationUri(String locationUri) { + soap11BindingProvider.setLocationUri(locationUri); + soap12BindingProvider.setLocationUri(locationUri); + } - /** Sets the service name. */ - public void setServiceName(String serviceName) { - soap11BindingProvider.setServiceName(serviceName); - soap12BindingProvider.setServiceName(serviceName); - } + /** Sets the service name. */ + public void setServiceName(String serviceName) { + soap11BindingProvider.setServiceName(serviceName); + soap12BindingProvider.setServiceName(serviceName); + } - @Override - public void addBindings(Definition definition) throws WSDLException { - if (createSoap11Binding) { - soap11BindingProvider.addBindings(definition); - } - if (createSoap12Binding) { - soap12BindingProvider.addBindings(definition); - } - } + @Override + public void addBindings(Definition definition) throws WSDLException { + if (createSoap11Binding) { + soap11BindingProvider.addBindings(definition); + } + if (createSoap12Binding) { + soap12BindingProvider.addBindings(definition); + } + } - @Override - public void addServices(Definition definition) throws WSDLException { - if (createSoap11Binding) { - soap11BindingProvider.addServices(definition); - } - if (createSoap12Binding) { - soap12BindingProvider.addServices(definition); - } - } + @Override + public void addServices(Definition definition) throws WSDLException { + if (createSoap11Binding) { + soap11BindingProvider.addServices(definition); + } + if (createSoap12Binding) { + soap12BindingProvider.addServices(definition); + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProvider.java index 6e409741..0e8c5d33 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProvider.java @@ -28,88 +28,88 @@ import org.springframework.util.Assert; */ public class SuffixBasedMessagesProvider extends DefaultMessagesProvider { - /** The default suffix used to detect request elements in the schema. */ - public static final String DEFAULT_REQUEST_SUFFIX = "Request"; + /** The default suffix used to detect request elements in the schema. */ + public static final String DEFAULT_REQUEST_SUFFIX = "Request"; - /** The default suffix used to detect response elements in the schema. */ - public static final String DEFAULT_RESPONSE_SUFFIX = "Response"; + /** The default suffix used to detect response elements in the schema. */ + public static final String DEFAULT_RESPONSE_SUFFIX = "Response"; - /** The default suffix used to detect fault elements in the schema. */ - public static final String DEFAULT_FAULT_SUFFIX = "Fault"; + /** The default suffix used to detect fault elements in the schema. */ + public static final String DEFAULT_FAULT_SUFFIX = "Fault"; - private String requestSuffix = DEFAULT_REQUEST_SUFFIX; + private String requestSuffix = DEFAULT_REQUEST_SUFFIX; - private String responseSuffix = DEFAULT_RESPONSE_SUFFIX; + private String responseSuffix = DEFAULT_RESPONSE_SUFFIX; - private String faultSuffix = DEFAULT_FAULT_SUFFIX; + private String faultSuffix = DEFAULT_FAULT_SUFFIX; - /** - * Returns the suffix used to detect request elements in the schema. - * - * @see #DEFAULT_REQUEST_SUFFIX - */ - public String getRequestSuffix() { - return requestSuffix; - } + /** + * Returns the suffix used to detect request elements in the schema. + * + * @see #DEFAULT_REQUEST_SUFFIX + */ + public String getRequestSuffix() { + return requestSuffix; + } - /** - * Sets the suffix used to detect request elements in the schema. - * - * @see #DEFAULT_REQUEST_SUFFIX - */ - public void setRequestSuffix(String requestSuffix) { - Assert.hasText(requestSuffix, "'requestSuffix' must not be empty"); - this.requestSuffix = requestSuffix; - } + /** + * Sets the suffix used to detect request elements in the schema. + * + * @see #DEFAULT_REQUEST_SUFFIX + */ + public void setRequestSuffix(String requestSuffix) { + Assert.hasText(requestSuffix, "'requestSuffix' must not be empty"); + this.requestSuffix = requestSuffix; + } - /** - * Returns the suffix used to detect response elements in the schema. - * - * @see #DEFAULT_RESPONSE_SUFFIX - */ - public String getResponseSuffix() { - return responseSuffix; - } + /** + * Returns the suffix used to detect response elements in the schema. + * + * @see #DEFAULT_RESPONSE_SUFFIX + */ + public String getResponseSuffix() { + return responseSuffix; + } - /** - * Sets the suffix used to detect response elements in the schema. - * - * @see #DEFAULT_RESPONSE_SUFFIX - */ - public void setResponseSuffix(String responseSuffix) { - Assert.hasText(responseSuffix, "'responseSuffix' must not be empty"); - this.responseSuffix = responseSuffix; - } + /** + * Sets the suffix used to detect response elements in the schema. + * + * @see #DEFAULT_RESPONSE_SUFFIX + */ + public void setResponseSuffix(String responseSuffix) { + Assert.hasText(responseSuffix, "'responseSuffix' must not be empty"); + this.responseSuffix = responseSuffix; + } - /** - * Returns the suffix used to detect fault elements in the schema. - * - * @see #DEFAULT_FAULT_SUFFIX - */ - public String getFaultSuffix() { - return faultSuffix; - } + /** + * Returns the suffix used to detect fault elements in the schema. + * + * @see #DEFAULT_FAULT_SUFFIX + */ + public String getFaultSuffix() { + return faultSuffix; + } - /** - * Sets the suffix used to detect fault elements in the schema. - * - * @see #DEFAULT_FAULT_SUFFIX - */ - public void setFaultSuffix(String faultSuffix) { - Assert.hasText(faultSuffix, "'faultSuffix' must not be empty"); - this.faultSuffix = faultSuffix; - } + /** + * Sets the suffix used to detect fault elements in the schema. + * + * @see #DEFAULT_FAULT_SUFFIX + */ + public void setFaultSuffix(String faultSuffix) { + Assert.hasText(faultSuffix, "'faultSuffix' must not be empty"); + this.faultSuffix = faultSuffix; + } - @Override - protected boolean isMessageElement(Element element) { - if (super.isMessageElement(element)) { - String elementName = getElementName(element); - Assert.hasText(elementName, "Element has no name"); - return elementName.endsWith(getRequestSuffix()) || elementName.endsWith(getResponseSuffix()) || - elementName.endsWith(getFaultSuffix()); - } - else { - return false; - } - } + @Override + protected boolean isMessageElement(Element element) { + if (super.isMessageElement(element)) { + String elementName = getElementName(element); + Assert.hasText(elementName, "Element has no name"); + return elementName.endsWith(getRequestSuffix()) || elementName.endsWith(getResponseSuffix()) || + elementName.endsWith(getFaultSuffix()); + } + else { + return false; + } + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProvider.java index aad6c0dd..947ff1f7 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProvider.java @@ -21,147 +21,147 @@ import javax.wsdl.Message; import org.springframework.util.Assert; /** - * Implementation of the {@link PortTypesProvider} interface that is based on suffixes. + * Implementation of the {@link PortTypesProvider} interface that is based on suffixes. * * @author Arjen Poutsma * @since 1.5.0 */ public class SuffixBasedPortTypesProvider extends AbstractPortTypesProvider { - /** The default suffix used to detect request elements in the schema. */ - public static final String DEFAULT_REQUEST_SUFFIX = "Request"; + /** The default suffix used to detect request elements in the schema. */ + public static final String DEFAULT_REQUEST_SUFFIX = "Request"; - /** The default suffix used to detect response elements in the schema. */ - public static final String DEFAULT_RESPONSE_SUFFIX = "Response"; + /** The default suffix used to detect response elements in the schema. */ + public static final String DEFAULT_RESPONSE_SUFFIX = "Response"; - /** The default suffix used to detect fault elements in the schema. */ - public static final String DEFAULT_FAULT_SUFFIX = "Fault"; + /** The default suffix used to detect fault elements in the schema. */ + public static final String DEFAULT_FAULT_SUFFIX = "Fault"; - private String requestSuffix = DEFAULT_REQUEST_SUFFIX; + private String requestSuffix = DEFAULT_REQUEST_SUFFIX; - private String responseSuffix = DEFAULT_RESPONSE_SUFFIX; + private String responseSuffix = DEFAULT_RESPONSE_SUFFIX; - private String faultSuffix = DEFAULT_FAULT_SUFFIX; + private String faultSuffix = DEFAULT_FAULT_SUFFIX; - /** - * Returns the suffix used to detect request elements in the schema. - * - * @see #DEFAULT_REQUEST_SUFFIX - */ - public String getRequestSuffix() { - return requestSuffix; - } + /** + * Returns the suffix used to detect request elements in the schema. + * + * @see #DEFAULT_REQUEST_SUFFIX + */ + public String getRequestSuffix() { + return requestSuffix; + } - /** - * Sets the suffix used to detect request elements in the schema. - * - * @see #DEFAULT_REQUEST_SUFFIX - */ - public void setRequestSuffix(String requestSuffix) { - Assert.hasText(requestSuffix, "'requestSuffix' must not be empty"); - this.requestSuffix = requestSuffix; - } + /** + * Sets the suffix used to detect request elements in the schema. + * + * @see #DEFAULT_REQUEST_SUFFIX + */ + public void setRequestSuffix(String requestSuffix) { + Assert.hasText(requestSuffix, "'requestSuffix' must not be empty"); + this.requestSuffix = requestSuffix; + } - /** - * Returns the suffix used to detect response elements in the schema. - * - * @see #DEFAULT_RESPONSE_SUFFIX - */ - public String getResponseSuffix() { - return responseSuffix; - } + /** + * Returns the suffix used to detect response elements in the schema. + * + * @see #DEFAULT_RESPONSE_SUFFIX + */ + public String getResponseSuffix() { + return responseSuffix; + } - /** - * Sets the suffix used to detect response elements in the schema. - * - * @see #DEFAULT_RESPONSE_SUFFIX - */ - public void setResponseSuffix(String responseSuffix) { - Assert.hasText(responseSuffix, "'responseSuffix' must not be empty"); - this.responseSuffix = responseSuffix; - } + /** + * Sets the suffix used to detect response elements in the schema. + * + * @see #DEFAULT_RESPONSE_SUFFIX + */ + public void setResponseSuffix(String responseSuffix) { + Assert.hasText(responseSuffix, "'responseSuffix' must not be empty"); + this.responseSuffix = responseSuffix; + } - /** - * Returns the suffix used to detect fault elements in the schema. - * - * @see #DEFAULT_FAULT_SUFFIX - */ - public String getFaultSuffix() { - return faultSuffix; - } + /** + * Returns the suffix used to detect fault elements in the schema. + * + * @see #DEFAULT_FAULT_SUFFIX + */ + public String getFaultSuffix() { + return faultSuffix; + } - /** - * Sets the suffix used to detect fault elements in the schema. - * - * @see #DEFAULT_FAULT_SUFFIX - */ - public void setFaultSuffix(String faultSuffix) { - Assert.hasText(faultSuffix, "'faultSuffix' must not be empty"); - this.faultSuffix = faultSuffix; - } + /** + * Sets the suffix used to detect fault elements in the schema. + * + * @see #DEFAULT_FAULT_SUFFIX + */ + public void setFaultSuffix(String faultSuffix) { + Assert.hasText(faultSuffix, "'faultSuffix' must not be empty"); + this.faultSuffix = faultSuffix; + } - @Override - protected String getOperationName(Message message) { - String messageName = getMessageName(message); - if (messageName != null) { - if (messageName.endsWith(getRequestSuffix())) { - return messageName.substring(0, messageName.length() - getRequestSuffix().length()); - } - else if (messageName.endsWith(getResponseSuffix())) { - return messageName.substring(0, messageName.length() - getResponseSuffix().length()); - } - else if (messageName.endsWith(getFaultSuffix())) { - return messageName.substring(0, messageName.length() - getFaultSuffix().length()); - } - } - return null; - } + @Override + protected String getOperationName(Message message) { + String messageName = getMessageName(message); + if (messageName != null) { + if (messageName.endsWith(getRequestSuffix())) { + return messageName.substring(0, messageName.length() - getRequestSuffix().length()); + } + else if (messageName.endsWith(getResponseSuffix())) { + return messageName.substring(0, messageName.length() - getResponseSuffix().length()); + } + else if (messageName.endsWith(getFaultSuffix())) { + return messageName.substring(0, messageName.length() - getFaultSuffix().length()); + } + } + return null; + } - /** - * Indicates whether the given name name should be included as {@link javax.wsdl.Input} message in the definition. - * - *

This implementation checks whether the message name ends with the {@link #setRequestSuffix(String) - * requestSuffix}. - * - * @param message the message - * @return {@code true} if to be included as input; {@code false} otherwise - */ - @Override - protected boolean isInputMessage(Message message) { - String messageName = getMessageName(message); - return messageName != null && messageName.endsWith(getRequestSuffix()); - } + /** + * Indicates whether the given name name should be included as {@link javax.wsdl.Input} message in the definition. + * + *

This implementation checks whether the message name ends with the {@link #setRequestSuffix(String) + * requestSuffix}. + * + * @param message the message + * @return {@code true} if to be included as input; {@code false} otherwise + */ + @Override + protected boolean isInputMessage(Message message) { + String messageName = getMessageName(message); + return messageName != null && messageName.endsWith(getRequestSuffix()); + } - /** - * Indicates whether the given name name should be included as {@link javax.wsdl.Output} message in the definition. - * - *

This implementation checks whether the message name ends with the {@link #setResponseSuffix(String) - * responseSuffix}. - * - * @param message the message - * @return {@code true} if to be included as output; {@code false} otherwise - */ - @Override - protected boolean isOutputMessage(Message message) { - String messageName = getMessageName(message); - return messageName != null && messageName.endsWith(getResponseSuffix()); - } + /** + * Indicates whether the given name name should be included as {@link javax.wsdl.Output} message in the definition. + * + *

This implementation checks whether the message name ends with the {@link #setResponseSuffix(String) + * responseSuffix}. + * + * @param message the message + * @return {@code true} if to be included as output; {@code false} otherwise + */ + @Override + protected boolean isOutputMessage(Message message) { + String messageName = getMessageName(message); + return messageName != null && messageName.endsWith(getResponseSuffix()); + } - /** - * Indicates whether the given name name should be included as {@link javax.wsdl.Fault} message in the definition. - * - *

This implementation checks whether the message name ends with the {@link #setFaultSuffix(String) faultSuffix}. - * - * @param message the message - * @return {@code true} if to be included as fault; {@code false} otherwise - */ - @Override - protected boolean isFaultMessage(Message message) { - String messageName = getMessageName(message); - return messageName != null && messageName.endsWith(getFaultSuffix()); - } + /** + * Indicates whether the given name name should be included as {@link javax.wsdl.Fault} message in the definition. + * + *

This implementation checks whether the message name ends with the {@link #setFaultSuffix(String) faultSuffix}. + * + * @param message the message + * @return {@code true} if to be included as fault; {@code false} otherwise + */ + @Override + protected boolean isFaultMessage(Message message) { + String messageName = getMessageName(message); + return messageName != null && messageName.endsWith(getFaultSuffix()); + } - private String getMessageName(Message message) { - return message.getQName().getLocalPart(); - } + private String getMessageName(Message message) { + return message.getQName().getLocalPart(); + } } diff --git a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/TypesProvider.java b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/TypesProvider.java index 1095e005..d865d55a 100644 --- a/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/TypesProvider.java +++ b/spring-ws-core/src/main/java/org/springframework/ws/wsdl/wsdl11/provider/TypesProvider.java @@ -29,6 +29,6 @@ import javax.wsdl.WSDLException; */ public interface TypesProvider { - void addTypes(Definition definition) throws WSDLException; + void addTypes(Definition definition) throws WSDLException; } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageFactoryTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageFactoryTestCase.java index 67843b33..304a7547 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageFactoryTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageFactoryTestCase.java @@ -22,18 +22,18 @@ import org.junit.Test; public abstract class AbstractWebServiceMessageFactoryTestCase { - protected WebServiceMessageFactory messageFactory; + protected WebServiceMessageFactory messageFactory; - @Before - public final void setUp() throws Exception { - messageFactory = createMessageFactory(); - } + @Before + public final void setUp() throws Exception { + messageFactory = createMessageFactory(); + } - @Test - public void testCreateEmptyMessage() throws Exception { - WebServiceMessage message = messageFactory.createWebServiceMessage(); - Assert.assertNotNull("WebServiceMessage is null", message); - } + @Test + public void testCreateEmptyMessage() throws Exception { + WebServiceMessage message = messageFactory.createWebServiceMessage(); + Assert.assertNotNull("WebServiceMessage is null", message); + } - protected abstract WebServiceMessageFactory createMessageFactory() throws Exception; + protected abstract WebServiceMessageFactory createMessageFactory() throws Exception; } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageTestCase.java index e9411e8b..593db134 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/AbstractWebServiceMessageTestCase.java @@ -60,116 +60,116 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public abstract class AbstractWebServiceMessageTestCase { - protected Transformer transformer; + protected Transformer transformer; - protected WebServiceMessage webServiceMessage; + protected WebServiceMessage webServiceMessage; - private Resource payload; + private Resource payload; - private String getExpectedString() throws IOException { - StringWriter expectedWriter = new StringWriter(); - FileCopyUtils.copy(new InputStreamReader(payload.getInputStream(), "UTF-8"), expectedWriter); - return expectedWriter.toString(); - } + private String getExpectedString() throws IOException { + StringWriter expectedWriter = new StringWriter(); + FileCopyUtils.copy(new InputStreamReader(payload.getInputStream(), "UTF-8"), expectedWriter); + return expectedWriter.toString(); + } - @Before - public final void setUp() throws Exception { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - webServiceMessage = createWebServiceMessage(); - payload = new ClassPathResource("payload.xml", AbstractWebServiceMessageTestCase.class); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public final void setUp() throws Exception { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + webServiceMessage = createWebServiceMessage(); + payload = new ClassPathResource("payload.xml", AbstractWebServiceMessageTestCase.class); + XMLUnit.setIgnoreWhitespace(true); + } - @Test - public void testDomPayload() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document payloadDocument = documentBuilder.parse(SaxUtils.createInputSource(payload)); - DOMSource domSource = new DOMSource(payloadDocument); - transformer.transform(domSource, webServiceMessage.getPayloadResult()); - Document resultDocument = documentBuilder.newDocument(); - DOMResult domResult = new DOMResult(resultDocument); - transformer.transform(webServiceMessage.getPayloadSource(), domResult); - assertXMLEqual(payloadDocument, resultDocument); - validateMessage(); - } + @Test + public void testDomPayload() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document payloadDocument = documentBuilder.parse(SaxUtils.createInputSource(payload)); + DOMSource domSource = new DOMSource(payloadDocument); + transformer.transform(domSource, webServiceMessage.getPayloadResult()); + Document resultDocument = documentBuilder.newDocument(); + DOMResult domResult = new DOMResult(resultDocument); + transformer.transform(webServiceMessage.getPayloadSource(), domResult); + assertXMLEqual(payloadDocument, resultDocument); + validateMessage(); + } - @Test - public void testEventReaderPayload() throws Exception { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLEventReader eventReader = inputFactory.createXMLEventReader(payload.getInputStream()); - Source staxSource = StaxUtils.createCustomStaxSource(eventReader); - transformer.transform(staxSource, webServiceMessage.getPayloadResult()); - StringWriter stringWriter = new StringWriter(); - XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); - XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter); - Result staxResult = StaxUtils.createCustomStaxResult(eventWriter); - transformer.transform(webServiceMessage.getPayloadSource(), staxResult); - eventWriter.flush(); - assertXMLEqual(getExpectedString(), stringWriter.toString()); - validateMessage(); - } + @Test + public void testEventReaderPayload() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLEventReader eventReader = inputFactory.createXMLEventReader(payload.getInputStream()); + Source staxSource = StaxUtils.createCustomStaxSource(eventReader); + transformer.transform(staxSource, webServiceMessage.getPayloadResult()); + StringWriter stringWriter = new StringWriter(); + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter); + Result staxResult = StaxUtils.createCustomStaxResult(eventWriter); + transformer.transform(webServiceMessage.getPayloadSource(), staxResult); + eventWriter.flush(); + assertXMLEqual(getExpectedString(), stringWriter.toString()); + validateMessage(); + } - @Test - public void testReaderPayload() throws Exception { - Reader reader = new InputStreamReader(payload.getInputStream(), "UTF-8"); - StreamSource streamSource = new StreamSource(reader, payload.getURL().toString()); - transformer.transform(streamSource, webServiceMessage.getPayloadResult()); - StringWriter resultWriter = new StringWriter(); - StreamResult streamResult = new StreamResult(resultWriter); - transformer.transform(webServiceMessage.getPayloadSource(), streamResult); - assertXMLEqual(getExpectedString(), resultWriter.toString()); - } + @Test + public void testReaderPayload() throws Exception { + Reader reader = new InputStreamReader(payload.getInputStream(), "UTF-8"); + StreamSource streamSource = new StreamSource(reader, payload.getURL().toString()); + transformer.transform(streamSource, webServiceMessage.getPayloadResult()); + StringWriter resultWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(resultWriter); + transformer.transform(webServiceMessage.getPayloadSource(), streamResult); + assertXMLEqual(getExpectedString(), resultWriter.toString()); + } - @Test - public void testSaxPayload() throws Exception { - SAXSource saxSource = new SAXSource(SaxUtils.createInputSource(payload)); - transformer.transform(saxSource, webServiceMessage.getPayloadResult()); - StringResult stringResult = new StringResult(); - transformer.transform(webServiceMessage.getPayloadSource(), stringResult); - assertXMLEqual(getExpectedString(), stringResult.toString()); - validateMessage(); - } + @Test + public void testSaxPayload() throws Exception { + SAXSource saxSource = new SAXSource(SaxUtils.createInputSource(payload)); + transformer.transform(saxSource, webServiceMessage.getPayloadResult()); + StringResult stringResult = new StringResult(); + transformer.transform(webServiceMessage.getPayloadSource(), stringResult); + assertXMLEqual(getExpectedString(), stringResult.toString()); + validateMessage(); + } - @Test - public void testStreamPayload() throws Exception { - StreamSource streamSource = new StreamSource(payload.getInputStream(), payload.getURL().toString()); - transformer.transform(streamSource, webServiceMessage.getPayloadResult()); - ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); - StreamResult streamResult = new StreamResult(resultStream); - transformer.transform(webServiceMessage.getPayloadSource(), streamResult); - ByteArrayOutputStream expectedStream = new ByteArrayOutputStream(); - FileCopyUtils.copy(payload.getInputStream(), expectedStream); - assertXMLEqual(expectedStream.toString("UTF-8"), resultStream.toString("UTF-8")); - validateMessage(); - } + @Test + public void testStreamPayload() throws Exception { + StreamSource streamSource = new StreamSource(payload.getInputStream(), payload.getURL().toString()); + transformer.transform(streamSource, webServiceMessage.getPayloadResult()); + ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); + StreamResult streamResult = new StreamResult(resultStream); + transformer.transform(webServiceMessage.getPayloadSource(), streamResult); + ByteArrayOutputStream expectedStream = new ByteArrayOutputStream(); + FileCopyUtils.copy(payload.getInputStream(), expectedStream); + assertXMLEqual(expectedStream.toString("UTF-8"), resultStream.toString("UTF-8")); + validateMessage(); + } - @Test - public void testStreamReaderPayload() throws Exception { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLStreamReader streamReader = inputFactory.createXMLStreamReader(payload.getInputStream()); - Source staxSource = StaxUtils.createCustomStaxSource(streamReader); - transformer.transform(staxSource, webServiceMessage.getPayloadResult()); - StringWriter stringWriter = new StringWriter(); - XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); - XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(stringWriter); - Result staxResult = StaxUtils.createCustomStaxResult(streamWriter); - transformer.transform(webServiceMessage.getPayloadSource(), staxResult); - streamWriter.flush(); - assertXMLEqual(getExpectedString(), stringWriter.toString()); - validateMessage(); - } + @Test + public void testStreamReaderPayload() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader streamReader = inputFactory.createXMLStreamReader(payload.getInputStream()); + Source staxSource = StaxUtils.createCustomStaxSource(streamReader); + transformer.transform(staxSource, webServiceMessage.getPayloadResult()); + StringWriter stringWriter = new StringWriter(); + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(stringWriter); + Result staxResult = StaxUtils.createCustomStaxResult(streamWriter); + transformer.transform(webServiceMessage.getPayloadSource(), staxResult); + streamWriter.flush(); + assertXMLEqual(getExpectedString(), stringWriter.toString()); + validateMessage(); + } - private void validateMessage() throws Exception { - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); - xmlReader.setContentHandler(new DefaultHandler()); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - webServiceMessage.writeTo(os); - ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); - xmlReader.parse(new InputSource(is)); - } + private void validateMessage() throws Exception { + XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader.setContentHandler(new DefaultHandler()); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + webServiceMessage.writeTo(os); + ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); + xmlReader.parse(new InputSource(is)); + } - protected abstract WebServiceMessage createWebServiceMessage() throws Exception; + protected abstract WebServiceMessage createWebServiceMessage() throws Exception; } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessage.java b/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessage.java index fc37d1a4..03cb9780 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessage.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessage.java @@ -46,88 +46,88 @@ import org.springframework.xml.transform.StringSource; */ public class MockWebServiceMessage implements FaultAwareWebServiceMessage { - private StringBuilder content; + private StringBuilder content; - private boolean fault = false; + private boolean fault = false; private QName faultCode; - private String faultReason; + private String faultReason; public MockWebServiceMessage() { - } + } - public MockWebServiceMessage(Source source) throws TransformerException { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - content = new StringBuilder(); - transformer.transform(source, getPayloadResult()); - } + public MockWebServiceMessage(Source source) throws TransformerException { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + content = new StringBuilder(); + transformer.transform(source, getPayloadResult()); + } - public MockWebServiceMessage(Resource resource) throws IOException, TransformerException { - this(new SAXSource(SaxUtils.createInputSource(resource))); - } + public MockWebServiceMessage(Resource resource) throws IOException, TransformerException { + this(new SAXSource(SaxUtils.createInputSource(resource))); + } - public MockWebServiceMessage(StringBuilder content) { - this.content = content; - } + public MockWebServiceMessage(StringBuilder content) { + this.content = content; + } - public MockWebServiceMessage(String content) { - if (content != null) { - this.content = new StringBuilder(content); - } - } + public MockWebServiceMessage(String content) { + if (content != null) { + this.content = new StringBuilder(content); + } + } - public String getPayloadAsString() { - return content != null ? content.toString() : null; - } + public String getPayloadAsString() { + return content != null ? content.toString() : null; + } - public void setPayload(InputStreamSource inputStreamSource) throws IOException { - checkContent(); - InputStream is = null; - try { - is = inputStreamSource.getInputStream(); - Reader reader = new InputStreamReader(is, "UTF-8"); - content.replace(0, content.length(), FileCopyUtils.copyToString(reader)); - } - finally { - if (is != null) { - is.close(); - } - } - } + public void setPayload(InputStreamSource inputStreamSource) throws IOException { + checkContent(); + InputStream is = null; + try { + is = inputStreamSource.getInputStream(); + Reader reader = new InputStreamReader(is, "UTF-8"); + content.replace(0, content.length(), FileCopyUtils.copyToString(reader)); + } + finally { + if (is != null) { + is.close(); + } + } + } - public void setPayload(String content) { - checkContent(); - this.content.replace(0, this.content.length(), content); - } + public void setPayload(String content) { + checkContent(); + this.content.replace(0, this.content.length(), content); + } - private void checkContent() { - if (content == null) { - content = new StringBuilder(); - } - } + private void checkContent() { + if (content == null) { + content = new StringBuilder(); + } + } - @Override - public Result getPayloadResult() { - checkContent(); - content.setLength(0); - return new StreamResult(new StringBufferWriter()); - } + @Override + public Result getPayloadResult() { + checkContent(); + content.setLength(0); + return new StreamResult(new StringBufferWriter()); + } - @Override - public Source getPayloadSource() { - return content != null ? new StringSource(content.toString()) : null; - } + @Override + public Source getPayloadSource() { + return content != null ? new StringSource(content.toString()) : null; + } - @Override - public boolean hasFault() { - return fault; - } + @Override + public boolean hasFault() { + return fault; + } - public void setFault(boolean fault) { - this.fault = fault; - } + public void setFault(boolean fault) { + this.fault = fault; + } @Override public QName getFaultCode() { @@ -139,69 +139,69 @@ public class MockWebServiceMessage implements FaultAwareWebServiceMessage { } @Override - public String getFaultReason() { - return faultReason; - } + public String getFaultReason() { + return faultReason; + } - public void setFaultReason(String faultReason) { - this.faultReason = faultReason; - } + public void setFaultReason(String faultReason) { + this.faultReason = faultReason; + } - @Override - public void writeTo(OutputStream outputStream) throws IOException { - if (content != null) { - PrintWriter writer = new PrintWriter(outputStream); - writer.write(content.toString()); - } - } + @Override + public void writeTo(OutputStream outputStream) throws IOException { + if (content != null) { + PrintWriter writer = new PrintWriter(outputStream); + writer.write(content.toString()); + } + } - public String toString() { - StringBuilder builder = new StringBuilder("MockWebServiceMessage {"); - if (content != null) { - builder.append(content); - } - builder.append('}'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("MockWebServiceMessage {"); + if (content != null) { + builder.append(content); + } + builder.append('}'); + return builder.toString(); + } - private class StringBufferWriter extends Writer { + private class StringBufferWriter extends Writer { - private StringBufferWriter() { - super(content); - } + private StringBufferWriter() { + super(content); + } - @Override - public void write(String str) { - content.append(str); - } + @Override + public void write(String str) { + content.append(str); + } - @Override - public void write(int c) { - content.append((char) c); - } + @Override + public void write(int c) { + content.append((char) c); + } - @Override - public void write(String str, int off, int len) { - content.append(str.substring(off, off + len)); - } + @Override + public void write(String str, int off, int len) { + content.append(str.substring(off, off + len)); + } - @Override - public void close() throws IOException { - } + @Override + public void close() throws IOException { + } - @Override - public void flush() { - } + @Override + public void flush() { + } - @Override - public void write(char cbuf[], int off, int len) { - if (off < 0 || off > cbuf.length || len < 0 || off + len > cbuf.length || off + len < 0) { - throw new IndexOutOfBoundsException(); - } - else if (len == 0) { - return; - } - content.append(cbuf, off, len); - } - } + @Override + public void write(char cbuf[], int off, int len) { + if (off < 0 || off > cbuf.length || len < 0 || off + len > cbuf.length || off + len < 0) { + throw new IndexOutOfBoundsException(); + } + else if (len == 0) { + return; + } + content.append(cbuf, off, len); + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessageFactory.java b/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessageFactory.java index 3bd41ff9..a9711ef8 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessageFactory.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/MockWebServiceMessageFactory.java @@ -23,18 +23,18 @@ import javax.xml.transform.stream.StreamSource; public class MockWebServiceMessageFactory implements WebServiceMessageFactory { - @Override - public MockWebServiceMessage createWebServiceMessage() { - return new MockWebServiceMessage(); - } + @Override + public MockWebServiceMessage createWebServiceMessage() { + return new MockWebServiceMessage(); + } - @Override - public MockWebServiceMessage createWebServiceMessage(InputStream inputStream) throws IOException { - try { - return new MockWebServiceMessage(new StreamSource(inputStream)); - } - catch (TransformerException ex) { - throw new IOException(ex.getMessage()); - } - } + @Override + public MockWebServiceMessage createWebServiceMessage(InputStream inputStream) throws IOException { + try { + return new MockWebServiceMessage(new StreamSource(inputStream)); + } + catch (TransformerException ex) { + throw new IOException(ex.getMessage()); + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap11WebServiceTemplateIntegrationTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap11WebServiceTemplateIntegrationTestCase.java index 7b57608b..3296439e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap11WebServiceTemplateIntegrationTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap11WebServiceTemplateIntegrationTestCase.java @@ -69,32 +69,32 @@ import org.springframework.xml.transform.StringSource; public abstract class AbstractSoap11WebServiceTemplateIntegrationTestCase { - private static Server jettyServer; + private static Server jettyServer; - private static String baseUrl; + private static String baseUrl; - private WebServiceTemplate template; + private WebServiceTemplate template; - private String messagePayload = ""; + private String messagePayload = ""; - @BeforeClass - public static void startJetty() throws Exception { - int port = FreePortScanner.getFreePort(); - baseUrl = "http://localhost:" + port; - jettyServer = new Server(port); - Context jettyContext = new Context(jettyServer, "/"); - jettyContext.addServlet(new ServletHolder(new EchoSoapServlet()), "/soap/echo"); - jettyContext.addServlet(new ServletHolder(new SoapFaultServlet()), "/soap/fault"); - SoapFaultServlet badRequestFault = new SoapFaultServlet(); - badRequestFault.setSc(400); - jettyContext.addServlet(new ServletHolder(badRequestFault), "/soap/badRequestFault"); - jettyContext.addServlet(new ServletHolder(new NoResponseSoapServlet()), "/soap/noResponse"); - jettyContext.addServlet(new ServletHolder(new AttachmentsServlet()), "/soap/attachment"); - jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); - jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); - jettyServer.start(); - } + @BeforeClass + public static void startJetty() throws Exception { + int port = FreePortScanner.getFreePort(); + baseUrl = "http://localhost:" + port; + jettyServer = new Server(port); + Context jettyContext = new Context(jettyServer, "/"); + jettyContext.addServlet(new ServletHolder(new EchoSoapServlet()), "/soap/echo"); + jettyContext.addServlet(new ServletHolder(new SoapFaultServlet()), "/soap/fault"); + SoapFaultServlet badRequestFault = new SoapFaultServlet(); + badRequestFault.setSc(400); + jettyContext.addServlet(new ServletHolder(badRequestFault), "/soap/badRequestFault"); + jettyContext.addServlet(new ServletHolder(new NoResponseSoapServlet()), "/soap/noResponse"); + jettyContext.addServlet(new ServletHolder(new AttachmentsServlet()), "/soap/attachment"); + jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); + jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); + jettyServer.start(); + } @AfterClass public static void stopJetty() throws Exception { @@ -113,277 +113,277 @@ public abstract class AbstractSoap11WebServiceTemplateIntegrationTestCase { public abstract SoapMessageFactory createMessageFactory() throws Exception; @Test - public void sendSourceAndReceiveToResult() throws SAXException, IOException { - StringResult result = new StringResult(); - boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/echo", - new StringSource(messagePayload), result); - Assert.assertTrue("Invalid result", b); - assertXMLEqual(messagePayload, result.toString()); - } + public void sendSourceAndReceiveToResult() throws SAXException, IOException { + StringResult result = new StringResult(); + boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/echo", + new StringSource(messagePayload), result); + Assert.assertTrue("Invalid result", b); + assertXMLEqual(messagePayload, result.toString()); + } @Test - public void sendSourceAndReceiveToResultNoResponse() { - boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/noResponse", - new StringSource(messagePayload), new StringResult()); - Assert.assertFalse("Invalid result", b); - } + public void sendSourceAndReceiveToResultNoResponse() { + boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/noResponse", + new StringSource(messagePayload), new StringResult()); + Assert.assertFalse("Invalid result", b); + } @Test - public void marshalSendAndReceiveResponse() throws TransformerConfigurationException { - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final Object requestObject = new Object(); - Marshaller marshaller = new Marshaller() { + public void marshalSendAndReceiveResponse() throws TransformerConfigurationException { + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final Object requestObject = new Object(); + Marshaller marshaller = new Marshaller() { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - Assert.assertEquals("Invalid object", graph, requestObject); - try { - transformer.transform(new StringSource(messagePayload), result); - } - catch (TransformerException e) { - Assert.fail(e.getMessage()); - } - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + Assert.assertEquals("Invalid object", graph, requestObject); + try { + transformer.transform(new StringSource(messagePayload), result); + } + catch (TransformerException e) { + Assert.fail(e.getMessage()); + } + } - @Override - public boolean supports(Class clazz) { - Assert.assertEquals("Invalid class", Object.class, clazz); - return true; - } - }; - final Object responseObject = new Object(); - Unmarshaller unmarshaller = new Unmarshaller() { + @Override + public boolean supports(Class clazz) { + Assert.assertEquals("Invalid class", Object.class, clazz); + return true; + } + }; + final Object responseObject = new Object(); + Unmarshaller unmarshaller = new Unmarshaller() { - @Override - public Object unmarshal(Source source) throws XmlMappingException, IOException { - return responseObject; - } + @Override + public Object unmarshal(Source source) throws XmlMappingException, IOException { + return responseObject; + } - @Override - public boolean supports(Class clazz) { - Assert.assertEquals("Invalid class", Object.class, clazz); - return true; - } - }; - template.setMarshaller(marshaller); - template.setUnmarshaller(unmarshaller); - Object result = template.marshalSendAndReceive(baseUrl + "/soap/echo", requestObject); - Assert.assertEquals("Invalid response object", responseObject, result); - } + @Override + public boolean supports(Class clazz) { + Assert.assertEquals("Invalid class", Object.class, clazz); + return true; + } + }; + template.setMarshaller(marshaller); + template.setUnmarshaller(unmarshaller); + Object result = template.marshalSendAndReceive(baseUrl + "/soap/echo", requestObject); + Assert.assertEquals("Invalid response object", responseObject, result); + } @Test - public void marshalSendAndReceiveNoResponse() throws TransformerConfigurationException { - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final Object requestObject = new Object(); - Marshaller marshaller = new Marshaller() { + public void marshalSendAndReceiveNoResponse() throws TransformerConfigurationException { + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final Object requestObject = new Object(); + Marshaller marshaller = new Marshaller() { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - Assert.assertEquals("Invalid object", graph, requestObject); - try { - transformer.transform(new StringSource(messagePayload), result); - } - catch (TransformerException e) { - Assert.fail(e.getMessage()); - } - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + Assert.assertEquals("Invalid object", graph, requestObject); + try { + transformer.transform(new StringSource(messagePayload), result); + } + catch (TransformerException e) { + Assert.fail(e.getMessage()); + } + } - @Override - public boolean supports(Class clazz) { - Assert.assertEquals("Invalid class", Object.class, clazz); - return true; - } - }; - template.setMarshaller(marshaller); - Object result = template.marshalSendAndReceive(baseUrl + "/soap/noResponse", requestObject); - Assert.assertNull("Invalid response object", result); - } + @Override + public boolean supports(Class clazz) { + Assert.assertEquals("Invalid class", Object.class, clazz); + return true; + } + }; + template.setMarshaller(marshaller); + Object result = template.marshalSendAndReceive(baseUrl + "/soap/noResponse", requestObject); + Assert.assertNull("Invalid response object", result); + } @Test - public void notFound() { - try { - template.sendSourceAndReceiveToResult(baseUrl + "/errors/notfound", - new StringSource(messagePayload), new StringResult()); - Assert.fail("WebServiceTransportException expected"); - } - catch (WebServiceTransportException ex) { - //expected - } - } + public void notFound() { + try { + template.sendSourceAndReceiveToResult(baseUrl + "/errors/notfound", + new StringSource(messagePayload), new StringResult()); + Assert.fail("WebServiceTransportException expected"); + } + catch (WebServiceTransportException ex) { + //expected + } + } @Test - public void fault() { - Result result = new StringResult(); - try { - template.sendSourceAndReceiveToResult(baseUrl + "/soap/fault", new StringSource(messagePayload), - result); - Assert.fail("SoapFaultClientException expected"); - } - catch (SoapFaultClientException ex) { - //expected - } - } + public void fault() { + Result result = new StringResult(); + try { + template.sendSourceAndReceiveToResult(baseUrl + "/soap/fault", new StringSource(messagePayload), + result); + Assert.fail("SoapFaultClientException expected"); + } + catch (SoapFaultClientException ex) { + //expected + } + } @Test - public void faultNonCompliant() { - Result result = new StringResult(); - template.setCheckConnectionForFault(false); - template.setCheckConnectionForError(false); - try { - template.sendSourceAndReceiveToResult(baseUrl + "/soap/badRequestFault", - new StringSource(messagePayload), result); - Assert.fail("SoapFaultClientException expected"); - } - catch (SoapFaultClientException ex) { - //expected - } - } + public void faultNonCompliant() { + Result result = new StringResult(); + template.setCheckConnectionForFault(false); + template.setCheckConnectionForError(false); + try { + template.sendSourceAndReceiveToResult(baseUrl + "/soap/badRequestFault", + new StringSource(messagePayload), result); + Assert.fail("SoapFaultClientException expected"); + } + catch (SoapFaultClientException ex) { + //expected + } + } @Test - public void attachment() { - template.sendSourceAndReceiveToResult(baseUrl + "/soap/attachment", new StringSource(messagePayload), - new WebServiceMessageCallback() { + public void attachment() { + template.sendSourceAndReceiveToResult(baseUrl + "/soap/attachment", new StringSource(messagePayload), + new WebServiceMessageCallback() { - @Override - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - SoapMessage soapMessage = (SoapMessage) message; - final String attachmentContent = "content"; - soapMessage.addAttachment("attachment-1", - new DataHandler(new ByteArrayDataSource(attachmentContent, "text/plain"))); - } - }, new StringResult()); - } + @Override + public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { + SoapMessage soapMessage = (SoapMessage) message; + final String attachmentContent = "content"; + soapMessage.addAttachment("attachment-1", + new DataHandler(new ByteArrayDataSource(attachmentContent, "text/plain"))); + } + }, new StringResult()); + } - /** Servlet that returns and error message for a given status code. */ - @SuppressWarnings("serial") - private static class ErrorServlet extends HttpServlet { + /** Servlet that returns and error message for a given status code. */ + @SuppressWarnings("serial") + private static class ErrorServlet extends HttpServlet { - private int sc; + private int sc; - private ErrorServlet(int sc) { - this.sc = sc; - } + private ErrorServlet(int sc) { + this.sc = sc; + } - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.sendError(sc); - } - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.sendError(sc); + } + } /** Abstract SOAP Servlet */ @SuppressWarnings("serial") - private abstract static class AbstractSoapServlet extends HttpServlet { + private abstract static class AbstractSoapServlet extends HttpServlet { - protected MessageFactory messageFactory = null; + protected MessageFactory messageFactory = null; - private int sc = -1; + private int sc = -1; - public void setSc(int sc) { - this.sc = sc; - } + public void setSc(int sc) { + this.sc = sc; + } - @Override - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - try { - messageFactory = MessageFactory.newInstance(); - } - catch (SOAPException ex) { - throw new ServletException("Unable to create message factory" + ex.getMessage()); - } - } + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + try { + messageFactory = MessageFactory.newInstance(); + } + catch (SOAPException ex) { + throw new ServletException("Unable to create message factory" + ex.getMessage()); + } + } - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - try { - MimeHeaders headers = getHeaders(req); - SOAPMessage request = messageFactory.createMessage(headers, req.getInputStream()); - SOAPMessage reply = onMessage(request); - if (sc != -1) { - resp.setStatus(sc); - } - if (reply != null) { - reply.saveChanges(); - if (sc == -1) { - resp.setStatus(!reply.getSOAPBody().hasFault() ? HttpServletResponse.SC_OK : - HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - putHeaders(reply.getMimeHeaders(), resp); - reply.writeTo(resp.getOutputStream()); - } - else if (sc == -1) { - resp.setStatus(HttpServletResponse.SC_ACCEPTED); - } - } - catch (Exception ex) { - throw new ServletException("SAAJ POST failed " + ex.getMessage(), ex); - } - } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + try { + MimeHeaders headers = getHeaders(req); + SOAPMessage request = messageFactory.createMessage(headers, req.getInputStream()); + SOAPMessage reply = onMessage(request); + if (sc != -1) { + resp.setStatus(sc); + } + if (reply != null) { + reply.saveChanges(); + if (sc == -1) { + resp.setStatus(!reply.getSOAPBody().hasFault() ? HttpServletResponse.SC_OK : + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + putHeaders(reply.getMimeHeaders(), resp); + reply.writeTo(resp.getOutputStream()); + } + else if (sc == -1) { + resp.setStatus(HttpServletResponse.SC_ACCEPTED); + } + } + catch (Exception ex) { + throw new ServletException("SAAJ POST failed " + ex.getMessage(), ex); + } + } - private MimeHeaders getHeaders(HttpServletRequest httpServletRequest) { - Enumeration enumeration = httpServletRequest.getHeaderNames(); - MimeHeaders headers = new MimeHeaders(); - while (enumeration.hasMoreElements()) { - String headerName = (String) enumeration.nextElement(); - String headerValue = httpServletRequest.getHeader(headerName); - StringTokenizer values = new StringTokenizer(headerValue, ","); - while (values.hasMoreTokens()) { - headers.addHeader(headerName, values.nextToken().trim()); - } - } - return headers; - } + private MimeHeaders getHeaders(HttpServletRequest httpServletRequest) { + Enumeration enumeration = httpServletRequest.getHeaderNames(); + MimeHeaders headers = new MimeHeaders(); + while (enumeration.hasMoreElements()) { + String headerName = (String) enumeration.nextElement(); + String headerValue = httpServletRequest.getHeader(headerName); + StringTokenizer values = new StringTokenizer(headerValue, ","); + while (values.hasMoreTokens()) { + headers.addHeader(headerName, values.nextToken().trim()); + } + } + return headers; + } - private void putHeaders(MimeHeaders headers, HttpServletResponse res) { - Iterator it = headers.getAllHeaders(); - while (it.hasNext()) { - MimeHeader header = (MimeHeader) it.next(); - String[] values = headers.getHeader(header.getName()); - res.setHeader(header.getName(), StringUtils.arrayToCommaDelimitedString(values)); - } - } + private void putHeaders(MimeHeaders headers, HttpServletResponse res) { + Iterator it = headers.getAllHeaders(); + while (it.hasNext()) { + MimeHeader header = (MimeHeader) it.next(); + String[] values = headers.getHeader(header.getName()); + res.setHeader(header.getName(), StringUtils.arrayToCommaDelimitedString(values)); + } + } - protected abstract SOAPMessage onMessage(SOAPMessage message) throws SOAPException; - } + protected abstract SOAPMessage onMessage(SOAPMessage message) throws SOAPException; + } @SuppressWarnings("serial") - private static class EchoSoapServlet extends AbstractSoapServlet { + private static class EchoSoapServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - return message; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + return message; + } + } @SuppressWarnings("serial") - private static class NoResponseSoapServlet extends AbstractSoapServlet { + private static class NoResponseSoapServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - return null; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + return null; + } + } @SuppressWarnings("serial") - private static class SoapFaultServlet extends AbstractSoapServlet { + private static class SoapFaultServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - SOAPMessage response = messageFactory.createMessage(); - SOAPBody body = response.getSOAPBody(); - body.addFault(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"), "Server fault"); - return response; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + SOAPMessage response = messageFactory.createMessage(); + SOAPBody body = response.getSOAPBody(); + body.addFault(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"), "Server fault"); + return response; + } + } @SuppressWarnings("serial") - private static class AttachmentsServlet extends AbstractSoapServlet { + private static class AttachmentsServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - assertEquals("No attachments found", 1, message.countAttachments()); - return null; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + assertEquals("No attachments found", 1, message.countAttachments()); + return null; + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap12WebServiceTemplateIntegrationTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap12WebServiceTemplateIntegrationTestCase.java index b2364ef2..1a30aed4 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap12WebServiceTemplateIntegrationTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AbstractSoap12WebServiceTemplateIntegrationTestCase.java @@ -70,30 +70,30 @@ import org.springframework.xml.transform.StringSource; public abstract class AbstractSoap12WebServiceTemplateIntegrationTestCase { - private static Server jettyServer; + private static Server jettyServer; - private static String baseUrl; + private static String baseUrl; - private WebServiceTemplate template; + private WebServiceTemplate template; - private String messagePayload = ""; + private String messagePayload = ""; - @BeforeClass - public static void startJetty() throws Exception { - int port = FreePortScanner.getFreePort(); - baseUrl = "http://localhost:" + port; - jettyServer = new Server(port); - Context jettyContext = new Context(jettyServer, "/"); - jettyContext.addServlet(new ServletHolder(new EchoSoapServlet()), "/soap/echo"); - jettyContext.addServlet(new ServletHolder(new SoapReceiverFaultServlet()), "/soap/receiverFault"); - jettyContext.addServlet(new ServletHolder(new SoapSenderFaultServlet()), "/soap/senderFault"); - jettyContext.addServlet(new ServletHolder(new NoResponseSoapServlet()), "/soap/noResponse"); - jettyContext.addServlet(new ServletHolder(new AttachmentsServlet()), "/soap/attachment"); - jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); - jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); - jettyServer.start(); - } + @BeforeClass + public static void startJetty() throws Exception { + int port = FreePortScanner.getFreePort(); + baseUrl = "http://localhost:" + port; + jettyServer = new Server(port); + Context jettyContext = new Context(jettyServer, "/"); + jettyContext.addServlet(new ServletHolder(new EchoSoapServlet()), "/soap/echo"); + jettyContext.addServlet(new ServletHolder(new SoapReceiverFaultServlet()), "/soap/receiverFault"); + jettyContext.addServlet(new ServletHolder(new SoapSenderFaultServlet()), "/soap/senderFault"); + jettyContext.addServlet(new ServletHolder(new NoResponseSoapServlet()), "/soap/noResponse"); + jettyContext.addServlet(new ServletHolder(new AttachmentsServlet()), "/soap/attachment"); + jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); + jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); + jettyServer.start(); + } @AfterClass public static void stopJetty() throws Exception { @@ -102,17 +102,17 @@ public abstract class AbstractSoap12WebServiceTemplateIntegrationTestCase { } } - /** - * A workaround for the faulty XmlDataContentHandler in the SAAJ RI, which cannot handle mime types such as - * "text/xml; charset=UTF-8", causing issues with Axiom. We basically reset the command map - */ - @Before - public void removeXmlDataContentHandler() throws SOAPException { - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage message = messageFactory.createMessage(); - message.createAttachmentPart(); - CommandMap.setDefaultCommandMap(new MailcapCommandMap()); - } + /** + * A workaround for the faulty XmlDataContentHandler in the SAAJ RI, which cannot handle mime types such as + * "text/xml; charset=UTF-8", causing issues with Axiom. We basically reset the command map + */ + @Before + public void removeXmlDataContentHandler() throws SOAPException { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage message = messageFactory.createMessage(); + message.createAttachmentPart(); + CommandMap.setDefaultCommandMap(new MailcapCommandMap()); + } @Before public void createWebServiceTemplate() throws Exception { @@ -124,290 +124,290 @@ public abstract class AbstractSoap12WebServiceTemplateIntegrationTestCase { public abstract SoapMessageFactory createMessageFactory() throws Exception; @Test - public void sendSourceAndReceiveToResult() throws SAXException, IOException { - StringResult result = new StringResult(); - boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/echo", - new StringSource(messagePayload), result); - Assert.assertTrue("Invalid result", b); - assertXMLEqual(messagePayload, result.toString()); - } + public void sendSourceAndReceiveToResult() throws SAXException, IOException { + StringResult result = new StringResult(); + boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/echo", + new StringSource(messagePayload), result); + Assert.assertTrue("Invalid result", b); + assertXMLEqual(messagePayload, result.toString()); + } @Test - public void sendSourceAndReceiveToResultNoResponse() { - boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/noResponse", - new StringSource(messagePayload), new StringResult()); - Assert.assertFalse("Invalid result", b); - } + public void sendSourceAndReceiveToResultNoResponse() { + boolean b = template.sendSourceAndReceiveToResult(baseUrl + "/soap/noResponse", + new StringSource(messagePayload), new StringResult()); + Assert.assertFalse("Invalid result", b); + } @Test - public void marshalSendAndReceiveResponse() throws TransformerConfigurationException { - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final Object requestObject = new Object(); - Marshaller marshaller = new Marshaller() { + public void marshalSendAndReceiveResponse() throws TransformerConfigurationException { + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final Object requestObject = new Object(); + Marshaller marshaller = new Marshaller() { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - Assert.assertEquals("Invalid object", graph, requestObject); - try { - transformer.transform(new StringSource(messagePayload), result); - } - catch (TransformerException e) { - Assert.fail(e.getMessage()); - } - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + Assert.assertEquals("Invalid object", graph, requestObject); + try { + transformer.transform(new StringSource(messagePayload), result); + } + catch (TransformerException e) { + Assert.fail(e.getMessage()); + } + } - @Override - public boolean supports(Class clazz) { - Assert.assertEquals("Invalid class", Object.class, clazz); - return true; - } - }; - final Object responseObject = new Object(); - Unmarshaller unmarshaller = new Unmarshaller() { + @Override + public boolean supports(Class clazz) { + Assert.assertEquals("Invalid class", Object.class, clazz); + return true; + } + }; + final Object responseObject = new Object(); + Unmarshaller unmarshaller = new Unmarshaller() { - @Override - public Object unmarshal(Source source) throws XmlMappingException, IOException { - return responseObject; - } + @Override + public Object unmarshal(Source source) throws XmlMappingException, IOException { + return responseObject; + } - @Override - public boolean supports(Class clazz) { - Assert.assertEquals("Invalid class", Object.class, clazz); - return true; - } - }; - template.setMarshaller(marshaller); - template.setUnmarshaller(unmarshaller); - Object result = template.marshalSendAndReceive(baseUrl + "/soap/echo", requestObject); - Assert.assertEquals("Invalid response object", responseObject, result); - } + @Override + public boolean supports(Class clazz) { + Assert.assertEquals("Invalid class", Object.class, clazz); + return true; + } + }; + template.setMarshaller(marshaller); + template.setUnmarshaller(unmarshaller); + Object result = template.marshalSendAndReceive(baseUrl + "/soap/echo", requestObject); + Assert.assertEquals("Invalid response object", responseObject, result); + } @Test - public void marshalSendAndReceiveNoResponse() throws TransformerConfigurationException { - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final Object requestObject = new Object(); - Marshaller marshaller = new Marshaller() { + public void marshalSendAndReceiveNoResponse() throws TransformerConfigurationException { + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final Object requestObject = new Object(); + Marshaller marshaller = new Marshaller() { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - Assert.assertEquals("Invalid object", graph, requestObject); - try { - transformer.transform(new StringSource(messagePayload), result); - } - catch (TransformerException e) { - Assert.fail(e.getMessage()); - } - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + Assert.assertEquals("Invalid object", graph, requestObject); + try { + transformer.transform(new StringSource(messagePayload), result); + } + catch (TransformerException e) { + Assert.fail(e.getMessage()); + } + } - @Override - public boolean supports(Class clazz) { - Assert.assertEquals("Invalid class", Object.class, clazz); - return true; - } - }; - template.setMarshaller(marshaller); - Object result = template.marshalSendAndReceive(baseUrl + "/soap/noResponse", requestObject); - Assert.assertNull("Invalid response object", result); - } + @Override + public boolean supports(Class clazz) { + Assert.assertEquals("Invalid class", Object.class, clazz); + return true; + } + }; + template.setMarshaller(marshaller); + Object result = template.marshalSendAndReceive(baseUrl + "/soap/noResponse", requestObject); + Assert.assertNull("Invalid response object", result); + } @Test - public void notFound() { - try { - template.sendSourceAndReceiveToResult(baseUrl + "/errors/notfound", - new StringSource(messagePayload), new StringResult()); - Assert.fail("WebServiceTransportException expected"); - } - catch (WebServiceTransportException ex) { - //expected - } - } + public void notFound() { + try { + template.sendSourceAndReceiveToResult(baseUrl + "/errors/notfound", + new StringSource(messagePayload), new StringResult()); + Assert.fail("WebServiceTransportException expected"); + } + catch (WebServiceTransportException ex) { + //expected + } + } @Test - public void receiverFault() { - Result result = new StringResult(); - try { - template.sendSourceAndReceiveToResult(baseUrl + "/soap/receiverFault", new StringSource(messagePayload), - result); - Assert.fail("SoapFaultClientException expected"); - } - catch (SoapFaultClientException ex) { - //expected - } - } + public void receiverFault() { + Result result = new StringResult(); + try { + template.sendSourceAndReceiveToResult(baseUrl + "/soap/receiverFault", new StringSource(messagePayload), + result); + Assert.fail("SoapFaultClientException expected"); + } + catch (SoapFaultClientException ex) { + //expected + } + } @Test - public void senderFault() { - Result result = new StringResult(); - try { - template.sendSourceAndReceiveToResult(baseUrl + "/soap/senderFault", new StringSource(messagePayload), - result); - Assert.fail("SoapFaultClientException expected"); - } - catch (SoapFaultClientException ex) { - //expected - } - } + public void senderFault() { + Result result = new StringResult(); + try { + template.sendSourceAndReceiveToResult(baseUrl + "/soap/senderFault", new StringSource(messagePayload), + result); + Assert.fail("SoapFaultClientException expected"); + } + catch (SoapFaultClientException ex) { + //expected + } + } @Test - public void attachment() { - template.sendSourceAndReceiveToResult(baseUrl + "/soap/attachment", new StringSource(messagePayload), - new WebServiceMessageCallback() { + public void attachment() { + template.sendSourceAndReceiveToResult(baseUrl + "/soap/attachment", new StringSource(messagePayload), + new WebServiceMessageCallback() { - @Override - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - SoapMessage soapMessage = (SoapMessage) message; - final String attachmentContent = "content"; - soapMessage.addAttachment("attachment-1", - new DataHandler(new ByteArrayDataSource(attachmentContent, "text/plain"))); - } - }, new StringResult()); - } + @Override + public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { + SoapMessage soapMessage = (SoapMessage) message; + final String attachmentContent = "content"; + soapMessage.addAttachment("attachment-1", + new DataHandler(new ByteArrayDataSource(attachmentContent, "text/plain"))); + } + }, new StringResult()); + } - /** Servlet that returns and error message for a given status code. */ - @SuppressWarnings("serial") - private static class ErrorServlet extends HttpServlet { + /** Servlet that returns and error message for a given status code. */ + @SuppressWarnings("serial") + private static class ErrorServlet extends HttpServlet { - private int sc; + private int sc; - private ErrorServlet(int sc) { - this.sc = sc; - } + private ErrorServlet(int sc) { + this.sc = sc; + } - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.sendError(sc); - } - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.sendError(sc); + } + } /** Abstract SOAP Servlet */ @SuppressWarnings("serial") - private abstract static class AbstractSoapServlet extends HttpServlet { + private abstract static class AbstractSoapServlet extends HttpServlet { - protected MessageFactory messageFactory = null; + protected MessageFactory messageFactory = null; - @Override - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - try { - messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - } - catch (SOAPException ex) { - throw new ServletException("Unable to create message factory" + ex.getMessage()); - } - } + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + try { + messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + } + catch (SOAPException ex) { + throw new ServletException("Unable to create message factory" + ex.getMessage()); + } + } - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - try { - MimeHeaders headers = getHeaders(req); - SOAPMessage request = messageFactory.createMessage(headers, req.getInputStream()); - SOAPMessage reply = onMessage(request); - if (reply != null) { - reply.saveChanges(); - SOAPBody replyBody = reply.getSOAPBody(); - if (!replyBody.hasFault()) { - resp.setStatus(HttpServletResponse.SC_OK); - } - else { - if (replyBody.getFault().getFaultCodeAsQName() - .equals(SOAPConstants.SOAP_SENDER_FAULT)) { - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + try { + MimeHeaders headers = getHeaders(req); + SOAPMessage request = messageFactory.createMessage(headers, req.getInputStream()); + SOAPMessage reply = onMessage(request); + if (reply != null) { + reply.saveChanges(); + SOAPBody replyBody = reply.getSOAPBody(); + if (!replyBody.hasFault()) { + resp.setStatus(HttpServletResponse.SC_OK); + } + else { + if (replyBody.getFault().getFaultCodeAsQName() + .equals(SOAPConstants.SOAP_SENDER_FAULT)) { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - } - else { - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - putHeaders(reply.getMimeHeaders(), resp); - reply.writeTo(resp.getOutputStream()); - } - else { - resp.setStatus(HttpServletResponse.SC_ACCEPTED); - } - } - catch (Exception ex) { - throw new ServletException("SAAJ POST failed " + ex.getMessage(), ex); - } - } + } + else { + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + putHeaders(reply.getMimeHeaders(), resp); + reply.writeTo(resp.getOutputStream()); + } + else { + resp.setStatus(HttpServletResponse.SC_ACCEPTED); + } + } + catch (Exception ex) { + throw new ServletException("SAAJ POST failed " + ex.getMessage(), ex); + } + } - private MimeHeaders getHeaders(HttpServletRequest httpServletRequest) { - Enumeration enumeration = httpServletRequest.getHeaderNames(); - MimeHeaders headers = new MimeHeaders(); - while (enumeration.hasMoreElements()) { - String headerName = (String) enumeration.nextElement(); - String headerValue = httpServletRequest.getHeader(headerName); - StringTokenizer values = new StringTokenizer(headerValue, ","); - while (values.hasMoreTokens()) { - headers.addHeader(headerName, values.nextToken().trim()); - } - } - return headers; - } + private MimeHeaders getHeaders(HttpServletRequest httpServletRequest) { + Enumeration enumeration = httpServletRequest.getHeaderNames(); + MimeHeaders headers = new MimeHeaders(); + while (enumeration.hasMoreElements()) { + String headerName = (String) enumeration.nextElement(); + String headerValue = httpServletRequest.getHeader(headerName); + StringTokenizer values = new StringTokenizer(headerValue, ","); + while (values.hasMoreTokens()) { + headers.addHeader(headerName, values.nextToken().trim()); + } + } + return headers; + } - private void putHeaders(MimeHeaders headers, HttpServletResponse res) { - Iterator it = headers.getAllHeaders(); - while (it.hasNext()) { - MimeHeader header = (MimeHeader) it.next(); - String[] values = headers.getHeader(header.getName()); - for (String value : values) { - res.addHeader(header.getName(), value); - } - } - } + private void putHeaders(MimeHeaders headers, HttpServletResponse res) { + Iterator it = headers.getAllHeaders(); + while (it.hasNext()) { + MimeHeader header = (MimeHeader) it.next(); + String[] values = headers.getHeader(header.getName()); + for (String value : values) { + res.addHeader(header.getName(), value); + } + } + } - protected abstract SOAPMessage onMessage(SOAPMessage message) throws SOAPException; - } + protected abstract SOAPMessage onMessage(SOAPMessage message) throws SOAPException; + } @SuppressWarnings("serial") - private static class EchoSoapServlet extends AbstractSoapServlet { + private static class EchoSoapServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - return message; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + return message; + } + } @SuppressWarnings("serial") - private static class NoResponseSoapServlet extends AbstractSoapServlet { + private static class NoResponseSoapServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - return null; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + return null; + } + } @SuppressWarnings("serial") - private static class SoapReceiverFaultServlet extends AbstractSoapServlet { + private static class SoapReceiverFaultServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - SOAPMessage response = messageFactory.createMessage(); - SOAPBody body = response.getSOAPBody(); - body.addFault(SOAPConstants.SOAP_RECEIVER_FAULT, "Receiver Fault"); - return response; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + SOAPMessage response = messageFactory.createMessage(); + SOAPBody body = response.getSOAPBody(); + body.addFault(SOAPConstants.SOAP_RECEIVER_FAULT, "Receiver Fault"); + return response; + } + } @SuppressWarnings("serial") - private static class SoapSenderFaultServlet extends AbstractSoapServlet { + private static class SoapSenderFaultServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - SOAPMessage response = messageFactory.createMessage(); - SOAPBody body = response.getSOAPBody(); - body.addFault(SOAPConstants.SOAP_SENDER_FAULT, "Sender Fault"); - return response; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + SOAPMessage response = messageFactory.createMessage(); + SOAPBody body = response.getSOAPBody(); + body.addFault(SOAPConstants.SOAP_SENDER_FAULT, "Sender Fault"); + return response; + } + } @SuppressWarnings("serial") - private static class AttachmentsServlet extends AbstractSoapServlet { + private static class AttachmentsServlet extends AbstractSoapServlet { - @Override - protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { - assertEquals("No attachments found", 1, message.countAttachments()); - return null; - } - } + @Override + protected SOAPMessage onMessage(SOAPMessage message) throws SOAPException { + assertEquals("No attachments found", 1, message.countAttachments()); + return null; + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap11WebServiceTemplateIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap11WebServiceTemplateIntegrationTest.java index 22b44509..32bd759d 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap11WebServiceTemplateIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap11WebServiceTemplateIntegrationTest.java @@ -28,7 +28,7 @@ public class AxiomStreamingSoap11WebServiceTemplateIntegrationTest @Override public SoapMessageFactory createMessageFactory() throws Exception { AxiomSoapMessageFactory axiomFactory = new AxiomSoapMessageFactory(); - axiomFactory.setPayloadCaching(false); + axiomFactory.setPayloadCaching(false); return axiomFactory; } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap12WebServiceTemplateIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap12WebServiceTemplateIntegrationTest.java index 34cd448e..68f7b848 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap12WebServiceTemplateIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/AxiomStreamingSoap12WebServiceTemplateIntegrationTest.java @@ -30,7 +30,7 @@ public class AxiomStreamingSoap12WebServiceTemplateIntegrationTest public SoapMessageFactory createMessageFactory() throws Exception { AxiomSoapMessageFactory axiomFactory = new AxiomSoapMessageFactory(); axiomFactory.setSoapVersion(SoapVersion.SOAP_12); - axiomFactory.setPayloadCaching(false); + axiomFactory.setPayloadCaching(false); return axiomFactory; } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/DomPoxWebServiceTemplateIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/DomPoxWebServiceTemplateIntegrationTest.java index d941290c..046f72d7 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/DomPoxWebServiceTemplateIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/DomPoxWebServiceTemplateIntegrationTest.java @@ -48,100 +48,100 @@ import org.springframework.xml.transform.StringSource; public class DomPoxWebServiceTemplateIntegrationTest { - private static Server jettyServer; + private static Server jettyServer; - private static String baseUrl; + private static String baseUrl; @BeforeClass - public static void startJetty() throws Exception { - int port = FreePortScanner.getFreePort(); - baseUrl = "http://localhost:" + port; - jettyServer = new Server(port); - Context jettyContext = new Context(jettyServer, "/"); - jettyContext.addServlet(new ServletHolder(new PoxServlet()), "/pox"); - jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); - jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); - jettyServer.start(); - } + public static void startJetty() throws Exception { + int port = FreePortScanner.getFreePort(); + baseUrl = "http://localhost:" + port; + jettyServer = new Server(port); + Context jettyContext = new Context(jettyServer, "/"); + jettyContext.addServlet(new ServletHolder(new PoxServlet()), "/pox"); + jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); + jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); + jettyServer.start(); + } - @AfterClass - public static void stopJetty() throws Exception { - if (jettyServer.isRunning()) { - jettyServer.stop(); - } - } + @AfterClass + public static void stopJetty() throws Exception { + if (jettyServer.isRunning()) { + jettyServer.stop(); + } + } - @Test - public void domPox() throws Exception { - WebServiceTemplate template = new WebServiceTemplate(new DomPoxMessageFactory()); - template.setMessageSender(new HttpComponentsMessageSender()); - String content = ""; - StringResult result = new StringResult(); - template.sendSourceAndReceiveToResult(baseUrl + "/pox", new StringSource(content), - result); - assertXMLEqual(content, result.toString()); - try { - template.sendSourceAndReceiveToResult(baseUrl + "/errors/notfound", - new StringSource(content), new StringResult()); - Assert.fail("WebServiceTransportException expected"); - } - catch (WebServiceTransportException ex) { - //expected - } - try { - template.sendSourceAndReceiveToResult(baseUrl + "/errors/server", - new StringSource(content), result); - Assert.fail("WebServiceTransportException expected"); - } - catch (WebServiceTransportException ex) { - //expected - } - } + @Test + public void domPox() throws Exception { + WebServiceTemplate template = new WebServiceTemplate(new DomPoxMessageFactory()); + template.setMessageSender(new HttpComponentsMessageSender()); + String content = ""; + StringResult result = new StringResult(); + template.sendSourceAndReceiveToResult(baseUrl + "/pox", new StringSource(content), + result); + assertXMLEqual(content, result.toString()); + try { + template.sendSourceAndReceiveToResult(baseUrl + "/errors/notfound", + new StringSource(content), new StringResult()); + Assert.fail("WebServiceTransportException expected"); + } + catch (WebServiceTransportException ex) { + //expected + } + try { + template.sendSourceAndReceiveToResult(baseUrl + "/errors/server", + new StringSource(content), result); + Assert.fail("WebServiceTransportException expected"); + } + catch (WebServiceTransportException ex) { + //expected + } + } /** Servlet that returns and error message for a given status code. */ @SuppressWarnings("serial") - private static class ErrorServlet extends HttpServlet { + private static class ErrorServlet extends HttpServlet { - private int sc; + private int sc; - private ErrorServlet(int sc) { - this.sc = sc; - } + private ErrorServlet(int sc) { + this.sc = sc; + } - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.sendError(sc); - } - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.sendError(sc); + } + } - /** Simple POX Servlet. */ - @SuppressWarnings("serial") - private static class PoxServlet extends HttpServlet { + /** Simple POX Servlet. */ + @SuppressWarnings("serial") + private static class PoxServlet extends HttpServlet { - private DocumentBuilderFactory documentBuilderFactory; + private DocumentBuilderFactory documentBuilderFactory; - private TransformerFactory transformerFactory; + private TransformerFactory transformerFactory; - @Override - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - transformerFactory = TransformerFactory.newInstance(); - } + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + transformerFactory = TransformerFactory.newInstance(); + } - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - try { - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document message = documentBuilder.parse(req.getInputStream()); - Transformer transformer = transformerFactory.newTransformer(); - transformer.transform(new DOMSource(message), new StreamResult(resp.getOutputStream())); - } - catch (Exception ex) { - throw new ServletException("POX POST failed" + ex.getMessage()); - } - } - } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + try { + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document message = documentBuilder.parse(req.getInputStream()); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(new DOMSource(message), new StreamResult(resp.getOutputStream())); + } + catch (Exception ex) { + throw new ServletException("POX POST failed" + ex.getMessage()); + } + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleFaultMessageResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleFaultMessageResolverTest.java index 95d6e6ae..a40a4cc3 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleFaultMessageResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleFaultMessageResolverTest.java @@ -27,29 +27,29 @@ import static org.easymock.EasyMock.*; public class SimpleFaultMessageResolverTest { - private SimpleFaultMessageResolver resolver; + private SimpleFaultMessageResolver resolver; - @Before - public void setUp() throws Exception { - resolver = new SimpleFaultMessageResolver(); - } + @Before + public void setUp() throws Exception { + resolver = new SimpleFaultMessageResolver(); + } - @Test - public void testResolveFault() throws Exception { - FaultAwareWebServiceMessage messageMock = createMock(FaultAwareWebServiceMessage.class); - String message = "message"; - expect(messageMock.getFaultReason()).andReturn(message); + @Test + public void testResolveFault() throws Exception { + FaultAwareWebServiceMessage messageMock = createMock(FaultAwareWebServiceMessage.class); + String message = "message"; + expect(messageMock.getFaultReason()).andReturn(message); - replay(messageMock); + replay(messageMock); - try { - resolver.resolveFault(messageMock); - Assert.fail("WebServiceFaultExcpetion expected"); - } - catch (WebServiceFaultException ex) { - // expected - Assert.assertEquals("Invalid exception message", message, ex.getMessage()); - } - verify(messageMock); - } + try { + resolver.resolveFault(messageMock); + Assert.fail("WebServiceFaultExcpetion expected"); + } + catch (WebServiceFaultException ex) { + // expected + Assert.assertEquals("Invalid exception message", message, ex.getMessage()); + } + verify(messageMock); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleSaajServlet.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleSaajServlet.java index d334b344..f350dbaa 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleSaajServlet.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/SimpleSaajServlet.java @@ -42,70 +42,70 @@ import org.springframework.util.StringUtils; @SuppressWarnings("serial") public class SimpleSaajServlet extends HttpServlet { - private MessageFactory msgFactory = null; + private MessageFactory msgFactory = null; - @Override - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - try { - msgFactory = MessageFactory.newInstance(); - } - catch (SOAPException ex) { - throw new ServletException("Unable to create message factory" + ex.getMessage()); - } - } + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + try { + msgFactory = MessageFactory.newInstance(); + } + catch (SOAPException ex) { + throw new ServletException("Unable to create message factory" + ex.getMessage()); + } + } - private MimeHeaders getHeaders(HttpServletRequest httpServletRequest) { - Enumeration enumeration = httpServletRequest.getHeaderNames(); - MimeHeaders headers = new MimeHeaders(); - while (enumeration.hasMoreElements()) { - String headerName = (String) enumeration.nextElement(); - String headerValue = httpServletRequest.getHeader(headerName); - StringTokenizer values = new StringTokenizer(headerValue, ","); - while (values.hasMoreTokens()) { - headers.addHeader(headerName, values.nextToken().trim()); - } - } - return headers; - } + private MimeHeaders getHeaders(HttpServletRequest httpServletRequest) { + Enumeration enumeration = httpServletRequest.getHeaderNames(); + MimeHeaders headers = new MimeHeaders(); + while (enumeration.hasMoreElements()) { + String headerName = (String) enumeration.nextElement(); + String headerValue = httpServletRequest.getHeader(headerName); + StringTokenizer values = new StringTokenizer(headerValue, ","); + while (values.hasMoreTokens()) { + headers.addHeader(headerName, values.nextToken().trim()); + } + } + return headers; + } - private void putHeaders(MimeHeaders headers, HttpServletResponse res) { - Iterator it = headers.getAllHeaders(); - while (it.hasNext()) { - MimeHeader header = (MimeHeader) it.next(); - String[] values = headers.getHeader(header.getName()); - String value = StringUtils.arrayToCommaDelimitedString(values); - res.setHeader(header.getName(), value); - } - } + private void putHeaders(MimeHeaders headers, HttpServletResponse res) { + Iterator it = headers.getAllHeaders(); + while (it.hasNext()) { + MimeHeader header = (MimeHeader) it.next(); + String[] values = headers.getHeader(header.getName()); + String value = StringUtils.arrayToCommaDelimitedString(values); + res.setHeader(header.getName(), value); + } + } - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - try { - MimeHeaders headers = getHeaders(req); - SOAPMessage request = msgFactory.createMessage(headers, req.getInputStream()); - SOAPMessage reply = onMessage(request); - if (reply != null) { - if (reply.saveRequired()) { - reply.saveChanges(); - } - resp.setStatus(!reply.getSOAPBody().hasFault() ? HttpServletResponse.SC_OK : - HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - putHeaders(reply.getMimeHeaders(), resp); - reply.writeTo(resp.getOutputStream()); - } - else { - resp.setStatus(HttpServletResponse.SC_ACCEPTED); - } - } - catch (Exception ex) { - throw new ServletException("SAAJ POST failed " + ex.getMessage()); - } - } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + try { + MimeHeaders headers = getHeaders(req); + SOAPMessage request = msgFactory.createMessage(headers, req.getInputStream()); + SOAPMessage reply = onMessage(request); + if (reply != null) { + if (reply.saveRequired()) { + reply.saveChanges(); + } + resp.setStatus(!reply.getSOAPBody().hasFault() ? HttpServletResponse.SC_OK : + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + putHeaders(reply.getMimeHeaders(), resp); + reply.writeTo(resp.getOutputStream()); + } + else { + resp.setStatus(HttpServletResponse.SC_ACCEPTED); + } + } + catch (Exception ex) { + throw new ServletException("SAAJ POST failed " + ex.getMessage()); + } + } - protected SOAPMessage onMessage(SOAPMessage message) { - return message; - } + protected SOAPMessage onMessage(SOAPMessage message) { + return message; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/core/WebServiceTemplateTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/core/WebServiceTemplateTest.java index 62143065..d8f5a50e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/core/WebServiceTemplateTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/core/WebServiceTemplateTest.java @@ -45,457 +45,457 @@ import org.springframework.xml.transform.StringSource; @SuppressWarnings("unchecked") public class WebServiceTemplateTest { - private WebServiceTemplate template; - - private FaultAwareWebServiceConnection connectionMock; - - private MockWebServiceMessageFactory messageFactory; - - @Before - public void setUp() throws Exception { - messageFactory = new MockWebServiceMessageFactory(); - template = new WebServiceTemplate(messageFactory); - connectionMock = createMock(FaultAwareWebServiceConnection.class); - final URI expectedUri = new URI("http://www.springframework.org/spring-ws"); - expect(connectionMock.getUri()).andReturn(expectedUri).anyTimes(); - template.setMessageSender(new WebServiceMessageSender() { - - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - return connectionMock; - } - - @Override - public boolean supports(URI uri) { - assertEquals("Invalid uri", expectedUri, uri); - return true; - } - }); - template.setDefaultUri(expectedUri.toString()); - } - - @Test - public void testMarshalAndSendNoMarshallerSet() throws Exception { - connectionMock.close(); - - replay(connectionMock); + private WebServiceTemplate template; + + private FaultAwareWebServiceConnection connectionMock; + + private MockWebServiceMessageFactory messageFactory; + + @Before + public void setUp() throws Exception { + messageFactory = new MockWebServiceMessageFactory(); + template = new WebServiceTemplate(messageFactory); + connectionMock = createMock(FaultAwareWebServiceConnection.class); + final URI expectedUri = new URI("http://www.springframework.org/spring-ws"); + expect(connectionMock.getUri()).andReturn(expectedUri).anyTimes(); + template.setMessageSender(new WebServiceMessageSender() { + + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + return connectionMock; + } + + @Override + public boolean supports(URI uri) { + assertEquals("Invalid uri", expectedUri, uri); + return true; + } + }); + template.setDefaultUri(expectedUri.toString()); + } + + @Test + public void testMarshalAndSendNoMarshallerSet() throws Exception { + connectionMock.close(); + + replay(connectionMock); - template.setMarshaller(null); - try { - template.marshalSendAndReceive(new Object()); - fail("IllegalStateException expected"); - } - catch (IllegalStateException ex) { - // expected behavior - } - - verify(connectionMock); - } + template.setMarshaller(null); + try { + template.marshalSendAndReceive(new Object()); + fail("IllegalStateException expected"); + } + catch (IllegalStateException ex) { + // expected behavior + } + + verify(connectionMock); + } - @Test - public void testMarshalAndSendNoUnmarshallerSet() throws Exception { - connectionMock.close(); - - replay(connectionMock); - - template.setUnmarshaller(null); - try { - template.marshalSendAndReceive(new Object()); - fail("IllegalStateException expected"); - } - catch (IllegalStateException ex) { - // expected behavior - } - - verify(connectionMock); - } - - @Test - public void testSendAndReceiveMessageResponse() throws Exception { - WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); - requestCallback.doWithMessage(isA(WebServiceMessage.class)); - - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - Object extracted = new Object(); - expect(extractorMock.extractData(isA(WebServiceMessage.class))).andReturn(extracted); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); - expect(connectionMock.hasFault()).andReturn(false); - connectionMock.close(); - - replay(connectionMock, requestCallback, extractorMock); - - Object result = template.sendAndReceive(requestCallback, extractorMock); - assertEquals("Invalid response", extracted, result); - - verify(connectionMock, requestCallback, extractorMock); - } - - @Test - public void testSendAndReceiveMessageNoResponse() throws Exception { - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(null); - connectionMock.close(); - - replay(connectionMock, extractorMock); - - Object result = template.sendAndReceive(null, extractorMock); - assertNull("Invalid response", result); - - verify(connectionMock, extractorMock); - } - - @Test - public void testSendAndReceiveMessageFault() throws Exception { - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - - FaultMessageResolver faultMessageResolverMock = createMock(FaultMessageResolver.class); - template.setFaultMessageResolver(faultMessageResolverMock); - faultMessageResolverMock.resolveFault(isA(WebServiceMessage.class)); - - MockWebServiceMessage response = new MockWebServiceMessage(""); - response.setFault(true); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.hasFault()).andReturn(true); - expect(connectionMock.receive(messageFactory)).andReturn(response); - connectionMock.close(); - - replay(connectionMock, extractorMock, faultMessageResolverMock); + @Test + public void testMarshalAndSendNoUnmarshallerSet() throws Exception { + connectionMock.close(); + + replay(connectionMock); + + template.setUnmarshaller(null); + try { + template.marshalSendAndReceive(new Object()); + fail("IllegalStateException expected"); + } + catch (IllegalStateException ex) { + // expected behavior + } + + verify(connectionMock); + } + + @Test + public void testSendAndReceiveMessageResponse() throws Exception { + WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); + requestCallback.doWithMessage(isA(WebServiceMessage.class)); + + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + Object extracted = new Object(); + expect(extractorMock.extractData(isA(WebServiceMessage.class))).andReturn(extracted); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); + expect(connectionMock.hasFault()).andReturn(false); + connectionMock.close(); + + replay(connectionMock, requestCallback, extractorMock); + + Object result = template.sendAndReceive(requestCallback, extractorMock); + assertEquals("Invalid response", extracted, result); + + verify(connectionMock, requestCallback, extractorMock); + } + + @Test + public void testSendAndReceiveMessageNoResponse() throws Exception { + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(null); + connectionMock.close(); + + replay(connectionMock, extractorMock); + + Object result = template.sendAndReceive(null, extractorMock); + assertNull("Invalid response", result); + + verify(connectionMock, extractorMock); + } + + @Test + public void testSendAndReceiveMessageFault() throws Exception { + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + + FaultMessageResolver faultMessageResolverMock = createMock(FaultMessageResolver.class); + template.setFaultMessageResolver(faultMessageResolverMock); + faultMessageResolverMock.resolveFault(isA(WebServiceMessage.class)); + + MockWebServiceMessage response = new MockWebServiceMessage(""); + response.setFault(true); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.hasFault()).andReturn(true); + expect(connectionMock.receive(messageFactory)).andReturn(response); + connectionMock.close(); + + replay(connectionMock, extractorMock, faultMessageResolverMock); - Object result = template.sendAndReceive(null, extractorMock); - assertNull("Invalid response", result); + Object result = template.sendAndReceive(null, extractorMock); + assertNull("Invalid response", result); - verify(connectionMock, extractorMock, faultMessageResolverMock); - } + verify(connectionMock, extractorMock, faultMessageResolverMock); + } - @Test - public void testSendAndReceiveConnectionError() throws Exception { - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - - template.setFaultMessageResolver(null); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(true); - expect(connectionMock.hasFault()).andReturn(false); - String errorMessage = "errorMessage"; - expect(connectionMock.getErrorMessage()).andReturn(errorMessage); - connectionMock.close(); + @Test + public void testSendAndReceiveConnectionError() throws Exception { + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + + template.setFaultMessageResolver(null); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(true); + expect(connectionMock.hasFault()).andReturn(false); + String errorMessage = "errorMessage"; + expect(connectionMock.getErrorMessage()).andReturn(errorMessage); + connectionMock.close(); - replay(connectionMock, extractorMock); + replay(connectionMock, extractorMock); - try { - template.sendAndReceive(null, extractorMock); - fail("Expected WebServiceTransportException"); - } - catch (WebServiceTransportException ex) { - //expected - assertEquals("Invalid exception message", errorMessage, ex.getMessage()); - } + try { + template.sendAndReceive(null, extractorMock); + fail("Expected WebServiceTransportException"); + } + catch (WebServiceTransportException ex) { + //expected + assertEquals("Invalid exception message", errorMessage, ex.getMessage()); + } - verify(connectionMock, extractorMock); - } + verify(connectionMock, extractorMock); + } - @Test - public void testSendAndReceiveSourceResponse() throws Exception { - SourceExtractor extractorMock = createMock(SourceExtractor.class); - Object extracted = new Object(); - expect(extractorMock.extractData(isA(Source.class))).andReturn(extracted); + @Test + public void testSendAndReceiveSourceResponse() throws Exception { + SourceExtractor extractorMock = createMock(SourceExtractor.class); + Object extracted = new Object(); + expect(extractorMock.extractData(isA(Source.class))).andReturn(extracted); - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); - expect(connectionMock.hasFault()).andReturn(false); - connectionMock.close(); + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); + expect(connectionMock.hasFault()).andReturn(false); + connectionMock.close(); - replay(connectionMock, extractorMock); + replay(connectionMock, extractorMock); - Object result = template.sendSourceAndReceive(new StringSource(""), extractorMock); - assertEquals("Invalid response", extracted, result); + Object result = template.sendSourceAndReceive(new StringSource(""), extractorMock); + assertEquals("Invalid response", extracted, result); - verify(connectionMock, extractorMock); - } + verify(connectionMock, extractorMock); + } - @Test - public void testSendAndReceiveSourceNoResponse() throws Exception { - SourceExtractor extractorMock = createMock(SourceExtractor.class); + @Test + public void testSendAndReceiveSourceNoResponse() throws Exception { + SourceExtractor extractorMock = createMock(SourceExtractor.class); - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(null); - connectionMock.close(); + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(null); + connectionMock.close(); - replay(connectionMock, extractorMock); + replay(connectionMock, extractorMock); - Object result = template.sendSourceAndReceive(new StringSource(""), extractorMock); - assertNull("Invalid response", result); + Object result = template.sendSourceAndReceive(new StringSource(""), extractorMock); + assertNull("Invalid response", result); - verify(connectionMock, extractorMock); - } + verify(connectionMock, extractorMock); + } - @Test - public void testSendAndReceiveResultResponse() throws Exception { - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); - expect(connectionMock.hasFault()).andReturn(false); - connectionMock.close(); + @Test + public void testSendAndReceiveResultResponse() throws Exception { + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); + expect(connectionMock.hasFault()).andReturn(false); + connectionMock.close(); - replay(connectionMock); + replay(connectionMock); - StringResult result = new StringResult(); - boolean b = template.sendSourceAndReceiveToResult(new StringSource(""), result); - assertTrue("Invalid result", b); - - verify(connectionMock); - } - - @Test - public void testSendAndReceiveResultNoResponse() throws Exception { - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(null); - connectionMock.close(); - - replay(connectionMock); - - StringResult result = new StringResult(); - boolean b = template.sendSourceAndReceiveToResult(new StringSource(""), result); - assertFalse("Invalid result", b); - - verify(connectionMock); - } - - @Test - public void testSendAndReceiveResultNoResponsePayload() throws Exception { - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - WebServiceMessage response = createMock(WebServiceMessage.class); - expect(connectionMock.receive(messageFactory)).andReturn(response); - expect(connectionMock.hasFault()).andReturn(false); - expect(response.getPayloadSource()).andReturn(null); - connectionMock.close(); - - replay(connectionMock, response); - - StringResult result = new StringResult(); - boolean b = template.sendSourceAndReceiveToResult(new StringSource(""), result); - assertTrue("Invalid result", b); - - verify(connectionMock, response); - } - - - @Test - public void testSendAndReceiveMarshalResponse() throws Exception { - Marshaller marshallerMock = createMock(Marshaller.class); - template.setMarshaller(marshallerMock); - marshallerMock.marshal(isA(Object.class), isA(Result.class)); - - Unmarshaller unmarshallerMock = createMock(Unmarshaller.class); - template.setUnmarshaller(unmarshallerMock); - Object unmarshalled = new Object(); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); - expect(connectionMock.hasFault()).andReturn(false); - connectionMock.close(); - - replay(connectionMock, marshallerMock, unmarshallerMock); - - Object result = template.marshalSendAndReceive(new Object()); - assertEquals("Invalid result", unmarshalled, result); - - verify(connectionMock, marshallerMock, unmarshallerMock); - } - - @Test - public void testSendAndReceiveMarshalNoResponse() throws Exception { - Marshaller marshallerMock = createMock(Marshaller.class); - template.setMarshaller(marshallerMock); - marshallerMock.marshal(isA(Object.class), isA(Result.class)); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(null); - connectionMock.close(); - - replay(connectionMock, marshallerMock); + StringResult result = new StringResult(); + boolean b = template.sendSourceAndReceiveToResult(new StringSource(""), result); + assertTrue("Invalid result", b); + + verify(connectionMock); + } + + @Test + public void testSendAndReceiveResultNoResponse() throws Exception { + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(null); + connectionMock.close(); + + replay(connectionMock); + + StringResult result = new StringResult(); + boolean b = template.sendSourceAndReceiveToResult(new StringSource(""), result); + assertFalse("Invalid result", b); + + verify(connectionMock); + } + + @Test + public void testSendAndReceiveResultNoResponsePayload() throws Exception { + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + WebServiceMessage response = createMock(WebServiceMessage.class); + expect(connectionMock.receive(messageFactory)).andReturn(response); + expect(connectionMock.hasFault()).andReturn(false); + expect(response.getPayloadSource()).andReturn(null); + connectionMock.close(); + + replay(connectionMock, response); + + StringResult result = new StringResult(); + boolean b = template.sendSourceAndReceiveToResult(new StringSource(""), result); + assertTrue("Invalid result", b); + + verify(connectionMock, response); + } + + + @Test + public void testSendAndReceiveMarshalResponse() throws Exception { + Marshaller marshallerMock = createMock(Marshaller.class); + template.setMarshaller(marshallerMock); + marshallerMock.marshal(isA(Object.class), isA(Result.class)); + + Unmarshaller unmarshallerMock = createMock(Unmarshaller.class); + template.setUnmarshaller(unmarshallerMock); + Object unmarshalled = new Object(); + expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); + expect(connectionMock.hasFault()).andReturn(false); + connectionMock.close(); + + replay(connectionMock, marshallerMock, unmarshallerMock); + + Object result = template.marshalSendAndReceive(new Object()); + assertEquals("Invalid result", unmarshalled, result); + + verify(connectionMock, marshallerMock, unmarshallerMock); + } + + @Test + public void testSendAndReceiveMarshalNoResponse() throws Exception { + Marshaller marshallerMock = createMock(Marshaller.class); + template.setMarshaller(marshallerMock); + marshallerMock.marshal(isA(Object.class), isA(Result.class)); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(null); + connectionMock.close(); + + replay(connectionMock, marshallerMock); - Object result = template.marshalSendAndReceive(new Object()); - assertNull("Invalid result", result); - - verify(connectionMock, marshallerMock); - } - - @Test - public void testSendAndReceiveCustomUri() throws Exception { - final URI customUri = new URI("http://www.springframework.org/spring-ws/custom"); - template.setMessageSender(new WebServiceMessageSender() { - - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - return connectionMock; - } - - @Override - public boolean supports(URI uri) { - assertEquals("Invalid uri", customUri, uri); - return true; - } - }); - WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); - requestCallback.doWithMessage(isA(WebServiceMessage.class)); - - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - Object extracted = new Object(); - expect(extractorMock.extractData(isA(WebServiceMessage.class))).andReturn(extracted); + Object result = template.marshalSendAndReceive(new Object()); + assertNull("Invalid result", result); + + verify(connectionMock, marshallerMock); + } + + @Test + public void testSendAndReceiveCustomUri() throws Exception { + final URI customUri = new URI("http://www.springframework.org/spring-ws/custom"); + template.setMessageSender(new WebServiceMessageSender() { + + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + return connectionMock; + } + + @Override + public boolean supports(URI uri) { + assertEquals("Invalid uri", customUri, uri); + return true; + } + }); + WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); + requestCallback.doWithMessage(isA(WebServiceMessage.class)); + + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + Object extracted = new Object(); + expect(extractorMock.extractData(isA(WebServiceMessage.class))).andReturn(extracted); - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); - expect(connectionMock.hasFault()).andReturn(false); - connectionMock.close(); - - replay(connectionMock, requestCallback, extractorMock); - - Object result = template.sendAndReceive(customUri.toString(), requestCallback, extractorMock); - assertEquals("Invalid response", extracted, result); - - verify(connectionMock, requestCallback, extractorMock); - } - - @Test - public void testInterceptors() throws Exception { - ClientInterceptor interceptorMock1 = createStrictMock("interceptor1", ClientInterceptor.class); - ClientInterceptor interceptorMock2 = createStrictMock("interceptor2", ClientInterceptor.class); - template.setInterceptors(new ClientInterceptor[]{interceptorMock1, interceptorMock2}); - expect(interceptorMock1.handleRequest(isA(MessageContext.class))).andReturn(true); - expect(interceptorMock2.handleRequest(isA(MessageContext.class))).andReturn(true); - expect(interceptorMock2.handleResponse(isA(MessageContext.class))).andReturn(true); - expect(interceptorMock1.handleResponse(isA(MessageContext.class))).andReturn(true); - interceptorMock2.afterCompletion(isA(MessageContext.class), (Exception)isNull()); - interceptorMock1.afterCompletion(isA(MessageContext.class), (Exception)isNull()); - - WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); - requestCallback.doWithMessage(isA(WebServiceMessage.class)); - - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - Object extracted = new Object(); - expect(extractorMock.extractData(isA(WebServiceMessage.class))).andReturn(extracted); - - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); - expect(connectionMock.hasFault()).andReturn(false); - connectionMock.close(); + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); + expect(connectionMock.hasFault()).andReturn(false); + connectionMock.close(); + + replay(connectionMock, requestCallback, extractorMock); + + Object result = template.sendAndReceive(customUri.toString(), requestCallback, extractorMock); + assertEquals("Invalid response", extracted, result); + + verify(connectionMock, requestCallback, extractorMock); + } + + @Test + public void testInterceptors() throws Exception { + ClientInterceptor interceptorMock1 = createStrictMock("interceptor1", ClientInterceptor.class); + ClientInterceptor interceptorMock2 = createStrictMock("interceptor2", ClientInterceptor.class); + template.setInterceptors(new ClientInterceptor[]{interceptorMock1, interceptorMock2}); + expect(interceptorMock1.handleRequest(isA(MessageContext.class))).andReturn(true); + expect(interceptorMock2.handleRequest(isA(MessageContext.class))).andReturn(true); + expect(interceptorMock2.handleResponse(isA(MessageContext.class))).andReturn(true); + expect(interceptorMock1.handleResponse(isA(MessageContext.class))).andReturn(true); + interceptorMock2.afterCompletion(isA(MessageContext.class), (Exception)isNull()); + interceptorMock1.afterCompletion(isA(MessageContext.class), (Exception)isNull()); + + WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); + requestCallback.doWithMessage(isA(WebServiceMessage.class)); + + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + Object extracted = new Object(); + expect(extractorMock.extractData(isA(WebServiceMessage.class))).andReturn(extracted); + + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(new MockWebServiceMessage("")); + expect(connectionMock.hasFault()).andReturn(false); + connectionMock.close(); - replay(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); - - Object result = template.sendAndReceive(requestCallback, extractorMock); - assertEquals("Invalid response", extracted, result); + replay(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); + + Object result = template.sendAndReceive(requestCallback, extractorMock); + assertEquals("Invalid response", extracted, result); - verify(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); - } + verify(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); + } - @Test - public void testInterceptorsInterceptedNoResponse() throws Exception { - MessageContext messageContext = new DefaultMessageContext(messageFactory); + @Test + public void testInterceptorsInterceptedNoResponse() throws Exception { + MessageContext messageContext = new DefaultMessageContext(messageFactory); - ClientInterceptor interceptorMock1 = createStrictMock("interceptor1", ClientInterceptor.class); - ClientInterceptor interceptorMock2 = createStrictMock("interceptor2", ClientInterceptor.class); - template.setInterceptors(new ClientInterceptor[]{interceptorMock1, interceptorMock2}); - expect(interceptorMock1.handleRequest(isA(MessageContext.class))).andReturn(false); - interceptorMock1.afterCompletion(isA(MessageContext.class), (Exception)isNull()); - - WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); - requestCallback.doWithMessage(messageContext.getRequest()); - - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - - replay(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); + ClientInterceptor interceptorMock1 = createStrictMock("interceptor1", ClientInterceptor.class); + ClientInterceptor interceptorMock2 = createStrictMock("interceptor2", ClientInterceptor.class); + template.setInterceptors(new ClientInterceptor[]{interceptorMock1, interceptorMock2}); + expect(interceptorMock1.handleRequest(isA(MessageContext.class))).andReturn(false); + interceptorMock1.afterCompletion(isA(MessageContext.class), (Exception)isNull()); + + WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); + requestCallback.doWithMessage(messageContext.getRequest()); + + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + + replay(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); - Object result = template.doSendAndReceive(messageContext, connectionMock, requestCallback, extractorMock); - assertNull(result); + Object result = template.doSendAndReceive(messageContext, connectionMock, requestCallback, extractorMock); + assertNull(result); - verify(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); - } - - @Test - public void testInterceptorsInterceptedCreateResponse() throws Exception { - MessageContext messageContext = new DefaultMessageContext(messageFactory); - // force creation of response - messageContext.getResponse(); - - ClientInterceptor interceptorMock1 = createStrictMock("interceptor1", ClientInterceptor.class); - ClientInterceptor interceptorMock2 = createStrictMock("interceptor2", ClientInterceptor.class); - template.setInterceptors(new ClientInterceptor[]{interceptorMock1, interceptorMock2}); - expect(interceptorMock1.handleRequest(isA(MessageContext.class))).andReturn(false); - expect(interceptorMock1.handleResponse(isA(MessageContext.class))).andReturn(true); - interceptorMock1.afterCompletion(isA(MessageContext.class), (Exception)isNull()); - - WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); - requestCallback.doWithMessage(messageContext.getRequest()); - - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - Object extracted = new Object(); - expect(extractorMock.extractData(messageContext.getResponse())).andReturn(extracted); - - expect(connectionMock.hasFault()).andReturn(false); + verify(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); + } + + @Test + public void testInterceptorsInterceptedCreateResponse() throws Exception { + MessageContext messageContext = new DefaultMessageContext(messageFactory); + // force creation of response + messageContext.getResponse(); + + ClientInterceptor interceptorMock1 = createStrictMock("interceptor1", ClientInterceptor.class); + ClientInterceptor interceptorMock2 = createStrictMock("interceptor2", ClientInterceptor.class); + template.setInterceptors(new ClientInterceptor[]{interceptorMock1, interceptorMock2}); + expect(interceptorMock1.handleRequest(isA(MessageContext.class))).andReturn(false); + expect(interceptorMock1.handleResponse(isA(MessageContext.class))).andReturn(true); + interceptorMock1.afterCompletion(isA(MessageContext.class), (Exception)isNull()); + + WebServiceMessageCallback requestCallback = createMock(WebServiceMessageCallback.class); + requestCallback.doWithMessage(messageContext.getRequest()); + + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + Object extracted = new Object(); + expect(extractorMock.extractData(messageContext.getResponse())).andReturn(extracted); + + expect(connectionMock.hasFault()).andReturn(false); - replay(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); + replay(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); - Object result = template.doSendAndReceive(messageContext, connectionMock, requestCallback, extractorMock); - assertEquals("Invalid response", extracted, result); + Object result = template.doSendAndReceive(messageContext, connectionMock, requestCallback, extractorMock); + assertEquals("Invalid response", extracted, result); - verify(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); - } + verify(connectionMock, interceptorMock1, interceptorMock2, requestCallback, extractorMock); + } - @Test - public void testDestinationResolver() throws Exception { - DestinationProvider providerMock = createMock(DestinationProvider.class); - template.setDestinationProvider(providerMock); - final URI providerUri = new URI("http://www.springframework.org/spring-ws/destinationProvider"); - expect(providerMock.getDestination()).andReturn(providerUri); + @Test + public void testDestinationResolver() throws Exception { + DestinationProvider providerMock = createMock(DestinationProvider.class); + template.setDestinationProvider(providerMock); + final URI providerUri = new URI("http://www.springframework.org/spring-ws/destinationProvider"); + expect(providerMock.getDestination()).andReturn(providerUri); - template.setMessageSender(new WebServiceMessageSender() { + template.setMessageSender(new WebServiceMessageSender() { - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - return connectionMock; - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + return connectionMock; + } - @Override - public boolean supports(URI uri) { - assertEquals("Invalid uri", providerUri, uri); - return true; - } - }); + @Override + public boolean supports(URI uri) { + assertEquals("Invalid uri", providerUri, uri); + return true; + } + }); - WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); + WebServiceMessageExtractor extractorMock = createMock(WebServiceMessageExtractor.class); - reset(connectionMock); - expect(connectionMock.getUri()).andReturn(providerUri); - connectionMock.send(isA(WebServiceMessage.class)); - expect(connectionMock.hasError()).andReturn(false); - expect(connectionMock.receive(messageFactory)).andReturn(null); - connectionMock.close(); + reset(connectionMock); + expect(connectionMock.getUri()).andReturn(providerUri); + connectionMock.send(isA(WebServiceMessage.class)); + expect(connectionMock.hasError()).andReturn(false); + expect(connectionMock.receive(messageFactory)).andReturn(null); + connectionMock.close(); - replay(connectionMock, extractorMock, providerMock); + replay(connectionMock, extractorMock, providerMock); - Object result = template.sendAndReceive(null, extractorMock); - assertNull("Invalid response", result); + Object result = template.sendAndReceive(null, extractorMock); + assertNull("Invalid response", result); - verify(connectionMock, extractorMock, providerMock); - } + verify(connectionMock, extractorMock, providerMock); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProviderTest.java index 00d9e649..e8b2e1cb 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/support/destination/Wsdl11DestinationProviderTest.java @@ -28,41 +28,41 @@ import org.junit.Test; public class Wsdl11DestinationProviderTest { - private Wsdl11DestinationProvider provider; + private Wsdl11DestinationProvider provider; - @Before - public void setUp() throws Exception { - provider = new Wsdl11DestinationProvider(); - } + @Before + public void setUp() throws Exception { + provider = new Wsdl11DestinationProvider(); + } - @Test - public void testSimple() throws URISyntaxException { - Resource wsdl = new ClassPathResource("simple.wsdl", getClass()); - provider.setWsdl(wsdl); + @Test + public void testSimple() throws URISyntaxException { + Resource wsdl = new ClassPathResource("simple.wsdl", getClass()); + provider.setWsdl(wsdl); - URI result = provider.getDestination(); + URI result = provider.getDestination(); - Assert.assertEquals("Invalid URI returned", new URI("http://example.com/myService"), result); - } + Assert.assertEquals("Invalid URI returned", new URI("http://example.com/myService"), result); + } - @Test - public void testComplex() throws URISyntaxException { - Resource wsdl = new ClassPathResource("complex.wsdl", getClass()); - provider.setWsdl(wsdl); + @Test + public void testComplex() throws URISyntaxException { + Resource wsdl = new ClassPathResource("complex.wsdl", getClass()); + provider.setWsdl(wsdl); - URI result = provider.getDestination(); + URI result = provider.getDestination(); - Assert.assertEquals("Invalid URI returned", new URI("http://example.com/soap11"), result); - } + Assert.assertEquals("Invalid URI returned", new URI("http://example.com/soap11"), result); + } - @Test - public void testCustomExpression() throws URISyntaxException { - provider.setLocationExpression("/wsdl:definitions/wsdl:service/wsdl:port/soap12:address/@location"); - Resource wsdl = new ClassPathResource("complex.wsdl", getClass()); - provider.setWsdl(wsdl); + @Test + public void testCustomExpression() throws URISyntaxException { + provider.setLocationExpression("/wsdl:definitions/wsdl:service/wsdl:port/soap12:address/@location"); + Resource wsdl = new ClassPathResource("complex.wsdl", getClass()); + provider.setWsdl(wsdl); - URI result = provider.getDestination(); + URI result = provider.getDestination(); - Assert.assertEquals("Invalid URI returned", new URI("http://example.com/soap12"), result); - } + Assert.assertEquals("Invalid URI returned", new URI("http://example.com/soap12"), result); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptorTest.java index c3fb8055..42ec4c80 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/client/support/interceptor/PayloadValidatingInterceptorTest.java @@ -44,220 +44,220 @@ import org.springframework.xml.xsd.SimpleXsdSchema; public class PayloadValidatingInterceptorTest { - private PayloadValidatingInterceptor interceptor; + private PayloadValidatingInterceptor interceptor; - private MessageContext context; + private MessageContext context; - private SaajSoapMessageFactory soap11Factory; + private SaajSoapMessageFactory soap11Factory; - private Transformer transformer; + private Transformer transformer; - private static final String INVALID_MESSAGE = "invalidMessage.xml"; + private static final String INVALID_MESSAGE = "invalidMessage.xml"; - private static final String SCHEMA = "schema.xsd"; + private static final String SCHEMA = "schema.xsd"; - private static final String VALID_MESSAGE = "validMessage.xml"; + private static final String VALID_MESSAGE = "validMessage.xml"; - private static final String PRODUCT_SCHEMA = "productSchema.xsd"; + private static final String PRODUCT_SCHEMA = "productSchema.xsd"; - private static final String SIZE_SCHEMA = "sizeSchema.xsd"; + private static final String SIZE_SCHEMA = "sizeSchema.xsd"; - private static final String VALID_SOAP_MESSAGE = "validSoapMessage.xml"; + private static final String VALID_SOAP_MESSAGE = "validSoapMessage.xml"; - private static final String SCHEMA2 = "schema2.xsd"; + private static final String SCHEMA2 = "schema2.xsd"; - @Before - public void setUp() throws Exception { - interceptor = new PayloadValidatingInterceptor(); - interceptor.setSchema(new ClassPathResource(SCHEMA, getClass())); - interceptor.setValidateRequest(true); - interceptor.setValidateResponse(true); - interceptor.afterPropertiesSet(); + @Before + public void setUp() throws Exception { + interceptor = new PayloadValidatingInterceptor(); + interceptor.setSchema(new ClassPathResource(SCHEMA, getClass())); + interceptor.setValidateRequest(true); + interceptor.setValidateResponse(true); + interceptor.afterPropertiesSet(); - soap11Factory = new SaajSoapMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL)); + soap11Factory = new SaajSoapMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL)); - transformer = TransformerFactory.newInstance().newTransformer(); - } + transformer = TransformerFactory.newInstance().newTransformer(); + } - @Test - public void testHandleInvalidRequest() throws Exception { - SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); - InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); - transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); - context = new DefaultMessageContext(invalidMessage, soap11Factory); + @Test + public void testHandleInvalidRequest() throws Exception { + SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); + InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); + transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); + context = new DefaultMessageContext(invalidMessage, soap11Factory); - boolean validated; - try { - validated = interceptor.handleRequest(context); - } - catch (WebServiceClientException e) { - validated = false; - Assert.assertNotNull("No exception details provided in WebServiceClientException", e.getMessage()); - } - Assert.assertFalse("Invalid response from interceptor", validated); - } + boolean validated; + try { + validated = interceptor.handleRequest(context); + } + catch (WebServiceClientException e) { + validated = false; + Assert.assertNotNull("No exception details provided in WebServiceClientException", e.getMessage()); + } + Assert.assertFalse("Invalid response from interceptor", validated); + } - @Test - public void testHandlerInvalidRequest() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - request.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testHandlerInvalidRequest() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + request.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean validated; - try { - validated = interceptor.handleRequest(context); - } - catch (WebServiceClientException e) { - validated = false; - Assert.assertNotNull("No exception details provided in WebServiceClientException", e.getMessage()); - } - Assert.assertFalse("Invalid response from interceptor", validated); - } + boolean validated; + try { + validated = interceptor.handleRequest(context); + } + catch (WebServiceClientException e) { + validated = false; + Assert.assertNotNull("No exception details provided in WebServiceClientException", e.getMessage()); + } + Assert.assertFalse("Invalid response from interceptor", validated); + } - @Test - public void testHandleValidRequest() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } + @Test + public void testHandleValidRequest() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + boolean result = interceptor.handleRequest(context); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } - @Test - public void testHandleInvalidResponse() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); + @Test + public void testHandleInvalidResponse() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context); - Assert.assertFalse("Invalid response from interceptor", result); - } + boolean result = interceptor.handleResponse(context); + Assert.assertFalse("Invalid response from interceptor", result); + } - @Test - public void testHandleValidResponse() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context); - Assert.assertTrue("Invalid response from interceptor", result); - } + @Test + public void testHandleValidResponse() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context); + Assert.assertTrue("Invalid response from interceptor", result); + } - @Test - public void testNamespacesInType() throws Exception { - // Make sure we use Xerces for this testcase: the JAXP implementation used internally by JDK 1.5 has a bug - // See http://opensource.atlassian.com/projects/spring/browse/SWS-35 - String previousSchemaFactory = - System.getProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, ""); - System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, - "org.apache.xerces.jaxp.validation.XMLSchemaFactory"); - try { - PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); - interceptor.setSchema(new ClassPathResource(SCHEMA2, PayloadValidatingInterceptorTest.class)); - interceptor.afterPropertiesSet(); - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage saajMessage = - SaajUtils.loadMessage(new ClassPathResource(VALID_SOAP_MESSAGE, getClass()), messageFactory); - context = new DefaultMessageContext(new SaajSoapMessage(saajMessage), - new SaajSoapMessageFactory(messageFactory)); + @Test + public void testNamespacesInType() throws Exception { + // Make sure we use Xerces for this testcase: the JAXP implementation used internally by JDK 1.5 has a bug + // See http://opensource.atlassian.com/projects/spring/browse/SWS-35 + String previousSchemaFactory = + System.getProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, ""); + System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, + "org.apache.xerces.jaxp.validation.XMLSchemaFactory"); + try { + PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); + interceptor.setSchema(new ClassPathResource(SCHEMA2, PayloadValidatingInterceptorTest.class)); + interceptor.afterPropertiesSet(); + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage saajMessage = + SaajUtils.loadMessage(new ClassPathResource(VALID_SOAP_MESSAGE, getClass()), messageFactory); + context = new DefaultMessageContext(new SaajSoapMessage(saajMessage), + new SaajSoapMessageFactory(messageFactory)); - boolean result = interceptor.handleRequest(context); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } - finally { - // Reset the property - System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, - previousSchemaFactory); - } - } + boolean result = interceptor.handleRequest(context); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } + finally { + // Reset the property + System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, + previousSchemaFactory); + } + } - @Test - public void testNonExistingSchema() throws Exception { - try { - interceptor.setSchema(new ClassPathResource("invalid")); - interceptor.afterPropertiesSet(); - Assert.fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + @Test + public void testNonExistingSchema() throws Exception { + try { + interceptor.setSchema(new ClassPathResource("invalid")); + interceptor.afterPropertiesSet(); + Assert.fail("IllegalArgumentException expected"); + } + catch (IllegalArgumentException ex) { + // expected + } + } - @Test - public void testHandlerInvalidRequestMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(INVALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testHandlerInvalidRequestMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(INVALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean validated; - try { - validated = interceptor.handleRequest(context); - } - catch (WebServiceClientException e) { - validated = false; - Assert.assertNotNull("No exception details provided in WebServiceClientException", e.getMessage()); - } - Assert.assertFalse("Invalid response from interceptor", validated); - } + boolean validated; + try { + validated = interceptor.handleRequest(context); + } + catch (WebServiceClientException e) { + validated = false; + Assert.assertNotNull("No exception details provided in WebServiceClientException", e.getMessage()); + } + Assert.assertFalse("Invalid response from interceptor", validated); + } - @Test - public void testHandleValidRequestMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(VALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testHandleValidRequestMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(VALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } + boolean result = interceptor.handleRequest(context); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } - @Test - public void testHandleInvalidResponseMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context); - Assert.assertFalse("Invalid response from interceptor", result); - } + @Test + public void testHandleInvalidResponseMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context); + Assert.assertFalse("Invalid response from interceptor", result); + } - @Test - public void testHandleValidResponseMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context); - Assert.assertTrue("Invalid response from interceptor", result); - } + @Test + public void testHandleValidResponseMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context); + Assert.assertTrue("Invalid response from interceptor", result); + } - @Test - public void testXsdSchema() throws Exception { - PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); - SimpleXsdSchema schema = new SimpleXsdSchema(new ClassPathResource(SCHEMA, getClass())); - schema.afterPropertiesSet(); - interceptor.setXsdSchema(schema); - interceptor.setValidateRequest(true); - interceptor.setValidateResponse(true); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(); - request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } + @Test + public void testXsdSchema() throws Exception { + PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); + SimpleXsdSchema schema = new SimpleXsdSchema(new ClassPathResource(SCHEMA, getClass())); + schema.afterPropertiesSet(); + interceptor.setXsdSchema(schema); + interceptor.setValidateRequest(true); + interceptor.setValidateResponse(true); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(); + request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + boolean result = interceptor.handleRequest(context); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParserTest.java b/spring-ws-core/src/test/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParserTest.java index b6af0514..49105582 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParserTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/AnnotationDrivenBeanDefinitionParserTest.java @@ -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, @@ -57,74 +57,74 @@ import static org.junit.Assert.assertTrue; */ public class AnnotationDrivenBeanDefinitionParserTest { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - @Before - public void setUp() throws Exception { - applicationContext = - new ClassPathXmlApplicationContext("annotationDrivenBeanDefinitionParserTest.xml", getClass()); - } + @Before + public void setUp() throws Exception { + applicationContext = + new ClassPathXmlApplicationContext("annotationDrivenBeanDefinitionParserTest.xml", getClass()); + } - @Test - public void endpointMappings() { - Map result = applicationContext.getBeansOfType(EndpointMapping.class); - assertEquals("invalid amount of endpoint mappings found", 3, result.size()); - assertContainsInstanceOf(result.values(), PayloadRootAnnotationMethodEndpointMapping.class); - assertContainsInstanceOf(result.values(), SoapActionAnnotationMethodEndpointMapping.class); - assertContainsInstanceOf(result.values(), AnnotationActionEndpointMapping.class); - } + @Test + public void endpointMappings() { + Map result = applicationContext.getBeansOfType(EndpointMapping.class); + assertEquals("invalid amount of endpoint mappings found", 3, result.size()); + assertContainsInstanceOf(result.values(), PayloadRootAnnotationMethodEndpointMapping.class); + assertContainsInstanceOf(result.values(), SoapActionAnnotationMethodEndpointMapping.class); + assertContainsInstanceOf(result.values(), AnnotationActionEndpointMapping.class); + } - @Test - public void endpointAdapters() { - Map result = - applicationContext.getBeansOfType(EndpointAdapter.class); - assertEquals("invalid amount of endpoint mappings found", 1, result.size()); - DefaultMethodEndpointAdapter endpointAdapter = (DefaultMethodEndpointAdapter) result.values().iterator().next(); + @Test + public void endpointAdapters() { + Map result = + applicationContext.getBeansOfType(EndpointAdapter.class); + assertEquals("invalid amount of endpoint mappings found", 1, result.size()); + DefaultMethodEndpointAdapter endpointAdapter = (DefaultMethodEndpointAdapter) result.values().iterator().next(); - List argumentResolvers = endpointAdapter.getMethodArgumentResolvers(); - assertTrue("No argumentResolvers created", !argumentResolvers.isEmpty()); - assertContainsInstanceOf(argumentResolvers, MessageContextMethodArgumentResolver.class); - assertContainsInstanceOf(argumentResolvers, XPathParamMethodArgumentResolver.class); - assertContainsInstanceOf(argumentResolvers, SoapMethodArgumentResolver.class); - assertContainsInstanceOf(argumentResolvers, SoapHeaderElementMethodArgumentResolver.class); - assertContainsInstanceOf(argumentResolvers, DomPayloadMethodProcessor.class); - assertContainsInstanceOf(argumentResolvers, SourcePayloadMethodProcessor.class); - assertContainsInstanceOf(argumentResolvers, Dom4jPayloadMethodProcessor.class); - assertContainsInstanceOf(argumentResolvers, XmlRootElementPayloadMethodProcessor.class); - assertContainsInstanceOf(argumentResolvers, JaxbElementPayloadMethodProcessor.class); - assertContainsInstanceOf(argumentResolvers, JDomPayloadMethodProcessor.class); - assertContainsInstanceOf(argumentResolvers, StaxPayloadMethodArgumentResolver.class); - assertContainsInstanceOf(argumentResolvers, XomPayloadMethodProcessor.class); + List argumentResolvers = endpointAdapter.getMethodArgumentResolvers(); + assertTrue("No argumentResolvers created", !argumentResolvers.isEmpty()); + assertContainsInstanceOf(argumentResolvers, MessageContextMethodArgumentResolver.class); + assertContainsInstanceOf(argumentResolvers, XPathParamMethodArgumentResolver.class); + assertContainsInstanceOf(argumentResolvers, SoapMethodArgumentResolver.class); + assertContainsInstanceOf(argumentResolvers, SoapHeaderElementMethodArgumentResolver.class); + assertContainsInstanceOf(argumentResolvers, DomPayloadMethodProcessor.class); + assertContainsInstanceOf(argumentResolvers, SourcePayloadMethodProcessor.class); + assertContainsInstanceOf(argumentResolvers, Dom4jPayloadMethodProcessor.class); + assertContainsInstanceOf(argumentResolvers, XmlRootElementPayloadMethodProcessor.class); + assertContainsInstanceOf(argumentResolvers, JaxbElementPayloadMethodProcessor.class); + assertContainsInstanceOf(argumentResolvers, JDomPayloadMethodProcessor.class); + assertContainsInstanceOf(argumentResolvers, StaxPayloadMethodArgumentResolver.class); + assertContainsInstanceOf(argumentResolvers, XomPayloadMethodProcessor.class); - List returnValueHandlers = endpointAdapter.getMethodReturnValueHandlers(); - assertTrue("No returnValueHandlers created", !returnValueHandlers.isEmpty()); - assertContainsInstanceOf(returnValueHandlers, DomPayloadMethodProcessor.class); - assertContainsInstanceOf(returnValueHandlers, SourcePayloadMethodProcessor.class); - assertContainsInstanceOf(returnValueHandlers, Dom4jPayloadMethodProcessor.class); - assertContainsInstanceOf(returnValueHandlers, XmlRootElementPayloadMethodProcessor.class); - assertContainsInstanceOf(returnValueHandlers, JaxbElementPayloadMethodProcessor.class); - assertContainsInstanceOf(returnValueHandlers, JDomPayloadMethodProcessor.class); - assertContainsInstanceOf(returnValueHandlers, XomPayloadMethodProcessor.class); - } + List returnValueHandlers = endpointAdapter.getMethodReturnValueHandlers(); + assertTrue("No returnValueHandlers created", !returnValueHandlers.isEmpty()); + assertContainsInstanceOf(returnValueHandlers, DomPayloadMethodProcessor.class); + assertContainsInstanceOf(returnValueHandlers, SourcePayloadMethodProcessor.class); + assertContainsInstanceOf(returnValueHandlers, Dom4jPayloadMethodProcessor.class); + assertContainsInstanceOf(returnValueHandlers, XmlRootElementPayloadMethodProcessor.class); + assertContainsInstanceOf(returnValueHandlers, JaxbElementPayloadMethodProcessor.class); + assertContainsInstanceOf(returnValueHandlers, JDomPayloadMethodProcessor.class); + assertContainsInstanceOf(returnValueHandlers, XomPayloadMethodProcessor.class); + } - @Test - public void endpointExceptionResolver() { - Map result = applicationContext.getBeansOfType(EndpointExceptionResolver.class); - assertEquals("invalid amount of endpoint exception resolvers found", 2, result.size()); - assertContainsInstanceOf(result.values(), SoapFaultAnnotationExceptionResolver.class); - assertContainsInstanceOf(result.values(), SimpleSoapExceptionResolver.class); - } + @Test + public void endpointExceptionResolver() { + Map result = applicationContext.getBeansOfType(EndpointExceptionResolver.class); + assertEquals("invalid amount of endpoint exception resolvers found", 2, result.size()); + assertContainsInstanceOf(result.values(), SoapFaultAnnotationExceptionResolver.class); + assertContainsInstanceOf(result.values(), SimpleSoapExceptionResolver.class); + } - private void assertContainsInstanceOf(Collection collection, Class clazz) { - boolean found = false; - for (T item : collection) { - if (item.getClass().equals(clazz)) { - found = true; - break; - } - } - assertTrue("No [" + clazz.getName() + "] instance found in " + collection, found); - } + private void assertContainsInstanceOf(Collection collection, Class clazz) { + boolean found = false; + for (T item : collection) { + if (item.getClass().equals(clazz)) { + found = true; + break; + } + } + assertTrue("No [" + clazz.getName() + "] instance found in " + collection, found); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/DummyMarshaller.java b/spring-ws-core/src/test/java/org/springframework/ws/config/DummyMarshaller.java index babd5206..392510cf 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/DummyMarshaller.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/DummyMarshaller.java @@ -26,18 +26,18 @@ import org.springframework.oxm.XmlMappingException; public class DummyMarshaller implements Marshaller, Unmarshaller { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - throw new UnsupportedOperationException(); - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + throw new UnsupportedOperationException(); + } - @Override - public boolean supports(Class clazz) { - throw new UnsupportedOperationException(); - } + @Override + public boolean supports(Class clazz) { + throw new UnsupportedOperationException(); + } - @Override - public Object unmarshal(Source source) throws XmlMappingException, IOException { - throw new UnsupportedOperationException(); - } + @Override + public Object unmarshal(Source source) throws XmlMappingException, IOException { + throw new UnsupportedOperationException(); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/InterceptorsBeanDefinitionParserTest.java b/spring-ws-core/src/test/java/org/springframework/ws/config/InterceptorsBeanDefinitionParserTest.java index d054f049..ff5f3930 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/InterceptorsBeanDefinitionParserTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/InterceptorsBeanDefinitionParserTest.java @@ -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,49 +32,49 @@ import org.springframework.ws.soap.server.endpoint.interceptor.SoapActionSmartEn public class InterceptorsBeanDefinitionParserTest { - @Test - public void namespace() throws Exception { - ApplicationContext applicationContext = - new ClassPathXmlApplicationContext("interceptorsBeanDefinitionParserTest.xml", getClass()); - Map result = applicationContext.getBeansOfType(DelegatingSmartEndpointInterceptor.class); - assertEquals("no smart interceptors found", 8, result.size()); + @Test + public void namespace() throws Exception { + ApplicationContext applicationContext = + new ClassPathXmlApplicationContext("interceptorsBeanDefinitionParserTest.xml", getClass()); + Map result = applicationContext.getBeansOfType(DelegatingSmartEndpointInterceptor.class); + assertEquals("no smart interceptors found", 8, result.size()); - result = applicationContext.getBeansOfType(PayloadRootSmartSoapEndpointInterceptor.class); - assertEquals("no interceptors found", 3, result.size()); + result = applicationContext.getBeansOfType(PayloadRootSmartSoapEndpointInterceptor.class); + assertEquals("no interceptors found", 3, result.size()); - result = applicationContext.getBeansOfType(SoapActionSmartEndpointInterceptor.class); - assertEquals("no interceptors found", 3, result.size()); - } + result = applicationContext.getBeansOfType(SoapActionSmartEndpointInterceptor.class); + assertEquals("no interceptors found", 3, result.size()); + } - @Test - public void ordering() throws Exception { - ApplicationContext applicationContext = - new ClassPathXmlApplicationContext("interceptorsBeanDefinitionParserOrderTest.xml", getClass()); + @Test + public void ordering() throws Exception { + ApplicationContext applicationContext = + new ClassPathXmlApplicationContext("interceptorsBeanDefinitionParserOrderTest.xml", getClass()); - List interceptors = new ArrayList( - applicationContext.getBeansOfType(DelegatingSmartEndpointInterceptor.class).values()); - assertEquals("not enough smart interceptors found", 6, interceptors.size()); + List interceptors = new ArrayList( + applicationContext.getBeansOfType(DelegatingSmartEndpointInterceptor.class).values()); + assertEquals("not enough smart interceptors found", 6, interceptors.size()); - for (int i = 0; i < interceptors.size(); i++) { - DelegatingSmartEndpointInterceptor delegatingInterceptor = interceptors.get(i); - MyInterceptor interceptor = (MyInterceptor) delegatingInterceptor.getDelegate(); - assertEquals("Invalid ordering found for [" + delegatingInterceptor + "]", i, interceptor.getOrder()); - } - } + for (int i = 0; i < interceptors.size(); i++) { + DelegatingSmartEndpointInterceptor delegatingInterceptor = interceptors.get(i); + MyInterceptor interceptor = (MyInterceptor) delegatingInterceptor.getDelegate(); + assertEquals("Invalid ordering found for [" + delegatingInterceptor + "]", i, interceptor.getOrder()); + } + } - @Test - public void injection() throws Exception { - ApplicationContext applicationContext = - new ClassPathXmlApplicationContext("interceptorsBeanDefinitionParserInjectionTest.xml", getClass()); + @Test + public void injection() throws Exception { + ApplicationContext applicationContext = + new ClassPathXmlApplicationContext("interceptorsBeanDefinitionParserInjectionTest.xml", getClass()); - List interceptors = new ArrayList( - applicationContext.getBeansOfType(DelegatingSmartEndpointInterceptor.class).values()); - assertEquals("not enough smart interceptors found", 1, interceptors.size()); + List interceptors = new ArrayList( + applicationContext.getBeansOfType(DelegatingSmartEndpointInterceptor.class).values()); + assertEquals("not enough smart interceptors found", 1, interceptors.size()); - DummyInterceptor interceptor = - (DummyInterceptor) interceptors.get(0).getDelegate(); - assertNotNull(interceptor.getPropertyDependency()); - assertNotNull(interceptor.getAutowiredDependency()); - } + DummyInterceptor interceptor = + (DummyInterceptor) interceptors.get(0).getDelegate(); + assertNotNull(interceptor.getPropertyDependency()); + assertNotNull(interceptor.getAutowiredDependency()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/MyInterceptor.java b/spring-ws-core/src/test/java/org/springframework/ws/config/MyInterceptor.java index 913d4314..4cd6b8af 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/MyInterceptor.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/MyInterceptor.java @@ -24,32 +24,32 @@ import org.springframework.ws.server.EndpointInterceptor; */ public class MyInterceptor implements EndpointInterceptor { - private int order; + private int order; - public int getOrder() { - return order; - } + public int getOrder() { + return order; + } - public void setOrder(int order) { - this.order = order; - } + public void setOrder(int order) { + this.order = order; + } - @Override - public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + @Override + public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { + return true; + } - @Override - public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + @Override + public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { + return true; + } - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + @Override + public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { + return true; + } - @Override - public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) { - } + @Override + public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/WebServiceNamespaceHandlerTest.java b/spring-ws-core/src/test/java/org/springframework/ws/config/WebServiceNamespaceHandlerTest.java index 9b4d2aac..bedb97bf 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/WebServiceNamespaceHandlerTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/WebServiceNamespaceHandlerTest.java @@ -28,16 +28,16 @@ import org.junit.Test; public class WebServiceNamespaceHandlerTest { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - @Before - public void setUp() throws Exception { - applicationContext = new ClassPathXmlApplicationContext("webServiceNamespaceHandlerTest.xml", getClass()); - } + @Before + public void setUp() throws Exception { + applicationContext = new ClassPathXmlApplicationContext("webServiceNamespaceHandlerTest.xml", getClass()); + } - @Test - public void testMarshallingMethods() throws Exception { - Map result = applicationContext.getBeansOfType(MarshallingMethodEndpointAdapter.class); - Assert.assertFalse("no MarshallingMethodEndpointAdapter found", result.isEmpty()); - } + @Test + public void testMarshallingMethods() throws Exception { + Map result = applicationContext.getBeansOfType(MarshallingMethodEndpointAdapter.class); + Assert.assertFalse("no MarshallingMethodEndpointAdapter found", result.isEmpty()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/WebServicesNamespaceHandlerTigerTest.java b/spring-ws-core/src/test/java/org/springframework/ws/config/WebServicesNamespaceHandlerTigerTest.java index cfe9c848..2a7c9e42 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/WebServicesNamespaceHandlerTigerTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/WebServicesNamespaceHandlerTigerTest.java @@ -29,25 +29,25 @@ import org.junit.Test; public class WebServicesNamespaceHandlerTigerTest { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - @Before - public void setUp() throws Exception { - applicationContext = - new ClassPathXmlApplicationContext("webServicesNamespaceHandlerTest-tiger.xml", getClass()); - } + @Before + public void setUp() throws Exception { + applicationContext = + new ClassPathXmlApplicationContext("webServicesNamespaceHandlerTest-tiger.xml", getClass()); + } - @Test - public void testMarshallingEndpoints() throws Exception { - Map result = - applicationContext.getBeansOfType(GenericMarshallingMethodEndpointAdapter.class); - Assert.assertFalse("no MarshallingMethodEndpointAdapter found", result.isEmpty()); - } + @Test + public void testMarshallingEndpoints() throws Exception { + Map result = + applicationContext.getBeansOfType(GenericMarshallingMethodEndpointAdapter.class); + Assert.assertFalse("no MarshallingMethodEndpointAdapter found", result.isEmpty()); + } - @Test - public void testXpathEndpoints() throws Exception { - Map result = - applicationContext.getBeansOfType(XPathParamAnnotationMethodEndpointAdapter.class); - Assert.assertFalse("no XPathParamAnnotationMethodEndpointAdapter found", result.isEmpty()); - } + @Test + public void testXpathEndpoints() throws Exception { + Map result = + applicationContext.getBeansOfType(XPathParamAnnotationMethodEndpointAdapter.class); + Assert.assertFalse("no XPathParamAnnotationMethodEndpointAdapter found", result.isEmpty()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/config/WsdlBeanDefinitionParserTest.java b/spring-ws-core/src/test/java/org/springframework/ws/config/WsdlBeanDefinitionParserTest.java index a86f70b7..9773c6cd 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/config/WsdlBeanDefinitionParserTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/config/WsdlBeanDefinitionParserTest.java @@ -33,27 +33,27 @@ import org.junit.Test; */ public class WsdlBeanDefinitionParserTest { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - @Before - public void setUp() throws Exception { - applicationContext = new ClassPathXmlApplicationContext("wsdlBeanDefinitionParserTest.xml", getClass()); - } + @Before + public void setUp() throws Exception { + applicationContext = new ClassPathXmlApplicationContext("wsdlBeanDefinitionParserTest.xml", getClass()); + } - @Test - public void staticWsdl() throws Exception { - Map result = applicationContext.getBeansOfType(SimpleWsdl11Definition.class); - Assert.assertFalse("no WSDL definitions found", result.isEmpty()); - String beanName = result.keySet().iterator().next(); - Assert.assertEquals("invalid bean name", "simple", beanName); - } + @Test + public void staticWsdl() throws Exception { + Map result = applicationContext.getBeansOfType(SimpleWsdl11Definition.class); + Assert.assertFalse("no WSDL definitions found", result.isEmpty()); + String beanName = result.keySet().iterator().next(); + Assert.assertEquals("invalid bean name", "simple", beanName); + } - @Test - public void dynamicWsdl() throws Exception { - Map result = applicationContext.getBeansOfType(DefaultWsdl11Definition.class); - Assert.assertFalse("no WSDL definitions found", result.isEmpty()); + @Test + public void dynamicWsdl() throws Exception { + Map result = applicationContext.getBeansOfType(DefaultWsdl11Definition.class); + Assert.assertFalse("no WSDL definitions found", result.isEmpty()); - result = applicationContext.getBeansOfType(CommonsXsdSchemaCollection.class); - Assert.assertFalse("no XSD definitions found", result.isEmpty()); - } + result = applicationContext.getBeansOfType(CommonsXsdSchemaCollection.class); + Assert.assertFalse("no XSD definitions found", result.isEmpty()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/context/DefaultMessageContextTest.java b/spring-ws-core/src/test/java/org/springframework/ws/context/DefaultMessageContextTest.java index 92837da1..4e9bda2a 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/context/DefaultMessageContextTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/context/DefaultMessageContextTest.java @@ -30,49 +30,49 @@ import static org.easymock.EasyMock.*; public class DefaultMessageContextTest { - private DefaultMessageContext context; + private DefaultMessageContext context; - private WebServiceMessageFactory factoryMock; + private WebServiceMessageFactory factoryMock; - private WebServiceMessage request; + private WebServiceMessage request; - @Before - public void setUp() throws Exception { - factoryMock = createMock(WebServiceMessageFactory.class); - request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, factoryMock); - } + @Before + public void setUp() throws Exception { + factoryMock = createMock(WebServiceMessageFactory.class); + request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, factoryMock); + } - @Test - public void testRequest() throws Exception { - Assert.assertEquals("Invalid request returned", request, context.getRequest()); - } + @Test + public void testRequest() throws Exception { + Assert.assertEquals("Invalid request returned", request, context.getRequest()); + } - @Test - public void testResponse() throws Exception { - WebServiceMessage response = new MockWebServiceMessage(); - expect(factoryMock.createWebServiceMessage()).andReturn(response); - replay(factoryMock); + @Test + public void testResponse() throws Exception { + WebServiceMessage response = new MockWebServiceMessage(); + expect(factoryMock.createWebServiceMessage()).andReturn(response); + replay(factoryMock); - WebServiceMessage result = context.getResponse(); - Assert.assertEquals("Invalid response returned", response, result); - verify(factoryMock); - } + WebServiceMessage result = context.getResponse(); + Assert.assertEquals("Invalid response returned", response, result); + verify(factoryMock); + } - @Test - public void testProperties() throws Exception { - Assert.assertEquals("Invalid property names returned", 0, context.getPropertyNames().length); - String name = "name"; - Assert.assertFalse("Property set", context.containsProperty(name)); - String value = "value"; - context.setProperty(name, value); - Assert.assertTrue("Property not set", context.containsProperty(name)); - Assert.assertEquals("Invalid property names returned", Arrays.asList(name), - Arrays.asList(context.getPropertyNames())); - Assert.assertEquals("Invalid property value returned", value, context.getProperty(name)); - context.removeProperty(name); - Assert.assertFalse("Property set", context.containsProperty(name)); - Assert.assertEquals("Invalid property names returned", 0, context.getPropertyNames().length); - } + @Test + public void testProperties() throws Exception { + Assert.assertEquals("Invalid property names returned", 0, context.getPropertyNames().length); + String name = "name"; + Assert.assertFalse("Property set", context.containsProperty(name)); + String value = "value"; + context.setProperty(name, value); + Assert.assertTrue("Property not set", context.containsProperty(name)); + Assert.assertEquals("Invalid property names returned", Arrays.asList(name), + Arrays.asList(context.getPropertyNames())); + Assert.assertEquals("Invalid property value returned", value, context.getProperty(name)); + context.removeProperty(name); + Assert.assertFalse("Property set", context.containsProperty(name)); + Assert.assertEquals("Invalid property names returned", 0, context.getPropertyNames().length); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/mime/AbstractMimeMessageTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/mime/AbstractMimeMessageTestCase.java index ef0a5c89..8fba10ed 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/mime/AbstractMimeMessageTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/mime/AbstractMimeMessageTestCase.java @@ -30,62 +30,62 @@ import org.springframework.ws.WebServiceMessage; public abstract class AbstractMimeMessageTestCase extends AbstractWebServiceMessageTestCase { - protected MimeMessage mimeMessage; + protected MimeMessage mimeMessage; - private Resource picture; + private Resource picture; - private String contentId; + private String contentId; - private String contentType; + private String contentType; - @Override - protected final WebServiceMessage createWebServiceMessage() throws Exception { - mimeMessage = createMimeMessage(); - picture = new ClassPathResource("spring-ws.png", AbstractMimeMessageTestCase.class); - contentId = "spring-ws"; - contentType = "image/png"; - return mimeMessage; - } + @Override + protected final WebServiceMessage createWebServiceMessage() throws Exception { + mimeMessage = createMimeMessage(); + picture = new ClassPathResource("spring-ws.png", AbstractMimeMessageTestCase.class); + contentId = "spring-ws"; + contentType = "image/png"; + return mimeMessage; + } - protected abstract MimeMessage createMimeMessage() throws Exception; + protected abstract MimeMessage createMimeMessage() throws Exception; - @Test - public void testEmptyMessage() throws Exception { - Iterator iterator = mimeMessage.getAttachments(); - assertFalse("Empty MimeMessage has attachments", iterator.hasNext()); - } + @Test + public void testEmptyMessage() throws Exception { + Iterator iterator = mimeMessage.getAttachments(); + assertFalse("Empty MimeMessage has attachments", iterator.hasNext()); + } - @Test - public void testAddAttachment() throws Exception { - Attachment attachment = mimeMessage.addAttachment(contentId, picture, contentType); - testAttachment(attachment); - } + @Test + public void testAddAttachment() throws Exception { + Attachment attachment = mimeMessage.addAttachment(contentId, picture, contentType); + testAttachment(attachment); + } - @Test - public void testGetAttachment() throws Exception { - mimeMessage.addAttachment(contentId, picture, contentType); - Attachment attachment = mimeMessage.getAttachment(contentId); - assertNotNull("Not Attachment found", attachment); - testAttachment(attachment); - } + @Test + public void testGetAttachment() throws Exception { + mimeMessage.addAttachment(contentId, picture, contentType); + Attachment attachment = mimeMessage.getAttachment(contentId); + assertNotNull("Not Attachment found", attachment); + testAttachment(attachment); + } - @Test - public void testGetAttachments() throws Exception { - mimeMessage.addAttachment(contentId, picture, contentType); - Iterator iterator = mimeMessage.getAttachments(); - assertNotNull("Attachment iterator is null", iterator); - assertTrue("Attachment iterator has no elements", iterator.hasNext()); - Attachment attachment = iterator.next(); - testAttachment(attachment); - assertFalse("Attachment iterator has too many elements", iterator.hasNext()); - } + @Test + public void testGetAttachments() throws Exception { + mimeMessage.addAttachment(contentId, picture, contentType); + Iterator iterator = mimeMessage.getAttachments(); + assertNotNull("Attachment iterator is null", iterator); + assertTrue("Attachment iterator has no elements", iterator.hasNext()); + Attachment attachment = iterator.next(); + testAttachment(attachment); + assertFalse("Attachment iterator has too many elements", iterator.hasNext()); + } - private void testAttachment(Attachment attachment) throws IOException { - assertEquals("Invalid content id", contentId, attachment.getContentId()); - assertEquals("Invalid content type", contentType, attachment.getContentType()); - assertTrue("Invalid size", attachment.getSize() != 0); - byte[] contents = FileCopyUtils.copyToByteArray(attachment.getInputStream()); - assertTrue("No contents", contents.length > 0); - } + private void testAttachment(Attachment attachment) throws IOException { + assertEquals("Invalid content id", contentId, attachment.getContentId()); + assertEquals("Invalid content type", contentType, attachment.getContentType()); + assertTrue("Invalid size", attachment.getSize() != 0); + byte[] contents = FileCopyUtils.copyToByteArray(attachment.getInputStream()); + assertTrue("No contents", contents.length > 0); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageFactoryTest.java b/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageFactoryTest.java index 1904a105..8ef9716a 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageFactoryTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageFactoryTest.java @@ -21,8 +21,8 @@ import org.springframework.ws.WebServiceMessageFactory; public class DomPoxMessageFactoryTest extends AbstractWebServiceMessageFactoryTestCase { - @Override - protected WebServiceMessageFactory createMessageFactory() throws Exception { - return new DomPoxMessageFactory(); - } + @Override + protected WebServiceMessageFactory createMessageFactory() throws Exception { + return new DomPoxMessageFactory(); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageTest.java b/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageTest.java index 49ef2c5d..5802ba8e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/pox/dom/DomPoxMessageTest.java @@ -33,47 +33,47 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class DomPoxMessageTest { - private DomPoxMessage message; + private DomPoxMessage message; - private Transformer transformer; + private Transformer transformer; - @Before - public void setUp() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - message = new DomPoxMessage(document, transformer, DomPoxMessageFactory.DEFAULT_CONTENT_TYPE); - } + @Before + public void setUp() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + message = new DomPoxMessage(document, transformer, DomPoxMessageFactory.DEFAULT_CONTENT_TYPE); + } - @Test - public void testGetPayload() throws Exception { - String content = "" + ""; - StringSource source = new StringSource(content); - transformer.transform(source, message.getPayloadResult()); - StringResult stringResult = new StringResult(); - transformer.transform(message.getPayloadSource(), stringResult); - assertXMLEqual(content, stringResult.toString()); - } + @Test + public void testGetPayload() throws Exception { + String content = "" + ""; + StringSource source = new StringSource(content); + transformer.transform(source, message.getPayloadResult()); + StringResult stringResult = new StringResult(); + transformer.transform(message.getPayloadSource(), stringResult); + assertXMLEqual(content, stringResult.toString()); + } - @Test - public void testGetPayloadResultTwice() throws Exception { - String content = ""; - transformer.transform(new StringSource(content), message.getPayloadResult()); - transformer.transform(new StringSource(content), message.getPayloadResult()); - StringResult stringResult = new StringResult(); - transformer.transform(message.getPayloadSource(), stringResult); - assertXMLEqual(content, stringResult.toString()); - } + @Test + public void testGetPayloadResultTwice() throws Exception { + String content = ""; + transformer.transform(new StringSource(content), message.getPayloadResult()); + transformer.transform(new StringSource(content), message.getPayloadResult()); + StringResult stringResult = new StringResult(); + transformer.transform(message.getPayloadSource(), stringResult); + assertXMLEqual(content, stringResult.toString()); + } - @Test - public void testWriteTo() throws Exception { - String content = "" + ""; - StringSource source = new StringSource(content); - transformer.transform(source, message.getPayloadResult()); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - message.writeTo(os); - assertXMLEqual(content, os.toString("UTF-8")); - } + @Test + public void testWriteTo() throws Exception { + String content = "" + ""; + StringSource source = new StringSource(content); + transformer.transform(source, message.getPayloadResult()); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + message.writeTo(os); + assertXMLEqual(content, os.toString("UTF-8")); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/MessageDispatcherTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/MessageDispatcherTest.java index 27fe5642..264fbe6c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/MessageDispatcherTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/MessageDispatcherTest.java @@ -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, @@ -36,386 +36,386 @@ import static org.easymock.EasyMock.*; public class MessageDispatcherTest { - private MessageDispatcher dispatcher; + private MessageDispatcher dispatcher; - private MessageContext messageContext; + private MessageContext messageContext; - private WebServiceMessageFactory factoryMock; + private WebServiceMessageFactory factoryMock; - @Before - public void setUp() throws Exception { - dispatcher = new MessageDispatcher(); - factoryMock = createMock(WebServiceMessageFactory.class); - messageContext = new DefaultMessageContext(new MockWebServiceMessage(), factoryMock); - } + @Before + public void setUp() throws Exception { + dispatcher = new MessageDispatcher(); + factoryMock = createMock(WebServiceMessageFactory.class); + messageContext = new DefaultMessageContext(new MockWebServiceMessage(), factoryMock); + } - @Test - public void testGetEndpoint() throws Exception { - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + @Test + public void testGetEndpoint() throws Exception { + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointInvocationChain chain = new EndpointInvocationChain(new Object()); + EndpointInvocationChain chain = new EndpointInvocationChain(new Object()); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - replay(mappingMock, factoryMock); + replay(mappingMock, factoryMock); - EndpointInvocationChain result = dispatcher.getEndpoint(messageContext); + EndpointInvocationChain result = dispatcher.getEndpoint(messageContext); - verify(mappingMock, factoryMock); + verify(mappingMock, factoryMock); - Assert.assertEquals("getEndpoint returns invalid EndpointInvocationChain", chain, result); - } + Assert.assertEquals("getEndpoint returns invalid EndpointInvocationChain", chain, result); + } - @Test - public void testGetEndpointAdapterSupportedEndpoint() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testGetEndpointAdapterSupportedEndpoint() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - Object endpoint = new Object(); - expect(adapterMock.supports(endpoint)).andReturn(true); + Object endpoint = new Object(); + expect(adapterMock.supports(endpoint)).andReturn(true); - replay(adapterMock, factoryMock); + replay(adapterMock, factoryMock); - EndpointAdapter result = dispatcher.getEndpointAdapter(endpoint); + EndpointAdapter result = dispatcher.getEndpointAdapter(endpoint); - verify(adapterMock, factoryMock); + verify(adapterMock, factoryMock); - Assert.assertEquals("getEndpointAdapter returns invalid EndpointAdapter", adapterMock, result); - } + Assert.assertEquals("getEndpointAdapter returns invalid EndpointAdapter", adapterMock, result); + } - @Test - public void testGetEndpointAdapterUnsupportedEndpoint() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testGetEndpointAdapterUnsupportedEndpoint() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - Object endpoint = new Object(); - expect(adapterMock.supports(endpoint)).andReturn(false); + Object endpoint = new Object(); + expect(adapterMock.supports(endpoint)).andReturn(false); - replay(adapterMock, factoryMock); + replay(adapterMock, factoryMock); - try { - dispatcher.getEndpointAdapter(endpoint); - Assert.fail("getEndpointAdapter does not throw IllegalStateException for unsupported endpoint"); - } - catch (IllegalStateException ex) { - // Expected - } + try { + dispatcher.getEndpointAdapter(endpoint); + Assert.fail("getEndpointAdapter does not throw IllegalStateException for unsupported endpoint"); + } + catch (IllegalStateException ex) { + // Expected + } - verify(adapterMock, factoryMock); - } + verify(adapterMock, factoryMock); + } - @Test - public void testResolveException() throws Exception { - final Exception ex = new Exception(); - EndpointMapping endpointMapping = new EndpointMapping() { + @Test + public void testResolveException() throws Exception { + final Exception ex = new Exception(); + EndpointMapping endpointMapping = new EndpointMapping() { - public EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception { - throw ex; - } - }; - dispatcher.setEndpointMappings(Collections.singletonList(endpointMapping)); - EndpointExceptionResolver resolver = new EndpointExceptionResolver() { + public EndpointInvocationChain getEndpoint(MessageContext messageContext) throws Exception { + throw ex; + } + }; + dispatcher.setEndpointMappings(Collections.singletonList(endpointMapping)); + EndpointExceptionResolver resolver = new EndpointExceptionResolver() { - public boolean resolveException(MessageContext givenMessageContext, - Object givenEndpoint, - Exception givenException) { - Assert.assertEquals("Invalid message context", messageContext, givenMessageContext); - Assert.assertNull("Invalid endpoint", givenEndpoint); - Assert.assertEquals("Invalid exception", ex, givenException); - givenMessageContext.getResponse(); - return true; - } + public boolean resolveException(MessageContext givenMessageContext, + Object givenEndpoint, + Exception givenException) { + Assert.assertEquals("Invalid message context", messageContext, givenMessageContext); + Assert.assertNull("Invalid endpoint", givenEndpoint); + Assert.assertEquals("Invalid exception", ex, givenException); + givenMessageContext.getResponse(); + return true; + } - }; - dispatcher.setEndpointExceptionResolvers(Collections.singletonList(resolver)); - expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); + }; + dispatcher.setEndpointExceptionResolvers(Collections.singletonList(resolver)); + expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); - replay(factoryMock); + replay(factoryMock); - dispatcher.dispatch(messageContext); - Assert.assertNotNull("processEndpointException sets no response", messageContext.getResponse()); + dispatcher.dispatch(messageContext); + Assert.assertNotNull("processEndpointException sets no response", messageContext.getResponse()); - verify(factoryMock); - } + verify(factoryMock); + } - @Test - public void testProcessUnsupportedEndpointException() throws Exception { - EndpointExceptionResolver resolverMock = createMock(EndpointExceptionResolver.class); - dispatcher.setEndpointExceptionResolvers(Collections.singletonList(resolverMock)); + @Test + public void testProcessUnsupportedEndpointException() throws Exception { + EndpointExceptionResolver resolverMock = createMock(EndpointExceptionResolver.class); + dispatcher.setEndpointExceptionResolvers(Collections.singletonList(resolverMock)); - Object endpoint = new Object(); - Exception ex = new Exception(); + Object endpoint = new Object(); + Exception ex = new Exception(); - expect(resolverMock.resolveException(messageContext, endpoint, ex)).andReturn(false); + expect(resolverMock.resolveException(messageContext, endpoint, ex)).andReturn(false); - replay(factoryMock, resolverMock); + replay(factoryMock, resolverMock); - try { - dispatcher.processEndpointException(messageContext, endpoint, ex); - } - catch (Exception result) { - Assert.assertEquals("processEndpointException throws invalid exception", ex, result); - } - verify(factoryMock, resolverMock); - } + try { + dispatcher.processEndpointException(messageContext, endpoint, ex); + } + catch (Exception result) { + Assert.assertEquals("processEndpointException throws invalid exception", ex, result); + } + verify(factoryMock, resolverMock); + } - @Test - public void testNormalFlow() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testNormalFlow() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - Object endpoint = new Object(); - expect(adapterMock.supports(endpoint)).andReturn(true); + Object endpoint = new Object(); + expect(adapterMock.supports(endpoint)).andReturn(true); - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); - EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); + EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); + EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); - expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(true); - expect(interceptorMock2.handleRequest(messageContext, endpoint)).andReturn(true); + expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(true); + expect(interceptorMock2.handleRequest(messageContext, endpoint)).andReturn(true); - adapterMock.invoke(messageContext, endpoint); + adapterMock.invoke(messageContext, endpoint); - expect(interceptorMock2.handleResponse(messageContext, endpoint)).andReturn(true); - expect(interceptorMock1.handleResponse(messageContext, endpoint)).andReturn(true); + expect(interceptorMock2.handleResponse(messageContext, endpoint)).andReturn(true); + expect(interceptorMock1.handleResponse(messageContext, endpoint)).andReturn(true); - interceptorMock2.afterCompletion(messageContext, endpoint, null); - interceptorMock1.afterCompletion(messageContext, endpoint, null); + interceptorMock2.afterCompletion(messageContext, endpoint, null); + interceptorMock1.afterCompletion(messageContext, endpoint, null); - EndpointInvocationChain chain = - new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); + EndpointInvocationChain chain = + new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); - replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - // response required for interceptor invocation - messageContext.getResponse(); - dispatcher.dispatch(messageContext); + // response required for interceptor invocation + messageContext.getResponse(); + dispatcher.dispatch(messageContext); - verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - } + verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + } - @Test - public void testFlowNoResponse() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testFlowNoResponse() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - Object endpoint = new Object(); - expect(adapterMock.supports(endpoint)).andReturn(true); + Object endpoint = new Object(); + expect(adapterMock.supports(endpoint)).andReturn(true); - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); - EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); + EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); + EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); - EndpointInvocationChain chain = - new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + EndpointInvocationChain chain = + new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(true); - expect(interceptorMock2.handleRequest(messageContext, endpoint)).andReturn(true); - interceptorMock2.afterCompletion(messageContext, endpoint, null); - interceptorMock1.afterCompletion(messageContext, endpoint, null); + expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(true); + expect(interceptorMock2.handleRequest(messageContext, endpoint)).andReturn(true); + interceptorMock2.afterCompletion(messageContext, endpoint, null); + interceptorMock1.afterCompletion(messageContext, endpoint, null); - adapterMock.invoke(messageContext, endpoint); + adapterMock.invoke(messageContext, endpoint); - replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - dispatcher.dispatch(messageContext); + dispatcher.dispatch(messageContext); - verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - } + verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + } - @Test - public void testInterceptedRequestFlow() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testInterceptedRequestFlow() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); - EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); + EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); + EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); - Object endpoint = new Object(); + Object endpoint = new Object(); - expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(false); - expect(interceptorMock1.handleResponse(messageContext, endpoint)).andReturn(true); - interceptorMock1.afterCompletion(messageContext, endpoint, null); + expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(false); + expect(interceptorMock1.handleResponse(messageContext, endpoint)).andReturn(true); + interceptorMock1.afterCompletion(messageContext, endpoint, null); - EndpointInvocationChain chain = - new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); + EndpointInvocationChain chain = + new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); - replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - // response required for interceptor invocation - messageContext.getResponse(); + // response required for interceptor invocation + messageContext.getResponse(); - dispatcher.dispatch(messageContext); + dispatcher.dispatch(messageContext); - verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - } + verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + } - @Test - public void testInterceptedResponseFlow() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testInterceptedResponseFlow() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); - EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); + EndpointInterceptor interceptorMock1 = createStrictMock("interceptor1", EndpointInterceptor.class); + EndpointInterceptor interceptorMock2 = createStrictMock("interceptor2", EndpointInterceptor.class); - Object endpoint = new Object(); - expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(true); - expect(interceptorMock2.handleRequest(messageContext, endpoint)).andReturn(false); - expect(interceptorMock2.handleResponse(messageContext, endpoint)).andReturn(false); - interceptorMock1.afterCompletion(messageContext, endpoint, null); - interceptorMock2.afterCompletion(messageContext, endpoint, null); + Object endpoint = new Object(); + expect(interceptorMock1.handleRequest(messageContext, endpoint)).andReturn(true); + expect(interceptorMock2.handleRequest(messageContext, endpoint)).andReturn(false); + expect(interceptorMock2.handleResponse(messageContext, endpoint)).andReturn(false); + interceptorMock1.afterCompletion(messageContext, endpoint, null); + interceptorMock2.afterCompletion(messageContext, endpoint, null); - EndpointInvocationChain chain = - new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); + EndpointInvocationChain chain = + new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock1, interceptorMock2}); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); - replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + replay(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - // response required for interceptor invocation - messageContext.getResponse(); + // response required for interceptor invocation + messageContext.getResponse(); - dispatcher.dispatch(messageContext); + dispatcher.dispatch(messageContext); - verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); - } + verify(mappingMock, interceptorMock1, interceptorMock2, adapterMock, factoryMock); + } - @Test - public void testResolveExceptionsWithInterceptors() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testResolveExceptionsWithInterceptors() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - Object endpoint = new Object(); - expect(adapterMock.supports(endpoint)).andReturn(true); + Object endpoint = new Object(); + expect(adapterMock.supports(endpoint)).andReturn(true); - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointExceptionResolver resolverMock = createMock(EndpointExceptionResolver.class); - dispatcher.setEndpointExceptionResolvers(Collections.singletonList(resolverMock)); + EndpointExceptionResolver resolverMock = createMock(EndpointExceptionResolver.class); + dispatcher.setEndpointExceptionResolvers(Collections.singletonList(resolverMock)); - EndpointInterceptor interceptorMock = createStrictMock("interceptor1", EndpointInterceptor.class); + EndpointInterceptor interceptorMock = createStrictMock("interceptor1", EndpointInterceptor.class); - expect(interceptorMock.handleRequest(messageContext, endpoint)).andReturn(true); + expect(interceptorMock.handleRequest(messageContext, endpoint)).andReturn(true); - adapterMock.invoke(messageContext, endpoint); - RuntimeException exception = new RuntimeException(); - expectLastCall().andThrow(exception); + adapterMock.invoke(messageContext, endpoint); + RuntimeException exception = new RuntimeException(); + expectLastCall().andThrow(exception); - expect(resolverMock.resolveException(messageContext, endpoint, exception)).andReturn(true); + expect(resolverMock.resolveException(messageContext, endpoint, exception)).andReturn(true); - expect(interceptorMock.handleResponse(messageContext, endpoint)).andReturn(true); + expect(interceptorMock.handleResponse(messageContext, endpoint)).andReturn(true); - interceptorMock.afterCompletion(messageContext, endpoint, null); + interceptorMock.afterCompletion(messageContext, endpoint, null); - EndpointInvocationChain chain = - new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock}); + EndpointInvocationChain chain = + new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock}); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); - replay(mappingMock, interceptorMock, adapterMock, factoryMock, resolverMock); + replay(mappingMock, interceptorMock, adapterMock, factoryMock, resolverMock); - // response required for interceptor invocation - messageContext.getResponse(); - try { - dispatcher.dispatch(messageContext); - } catch (RuntimeException ex) { + // response required for interceptor invocation + messageContext.getResponse(); + try { + dispatcher.dispatch(messageContext); + } catch (RuntimeException ex) { - } + } - verify(mappingMock, interceptorMock, adapterMock, factoryMock, resolverMock); - } + verify(mappingMock, interceptorMock, adapterMock, factoryMock, resolverMock); + } - @Test - public void testFaultFlow() throws Exception { - EndpointAdapter adapterMock = createMock(EndpointAdapter.class); - dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); + @Test + public void testFaultFlow() throws Exception { + EndpointAdapter adapterMock = createMock(EndpointAdapter.class); + dispatcher.setEndpointAdapters(Collections.singletonList(adapterMock)); - Object endpoint = new Object(); - expect(adapterMock.supports(endpoint)).andReturn(true); + Object endpoint = new Object(); + expect(adapterMock.supports(endpoint)).andReturn(true); - EndpointMapping mappingMock = createMock(EndpointMapping.class); - dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); + EndpointMapping mappingMock = createMock(EndpointMapping.class); + dispatcher.setEndpointMappings(Collections.singletonList(mappingMock)); - EndpointInterceptor interceptorMock = createStrictMock(EndpointInterceptor.class); + EndpointInterceptor interceptorMock = createStrictMock(EndpointInterceptor.class); - expect(interceptorMock.handleRequest(messageContext, endpoint)).andReturn(true); - adapterMock.invoke(messageContext, endpoint); - expect(interceptorMock.handleFault(messageContext, endpoint)).andReturn(true); - interceptorMock.afterCompletion(messageContext, endpoint, null); + expect(interceptorMock.handleRequest(messageContext, endpoint)).andReturn(true); + adapterMock.invoke(messageContext, endpoint); + expect(interceptorMock.handleFault(messageContext, endpoint)).andReturn(true); + interceptorMock.afterCompletion(messageContext, endpoint, null); - EndpointInvocationChain chain = - new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock}); + EndpointInvocationChain chain = + new EndpointInvocationChain(endpoint, new EndpointInterceptor[]{interceptorMock}); - expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); - MockWebServiceMessage response = new MockWebServiceMessage(); - response.setFault(true); - expect(factoryMock.createWebServiceMessage()).andReturn(response); + expect(mappingMock.getEndpoint(messageContext)).andReturn(chain); + MockWebServiceMessage response = new MockWebServiceMessage(); + response.setFault(true); + expect(factoryMock.createWebServiceMessage()).andReturn(response); - replay(mappingMock, interceptorMock, adapterMock, factoryMock); + replay(mappingMock, interceptorMock, adapterMock, factoryMock); - // response required for interceptor invocation - messageContext.getResponse(); - dispatcher.dispatch(messageContext); + // response required for interceptor invocation + messageContext.getResponse(); + dispatcher.dispatch(messageContext); - verify(mappingMock, interceptorMock, adapterMock, factoryMock); - } + verify(mappingMock, interceptorMock, adapterMock, factoryMock); + } - @Test - public void testNoEndpointFound() throws Exception { - dispatcher.setEndpointMappings(Collections.emptyList()); - try { - dispatcher.receive(messageContext); - Assert.fail("NoEndpointFoundException expected"); - } - catch (NoEndpointFoundException ex) { - // expected - } - } + @Test + public void testNoEndpointFound() throws Exception { + dispatcher.setEndpointMappings(Collections.emptyList()); + try { + dispatcher.receive(messageContext); + Assert.fail("NoEndpointFoundException expected"); + } + catch (NoEndpointFoundException ex) { + // expected + } + } - @Test - public void testDetectStrategies() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("mapping", PayloadRootQNameEndpointMapping.class); - applicationContext.registerSingleton("adapter", PayloadEndpointAdapter.class); - applicationContext.registerSingleton("resolver", SimpleSoapExceptionResolver.class); - dispatcher.setApplicationContext(applicationContext); - Assert.assertEquals("Invalid amount of mappings detected", 1, dispatcher.getEndpointMappings().size()); - Assert.assertTrue("Invalid mappings detected", - dispatcher.getEndpointMappings().get(0) instanceof PayloadRootQNameEndpointMapping); - Assert.assertEquals("Invalid amount of adapters detected", 1, dispatcher.getEndpointAdapters().size()); - Assert.assertTrue("Invalid mappings detected", - dispatcher.getEndpointAdapters().get(0) instanceof PayloadEndpointAdapter); - Assert.assertEquals("Invalid amount of resolvers detected", 1, - dispatcher.getEndpointExceptionResolvers().size()); - Assert.assertTrue("Invalid mappings detected", - dispatcher.getEndpointExceptionResolvers().get(0) instanceof SimpleSoapExceptionResolver); - } - - @Test - public void testDefaultStrategies() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - dispatcher.setApplicationContext(applicationContext); - } + @Test + public void testDetectStrategies() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("mapping", PayloadRootQNameEndpointMapping.class); + applicationContext.registerSingleton("adapter", PayloadEndpointAdapter.class); + applicationContext.registerSingleton("resolver", SimpleSoapExceptionResolver.class); + dispatcher.setApplicationContext(applicationContext); + Assert.assertEquals("Invalid amount of mappings detected", 1, dispatcher.getEndpointMappings().size()); + Assert.assertTrue("Invalid mappings detected", + dispatcher.getEndpointMappings().get(0) instanceof PayloadRootQNameEndpointMapping); + Assert.assertEquals("Invalid amount of adapters detected", 1, dispatcher.getEndpointAdapters().size()); + Assert.assertTrue("Invalid mappings detected", + dispatcher.getEndpointAdapters().get(0) instanceof PayloadEndpointAdapter); + Assert.assertEquals("Invalid amount of resolvers detected", 1, + dispatcher.getEndpointExceptionResolvers().size()); + Assert.assertTrue("Invalid mappings detected", + dispatcher.getEndpointExceptionResolvers().get(0) instanceof SimpleSoapExceptionResolver); + } + + @Test + public void testDefaultStrategies() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + dispatcher.setApplicationContext(applicationContext); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractEndpointTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractEndpointTestCase.java index feee526f..f901e6ba 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractEndpointTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractEndpointTestCase.java @@ -41,57 +41,57 @@ import org.xml.sax.helpers.XMLReaderFactory; @SuppressWarnings("Since15") public abstract class AbstractEndpointTestCase { - protected static final String NAMESPACE_URI = "http://springframework.org/ws"; + protected static final String NAMESPACE_URI = "http://springframework.org/ws"; - protected static final String REQUEST_ELEMENT = "request"; + protected static final String REQUEST_ELEMENT = "request"; - protected static final String RESPONSE_ELEMENT = "response"; + protected static final String RESPONSE_ELEMENT = "response"; - protected static final String REQUEST = "<" + REQUEST_ELEMENT + " xmlns=\"" + NAMESPACE_URI + "\"/>"; + protected static final String REQUEST = "<" + REQUEST_ELEMENT + " xmlns=\"" + NAMESPACE_URI + "\"/>"; - protected static final String RESPONSE = "<" + RESPONSE_ELEMENT + " xmlns=\"" + NAMESPACE_URI + "\"/>"; + protected static final String RESPONSE = "<" + RESPONSE_ELEMENT + " xmlns=\"" + NAMESPACE_URI + "\"/>"; - @Test - public void testDomSource() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document requestDocument = documentBuilder.parse(new InputSource(new StringReader(REQUEST))); - testSource(new DOMSource(requestDocument.getDocumentElement())); - } + @Test + public void testDomSource() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDocument = documentBuilder.parse(new InputSource(new StringReader(REQUEST))); + testSource(new DOMSource(requestDocument.getDocumentElement())); + } - @Test - public void testSaxSource() throws Exception { - XMLReader reader = XMLReaderFactory.createXMLReader(); - InputSource inputSource = new InputSource(new StringReader(REQUEST)); - testSource(new SAXSource(reader, inputSource)); - } + @Test + public void testSaxSource() throws Exception { + XMLReader reader = XMLReaderFactory.createXMLReader(); + InputSource inputSource = new InputSource(new StringReader(REQUEST)); + testSource(new SAXSource(reader, inputSource)); + } - @Test - public void testStaxSourceEventReader() throws Exception { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(REQUEST)); - testSource(new SAXSource(StaxUtils.createXMLReader(eventReader), new InputSource())); - } + @Test + public void testStaxSourceEventReader() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(REQUEST)); + testSource(new SAXSource(StaxUtils.createXMLReader(eventReader), new InputSource())); + } - @Test - public void testStaxSourceStreamReader() throws Exception { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(REQUEST)); - testSource(new SAXSource(StaxUtils.createXMLReader(streamReader), new InputSource())); - } + @Test + public void testStaxSourceStreamReader() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(REQUEST)); + testSource(new SAXSource(StaxUtils.createXMLReader(streamReader), new InputSource())); + } - @Test - public void testStreamSourceInputStream() throws Exception { - InputStream is = new ByteArrayInputStream(REQUEST.getBytes("UTF-8")); - testSource(new StreamSource(is)); - } + @Test + public void testStreamSourceInputStream() throws Exception { + InputStream is = new ByteArrayInputStream(REQUEST.getBytes("UTF-8")); + testSource(new StreamSource(is)); + } - @Test - public void testStreamSourceReader() throws Exception { - Reader reader = new StringReader(REQUEST); - testSource(new StreamSource(reader)); - } + @Test + public void testStreamSourceReader() throws Exception { + Reader reader = new StringReader(REQUEST); + testSource(new StreamSource(reader)); + } - protected abstract void testSource(Source requestSource) throws Exception; + protected abstract void testSource(Source requestSource) throws Exception; } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractMessageEndpointTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractMessageEndpointTestCase.java index d314f867..928e4757 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractMessageEndpointTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractMessageEndpointTestCase.java @@ -33,47 +33,47 @@ import static org.junit.Assert.assertTrue; public abstract class AbstractMessageEndpointTestCase extends AbstractEndpointTestCase { - private MessageEndpoint endpoint; + private MessageEndpoint endpoint; - @Before - public void createEndpoint() throws Exception { - endpoint = createResponseEndpoint(); - } + @Before + public void createEndpoint() throws Exception { + endpoint = createResponseEndpoint(); + } - @Test - public void testNoResponse() throws Exception { - endpoint = createNoResponseEndpoint(); - StringSource requestSource = new StringSource(REQUEST); + @Test + public void testNoResponse() throws Exception { + endpoint = createNoResponseEndpoint(); + StringSource requestSource = new StringSource(REQUEST); - MessageContext context = - new DefaultMessageContext(new MockWebServiceMessage(requestSource), new MockWebServiceMessageFactory()); - endpoint.invoke(context); - assertFalse("Response message created", context.hasResponse()); - } + MessageContext context = + new DefaultMessageContext(new MockWebServiceMessage(requestSource), new MockWebServiceMessageFactory()); + endpoint.invoke(context); + assertFalse("Response message created", context.hasResponse()); + } - @Test - public void testNoRequestPayload() throws Exception { - endpoint = createNoRequestPayloadEndpoint(); + @Test + public void testNoRequestPayload() throws Exception { + endpoint = createNoRequestPayloadEndpoint(); - MessageContext context = new DefaultMessageContext(new MockWebServiceMessage((StringBuilder) null), - new MockWebServiceMessageFactory()); - endpoint.invoke(context); - assertFalse("Response message created", context.hasResponse()); - } + MessageContext context = new DefaultMessageContext(new MockWebServiceMessage((StringBuilder) null), + new MockWebServiceMessageFactory()); + endpoint.invoke(context); + assertFalse("Response message created", context.hasResponse()); + } - @Override - protected final void testSource(Source requestSource) throws Exception { - MessageContext context = - new DefaultMessageContext(new MockWebServiceMessage(requestSource), new MockWebServiceMessageFactory()); - endpoint.invoke(context); - assertTrue("No response message created", context.hasResponse()); - assertXMLEqual(RESPONSE, ((MockWebServiceMessage) context.getResponse()).getPayloadAsString()); - } + @Override + protected final void testSource(Source requestSource) throws Exception { + MessageContext context = + new DefaultMessageContext(new MockWebServiceMessage(requestSource), new MockWebServiceMessageFactory()); + endpoint.invoke(context); + assertTrue("No response message created", context.hasResponse()); + assertXMLEqual(RESPONSE, ((MockWebServiceMessage) context.getResponse()).getPayloadAsString()); + } - protected abstract MessageEndpoint createNoResponseEndpoint(); + protected abstract MessageEndpoint createNoResponseEndpoint(); - protected abstract MessageEndpoint createNoRequestPayloadEndpoint(); + protected abstract MessageEndpoint createNoRequestPayloadEndpoint(); - protected abstract MessageEndpoint createResponseEndpoint(); + protected abstract MessageEndpoint createResponseEndpoint(); } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractPayloadEndpointTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractPayloadEndpointTestCase.java index ff174729..2c98bb08 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractPayloadEndpointTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/AbstractPayloadEndpointTestCase.java @@ -32,43 +32,43 @@ import static org.junit.Assert.assertNull; public abstract class AbstractPayloadEndpointTestCase extends AbstractEndpointTestCase { - private PayloadEndpoint endpoint; + private PayloadEndpoint endpoint; - private Transformer transformer; + private Transformer transformer; - @Before - public void createEndpoint() throws Exception { - endpoint = createResponseEndpoint(); - transformer = TransformerFactory.newInstance().newTransformer(); - } + @Before + public void createEndpoint() throws Exception { + endpoint = createResponseEndpoint(); + transformer = TransformerFactory.newInstance().newTransformer(); + } - @Test - public void testNoResponse() throws Exception { - endpoint = createNoResponseEndpoint(); - StringSource requestSource = new StringSource(REQUEST); - Source resultSource = endpoint.invoke(requestSource); - assertNull("Response source returned", resultSource); - } + @Test + public void testNoResponse() throws Exception { + endpoint = createNoResponseEndpoint(); + StringSource requestSource = new StringSource(REQUEST); + Source resultSource = endpoint.invoke(requestSource); + assertNull("Response source returned", resultSource); + } - @Test - public void testNoRequest() throws Exception { - endpoint = createNoRequestEndpoint(); - Source resultSource = endpoint.invoke(null); - assertNull("Response source returned", resultSource); - } + @Test + public void testNoRequest() throws Exception { + endpoint = createNoRequestEndpoint(); + Source resultSource = endpoint.invoke(null); + assertNull("Response source returned", resultSource); + } - @Override - protected final void testSource(Source requestSource) throws Exception { - Source responseSource = endpoint.invoke(requestSource); - assertNotNull("No response source returned", responseSource); - StringResult result = new StringResult(); - transformer.transform(responseSource, result); - assertXMLEqual(RESPONSE, result.toString()); - } + @Override + protected final void testSource(Source requestSource) throws Exception { + Source responseSource = endpoint.invoke(requestSource); + assertNotNull("No response source returned", responseSource); + StringResult result = new StringResult(); + transformer.transform(responseSource, result); + assertXMLEqual(RESPONSE, result.toString()); + } - protected abstract PayloadEndpoint createNoResponseEndpoint() throws Exception; + protected abstract PayloadEndpoint createNoResponseEndpoint() throws Exception; - protected abstract PayloadEndpoint createResponseEndpoint() throws Exception; + protected abstract PayloadEndpoint createResponseEndpoint() throws Exception; - protected abstract PayloadEndpoint createNoRequestEndpoint() throws Exception; + protected abstract PayloadEndpoint createNoRequestEndpoint() throws Exception; } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/Dom4jPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/Dom4jPayloadEndpointTest.java index b858de53..2c0d8d18 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/Dom4jPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/Dom4jPayloadEndpointTest.java @@ -23,43 +23,43 @@ import static org.junit.Assert.*; public class Dom4jPayloadEndpointTest extends AbstractPayloadEndpointTestCase { - @Override - protected PayloadEndpoint createResponseEndpoint() { - return new AbstractDom4jPayloadEndpoint() { + @Override + protected PayloadEndpoint createResponseEndpoint() { + return new AbstractDom4jPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { - assertNotNull("No requestElement passed", requestElement); - assertNotNull("No responseDocument passed", responseDocument); - assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getName()); - assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); - return responseDocument.addElement(RESPONSE_ELEMENT, NAMESPACE_URI); - } - }; - } + @Override + protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { + assertNotNull("No requestElement passed", requestElement); + assertNotNull("No responseDocument passed", responseDocument); + assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getName()); + assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); + return responseDocument.addElement(RESPONSE_ELEMENT, NAMESPACE_URI); + } + }; + } - @Override - protected PayloadEndpoint createNoResponseEndpoint() throws Exception { - return new AbstractDom4jPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoResponseEndpoint() throws Exception { + return new AbstractDom4jPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { + return null; + } + }; + } - @Override - protected PayloadEndpoint createNoRequestEndpoint() throws Exception { - return new AbstractDom4jPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoRequestEndpoint() throws Exception { + return new AbstractDom4jPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { - assertNull("RequestElement passed", requestElement); - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { + assertNull("RequestElement passed", requestElement); + return null; + } + }; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/DomPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/DomPayloadEndpointTest.java index 3bc9163a..1185e732 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/DomPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/DomPayloadEndpointTest.java @@ -23,41 +23,41 @@ import static org.junit.Assert.*; public class DomPayloadEndpointTest extends AbstractPayloadEndpointTestCase { - @Override - protected PayloadEndpoint createNoResponseEndpoint() throws Exception { - return new AbstractDomPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoResponseEndpoint() throws Exception { + return new AbstractDomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement, Document document) throws Exception { - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement, Document document) throws Exception { + return null; + } + }; + } - @Override - protected PayloadEndpoint createResponseEndpoint() throws Exception { - return new AbstractDomPayloadEndpoint() { + @Override + protected PayloadEndpoint createResponseEndpoint() throws Exception { + return new AbstractDomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { - assertNotNull("No requestElement passed", requestElement); - assertNotNull("No responseDocument passed", responseDocument); - assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getLocalName()); - assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); - return responseDocument.createElementNS(NAMESPACE_URI, RESPONSE_ELEMENT); - } - }; - } + @Override + protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { + assertNotNull("No requestElement passed", requestElement); + assertNotNull("No responseDocument passed", responseDocument); + assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getLocalName()); + assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); + return responseDocument.createElementNS(NAMESPACE_URI, RESPONSE_ELEMENT); + } + }; + } - @Override - protected PayloadEndpoint createNoRequestEndpoint() throws Exception { - return new AbstractDomPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoRequestEndpoint() throws Exception { + return new AbstractDomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { - assertNull("RequestElement passed", requestElement); - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement, Document responseDocument) throws Exception { + assertNull("RequestElement passed", requestElement); + return null; + } + }; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/EndpointExceptionResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/EndpointExceptionResolverTest.java index 54533843..e428423a 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/EndpointExceptionResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/EndpointExceptionResolverTest.java @@ -32,30 +32,30 @@ import org.junit.Test; */ public class EndpointExceptionResolverTest { - private MethodEndpoint methodEndpoint; + private MethodEndpoint methodEndpoint; - private AbstractEndpointExceptionResolver exceptionResolver; + private AbstractEndpointExceptionResolver exceptionResolver; - @Before - public void setUp() throws Exception { - exceptionResolver = new AbstractEndpointExceptionResolver() { + @Before + public void setUp() throws Exception { + exceptionResolver = new AbstractEndpointExceptionResolver() { - @Override - protected boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) { - return true; - } - }; + @Override + protected boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) { + return true; + } + }; - exceptionResolver.setMappedEndpoints(Collections.singleton(this)); - methodEndpoint = new MethodEndpoint(this, getClass().getMethod("emptyMethod", new Class[0])); - } + exceptionResolver.setMappedEndpoints(Collections.singleton(this)); + methodEndpoint = new MethodEndpoint(this, getClass().getMethod("emptyMethod", new Class[0])); + } - @Test - public void testMatchMethodEndpoint() { - boolean matched = exceptionResolver.resolveException(null, methodEndpoint, null); - Assert.assertTrue("AbstractEndpointExceptionResolver did not match mapped MethodEndpoint", matched); - } + @Test + public void testMatchMethodEndpoint() { + boolean matched = exceptionResolver.resolveException(null, methodEndpoint, null); + Assert.assertTrue("AbstractEndpointExceptionResolver did not match mapped MethodEndpoint", matched); + } - public void emptyMethod() { - } + public void emptyMethod() { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/JDomPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/JDomPayloadEndpointTest.java index 79dee8e2..4d2c05f1 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/JDomPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/JDomPayloadEndpointTest.java @@ -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, @@ -23,40 +23,40 @@ import static org.junit.Assert.*; public class JDomPayloadEndpointTest extends AbstractPayloadEndpointTestCase { - @Override - protected PayloadEndpoint createNoResponseEndpoint() throws Exception { - return new AbstractJDomPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoResponseEndpoint() throws Exception { + return new AbstractJDomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement) throws Exception { - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement) throws Exception { + return null; + } + }; + } - @Override - protected PayloadEndpoint createResponseEndpoint() throws Exception { - return new AbstractJDomPayloadEndpoint() { + @Override + protected PayloadEndpoint createResponseEndpoint() throws Exception { + return new AbstractJDomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement) throws Exception { - assertNotNull("No requestElement passed", requestElement); - assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getName()); - assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); - return new Element(RESPONSE_ELEMENT, Namespace.getNamespace("tns", NAMESPACE_URI)); - } - }; - } + @Override + protected Element invokeInternal(Element requestElement) throws Exception { + assertNotNull("No requestElement passed", requestElement); + assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getName()); + assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); + return new Element(RESPONSE_ELEMENT, Namespace.getNamespace("tns", NAMESPACE_URI)); + } + }; + } - @Override - protected PayloadEndpoint createNoRequestEndpoint() throws Exception { - return new AbstractJDomPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoRequestEndpoint() throws Exception { + return new AbstractJDomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement) throws Exception { - assertNull("RequestElement passed", requestElement); - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement) throws Exception { + assertNull("RequestElement passed", requestElement); + return null; + } + }; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MarshallingPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MarshallingPayloadEndpointTest.java index eb7f7896..1649f6f2 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MarshallingPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MarshallingPayloadEndpointTest.java @@ -50,184 +50,184 @@ import org.springframework.xml.transform.StringSource; public class MarshallingPayloadEndpointTest { - private Transformer transformer; + private Transformer transformer; - private MessageContext context; + private MessageContext context; - private WebServiceMessageFactory factoryMock; + private WebServiceMessageFactory factoryMock; - @Before - public void setUp() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - transformer = TransformerFactory.newInstance().newTransformer(); - factoryMock = createMock(WebServiceMessageFactory.class); + @Before + public void setUp() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + transformer = TransformerFactory.newInstance().newTransformer(); + factoryMock = createMock(WebServiceMessageFactory.class); - context = new DefaultMessageContext(request, factoryMock); - } + context = new DefaultMessageContext(request, factoryMock); + } - @Test - public void testInvoke() throws Exception { - Unmarshaller unmarshaller = new SimpleMarshaller() { - @Override - public Object unmarshal(Source source) throws XmlMappingException { - try { - StringWriter writer = new StringWriter(); - transformer.transform(source, new StreamResult(writer)); - assertXMLEqual("Invalid source", "", writer.toString()); - return 42L; - } - catch (Exception e) { - Assert.fail(e.getMessage()); - return null; - } - } - }; - Marshaller marshaller = new SimpleMarshaller() { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException { - Assert.assertEquals("Invalid graph", "result", graph); - try { - transformer.transform(new StreamSource(new StringReader("")), result); - } - catch (TransformerException e) { - Assert.fail(e.getMessage()); - } - } - }; - AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { - @Override - protected Object invokeInternal(Object requestObject) throws Exception { - Assert.assertEquals("Invalid request object", 42L, requestObject); - return "result"; - } - }; - endpoint.setMarshaller(marshaller); - endpoint.setUnmarshaller(unmarshaller); - endpoint.afterPropertiesSet(); + @Test + public void testInvoke() throws Exception { + Unmarshaller unmarshaller = new SimpleMarshaller() { + @Override + public Object unmarshal(Source source) throws XmlMappingException { + try { + StringWriter writer = new StringWriter(); + transformer.transform(source, new StreamResult(writer)); + assertXMLEqual("Invalid source", "", writer.toString()); + return 42L; + } + catch (Exception e) { + Assert.fail(e.getMessage()); + return null; + } + } + }; + Marshaller marshaller = new SimpleMarshaller() { + @Override + public void marshal(Object graph, Result result) throws XmlMappingException { + Assert.assertEquals("Invalid graph", "result", graph); + try { + transformer.transform(new StreamSource(new StringReader("")), result); + } + catch (TransformerException e) { + Assert.fail(e.getMessage()); + } + } + }; + AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { + @Override + protected Object invokeInternal(Object requestObject) throws Exception { + Assert.assertEquals("Invalid request object", 42L, requestObject); + return "result"; + } + }; + endpoint.setMarshaller(marshaller); + endpoint.setUnmarshaller(unmarshaller); + endpoint.afterPropertiesSet(); - expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); + expect(factoryMock.createWebServiceMessage()).andReturn(new MockWebServiceMessage()); - replay(factoryMock); + replay(factoryMock); - endpoint.invoke(context); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - Assert.assertNotNull("Invalid result", response); - assertXMLEqual("Invalid response", "", response.getPayloadAsString()); + endpoint.invoke(context); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + Assert.assertNotNull("Invalid result", response); + assertXMLEqual("Invalid response", "", response.getPayloadAsString()); - verify(factoryMock); - } + verify(factoryMock); + } - @Test - public void testInvokeNullResponse() throws Exception { - Unmarshaller unmarshaller = new SimpleMarshaller() { - @Override - public Object unmarshal(Source source) throws XmlMappingException { - try { - StringWriter writer = new StringWriter(); - transformer.transform(source, new StreamResult(writer)); - assertXMLEqual("Invalid source", "", writer.toString()); - return (long) 42; - } - catch (Exception e) { - Assert.fail(e.getMessage()); - return null; - } - } - }; - Marshaller marshaller = new SimpleMarshaller() { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException { - Assert.fail("marshal not expected"); - } - }; - AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { - @Override - protected Object invokeInternal(Object requestObject) throws Exception { - Assert.assertEquals("Invalid request object", (long) 42, requestObject); - return null; - } - }; - endpoint.setMarshaller(marshaller); - endpoint.setUnmarshaller(unmarshaller); - endpoint.afterPropertiesSet(); - replay(factoryMock); - endpoint.invoke(context); - Assert.assertFalse("Response created", context.hasResponse()); - verify(factoryMock); - } + @Test + public void testInvokeNullResponse() throws Exception { + Unmarshaller unmarshaller = new SimpleMarshaller() { + @Override + public Object unmarshal(Source source) throws XmlMappingException { + try { + StringWriter writer = new StringWriter(); + transformer.transform(source, new StreamResult(writer)); + assertXMLEqual("Invalid source", "", writer.toString()); + return (long) 42; + } + catch (Exception e) { + Assert.fail(e.getMessage()); + return null; + } + } + }; + Marshaller marshaller = new SimpleMarshaller() { + @Override + public void marshal(Object graph, Result result) throws XmlMappingException { + Assert.fail("marshal not expected"); + } + }; + AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { + @Override + protected Object invokeInternal(Object requestObject) throws Exception { + Assert.assertEquals("Invalid request object", (long) 42, requestObject); + return null; + } + }; + endpoint.setMarshaller(marshaller); + endpoint.setUnmarshaller(unmarshaller); + endpoint.afterPropertiesSet(); + replay(factoryMock); + endpoint.invoke(context); + Assert.assertFalse("Response created", context.hasResponse()); + verify(factoryMock); + } - @Test - public void testInvokeNoRequest() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage((StringBuilder) null); - context = new DefaultMessageContext(request, factoryMock); - AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { + @Test + public void testInvokeNoRequest() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage((StringBuilder) null); + context = new DefaultMessageContext(request, factoryMock); + AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { - @Override - protected Object invokeInternal(Object requestObject) throws Exception { - Assert.assertNull("No request expected", requestObject); - return null; - } - }; - endpoint.setMarshaller(new SimpleMarshaller()); - endpoint.setUnmarshaller(new SimpleMarshaller()); - endpoint.afterPropertiesSet(); - replay(factoryMock); - endpoint.invoke(context); - Assert.assertFalse("Response created", context.hasResponse()); - verify(factoryMock); - } + @Override + protected Object invokeInternal(Object requestObject) throws Exception { + Assert.assertNull("No request expected", requestObject); + return null; + } + }; + endpoint.setMarshaller(new SimpleMarshaller()); + endpoint.setUnmarshaller(new SimpleMarshaller()); + endpoint.afterPropertiesSet(); + replay(factoryMock); + endpoint.invoke(context); + Assert.assertFalse("Response created", context.hasResponse()); + verify(factoryMock); + } - @Test - public void testInvokeMimeMarshaller() throws Exception { - MimeUnmarshaller unmarshaller = createMock(MimeUnmarshaller.class); - MimeMarshaller marshaller = createMock(MimeMarshaller.class); - MimeMessage request = createMock("request", MimeMessage.class); - MimeMessage response = createMock("response", MimeMessage.class); - Source requestSource = new StringSource(""); - expect(request.getPayloadSource()).andReturn(requestSource); - expect(factoryMock.createWebServiceMessage()).andReturn(response); - expect(unmarshaller.unmarshal(eq(requestSource), isA(MimeContainer.class))).andReturn(42L); - Result responseResult = new StringResult(); - expect(response.getPayloadResult()).andReturn(responseResult); - marshaller.marshal(eq("result"), eq(responseResult), isA(MimeContainer.class)); + @Test + public void testInvokeMimeMarshaller() throws Exception { + MimeUnmarshaller unmarshaller = createMock(MimeUnmarshaller.class); + MimeMarshaller marshaller = createMock(MimeMarshaller.class); + MimeMessage request = createMock("request", MimeMessage.class); + MimeMessage response = createMock("response", MimeMessage.class); + Source requestSource = new StringSource(""); + expect(request.getPayloadSource()).andReturn(requestSource); + expect(factoryMock.createWebServiceMessage()).andReturn(response); + expect(unmarshaller.unmarshal(eq(requestSource), isA(MimeContainer.class))).andReturn(42L); + Result responseResult = new StringResult(); + expect(response.getPayloadResult()).andReturn(responseResult); + marshaller.marshal(eq("result"), eq(responseResult), isA(MimeContainer.class)); - replay(factoryMock, unmarshaller, marshaller, request, response); + replay(factoryMock, unmarshaller, marshaller, request, response); - AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { - @Override - protected Object invokeInternal(Object requestObject) throws Exception { - Assert.assertEquals("Invalid request object", 42L, requestObject); - return "result"; - } - }; - endpoint.setMarshaller(marshaller); - endpoint.setUnmarshaller(unmarshaller); - endpoint.afterPropertiesSet(); + AbstractMarshallingPayloadEndpoint endpoint = new AbstractMarshallingPayloadEndpoint() { + @Override + protected Object invokeInternal(Object requestObject) throws Exception { + Assert.assertEquals("Invalid request object", 42L, requestObject); + return "result"; + } + }; + endpoint.setMarshaller(marshaller); + endpoint.setUnmarshaller(unmarshaller); + endpoint.afterPropertiesSet(); - context = new DefaultMessageContext(request, factoryMock); - endpoint.invoke(context); - Assert.assertNotNull("Invalid result", response); + context = new DefaultMessageContext(request, factoryMock); + endpoint.invoke(context); + Assert.assertNotNull("Invalid result", response); - verify(factoryMock, unmarshaller, marshaller, request, response); - } + verify(factoryMock, unmarshaller, marshaller, request, response); + } - private static class SimpleMarshaller implements Marshaller, Unmarshaller { + private static class SimpleMarshaller implements Marshaller, Unmarshaller { - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - fail("Not expected"); - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + fail("Not expected"); + } - @Override - public Object unmarshal(Source source) throws XmlMappingException, IOException { - fail("Not expected"); - return null; - } + @Override + public Object unmarshal(Source source) throws XmlMappingException, IOException { + fail("Not expected"); + return null; + } - @Override - public boolean supports(Class clazz) { - return false; - } - } + @Override + public boolean supports(Class clazz) { + return false; + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MethodEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MethodEndpointTest.java index 29e47ad9..55f8cd6b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MethodEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/MethodEndpointTest.java @@ -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, @@ -24,54 +24,54 @@ import org.junit.Test; public class MethodEndpointTest { - private MethodEndpoint endpoint; + private MethodEndpoint endpoint; - private boolean myMethodInvoked; + private boolean myMethodInvoked; - private Method method; + private Method method; - @Before - public void setUp() throws Exception { - myMethodInvoked = false; - method = getClass().getMethod("myMethod", String.class); - endpoint = new MethodEndpoint(this, method); - } + @Before + public void setUp() throws Exception { + myMethodInvoked = false; + method = getClass().getMethod("myMethod", String.class); + endpoint = new MethodEndpoint(this, method); + } - @Test - public void testGetters() throws Exception { - Assert.assertEquals("Invalid bean", this, endpoint.getBean()); - Assert.assertEquals("Invalid bean", method, endpoint.getMethod()); - } + @Test + public void testGetters() throws Exception { + Assert.assertEquals("Invalid bean", this, endpoint.getBean()); + Assert.assertEquals("Invalid bean", method, endpoint.getMethod()); + } - @Test - public void testInvoke() throws Exception { - Assert.assertFalse("Method invoked before invocation", myMethodInvoked); - endpoint.invoke("arg"); - Assert.assertTrue("Method invoked before invocation", myMethodInvoked); - } + @Test + public void testInvoke() throws Exception { + Assert.assertFalse("Method invoked before invocation", myMethodInvoked); + endpoint.invoke("arg"); + Assert.assertTrue("Method invoked before invocation", myMethodInvoked); + } - @Test - public void testEquals() throws Exception { - Assert.assertEquals("Not equal", endpoint, endpoint); - Assert.assertEquals("Not equal", new MethodEndpoint(this, method), endpoint); - Method otherMethod = getClass().getMethod("testEquals"); - Assert.assertFalse("Equal", new MethodEndpoint(this, otherMethod).equals(endpoint)); - } + @Test + public void testEquals() throws Exception { + Assert.assertEquals("Not equal", endpoint, endpoint); + Assert.assertEquals("Not equal", new MethodEndpoint(this, method), endpoint); + Method otherMethod = getClass().getMethod("testEquals"); + Assert.assertFalse("Equal", new MethodEndpoint(this, otherMethod).equals(endpoint)); + } - @Test - public void testHashCode() throws Exception { - Assert.assertEquals("Not equal", new MethodEndpoint(this, method).hashCode(), endpoint.hashCode()); - Method otherMethod = getClass().getMethod("testEquals"); - Assert.assertFalse("Equal", new MethodEndpoint(this, otherMethod).hashCode() == endpoint.hashCode()); - } + @Test + public void testHashCode() throws Exception { + Assert.assertEquals("Not equal", new MethodEndpoint(this, method).hashCode(), endpoint.hashCode()); + Method otherMethod = getClass().getMethod("testEquals"); + Assert.assertFalse("Equal", new MethodEndpoint(this, otherMethod).hashCode() == endpoint.hashCode()); + } - @Test - public void testToString() throws Exception { - Assert.assertNotNull("No valid toString", endpoint.toString()); - } + @Test + public void testToString() throws Exception { + Assert.assertNotNull("No valid toString", endpoint.toString()); + } - public void myMethod(String arg) { - Assert.assertEquals("Invalid argument", "arg", arg); - myMethodInvoked = true; - } + public void myMethod(String arg) { + Assert.assertEquals("Invalid argument", "arg", arg); + myMethodInvoked = true; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/SaxPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/SaxPayloadEndpointTest.java index 3af7e161..40ea9245 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/SaxPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/SaxPayloadEndpointTest.java @@ -30,70 +30,70 @@ import static org.junit.Assert.fail; public class SaxPayloadEndpointTest extends AbstractPayloadEndpointTestCase { - @Override - protected PayloadEndpoint createNoResponseEndpoint() throws Exception { - return new AbstractSaxPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoResponseEndpoint() throws Exception { + return new AbstractSaxPayloadEndpoint() { - @Override - protected Source getResponse(ContentHandler contentHandler) { - return null; - } + @Override + protected Source getResponse(ContentHandler contentHandler) { + return null; + } - @Override - protected ContentHandler createContentHandler() { - return new DefaultHandler(); - } - }; - } + @Override + protected ContentHandler createContentHandler() { + return new DefaultHandler(); + } + }; + } - @Override - protected PayloadEndpoint createResponseEndpoint() throws Exception { - return new AbstractSaxPayloadEndpoint() { + @Override + protected PayloadEndpoint createResponseEndpoint() throws Exception { + return new AbstractSaxPayloadEndpoint() { - @Override - protected ContentHandler createContentHandler() { - return new TestContentHandler(); - } + @Override + protected ContentHandler createContentHandler() { + return new TestContentHandler(); + } - @Override - protected Source getResponse(ContentHandler contentHandler) { - return new StringSource(RESPONSE); - } - }; - } + @Override + protected Source getResponse(ContentHandler contentHandler) { + return new StringSource(RESPONSE); + } + }; + } - @Override - protected PayloadEndpoint createNoRequestEndpoint() throws Exception { - return new AbstractSaxPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoRequestEndpoint() throws Exception { + return new AbstractSaxPayloadEndpoint() { - @Override - protected ContentHandler createContentHandler() throws Exception { - fail("Not expected"); - return null; - } + @Override + protected ContentHandler createContentHandler() throws Exception { + fail("Not expected"); + return null; + } - @Override - protected Source getResponse(ContentHandler contentHandler) throws Exception { - return null; - } - }; - } + @Override + protected Source getResponse(ContentHandler contentHandler) throws Exception { + return null; + } + }; + } - private static class TestContentHandler extends DefaultHandler { + private static class TestContentHandler extends DefaultHandler { - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - assertEquals("Invalid local name", REQUEST_ELEMENT, localName); - assertEquals("Invalid qName", REQUEST_ELEMENT, localName); - assertEquals("Invalid namespace", NAMESPACE_URI, uri); - } + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + assertEquals("Invalid local name", REQUEST_ELEMENT, localName); + assertEquals("Invalid qName", REQUEST_ELEMENT, localName); + assertEquals("Invalid namespace", NAMESPACE_URI, uri); + } - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) - throws SAXException { - assertEquals("Invalid local name", REQUEST_ELEMENT, localName); - assertEquals("Invalid qName", REQUEST_ELEMENT, localName); - assertEquals("Invalid namespace", NAMESPACE_URI, uri); - } - } + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) + throws SAXException { + assertEquals("Invalid local name", REQUEST_ELEMENT, localName); + assertEquals("Invalid qName", REQUEST_ELEMENT, localName); + assertEquals("Invalid namespace", NAMESPACE_URI, uri); + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxEventPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxEventPayloadEndpointTest.java index 96158954..df2667e7 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxEventPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxEventPayloadEndpointTest.java @@ -35,67 +35,67 @@ import static org.junit.Assert.*; @SuppressWarnings("Since15") public class StaxEventPayloadEndpointTest extends AbstractMessageEndpointTestCase { - @Override - protected MessageEndpoint createNoResponseEndpoint() { - return new AbstractStaxEventPayloadEndpoint() { - @Override - protected void invokeInternal(XMLEventReader eventReader, - XMLEventConsumer eventWriter, - XMLEventFactory eventFactory) throws Exception { - assertNotNull("No EventReader passed", eventReader); - } - }; - } + @Override + protected MessageEndpoint createNoResponseEndpoint() { + return new AbstractStaxEventPayloadEndpoint() { + @Override + protected void invokeInternal(XMLEventReader eventReader, + XMLEventConsumer eventWriter, + XMLEventFactory eventFactory) throws Exception { + assertNotNull("No EventReader passed", eventReader); + } + }; + } - @Override - protected MessageEndpoint createNoRequestPayloadEndpoint() { - return new AbstractStaxEventPayloadEndpoint() { + @Override + protected MessageEndpoint createNoRequestPayloadEndpoint() { + return new AbstractStaxEventPayloadEndpoint() { - @Override - protected void invokeInternal(XMLEventReader eventReader, - XMLEventConsumer eventWriter, - XMLEventFactory eventFactory) throws Exception { - assertNull("EventReader passed", eventReader); - } - }; - } + @Override + protected void invokeInternal(XMLEventReader eventReader, + XMLEventConsumer eventWriter, + XMLEventFactory eventFactory) throws Exception { + assertNull("EventReader passed", eventReader); + } + }; + } - @Override - protected MessageEndpoint createResponseEndpoint() { - return new AbstractStaxEventPayloadEndpoint() { + @Override + protected MessageEndpoint createResponseEndpoint() { + return new AbstractStaxEventPayloadEndpoint() { - @Override - protected void invokeInternal(XMLEventReader eventReader, - XMLEventConsumer eventWriter, - XMLEventFactory eventFactory) throws XMLStreamException { - assertNotNull("eventReader not given", eventReader); - assertNotNull("eventWriter not given", eventWriter); - assertNotNull("eventFactory not given", eventFactory); - assertTrue("eventReader has not next element", eventReader.hasNext()); - XMLEvent event = eventReader.nextEvent(); - assertTrue("Not a start document", event.isStartDocument()); - event = eventReader.nextEvent(); - assertTrue("Not a start element", event.isStartElement()); - assertEquals("Invalid start event local name", REQUEST_ELEMENT, - event.asStartElement().getName().getLocalPart()); - assertEquals("Invalid start event namespace", NAMESPACE_URI, - event.asStartElement().getName().getNamespaceURI()); - assertTrue("eventReader has not next element", eventReader.hasNext()); - event = eventReader.nextEvent(); - assertTrue("Not a end element", event.isEndElement()); - assertEquals("Invalid end event local name", REQUEST_ELEMENT, - event.asEndElement().getName().getLocalPart()); - assertEquals("Invalid end event namespace", NAMESPACE_URI, - event.asEndElement().getName().getNamespaceURI()); - Namespace namespace = eventFactory.createNamespace(NAMESPACE_URI); - QName name = new QName(NAMESPACE_URI, RESPONSE_ELEMENT); - eventWriter - .add(eventFactory.createStartElement(name, null, Collections.singleton(namespace).iterator())); - eventWriter.add(eventFactory.createEndElement(name, Collections.singleton(namespace).iterator())); - eventWriter.add(eventFactory.createEndDocument()); - } - }; - } + @Override + protected void invokeInternal(XMLEventReader eventReader, + XMLEventConsumer eventWriter, + XMLEventFactory eventFactory) throws XMLStreamException { + assertNotNull("eventReader not given", eventReader); + assertNotNull("eventWriter not given", eventWriter); + assertNotNull("eventFactory not given", eventFactory); + assertTrue("eventReader has not next element", eventReader.hasNext()); + XMLEvent event = eventReader.nextEvent(); + assertTrue("Not a start document", event.isStartDocument()); + event = eventReader.nextEvent(); + assertTrue("Not a start element", event.isStartElement()); + assertEquals("Invalid start event local name", REQUEST_ELEMENT, + event.asStartElement().getName().getLocalPart()); + assertEquals("Invalid start event namespace", NAMESPACE_URI, + event.asStartElement().getName().getNamespaceURI()); + assertTrue("eventReader has not next element", eventReader.hasNext()); + event = eventReader.nextEvent(); + assertTrue("Not a end element", event.isEndElement()); + assertEquals("Invalid end event local name", REQUEST_ELEMENT, + event.asEndElement().getName().getLocalPart()); + assertEquals("Invalid end event namespace", NAMESPACE_URI, + event.asEndElement().getName().getNamespaceURI()); + Namespace namespace = eventFactory.createNamespace(NAMESPACE_URI); + QName name = new QName(NAMESPACE_URI, RESPONSE_ELEMENT); + eventWriter + .add(eventFactory.createStartElement(name, null, Collections.singleton(namespace).iterator())); + eventWriter.add(eventFactory.createEndElement(name, Collections.singleton(namespace).iterator())); + eventWriter.add(eventFactory.createEndDocument()); + } + }; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxStreamPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxStreamPayloadEndpointTest.java index 2b436584..45b9ce78 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxStreamPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/StaxStreamPayloadEndpointTest.java @@ -48,143 +48,143 @@ import static org.junit.Assert.*; @SuppressWarnings("Since15") public class StaxStreamPayloadEndpointTest extends AbstractMessageEndpointTestCase { - @Override - protected MessageEndpoint createNoResponseEndpoint() { - return new AbstractStaxStreamPayloadEndpoint() { - @Override - protected void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception { - assertNotNull("No StreamReader passed", streamReader); - } - }; - } + @Override + protected MessageEndpoint createNoResponseEndpoint() { + return new AbstractStaxStreamPayloadEndpoint() { + @Override + protected void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception { + assertNotNull("No StreamReader passed", streamReader); + } + }; + } - @Override - protected MessageEndpoint createNoRequestPayloadEndpoint() { - return new AbstractStaxStreamPayloadEndpoint() { - @Override - protected void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception { - assertNull("StreamReader passed", streamReader); - } - }; - } + @Override + protected MessageEndpoint createNoRequestPayloadEndpoint() { + return new AbstractStaxStreamPayloadEndpoint() { + @Override + protected void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception { + assertNull("StreamReader passed", streamReader); + } + }; + } - @Override - protected MessageEndpoint createResponseEndpoint() { - return new AbstractStaxStreamPayloadEndpoint() { - @Override - protected void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception { - assertNotNull("No streamReader passed", streamReader); - assertNotNull("No streamWriter passed", streamReader); - assertEquals("Not a start element", XMLStreamConstants.START_ELEMENT, streamReader.next()); - assertEquals("Invalid start event local name", REQUEST_ELEMENT, streamReader.getLocalName()); - assertEquals("Invalid start event namespace", NAMESPACE_URI, streamReader.getNamespaceURI()); - assertTrue("streamReader has no next element", streamReader.hasNext()); - assertEquals("Not a end element", XMLStreamConstants.END_ELEMENT, streamReader.next()); - assertEquals("Invalid end event local name", REQUEST_ELEMENT, streamReader.getLocalName()); - assertEquals("Invalid end event namespace", NAMESPACE_URI, streamReader.getNamespaceURI()); - streamWriter.setDefaultNamespace(NAMESPACE_URI); - streamWriter.writeStartElement(NAMESPACE_URI, RESPONSE_ELEMENT); - streamWriter.writeDefaultNamespace(NAMESPACE_URI); - streamWriter.writeEndElement(); - streamWriter.flush(); - streamWriter.close(); - } + @Override + protected MessageEndpoint createResponseEndpoint() { + return new AbstractStaxStreamPayloadEndpoint() { + @Override + protected void invokeInternal(XMLStreamReader streamReader, XMLStreamWriter streamWriter) throws Exception { + assertNotNull("No streamReader passed", streamReader); + assertNotNull("No streamWriter passed", streamReader); + assertEquals("Not a start element", XMLStreamConstants.START_ELEMENT, streamReader.next()); + assertEquals("Invalid start event local name", REQUEST_ELEMENT, streamReader.getLocalName()); + assertEquals("Invalid start event namespace", NAMESPACE_URI, streamReader.getNamespaceURI()); + assertTrue("streamReader has no next element", streamReader.hasNext()); + assertEquals("Not a end element", XMLStreamConstants.END_ELEMENT, streamReader.next()); + assertEquals("Invalid end event local name", REQUEST_ELEMENT, streamReader.getLocalName()); + assertEquals("Invalid end event namespace", NAMESPACE_URI, streamReader.getNamespaceURI()); + streamWriter.setDefaultNamespace(NAMESPACE_URI); + streamWriter.writeStartElement(NAMESPACE_URI, RESPONSE_ELEMENT); + streamWriter.writeDefaultNamespace(NAMESPACE_URI); + streamWriter.writeEndElement(); + streamWriter.flush(); + streamWriter.close(); + } - @Override - protected XMLOutputFactory createXmlOutputFactory() { - XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); - outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE); - return outputFactory; - } - }; - } + @Override + protected XMLOutputFactory createXmlOutputFactory() { + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE); + return outputFactory; + } + }; + } - @Test - public void testSaajResponse() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - MessageFactory messageFactory = MessageFactory.newInstance(); - SaajSoapMessage request = new SaajSoapMessage(messageFactory.createMessage()); - transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); - SaajSoapMessageFactory soapMessageFactory = new SaajSoapMessageFactory(); - soapMessageFactory.afterPropertiesSet(); - MessageContext context = new DefaultMessageContext(request, soapMessageFactory); + @Test + public void testSaajResponse() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + MessageFactory messageFactory = MessageFactory.newInstance(); + SaajSoapMessage request = new SaajSoapMessage(messageFactory.createMessage()); + transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); + SaajSoapMessageFactory soapMessageFactory = new SaajSoapMessageFactory(); + soapMessageFactory.afterPropertiesSet(); + MessageContext context = new DefaultMessageContext(request, soapMessageFactory); - MessageEndpoint endpoint = createResponseEndpoint(); - endpoint.invoke(context); - assertTrue("context has not response", context.hasResponse()); - StringResult stringResult = new StringResult(); - transformer.transform(context.getResponse().getPayloadSource(), stringResult); - assertXMLEqual(RESPONSE, stringResult.toString()); - } + MessageEndpoint endpoint = createResponseEndpoint(); + endpoint.invoke(context); + assertTrue("context has not response", context.hasResponse()); + StringResult stringResult = new StringResult(); + transformer.transform(context.getResponse().getPayloadSource(), stringResult); + assertXMLEqual(RESPONSE, stringResult.toString()); + } - @Test - public void testAxiomResponse() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); - transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); - AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); - soapMessageFactory.afterPropertiesSet(); - MessageContext context = new DefaultMessageContext(request, soapMessageFactory); + @Test + public void testAxiomResponse() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); + transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); + AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); + soapMessageFactory.afterPropertiesSet(); + MessageContext context = new DefaultMessageContext(request, soapMessageFactory); - MessageEndpoint endpoint = createResponseEndpoint(); - endpoint.invoke(context); - assertTrue("context has not response", context.hasResponse()); - StringResult stringResult = new StringResult(); - transformer.transform(context.getResponse().getPayloadSource(), stringResult); - assertXMLEqual(RESPONSE, stringResult.toString()); - } + MessageEndpoint endpoint = createResponseEndpoint(); + endpoint.invoke(context); + assertTrue("context has not response", context.hasResponse()); + StringResult stringResult = new StringResult(); + transformer.transform(context.getResponse().getPayloadSource(), stringResult); + assertXMLEqual(RESPONSE, stringResult.toString()); + } - @Test - public void testAxiomNoResponse() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); - transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); - AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); - soapMessageFactory.afterPropertiesSet(); - MessageContext context = new DefaultMessageContext(request, soapMessageFactory); + @Test + public void testAxiomNoResponse() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); + transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); + AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); + soapMessageFactory.afterPropertiesSet(); + MessageContext context = new DefaultMessageContext(request, soapMessageFactory); - MessageEndpoint endpoint = createNoResponseEndpoint(); - endpoint.invoke(context); - assertFalse("context has response", context.hasResponse()); - } + MessageEndpoint endpoint = createNoResponseEndpoint(); + endpoint.invoke(context); + assertFalse("context has response", context.hasResponse()); + } - @Test - public void testAxiomResponseNoPayloadCaching() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); - transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); - AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); - soapMessageFactory.setPayloadCaching(false); - soapMessageFactory.afterPropertiesSet(); - MessageContext context = new DefaultMessageContext(request, soapMessageFactory); + @Test + public void testAxiomResponseNoPayloadCaching() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); + transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); + AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); + soapMessageFactory.setPayloadCaching(false); + soapMessageFactory.afterPropertiesSet(); + MessageContext context = new DefaultMessageContext(request, soapMessageFactory); - MessageEndpoint endpoint = createResponseEndpoint(); - endpoint.invoke(context); - assertTrue("context has not response", context.hasResponse()); + MessageEndpoint endpoint = createResponseEndpoint(); + endpoint.invoke(context); + assertTrue("context has not response", context.hasResponse()); - StringResult stringResult = new StringResult(); - transformer.transform(context.getResponse().getPayloadSource(), stringResult); - assertXMLEqual(RESPONSE, stringResult.toString()); - } + StringResult stringResult = new StringResult(); + transformer.transform(context.getResponse().getPayloadSource(), stringResult); + assertXMLEqual(RESPONSE, stringResult.toString()); + } - @Test - public void testAxiomNoResponseNoPayloadCaching() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); - transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); - AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); - soapMessageFactory.setPayloadCaching(false); - soapMessageFactory.afterPropertiesSet(); - MessageContext context = new DefaultMessageContext(request, soapMessageFactory); + @Test + public void testAxiomNoResponseNoPayloadCaching() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory); + transformer.transform(new StringSource(REQUEST), request.getPayloadResult()); + AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); + soapMessageFactory.setPayloadCaching(false); + soapMessageFactory.afterPropertiesSet(); + MessageContext context = new DefaultMessageContext(request, soapMessageFactory); - MessageEndpoint endpoint = createNoResponseEndpoint(); - endpoint.invoke(context); - assertFalse("context has response", context.hasResponse()); - } + MessageEndpoint endpoint = createNoResponseEndpoint(); + endpoint.invoke(context); + assertFalse("context has response", context.hasResponse()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/XomPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/XomPayloadEndpointTest.java index 8e79df8e..74bbe61c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/XomPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/XomPayloadEndpointTest.java @@ -22,51 +22,51 @@ import static org.junit.Assert.*; public class XomPayloadEndpointTest extends AbstractPayloadEndpointTestCase { - @Override - protected PayloadEndpoint createNoResponseEndpoint() throws Exception { - return new AbstractXomPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoResponseEndpoint() throws Exception { + return new AbstractXomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement) throws Exception { - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement) throws Exception { + return null; + } + }; + } - @Override - protected PayloadEndpoint createResponseEndpoint() throws Exception { - return new AbstractXomPayloadEndpoint() { + @Override + protected PayloadEndpoint createResponseEndpoint() throws Exception { + return new AbstractXomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement) throws Exception { - assertNotNull("No requestElement passed", requestElement); - assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getLocalName()); - assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); - return new Element(RESPONSE_ELEMENT, NAMESPACE_URI); - } - }; - } + @Override + protected Element invokeInternal(Element requestElement) throws Exception { + assertNotNull("No requestElement passed", requestElement); + assertEquals("Invalid request element", REQUEST_ELEMENT, requestElement.getLocalName()); + assertEquals("Invalid request element", NAMESPACE_URI, requestElement.getNamespaceURI()); + return new Element(RESPONSE_ELEMENT, NAMESPACE_URI); + } + }; + } - @Override - protected PayloadEndpoint createNoRequestEndpoint() throws Exception { - return new AbstractXomPayloadEndpoint() { + @Override + protected PayloadEndpoint createNoRequestEndpoint() throws Exception { + return new AbstractXomPayloadEndpoint() { - @Override - protected Element invokeInternal(Element requestElement) throws Exception { - assertNull("RequestElement passed", requestElement); - return null; - } - }; - } + @Override + protected Element invokeInternal(Element requestElement) throws Exception { + assertNull("RequestElement passed", requestElement); + return null; + } + }; + } - @Override - public void testStaxSourceEventReader() throws Exception { - // overriden, because XOM doesn't not support it - } + @Override + public void testStaxSourceEventReader() throws Exception { + // overriden, because XOM doesn't not support it + } - @Override - public void testStaxSourceStreamReader() throws Exception { - // overriden, because XOM doesn't not support it - } + @Override + public void testStaxSourceStreamReader() throws Exception { + // overriden, because XOM doesn't not support it + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapterTest.java index ff7e815b..488aac4e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/DefaultMethodEndpointAdapterTest.java @@ -37,181 +37,181 @@ import org.springframework.ws.server.endpoint.adapter.method.MethodReturnValueHa /** @author Arjen Poutsma */ public class DefaultMethodEndpointAdapterTest { - private DefaultMethodEndpointAdapter adapter; + private DefaultMethodEndpointAdapter adapter; - private MethodArgumentResolver argumentResolver1; + private MethodArgumentResolver argumentResolver1; - private MethodArgumentResolver argumentResolver2; + private MethodArgumentResolver argumentResolver2; - private MethodReturnValueHandler returnValueHandler; + private MethodReturnValueHandler returnValueHandler; - private MethodEndpoint supportedEndpoint; + private MethodEndpoint supportedEndpoint; private MethodEndpoint nullReturnValue; - private MethodEndpoint unsupportedEndpoint; + private MethodEndpoint unsupportedEndpoint; - private MethodEndpoint exceptionEndpoint; + private MethodEndpoint exceptionEndpoint; - private String supportedArgument; + private String supportedArgument; @Before - public void setUp() throws Exception { - adapter = new DefaultMethodEndpointAdapter(); - argumentResolver1 = createMock("stringResolver", MethodArgumentResolver.class); - argumentResolver2 = createMock("intResolver", MethodArgumentResolver.class); - returnValueHandler = createMock(MethodReturnValueHandler.class); - adapter.setMethodArgumentResolvers(Arrays.asList(argumentResolver1, argumentResolver2)); - adapter.setMethodReturnValueHandlers( - Collections.singletonList(returnValueHandler)); - supportedEndpoint = new MethodEndpoint(this, "supported", String.class, Integer.class); - nullReturnValue = new MethodEndpoint(this, "nullReturnValue", String.class); - unsupportedEndpoint = new MethodEndpoint(this, "unsupported", String.class); - exceptionEndpoint = new MethodEndpoint(this, "exception", String.class); - } + public void setUp() throws Exception { + adapter = new DefaultMethodEndpointAdapter(); + argumentResolver1 = createMock("stringResolver", MethodArgumentResolver.class); + argumentResolver2 = createMock("intResolver", MethodArgumentResolver.class); + returnValueHandler = createMock(MethodReturnValueHandler.class); + adapter.setMethodArgumentResolvers(Arrays.asList(argumentResolver1, argumentResolver2)); + adapter.setMethodReturnValueHandlers( + Collections.singletonList(returnValueHandler)); + supportedEndpoint = new MethodEndpoint(this, "supported", String.class, Integer.class); + nullReturnValue = new MethodEndpoint(this, "nullReturnValue", String.class); + unsupportedEndpoint = new MethodEndpoint(this, "unsupported", String.class); + exceptionEndpoint = new MethodEndpoint(this, "exception", String.class); + } - @Test - public void initDefaultStrategies() throws Exception { - adapter = new DefaultMethodEndpointAdapter(); - adapter.setBeanClassLoader(DefaultMethodEndpointAdapterTest.class.getClassLoader()); - adapter.afterPropertiesSet(); + @Test + public void initDefaultStrategies() throws Exception { + adapter = new DefaultMethodEndpointAdapter(); + adapter.setBeanClassLoader(DefaultMethodEndpointAdapterTest.class.getClassLoader()); + adapter.afterPropertiesSet(); - assertFalse("No default MethodArgumentResolvers loaded", adapter.getMethodArgumentResolvers().isEmpty()); - assertFalse("No default MethodReturnValueHandlers loaded", adapter.getMethodReturnValueHandlers().isEmpty()); - } + assertFalse("No default MethodArgumentResolvers loaded", adapter.getMethodArgumentResolvers().isEmpty()); + assertFalse("No default MethodReturnValueHandlers loaded", adapter.getMethodReturnValueHandlers().isEmpty()); + } - @Test - public void supportsSupported() throws Exception { - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(false); - expect(argumentResolver2.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(true); + @Test + public void supportsSupported() throws Exception { + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(false); + expect(argumentResolver2.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(true); - replay(argumentResolver1, argumentResolver2, returnValueHandler); + replay(argumentResolver1, argumentResolver2, returnValueHandler); - boolean result = adapter.supports(supportedEndpoint); - assertTrue("adapter does not support method", result); + boolean result = adapter.supports(supportedEndpoint); + assertTrue("adapter does not support method", result); - verify(argumentResolver1, argumentResolver2, returnValueHandler); - } + verify(argumentResolver1, argumentResolver2, returnValueHandler); + } - @Test - public void supportsUnsupportedParameter() throws Exception { - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(false); - expect(argumentResolver2.supportsParameter(isA(MethodParameter.class))).andReturn(false); + @Test + public void supportsUnsupportedParameter() throws Exception { + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(false); + expect(argumentResolver2.supportsParameter(isA(MethodParameter.class))).andReturn(false); - replay(argumentResolver1, argumentResolver2, returnValueHandler); + replay(argumentResolver1, argumentResolver2, returnValueHandler); - boolean result = adapter.supports(unsupportedEndpoint); - assertFalse("adapter does not support method", result); + boolean result = adapter.supports(unsupportedEndpoint); + assertFalse("adapter does not support method", result); - verify(argumentResolver1, argumentResolver2, returnValueHandler); - } + verify(argumentResolver1, argumentResolver2, returnValueHandler); + } - @Test - public void supportsUnsupportedReturnType() throws Exception { - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(false); + @Test + public void supportsUnsupportedReturnType() throws Exception { + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(false); - replay(argumentResolver1, argumentResolver2, returnValueHandler); + replay(argumentResolver1, argumentResolver2, returnValueHandler); - boolean result = adapter.supports(unsupportedEndpoint); - assertFalse("adapter does not support method", result); + boolean result = adapter.supports(unsupportedEndpoint); + assertFalse("adapter does not support method", result); - verify(argumentResolver1, argumentResolver2, returnValueHandler); - } + verify(argumentResolver1, argumentResolver2, returnValueHandler); + } - @Test - public void invokeSupported() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void invokeSupported() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - String value = "Foo"; + String value = "Foo"; - // arg 0 - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(argumentResolver1.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(value); + // arg 0 + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(argumentResolver1.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(value); - // arg 1 - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(false); - expect(argumentResolver2.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(argumentResolver2.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(new Integer(42)); + // arg 1 + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(false); + expect(argumentResolver2.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(argumentResolver2.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(new Integer(42)); - expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(true); - returnValueHandler.handleReturnValue(eq(messageContext), isA(MethodParameter.class), eq(value)); + expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(true); + returnValueHandler.handleReturnValue(eq(messageContext), isA(MethodParameter.class), eq(value)); - replay(argumentResolver1, argumentResolver2, returnValueHandler); + replay(argumentResolver1, argumentResolver2, returnValueHandler); - adapter.invoke(messageContext, supportedEndpoint); - assertEquals("Invalid argument passed", value, supportedArgument); + adapter.invoke(messageContext, supportedEndpoint); + assertEquals("Invalid argument passed", value, supportedArgument); - verify(argumentResolver1, argumentResolver2, returnValueHandler); - } + verify(argumentResolver1, argumentResolver2, returnValueHandler); + } - @Test - public void invokeNullReturnValue() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void invokeNullReturnValue() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - String value = "Foo"; + String value = "Foo"; - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(argumentResolver1.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(value); + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(argumentResolver1.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(value); - expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(true); - returnValueHandler.handleReturnValue(eq(messageContext), isA(MethodParameter.class), isNull()); + expect(returnValueHandler.supportsReturnType(isA(MethodParameter.class))).andReturn(true); + returnValueHandler.handleReturnValue(eq(messageContext), isA(MethodParameter.class), isNull()); - replay(argumentResolver1, argumentResolver2, returnValueHandler); + replay(argumentResolver1, argumentResolver2, returnValueHandler); - adapter.invoke(messageContext, nullReturnValue); - assertEquals("Invalid argument passed", value, supportedArgument); + adapter.invoke(messageContext, nullReturnValue); + assertEquals("Invalid argument passed", value, supportedArgument); - verify(argumentResolver1, argumentResolver2, returnValueHandler); - } + verify(argumentResolver1, argumentResolver2, returnValueHandler); + } - @Test - public void invokeException() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void invokeException() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - String value = "Foo"; + String value = "Foo"; - expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); - expect(argumentResolver1.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(value); + expect(argumentResolver1.supportsParameter(isA(MethodParameter.class))).andReturn(true); + expect(argumentResolver1.resolveArgument(eq(messageContext), isA(MethodParameter.class))).andReturn(value); - replay(argumentResolver1, argumentResolver2, returnValueHandler); + replay(argumentResolver1, argumentResolver2, returnValueHandler); - try { - adapter.invoke(messageContext, exceptionEndpoint); - fail("IOException expected"); - } - catch (IOException expected) { - // expected - } - assertEquals("Invalid argument passed", value, supportedArgument); + try { + adapter.invoke(messageContext, exceptionEndpoint); + fail("IOException expected"); + } + catch (IOException expected) { + // expected + } + assertEquals("Invalid argument passed", value, supportedArgument); - verify(argumentResolver1, argumentResolver2, returnValueHandler); - } + verify(argumentResolver1, argumentResolver2, returnValueHandler); + } - public String supported(String s, Integer i) { - supportedArgument = s; - return s; + public String supported(String s, Integer i) { + supportedArgument = s; + return s; - } + } - public String nullReturnValue(String s) { - supportedArgument = s; - return null; - } + public String nullReturnValue(String s) { + supportedArgument = s; + return null; + } - public String unsupported(String s) { - return s; - } + public String unsupported(String s) { + return s; + } - public String exception(String s) throws IOException { - supportedArgument = s; - throw new IOException(s); - } + public String exception(String s) throws IOException { + supportedArgument = s; + throw new IOException(s); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapterTest.java index d838876e..55407888 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapterTest.java @@ -38,177 +38,177 @@ import static org.easymock.EasyMock.*; public class GenericMarshallingMethodEndpointAdapterTest { - private GenericMarshallingMethodEndpointAdapter adapter; + private GenericMarshallingMethodEndpointAdapter adapter; - private boolean noResponseInvoked; + private boolean noResponseInvoked; - private GenericMarshaller marshallerMock; + private GenericMarshaller marshallerMock; - private GenericUnmarshaller unmarshallerMock; + private GenericUnmarshaller unmarshallerMock; - private boolean responseInvoked; + private boolean responseInvoked; - @Before - public void setUp() throws Exception { - adapter = new GenericMarshallingMethodEndpointAdapter(); - marshallerMock = createMock(GenericMarshaller.class); - adapter.setMarshaller(marshallerMock); - unmarshallerMock = createMock(GenericUnmarshaller.class); - adapter.setUnmarshaller(unmarshallerMock); - adapter.afterPropertiesSet(); - } + @Before + public void setUp() throws Exception { + adapter = new GenericMarshallingMethodEndpointAdapter(); + marshallerMock = createMock(GenericMarshaller.class); + adapter.setMarshaller(marshallerMock); + unmarshallerMock = createMock(GenericUnmarshaller.class); + adapter.setUnmarshaller(unmarshallerMock); + adapter.afterPropertiesSet(); + } - @Test - public void testNoResponse() throws Exception { - WebServiceMessage messageMock = createMock(WebServiceMessage.class); - expect(messageMock.getPayloadSource()).andReturn(new StringSource("")); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - MessageContext messageContext = new DefaultMessageContext(messageMock, factoryMock); + @Test + public void testNoResponse() throws Exception { + WebServiceMessage messageMock = createMock(WebServiceMessage.class); + expect(messageMock.getPayloadSource()).andReturn(new StringSource("")); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + MessageContext messageContext = new DefaultMessageContext(messageMock, factoryMock); - Method noResponse = getClass().getMethod("noResponse", MyGenericType.class); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyGenericType()); + Method noResponse = getClass().getMethod("noResponse", MyGenericType.class); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); + expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyGenericType()); - replay(marshallerMock, unmarshallerMock, messageMock, factoryMock); + replay(marshallerMock, unmarshallerMock, messageMock, factoryMock); - Assert.assertFalse("Method invoked", noResponseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", noResponseInvoked); + Assert.assertFalse("Method invoked", noResponseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", noResponseInvoked); - verify(marshallerMock, unmarshallerMock, messageMock, factoryMock); - } + verify(marshallerMock, unmarshallerMock, messageMock, factoryMock); + } - @Test - public void testNoRequestPayload() throws Exception { - WebServiceMessage messageMock = createMock(WebServiceMessage.class); - expect(messageMock.getPayloadSource()).andReturn(null); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - MessageContext messageContext = new DefaultMessageContext(messageMock, factoryMock); + @Test + public void testNoRequestPayload() throws Exception { + WebServiceMessage messageMock = createMock(WebServiceMessage.class); + expect(messageMock.getPayloadSource()).andReturn(null); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + MessageContext messageContext = new DefaultMessageContext(messageMock, factoryMock); - Method noResponse = getClass().getMethod("noResponse", MyGenericType.class); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); + Method noResponse = getClass().getMethod("noResponse", MyGenericType.class); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); - replay(marshallerMock, unmarshallerMock, messageMock, factoryMock); + replay(marshallerMock, unmarshallerMock, messageMock, factoryMock); - Assert.assertFalse("Method invoked", noResponseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", noResponseInvoked); + Assert.assertFalse("Method invoked", noResponseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", noResponseInvoked); - verify(marshallerMock, unmarshallerMock, messageMock, factoryMock); - } + verify(marshallerMock, unmarshallerMock, messageMock, factoryMock); + } - @Test - public void testResponse() throws Exception { - WebServiceMessage requestMock = createMock(WebServiceMessage.class); - expect(requestMock.getPayloadSource()).andReturn(new StringSource("")); - WebServiceMessage responseMock = createMock(WebServiceMessage.class); - expect(responseMock.getPayloadResult()).andReturn(new StringResult()); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); - MessageContext messageContext = new DefaultMessageContext(requestMock, factoryMock); + @Test + public void testResponse() throws Exception { + WebServiceMessage requestMock = createMock(WebServiceMessage.class); + expect(requestMock.getPayloadSource()).andReturn(new StringSource("")); + WebServiceMessage responseMock = createMock(WebServiceMessage.class); + expect(responseMock.getPayloadResult()).andReturn(new StringResult()); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); + MessageContext messageContext = new DefaultMessageContext(requestMock, factoryMock); - Method response = getClass().getMethod("response", MyGenericType.class); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyGenericType()); - marshallerMock.marshal(isA(MyGenericType.class), isA(Result.class)); + Method response = getClass().getMethod("response", MyGenericType.class); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); + expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyGenericType()); + marshallerMock.marshal(isA(MyGenericType.class), isA(Result.class)); - replay(marshallerMock, unmarshallerMock, requestMock, responseMock, factoryMock); + replay(marshallerMock, unmarshallerMock, requestMock, responseMock, factoryMock); - Assert.assertFalse("Method invoked", responseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", responseInvoked); + Assert.assertFalse("Method invoked", responseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", responseInvoked); - verify(marshallerMock, unmarshallerMock, requestMock, responseMock, factoryMock); - } + verify(marshallerMock, unmarshallerMock, requestMock, responseMock, factoryMock); + } - @Test - public void testSupportedNoResponse() throws NoSuchMethodException { - Method noResponse = getClass().getMethod("noResponse", MyGenericType.class); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); - expect(unmarshallerMock.supports(noResponse.getGenericParameterTypes()[0])).andReturn(true); + @Test + public void testSupportedNoResponse() throws NoSuchMethodException { + Method noResponse = getClass().getMethod("noResponse", MyGenericType.class); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); + expect(unmarshallerMock.supports(noResponse.getGenericParameterTypes()[0])).andReturn(true); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testSupportedResponse() throws NoSuchMethodException { - Method response = getClass().getMethod("response", MyGenericType.class); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); + @Test + public void testSupportedResponse() throws NoSuchMethodException { + Method response = getClass().getMethod("response", MyGenericType.class); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); - expect(unmarshallerMock.supports(response.getGenericParameterTypes()[0])).andReturn(true); - expect(marshallerMock.supports(response.getGenericReturnType())).andReturn(true); + expect(unmarshallerMock.supports(response.getGenericParameterTypes()[0])).andReturn(true); + expect(marshallerMock.supports(response.getGenericReturnType())).andReturn(true); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { - Method unsupported = getClass().getMethod("unsupportedMultipleParams", String.class, String.class); + @Test + public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { + Method unsupported = getClass().getMethod("unsupportedMultipleParams", String.class, String.class); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); + Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { - Method unsupported = getClass().getMethod("unsupportedWrongParam", String.class); - expect(unmarshallerMock.supports(unsupported.getGenericParameterTypes()[0])).andReturn(false); - expect(marshallerMock.supports(unsupported.getGenericReturnType())).andReturn(true); + @Test + public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { + Method unsupported = getClass().getMethod("unsupportedWrongParam", String.class); + expect(unmarshallerMock.supports(unsupported.getGenericParameterTypes()[0])).andReturn(false); + expect(marshallerMock.supports(unsupported.getGenericReturnType())).andReturn(true); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); + Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testUnsupportedMethodWrongReturnType() throws NoSuchMethodException { - Method unsupported = getClass().getMethod("unsupportedWrongParam", String.class); - expect(marshallerMock.supports(unsupported.getGenericReturnType())).andReturn(false); + @Test + public void testUnsupportedMethodWrongReturnType() throws NoSuchMethodException { + Method unsupported = getClass().getMethod("unsupportedWrongParam", String.class); + expect(marshallerMock.supports(unsupported.getGenericReturnType())).andReturn(false); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); + Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - public void noResponse(MyGenericType type) { - noResponseInvoked = true; + public void noResponse(MyGenericType type) { + noResponseInvoked = true; - } + } - public MyGenericType response(MyGenericType type) { - responseInvoked = true; - return type; - } + public MyGenericType response(MyGenericType type) { + responseInvoked = true; + return type; + } - public void unsupportedMultipleParams(String s1, String s2) { - } + public void unsupportedMultipleParams(String s1, String s2) { + } - public String unsupportedWrongParam(String s) { - return s; - } + public String unsupportedWrongParam(String s) { + return s; + } - private static class MyType { + private static class MyType { - } + } - private static class MyGenericType { + private static class MyGenericType { - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapterTest.java index 4969676f..844cea77 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MarshallingMethodEndpointAdapterTest.java @@ -36,159 +36,159 @@ import static org.easymock.EasyMock.*; public class MarshallingMethodEndpointAdapterTest { - private MarshallingMethodEndpointAdapter adapter; + private MarshallingMethodEndpointAdapter adapter; - private boolean noResponseInvoked; + private boolean noResponseInvoked; - private Marshaller marshallerMock; + private Marshaller marshallerMock; - private Unmarshaller unmarshallerMock; + private Unmarshaller unmarshallerMock; - private MessageContext messageContext; + private MessageContext messageContext; - private boolean responseInvoked; + private boolean responseInvoked; - @Before - public void setUp() throws Exception { - adapter = new MarshallingMethodEndpointAdapter(); - marshallerMock = createMock(Marshaller.class); - adapter.setMarshaller(marshallerMock); - unmarshallerMock = createMock(Unmarshaller.class); - adapter.setUnmarshaller(unmarshallerMock); - adapter.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(""); - messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - } + @Before + public void setUp() throws Exception { + adapter = new MarshallingMethodEndpointAdapter(); + marshallerMock = createMock(Marshaller.class); + adapter.setMarshaller(marshallerMock); + unmarshallerMock = createMock(Unmarshaller.class); + adapter.setUnmarshaller(unmarshallerMock); + adapter.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(""); + messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + } - @Test - public void testNoResponse() throws Exception { - Method noResponse = getClass().getMethod("noResponse", new Class[]{MyType.class}); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyType()); + @Test + public void testNoResponse() throws Exception { + Method noResponse = getClass().getMethod("noResponse", new Class[]{MyType.class}); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); + expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyType()); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method invoked", noResponseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", noResponseInvoked); + Assert.assertFalse("Method invoked", noResponseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", noResponseInvoked); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testNoRequestPayload() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Method noResponse = getClass().getMethod("noResponse", new Class[]{MyType.class}); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); + @Test + public void testNoRequestPayload() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + Method noResponse = getClass().getMethod("noResponse", new Class[]{MyType.class}); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method invoked", noResponseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", noResponseInvoked); + Assert.assertFalse("Method invoked", noResponseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", noResponseInvoked); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testResponse() throws Exception { - Method response = getClass().getMethod("response", new Class[]{MyType.class}); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyType()); - marshallerMock.marshal(isA(MyType.class), isA(Result.class)); + @Test + public void testResponse() throws Exception { + Method response = getClass().getMethod("response", new Class[]{MyType.class}); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); + expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(new MyType()); + marshallerMock.marshal(isA(MyType.class), isA(Result.class)); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method invoked", responseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", responseInvoked); + Assert.assertFalse("Method invoked", responseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", responseInvoked); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testSupportedNoResponse() throws NoSuchMethodException { - Method noResponse = getClass().getMethod("noResponse", new Class[]{MyType.class}); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); - expect(unmarshallerMock.supports(MyType.class)).andReturn(true); + @Test + public void testSupportedNoResponse() throws NoSuchMethodException { + Method noResponse = getClass().getMethod("noResponse", new Class[]{MyType.class}); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, noResponse); + expect(unmarshallerMock.supports(MyType.class)).andReturn(true); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testSupportedResponse() throws NoSuchMethodException { - Method response = getClass().getMethod("response", new Class[]{MyType.class}); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); - expect(unmarshallerMock.supports(MyType.class)).andReturn(true); - expect(marshallerMock.supports(MyType.class)).andReturn(true); + @Test + public void testSupportedResponse() throws NoSuchMethodException { + Method response = getClass().getMethod("response", new Class[]{MyType.class}); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, response); + expect(unmarshallerMock.supports(MyType.class)).andReturn(true); + expect(marshallerMock.supports(MyType.class)).andReturn(true); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { - Method unsupported = getClass().getMethod("unsupportedMultipleParams", new Class[]{String.class, String.class}); + @Test + public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { + Method unsupported = getClass().getMethod("unsupportedMultipleParams", new Class[]{String.class, String.class}); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); + Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { - Method unsupported = getClass().getMethod("unsupportedWrongParam", new Class[]{String.class}); - expect(unmarshallerMock.supports(String.class)).andReturn(false); - expect(marshallerMock.supports(String.class)).andReturn(true); + @Test + public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { + Method unsupported = getClass().getMethod("unsupportedWrongParam", new Class[]{String.class}); + expect(unmarshallerMock.supports(String.class)).andReturn(false); + expect(marshallerMock.supports(String.class)).andReturn(true); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); + Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - @Test - public void testUnsupportedMethodWrongReturnType() throws NoSuchMethodException { - Method unsupported = getClass().getMethod("unsupportedWrongParam", new Class[]{String.class}); - expect(marshallerMock.supports(String.class)).andReturn(false); + @Test + public void testUnsupportedMethodWrongReturnType() throws NoSuchMethodException { + Method unsupported = getClass().getMethod("unsupportedWrongParam", new Class[]{String.class}); + expect(marshallerMock.supports(String.class)).andReturn(false); - replay(marshallerMock, unmarshallerMock); + replay(marshallerMock, unmarshallerMock); - Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); + Assert.assertFalse("Method supported", adapter.supportsInternal(new MethodEndpoint(this, unsupported))); - verify(marshallerMock, unmarshallerMock); - } + verify(marshallerMock, unmarshallerMock); + } - public void noResponse(MyType type) { - noResponseInvoked = true; + public void noResponse(MyType type) { + noResponseInvoked = true; - } + } - public MyType response(MyType type) { - responseInvoked = true; - return new MyType(); - } + public MyType response(MyType type) { + responseInvoked = true; + return new MyType(); + } - public void unsupportedMultipleParams(String s1, String s2) { - } + public void unsupportedMultipleParams(String s1, String s2) { + } - public String unsupportedWrongParam(String s) { - return s; - } + public String unsupportedWrongParam(String s) { + return s; + } - private static class MyType { + private static class MyType { - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapterTest.java index 63f22838..b7ae3932 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageEndpointAdapterTest.java @@ -29,33 +29,33 @@ import static org.easymock.EasyMock.*; public class MessageEndpointAdapterTest { - private MessageEndpointAdapter adapter; + private MessageEndpointAdapter adapter; - private MessageEndpoint endpointMock; + private MessageEndpoint endpointMock; - @Before - public void setUp() throws Exception { - adapter = new MessageEndpointAdapter(); - endpointMock = createMock(MessageEndpoint.class); - } + @Before + public void setUp() throws Exception { + adapter = new MessageEndpointAdapter(); + endpointMock = createMock(MessageEndpoint.class); + } - @Test - public void testSupports() throws Exception { - Assert.assertTrue("MessageEndpointAdapter does not support MessageEndpoint", adapter.supports(endpointMock)); - } + @Test + public void testSupports() throws Exception { + Assert.assertTrue("MessageEndpointAdapter does not support MessageEndpoint", adapter.supports(endpointMock)); + } - @Test - public void testInvoke() throws Exception { - MessageContext context = new DefaultMessageContext(new MockWebServiceMessageFactory()); + @Test + public void testInvoke() throws Exception { + MessageContext context = new DefaultMessageContext(new MockWebServiceMessageFactory()); - endpointMock.invoke(context); + endpointMock.invoke(context); - replay(endpointMock); + replay(endpointMock); - adapter.invoke(context, endpointMock); + adapter.invoke(context, endpointMock); - verify(endpointMock); - } + verify(endpointMock); + } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapterTest.java index 00a35039..6d27de12 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/MessageMethodEndpointAdapterTest.java @@ -27,52 +27,52 @@ import org.junit.Test; public class MessageMethodEndpointAdapterTest { - private MessageMethodEndpointAdapter adapter; + private MessageMethodEndpointAdapter adapter; - private boolean supportedInvoked; + private boolean supportedInvoked; - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() throws Exception { - adapter = new MessageMethodEndpointAdapter(); - messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - } + @Before + public void setUp() throws Exception { + adapter = new MessageMethodEndpointAdapter(); + messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + } - @Test - public void testSupported() throws NoSuchMethodException { - MethodEndpoint methodEndpoint = new MethodEndpoint(this, "supported", new Class[]{MessageContext.class}); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - } + @Test + public void testSupported() throws NoSuchMethodException { + MethodEndpoint methodEndpoint = new MethodEndpoint(this, "supported", new Class[]{MessageContext.class}); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + } - @Test - public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { - Assert.assertFalse("Method supported", adapter.supportsInternal( - new MethodEndpoint(this, "unsupportedMultipleParams", - new Class[]{MessageContext.class, MessageContext.class}))); - } + @Test + public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { + Assert.assertFalse("Method supported", adapter.supportsInternal( + new MethodEndpoint(this, "unsupportedMultipleParams", + new Class[]{MessageContext.class, MessageContext.class}))); + } - @Test - public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { - Assert.assertFalse("Method supported", - adapter.supportsInternal(new MethodEndpoint(this, "unsupportedWrongParam", new Class[]{String.class}))); - } + @Test + public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { + Assert.assertFalse("Method supported", + adapter.supportsInternal(new MethodEndpoint(this, "unsupportedWrongParam", new Class[]{String.class}))); + } - @Test - public void testInvokeSupported() throws Exception { - MethodEndpoint methodEndpoint = new MethodEndpoint(this, "supported", new Class[]{MessageContext.class}); - Assert.assertFalse("Method invoked", supportedInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", supportedInvoked); - } + @Test + public void testInvokeSupported() throws Exception { + MethodEndpoint methodEndpoint = new MethodEndpoint(this, "supported", new Class[]{MessageContext.class}); + Assert.assertFalse("Method invoked", supportedInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", supportedInvoked); + } - public void supported(MessageContext context) { - supportedInvoked = true; - } + public void supported(MessageContext context) { + supportedInvoked = true; + } - public void unsupportedMultipleParams(MessageContext s1, MessageContext s2) { - } + public void unsupportedMultipleParams(MessageContext s1, MessageContext s2) { + } - public void unsupportedWrongParam(String request) { - } + public void unsupportedWrongParam(String request) { + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapterTest.java index 8b7b2af7..0e138fa3 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadEndpointAdapterTest.java @@ -39,54 +39,54 @@ import static org.easymock.EasyMock.*; public class PayloadEndpointAdapterTest { - private PayloadEndpointAdapter adapter; + private PayloadEndpointAdapter adapter; - private PayloadEndpoint endpointMock; + private PayloadEndpoint endpointMock; - @Before - public void setUp() throws Exception { - adapter = new PayloadEndpointAdapter(); - endpointMock = createMock(PayloadEndpoint.class); - } + @Before + public void setUp() throws Exception { + adapter = new PayloadEndpointAdapter(); + endpointMock = createMock(PayloadEndpoint.class); + } - @Test - public void testSupports() throws Exception { - Assert.assertTrue("PayloadEndpointAdapter does not support PayloadEndpoint", adapter.supports(endpointMock)); - } + @Test + public void testSupports() throws Exception { + Assert.assertTrue("PayloadEndpointAdapter does not support PayloadEndpoint", adapter.supports(endpointMock)); + } - @Test - public void testInvoke() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - PayloadEndpoint endpoint = new PayloadEndpoint() { - public Source invoke(Source request) throws Exception { - StringWriter writer = new StringWriter(); - transformer.transform(request, new StreamResult(writer)); - assertXMLEqual("Invalid request", "", writer.toString()); - return new StreamSource(new StringReader("")); - } - }; - endpoint.invoke(request.getPayloadSource()); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - adapter.invoke(messageContext, endpoint); - MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); - Assert.assertNotNull("No response created", response); - assertXMLEqual("Invalid payload", "", response.getPayloadAsString()); - } + @Test + public void testInvoke() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + PayloadEndpoint endpoint = new PayloadEndpoint() { + public Source invoke(Source request) throws Exception { + StringWriter writer = new StringWriter(); + transformer.transform(request, new StreamResult(writer)); + assertXMLEqual("Invalid request", "", writer.toString()); + return new StreamSource(new StringReader("")); + } + }; + endpoint.invoke(request.getPayloadSource()); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + adapter.invoke(messageContext, endpoint); + MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); + Assert.assertNotNull("No response created", response); + assertXMLEqual("Invalid payload", "", response.getPayloadAsString()); + } - @Test - public void testInvokeNoResponse() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - expect(endpointMock.invoke(isA(Source.class))).andReturn(null); + @Test + public void testInvokeNoResponse() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + expect(endpointMock.invoke(isA(Source.class))).andReturn(null); - replay(endpointMock); + replay(endpointMock); - adapter.invoke(messageContext, endpointMock); + adapter.invoke(messageContext, endpointMock); - verify(endpointMock); + verify(endpointMock); - Assert.assertFalse("Response created", messageContext.hasResponse()); - } + Assert.assertFalse("Response created", messageContext.hasResponse()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapterTest.java index d7770170..2646fbb8 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/PayloadMethodEndpointAdapterTest.java @@ -33,86 +33,86 @@ import org.junit.Test; public class PayloadMethodEndpointAdapterTest { - private PayloadMethodEndpointAdapter adapter; + private PayloadMethodEndpointAdapter adapter; - private boolean noResponseInvoked; + private boolean noResponseInvoked; - private boolean responseInvoked; + private boolean responseInvoked; - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() throws Exception { - adapter = new PayloadMethodEndpointAdapter(); - messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - } + @Before + public void setUp() throws Exception { + adapter = new PayloadMethodEndpointAdapter(); + messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + } - @Test - public void testSupportedNoResponse() throws NoSuchMethodException { - MethodEndpoint methodEndpoint = new MethodEndpoint(this, "noResponse", new Class[]{DOMSource.class}); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - } + @Test + public void testSupportedNoResponse() throws NoSuchMethodException { + MethodEndpoint methodEndpoint = new MethodEndpoint(this, "noResponse", new Class[]{DOMSource.class}); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + } - @Test - public void testSupportedResponse() throws NoSuchMethodException { - MethodEndpoint methodEndpoint = new MethodEndpoint(this, "response", new Class[]{StreamSource.class}); - Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); - } + @Test + public void testSupportedResponse() throws NoSuchMethodException { + MethodEndpoint methodEndpoint = new MethodEndpoint(this, "response", new Class[]{StreamSource.class}); + Assert.assertTrue("Method unsupported", adapter.supportsInternal(methodEndpoint)); + } - @Test - public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { - Assert.assertFalse("Method supported", adapter.supportsInternal( - new MethodEndpoint(this, "unsupportedMultipleParams", new Class[]{Source.class, Source.class}))); - } + @Test + public void testUnsupportedMethodMultipleParams() throws NoSuchMethodException { + Assert.assertFalse("Method supported", adapter.supportsInternal( + new MethodEndpoint(this, "unsupportedMultipleParams", new Class[]{Source.class, Source.class}))); + } - @Test - public void testUnsupportedMethodWrongReturnType() throws NoSuchMethodException { - Assert.assertFalse("Method supported", adapter.supportsInternal( - new MethodEndpoint(this, "unsupportedWrongReturnType", new Class[]{Source.class}))); - } + @Test + public void testUnsupportedMethodWrongReturnType() throws NoSuchMethodException { + Assert.assertFalse("Method supported", adapter.supportsInternal( + new MethodEndpoint(this, "unsupportedWrongReturnType", new Class[]{Source.class}))); + } - @Test - public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { - Assert.assertFalse("Method supported", - adapter.supportsInternal(new MethodEndpoint(this, "unsupportedWrongParam", new Class[]{String.class}))); - } + @Test + public void testUnsupportedMethodWrongParam() throws NoSuchMethodException { + Assert.assertFalse("Method supported", + adapter.supportsInternal(new MethodEndpoint(this, "unsupportedWrongParam", new Class[]{String.class}))); + } - @Test - public void testNoResponse() throws Exception { - MethodEndpoint methodEndpoint = new MethodEndpoint(this, "noResponse", new Class[]{DOMSource.class}); - Assert.assertFalse("Method invoked", noResponseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", noResponseInvoked); - } + @Test + public void testNoResponse() throws Exception { + MethodEndpoint methodEndpoint = new MethodEndpoint(this, "noResponse", new Class[]{DOMSource.class}); + Assert.assertFalse("Method invoked", noResponseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", noResponseInvoked); + } - @Test - public void testResponse() throws Exception { - WebServiceMessage request = new MockWebServiceMessage(""); - messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MethodEndpoint methodEndpoint = new MethodEndpoint(this, "response", new Class[]{StreamSource.class}); - Assert.assertFalse("Method invoked", responseInvoked); - adapter.invoke(messageContext, methodEndpoint); - Assert.assertTrue("Method not invoked", responseInvoked); - } + @Test + public void testResponse() throws Exception { + WebServiceMessage request = new MockWebServiceMessage(""); + messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MethodEndpoint methodEndpoint = new MethodEndpoint(this, "response", new Class[]{StreamSource.class}); + Assert.assertFalse("Method invoked", responseInvoked); + adapter.invoke(messageContext, methodEndpoint); + Assert.assertTrue("Method not invoked", responseInvoked); + } - public void noResponse(DOMSource request) { - noResponseInvoked = true; - } + public void noResponse(DOMSource request) { + noResponseInvoked = true; + } - public Source response(StreamSource request) { - responseInvoked = true; - return request; - } + public Source response(StreamSource request) { + responseInvoked = true; + return request; + } - public void unsupportedMultipleParams(Source s1, Source s2) { - } + public void unsupportedMultipleParams(Source s1, Source s2) { + } - public Source unsupportedWrongParam(String request) { - return null; - } + public Source unsupportedWrongParam(String request) { + return null; + } - public String unsupportedWrongReturnType(Source request) { - return null; - } + public String unsupportedWrongReturnType(Source request) { + return null; + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapterTest.java index 9662cb76..240c84e7 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/XPathParamAnnotationMethodEndpointAdapterTest.java @@ -45,174 +45,174 @@ import static org.easymock.EasyMock.*; public class XPathParamAnnotationMethodEndpointAdapterTest { - private static final String CONTENTS = "text42.0"; + private static final String CONTENTS = "text42.0"; - private XPathParamAnnotationMethodEndpointAdapter adapter; + private XPathParamAnnotationMethodEndpointAdapter adapter; - private boolean supportedTypesInvoked = false; + private boolean supportedTypesInvoked = false; - private boolean supportedSourceInvoked; + private boolean supportedSourceInvoked; - private boolean namespacesInvoked; + private boolean namespacesInvoked; - @Before - public void setUp() throws Exception { - adapter = new XPathParamAnnotationMethodEndpointAdapter(); - adapter.afterPropertiesSet(); - } + @Before + public void setUp() throws Exception { + adapter = new XPathParamAnnotationMethodEndpointAdapter(); + adapter.afterPropertiesSet(); + } - @Test - public void testUnsupportedInvalidParam() throws NoSuchMethodException { - MethodEndpoint endpoint = new MethodEndpoint(this, "unsupportedInvalidParamType", new Class[]{Integer.TYPE}); - Assert.assertFalse("Method supported", adapter.supports(endpoint)); - } + @Test + public void testUnsupportedInvalidParam() throws NoSuchMethodException { + MethodEndpoint endpoint = new MethodEndpoint(this, "unsupportedInvalidParamType", new Class[]{Integer.TYPE}); + Assert.assertFalse("Method supported", adapter.supports(endpoint)); + } - @Test - public void testUnsupportedInvalidReturnType() throws NoSuchMethodException { - MethodEndpoint endpoint = new MethodEndpoint(this, "unsupportedInvalidReturnType", new Class[]{String.class}); - Assert.assertFalse("Method supported", adapter.supports(endpoint)); - } + @Test + public void testUnsupportedInvalidReturnType() throws NoSuchMethodException { + MethodEndpoint endpoint = new MethodEndpoint(this, "unsupportedInvalidReturnType", new Class[]{String.class}); + Assert.assertFalse("Method supported", adapter.supports(endpoint)); + } - @Test - public void testUnsupportedInvalidParams() throws NoSuchMethodException { - MethodEndpoint endpoint = - new MethodEndpoint(this, "unsupportedInvalidParams", new Class[]{String.class, String.class}); - Assert.assertFalse("Method supported", adapter.supports(endpoint)); - } + @Test + public void testUnsupportedInvalidParams() throws NoSuchMethodException { + MethodEndpoint endpoint = + new MethodEndpoint(this, "unsupportedInvalidParams", new Class[]{String.class, String.class}); + Assert.assertFalse("Method supported", adapter.supports(endpoint)); + } - @Test - public void testSupportedTypes() throws NoSuchMethodException { - MethodEndpoint endpoint = new MethodEndpoint(this, "supportedTypes", - new Class[]{Boolean.TYPE, Double.TYPE, Node.class, NodeList.class, String.class}); - Assert.assertTrue("Not all types supported", adapter.supports(endpoint)); - } + @Test + public void testSupportedTypes() throws NoSuchMethodException { + MethodEndpoint endpoint = new MethodEndpoint(this, "supportedTypes", + new Class[]{Boolean.TYPE, Double.TYPE, Node.class, NodeList.class, String.class}); + Assert.assertTrue("Not all types supported", adapter.supports(endpoint)); + } - @Test - public void testSupportsStringSource() throws NoSuchMethodException { - MethodEndpoint endpoint = new MethodEndpoint(this, "supportedStringSource", new Class[]{String.class}); - Assert.assertTrue("StringSource method not supported", adapter.supports(endpoint)); - } + @Test + public void testSupportsStringSource() throws NoSuchMethodException { + MethodEndpoint endpoint = new MethodEndpoint(this, "supportedStringSource", new Class[]{String.class}); + Assert.assertTrue("StringSource method not supported", adapter.supports(endpoint)); + } - @Test - public void testSupportsSource() throws NoSuchMethodException { - MethodEndpoint endpoint = new MethodEndpoint(this, "supportedSource", new Class[]{String.class}); - Assert.assertTrue("Source method not supported", adapter.supports(endpoint)); - } + @Test + public void testSupportsSource() throws NoSuchMethodException { + MethodEndpoint endpoint = new MethodEndpoint(this, "supportedSource", new Class[]{String.class}); + Assert.assertTrue("Source method not supported", adapter.supports(endpoint)); + } - @Test - public void testSupportsVoid() throws NoSuchMethodException { - MethodEndpoint endpoint = new MethodEndpoint(this, "supportedVoid", new Class[]{String.class}); - Assert.assertTrue("void method not supported", adapter.supports(endpoint)); - } + @Test + public void testSupportsVoid() throws NoSuchMethodException { + MethodEndpoint endpoint = new MethodEndpoint(this, "supportedVoid", new Class[]{String.class}); + Assert.assertTrue("void method not supported", adapter.supports(endpoint)); + } - @Test - public void testInvokeTypes() throws Exception { - WebServiceMessage messageMock = createMock(WebServiceMessage.class); - expect(messageMock.getPayloadSource()).andReturn(new StringSource(CONTENTS)); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - replay(messageMock, factoryMock); + @Test + public void testInvokeTypes() throws Exception { + WebServiceMessage messageMock = createMock(WebServiceMessage.class); + expect(messageMock.getPayloadSource()).andReturn(new StringSource(CONTENTS)); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + replay(messageMock, factoryMock); - MessageContext messageContext = new DefaultMessageContext(messageMock, factoryMock); - MethodEndpoint endpoint = new MethodEndpoint(this, "supportedTypes", - new Class[]{Boolean.TYPE, Double.TYPE, Node.class, NodeList.class, String.class}); - adapter.invoke(messageContext, endpoint); - Assert.assertTrue("Method not invoked", supportedTypesInvoked); + MessageContext messageContext = new DefaultMessageContext(messageMock, factoryMock); + MethodEndpoint endpoint = new MethodEndpoint(this, "supportedTypes", + new Class[]{Boolean.TYPE, Double.TYPE, Node.class, NodeList.class, String.class}); + adapter.invoke(messageContext, endpoint); + Assert.assertTrue("Method not invoked", supportedTypesInvoked); - verify(messageMock, factoryMock); - } + verify(messageMock, factoryMock); + } - @Test - public void testInvokeSource() throws Exception { - WebServiceMessage requestMock = createMock(WebServiceMessage.class); - WebServiceMessage responseMock = createMock(WebServiceMessage.class); - expect(requestMock.getPayloadSource()).andReturn(new StringSource(CONTENTS)); - expect(responseMock.getPayloadResult()).andReturn(new StringResult()); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); - replay(requestMock, responseMock, factoryMock); + @Test + public void testInvokeSource() throws Exception { + WebServiceMessage requestMock = createMock(WebServiceMessage.class); + WebServiceMessage responseMock = createMock(WebServiceMessage.class); + expect(requestMock.getPayloadSource()).andReturn(new StringSource(CONTENTS)); + expect(responseMock.getPayloadResult()).andReturn(new StringResult()); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); + replay(requestMock, responseMock, factoryMock); - MessageContext messageContext = new DefaultMessageContext(requestMock, factoryMock); - MethodEndpoint endpoint = new MethodEndpoint(this, "supportedSource", new Class[]{String.class}); - adapter.invoke(messageContext, endpoint); - Assert.assertTrue("Method not invoked", supportedSourceInvoked); + MessageContext messageContext = new DefaultMessageContext(requestMock, factoryMock); + MethodEndpoint endpoint = new MethodEndpoint(this, "supportedSource", new Class[]{String.class}); + adapter.invoke(messageContext, endpoint); + Assert.assertTrue("Method not invoked", supportedSourceInvoked); - verify(requestMock, responseMock, factoryMock); - } + verify(requestMock, responseMock, factoryMock); + } - @Test - public void testInvokeVoidDom() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - String rootNamespace = "http://rootnamespace"; - Element rootElement = document.createElementNS(rootNamespace, "root"); - document.appendChild(rootElement); - String childNamespace = "http://childnamespace"; - Element first = document.createElementNS(childNamespace, "child"); - rootElement.appendChild(first); - Text text = document.createTextNode("value"); - first.appendChild(text); - Element second = document.createElementNS(rootNamespace, "other-child"); - rootElement.appendChild(second); - text = document.createTextNode("other-value"); - second.appendChild(text); + @Test + public void testInvokeVoidDom() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + String rootNamespace = "http://rootnamespace"; + Element rootElement = document.createElementNS(rootNamespace, "root"); + document.appendChild(rootElement); + String childNamespace = "http://childnamespace"; + Element first = document.createElementNS(childNamespace, "child"); + rootElement.appendChild(first); + Text text = document.createTextNode("value"); + first.appendChild(text); + Element second = document.createElementNS(rootNamespace, "other-child"); + rootElement.appendChild(second); + text = document.createTextNode("other-value"); + second.appendChild(text); - WebServiceMessage requestMock = createMock(WebServiceMessage.class); - expect(requestMock.getPayloadSource()).andReturn(new DOMSource(first)); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + WebServiceMessage requestMock = createMock(WebServiceMessage.class); + expect(requestMock.getPayloadSource()).andReturn(new DOMSource(first)); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - replay(requestMock, factoryMock); + replay(requestMock, factoryMock); - Map namespaces = new HashMap(); - namespaces.put("root", rootNamespace); - namespaces.put("child", childNamespace); - adapter.setNamespaces(namespaces); + Map namespaces = new HashMap(); + namespaces.put("root", rootNamespace); + namespaces.put("child", childNamespace); + adapter.setNamespaces(namespaces); - MessageContext messageContext = new DefaultMessageContext(requestMock, factoryMock); - MethodEndpoint endpoint = new MethodEndpoint(this, "namespaces", new Class[]{Node.class}); - adapter.invoke(messageContext, endpoint); - Assert.assertTrue("Method not invoked", namespacesInvoked); - } + MessageContext messageContext = new DefaultMessageContext(requestMock, factoryMock); + MethodEndpoint endpoint = new MethodEndpoint(this, "namespaces", new Class[]{Node.class}); + adapter.invoke(messageContext, endpoint); + Assert.assertTrue("Method not invoked", namespacesInvoked); + } - public void supportedVoid(@XPathParam("/")String param1) { - } + public void supportedVoid(@XPathParam("/")String param1) { + } - public Source supportedSource(@XPathParam("/")String param1) { - supportedSourceInvoked = true; - return new StringSource(""); - } + public Source supportedSource(@XPathParam("/")String param1) { + supportedSourceInvoked = true; + return new StringSource(""); + } - public StringSource supportedStringSource(@XPathParam("/")String param1) { - return null; - } + public StringSource supportedStringSource(@XPathParam("/")String param1) { + return null; + } - public void supportedTypes(@XPathParam("/root/child")boolean param1, - @XPathParam("/root/child/number")double param2, - @XPathParam("/root/child")Node param3, - @XPathParam("/root/*")NodeList param4, - @XPathParam("/root/child/text")String param5) { - supportedTypesInvoked = true; - Assert.assertTrue("Invalid boolean value", param1); - Assert.assertEquals("Invalid double value", 42D, param2, 0.00001D); - Assert.assertEquals("Invalid Node value", "child", param3.getLocalName()); - Assert.assertEquals("Invalid NodeList value", 1, param4.getLength()); - Assert.assertEquals("Invalid Node value", "child", param4.item(0).getLocalName()); - Assert.assertEquals("Invalid Node value", "text", param5); - } + public void supportedTypes(@XPathParam("/root/child")boolean param1, + @XPathParam("/root/child/number")double param2, + @XPathParam("/root/child")Node param3, + @XPathParam("/root/*")NodeList param4, + @XPathParam("/root/child/text")String param5) { + supportedTypesInvoked = true; + Assert.assertTrue("Invalid boolean value", param1); + Assert.assertEquals("Invalid double value", 42D, param2, 0.00001D); + Assert.assertEquals("Invalid Node value", "child", param3.getLocalName()); + Assert.assertEquals("Invalid NodeList value", 1, param4.getLength()); + Assert.assertEquals("Invalid Node value", "child", param4.item(0).getLocalName()); + Assert.assertEquals("Invalid Node value", "text", param5); + } - public void unsupportedInvalidParams(@XPathParam("/")String param1, String param2) { + public void unsupportedInvalidParams(@XPathParam("/")String param1, String param2) { - } + } - public String unsupportedInvalidReturnType(@XPathParam("/")String param1) { - return null; - } + public String unsupportedInvalidReturnType(@XPathParam("/")String param1) { + return null; + } - public void unsupportedInvalidParamType(@XPathParam("/")int param1) { - } + public void unsupportedInvalidParamType(@XPathParam("/")int param1) { + } - public void namespaces(@XPathParam(".")Node param) { - namespacesInvoked = true; - Assert.assertEquals("Invalid parameter", "child", param.getLocalName()); - } + public void namespaces(@XPathParam(".")Node param) { + namespacesInvoked = true; + Assert.assertEquals("Invalid parameter", "child", param.getLocalName()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractMethodArgumentResolverTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractMethodArgumentResolverTestCase.java index 51e64965..16be585d 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractMethodArgumentResolverTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractMethodArgumentResolverTestCase.java @@ -34,40 +34,40 @@ import org.apache.axiom.soap.SOAPFactory; public class AbstractMethodArgumentResolverTestCase extends TransformerObjectSupport { - protected static final String NAMESPACE_URI = "http://springframework.org/ws"; + protected static final String NAMESPACE_URI = "http://springframework.org/ws"; - protected static final String LOCAL_NAME = "request"; + protected static final String LOCAL_NAME = "request"; - protected static final String XML = "<" + LOCAL_NAME + " xmlns=\"" + NAMESPACE_URI + "\"/>"; + protected static final String XML = "<" + LOCAL_NAME + " xmlns=\"" + NAMESPACE_URI + "\"/>"; - protected MessageContext createSaajMessageContext() throws javax.xml.soap.SOAPException { - javax.xml.soap.MessageFactory saajFactory = javax.xml.soap.MessageFactory.newInstance(); - javax.xml.soap.SOAPMessage saajMessage = saajFactory.createMessage(); - saajMessage.getSOAPBody().addChildElement(LOCAL_NAME, "", NAMESPACE_URI); - return new DefaultMessageContext(new SaajSoapMessage(saajMessage), new SaajSoapMessageFactory(saajFactory)); - } + protected MessageContext createSaajMessageContext() throws javax.xml.soap.SOAPException { + javax.xml.soap.MessageFactory saajFactory = javax.xml.soap.MessageFactory.newInstance(); + javax.xml.soap.SOAPMessage saajMessage = saajFactory.createMessage(); + saajMessage.getSOAPBody().addChildElement(LOCAL_NAME, "", NAMESPACE_URI); + return new DefaultMessageContext(new SaajSoapMessage(saajMessage), new SaajSoapMessageFactory(saajFactory)); + } - protected MessageContext createMockMessageContext() throws TransformerException { - MockWebServiceMessage request = new MockWebServiceMessage(new StringSource(XML)); - return new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - } + protected MessageContext createMockMessageContext() throws TransformerException { + MockWebServiceMessage request = new MockWebServiceMessage(new StringSource(XML)); + return new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + } - protected MessageContext createCachingAxiomMessageContext() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory, true, false); - transform(new StringSource(XML), request.getPayloadResult()); - AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); - soapMessageFactory.afterPropertiesSet(); - return new DefaultMessageContext(request, soapMessageFactory); - } + protected MessageContext createCachingAxiomMessageContext() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory, true, false); + transform(new StringSource(XML), request.getPayloadResult()); + AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); + soapMessageFactory.afterPropertiesSet(); + return new DefaultMessageContext(request, soapMessageFactory); + } - protected MessageContext createNonCachingAxiomMessageContext() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory, false, false); - transform(new StringSource(XML), request.getPayloadResult()); - AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); - soapMessageFactory.setPayloadCaching(false); - soapMessageFactory.afterPropertiesSet(); - return new DefaultMessageContext(request, soapMessageFactory); - } + protected MessageContext createNonCachingAxiomMessageContext() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage request = new AxiomSoapMessage(axiomFactory, false, false); + transform(new StringSource(XML), request.getPayloadResult()); + AxiomSoapMessageFactory soapMessageFactory = new AxiomSoapMessageFactory(); + soapMessageFactory.setPayloadCaching(false); + soapMessageFactory.afterPropertiesSet(); + return new DefaultMessageContext(request, soapMessageFactory); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessorTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessorTestCase.java index b097a891..4d7b0d03 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessorTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/AbstractPayloadMethodProcessorTestCase.java @@ -31,118 +31,118 @@ import static org.junit.Assert.assertTrue; public abstract class AbstractPayloadMethodProcessorTestCase extends AbstractMethodArgumentResolverTestCase { - private AbstractPayloadSourceMethodProcessor processor; + private AbstractPayloadSourceMethodProcessor processor; - private MethodParameter[] supportedParameters; + private MethodParameter[] supportedParameters; - private MethodParameter[] supportedReturnTypes; + private MethodParameter[] supportedReturnTypes; - @Before - public final void setUp() throws NoSuchMethodException { - processor = createProcessor(); - supportedParameters = createSupportedParameters(); - supportedReturnTypes = createSupportedReturnTypes(); - } + @Before + public final void setUp() throws NoSuchMethodException { + processor = createProcessor(); + supportedParameters = createSupportedParameters(); + supportedReturnTypes = createSupportedReturnTypes(); + } - protected abstract AbstractPayloadSourceMethodProcessor createProcessor(); + protected abstract AbstractPayloadSourceMethodProcessor createProcessor(); - protected abstract MethodParameter[] createSupportedParameters() throws NoSuchMethodException; + protected abstract MethodParameter[] createSupportedParameters() throws NoSuchMethodException; - protected abstract MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException; + protected abstract MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException; - @Test - public void supportsParameter() throws NoSuchMethodException { - for (MethodParameter supportedParameter : supportedParameters) { - assertTrue("processor does not support " + supportedParameter.getParameterType() + " parameter", - processor.supportsParameter(supportedParameter)); - } - MethodParameter unsupportedParameter = - new MethodParameter(getClass().getMethod("unsupported", String.class), 0); - assertFalse("processor supports invalid parameter", processor.supportsParameter(unsupportedParameter)); - } + @Test + public void supportsParameter() throws NoSuchMethodException { + for (MethodParameter supportedParameter : supportedParameters) { + assertTrue("processor does not support " + supportedParameter.getParameterType() + " parameter", + processor.supportsParameter(supportedParameter)); + } + MethodParameter unsupportedParameter = + new MethodParameter(getClass().getMethod("unsupported", String.class), 0); + assertFalse("processor supports invalid parameter", processor.supportsParameter(unsupportedParameter)); + } - @Test - public void supportsReturnType() throws NoSuchMethodException { - for (MethodParameter supportedReturnType : supportedReturnTypes) { - assertTrue("processor does not support " + supportedReturnType.getParameterType() + " return type", - processor.supportsReturnType(supportedReturnType)); - } - MethodParameter unsupportedReturnType = - new MethodParameter(getClass().getMethod("unsupported", String.class), -1); - assertFalse("processor supports invalid return type", processor.supportsReturnType(unsupportedReturnType)); - } + @Test + public void supportsReturnType() throws NoSuchMethodException { + for (MethodParameter supportedReturnType : supportedReturnTypes) { + assertTrue("processor does not support " + supportedReturnType.getParameterType() + " return type", + processor.supportsReturnType(supportedReturnType)); + } + MethodParameter unsupportedReturnType = + new MethodParameter(getClass().getMethod("unsupported", String.class), -1); + assertFalse("processor supports invalid return type", processor.supportsReturnType(unsupportedReturnType)); + } - @Test - public void saajArgument() throws Exception { - testResolveArgument(createSaajMessageContext()); - } + @Test + public void saajArgument() throws Exception { + testResolveArgument(createSaajMessageContext()); + } - @Test - public void mockArgument() throws Exception { - testResolveArgument(createMockMessageContext()); - } + @Test + public void mockArgument() throws Exception { + testResolveArgument(createMockMessageContext()); + } - @Test - public void axiomCachingArgument() throws Exception { - testResolveArgument(createCachingAxiomMessageContext()); - } + @Test + public void axiomCachingArgument() throws Exception { + testResolveArgument(createCachingAxiomMessageContext()); + } - @Test - public void axiomNonCachingArgument() throws Exception { - testResolveArgument(createNonCachingAxiomMessageContext()); - } + @Test + public void axiomNonCachingArgument() throws Exception { + testResolveArgument(createNonCachingAxiomMessageContext()); + } - private void testResolveArgument(MessageContext messageContext) throws Exception { - for (MethodParameter supportedParameter : supportedParameters) { - Object argument = processor.resolveArgument(messageContext, supportedParameter); + private void testResolveArgument(MessageContext messageContext) throws Exception { + for (MethodParameter supportedParameter : supportedParameters) { + Object argument = processor.resolveArgument(messageContext, supportedParameter); - assertTrue(argument + " is not an instance of " + supportedParameter.getParameterType(), - supportedParameter.getParameterType().isInstance(argument)); - testArgument(argument, supportedParameter); - } - } + assertTrue(argument + " is not an instance of " + supportedParameter.getParameterType(), + supportedParameter.getParameterType().isInstance(argument)); + testArgument(argument, supportedParameter); + } + } - protected void testArgument(Object argument, MethodParameter parameter) { - } + protected void testArgument(Object argument, MethodParameter parameter) { + } - @Test - public void saajReturnValue() throws Exception { - testHandleReturnValue(createSaajMessageContext()); - } + @Test + public void saajReturnValue() throws Exception { + testHandleReturnValue(createSaajMessageContext()); + } - @Test - public void mockReturnValue() throws Exception { - testHandleReturnValue(createMockMessageContext()); - } + @Test + public void mockReturnValue() throws Exception { + testHandleReturnValue(createMockMessageContext()); + } - @Test - public void axiomCachingReturnValue() throws Exception { - testHandleReturnValue(createCachingAxiomMessageContext()); - } + @Test + public void axiomCachingReturnValue() throws Exception { + testHandleReturnValue(createCachingAxiomMessageContext()); + } - @Test - public void axiomNonCachingReturnValue() throws Exception { - testHandleReturnValue(createNonCachingAxiomMessageContext()); - } + @Test + public void axiomNonCachingReturnValue() throws Exception { + testHandleReturnValue(createNonCachingAxiomMessageContext()); + } - private void testHandleReturnValue(MessageContext messageContext) throws Exception { - for (MethodParameter supportedReturnType : supportedReturnTypes) { - Object returnValue = getReturnValue(supportedReturnType); - processor.handleReturnValue(messageContext, supportedReturnType, returnValue); - assertTrue("No response created", messageContext.hasResponse()); - Source responsePayload = messageContext.getResponse().getPayloadSource(); - StringResult result = new StringResult(); - transform(responsePayload, result); - assertXMLEqual(XML, result.toString()); - } - } + private void testHandleReturnValue(MessageContext messageContext) throws Exception { + for (MethodParameter supportedReturnType : supportedReturnTypes) { + Object returnValue = getReturnValue(supportedReturnType); + processor.handleReturnValue(messageContext, supportedReturnType, returnValue); + assertTrue("No response created", messageContext.hasResponse()); + Source responsePayload = messageContext.getResponse().getPayloadSource(); + StringResult result = new StringResult(); + transform(responsePayload, result); + assertXMLEqual(XML, result.toString()); + } + } - protected abstract Object getReturnValue(MethodParameter returnType) throws Exception; + protected abstract Object getReturnValue(MethodParameter returnType) throws Exception; - public String unsupported(String s) { - return s; - } + public String unsupported(String s) { + return s; + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessorTest.java index 9fcd7768..a4a17702 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MarshallingPayloadMethodProcessorTest.java @@ -35,155 +35,155 @@ import static org.junit.Assert.*; public class MarshallingPayloadMethodProcessorTest extends AbstractMethodArgumentResolverTestCase { - private MarshallingPayloadMethodProcessor processor; + private MarshallingPayloadMethodProcessor processor; - private GenericMarshaller marshaller; + private GenericMarshaller marshaller; - private GenericUnmarshaller unmarshaller; + private GenericUnmarshaller unmarshaller; - private MethodParameter supportedParameter; + private MethodParameter supportedParameter; - private MethodParameter supportedReturnType; + private MethodParameter supportedReturnType; - @Before - public void setUp() throws Exception { - marshaller = createMock("marshaller", GenericMarshaller.class); - unmarshaller = createMock("unmarshaller", GenericUnmarshaller.class); - processor = new MarshallingPayloadMethodProcessor(marshaller, unmarshaller); - supportedParameter = new MethodParameter(getClass().getMethod("method", MyObject.class), 0); - supportedReturnType = new MethodParameter(getClass().getMethod("method", MyObject.class), -1); - } + @Before + public void setUp() throws Exception { + marshaller = createMock("marshaller", GenericMarshaller.class); + unmarshaller = createMock("unmarshaller", GenericUnmarshaller.class); + processor = new MarshallingPayloadMethodProcessor(marshaller, unmarshaller); + supportedParameter = new MethodParameter(getClass().getMethod("method", MyObject.class), 0); + supportedReturnType = new MethodParameter(getClass().getMethod("method", MyObject.class), -1); + } - @Test - public void supportsParameterSupported() { - expect(unmarshaller.supports(isA(Type.class))).andReturn(true); + @Test + public void supportsParameterSupported() { + expect(unmarshaller.supports(isA(Type.class))).andReturn(true); - replay(marshaller, unmarshaller); + replay(marshaller, unmarshaller); - assertTrue("processor does not support supported parameter", processor.supportsParameter(supportedParameter)); + assertTrue("processor does not support supported parameter", processor.supportsParameter(supportedParameter)); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test - public void supportsParameterUnsupported() { - expect(unmarshaller.supports(isA(Type.class))).andReturn(false); + @Test + public void supportsParameterUnsupported() { + expect(unmarshaller.supports(isA(Type.class))).andReturn(false); - replay(marshaller, unmarshaller); + replay(marshaller, unmarshaller); - assertFalse("processor supports unsupported parameter", processor.supportsParameter(supportedParameter)); + assertFalse("processor supports unsupported parameter", processor.supportsParameter(supportedParameter)); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test - public void supportsParameterNoUnmarshallerSupported() { - processor = new MarshallingPayloadMethodProcessor(); - processor.setMarshaller(marshaller); + @Test + public void supportsParameterNoUnmarshallerSupported() { + processor = new MarshallingPayloadMethodProcessor(); + processor.setMarshaller(marshaller); - replay(marshaller, unmarshaller); + replay(marshaller, unmarshaller); - assertFalse("processor supports parameter with no unmarshaller set", - processor.supportsParameter(supportedParameter)); + assertFalse("processor supports parameter with no unmarshaller set", + processor.supportsParameter(supportedParameter)); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test - public void supportsReturnTypeSupported() { - expect(marshaller.supports(isA(Type.class))).andReturn(true); + @Test + public void supportsReturnTypeSupported() { + expect(marshaller.supports(isA(Type.class))).andReturn(true); - replay(marshaller, unmarshaller); + replay(marshaller, unmarshaller); - assertTrue("processor does not support supported return type", processor.supportsReturnType(supportedReturnType)); + assertTrue("processor does not support supported return type", processor.supportsReturnType(supportedReturnType)); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test - public void supportsReturnTypeUnsupported() { - expect(marshaller.supports(isA(Type.class))).andReturn(false); + @Test + public void supportsReturnTypeUnsupported() { + expect(marshaller.supports(isA(Type.class))).andReturn(false); - replay(marshaller, unmarshaller); + replay(marshaller, unmarshaller); - assertFalse("processor supports unsupported parameter", processor.supportsReturnType(supportedReturnType)); + assertFalse("processor supports unsupported parameter", processor.supportsReturnType(supportedReturnType)); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test - public void supportsReturnTypeNoMarshaller() { - processor = new MarshallingPayloadMethodProcessor(); - processor.setUnmarshaller(unmarshaller); + @Test + public void supportsReturnTypeNoMarshaller() { + processor = new MarshallingPayloadMethodProcessor(); + processor.setUnmarshaller(unmarshaller); - replay(marshaller, unmarshaller); + replay(marshaller, unmarshaller); - assertFalse("processor supports return type with no marshaller set", - processor.supportsReturnType(supportedReturnType)); + assertFalse("processor supports return type with no marshaller set", + processor.supportsReturnType(supportedReturnType)); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test - public void resolveArgument() throws Exception { - MyObject expected = new MyObject(); + @Test + public void resolveArgument() throws Exception { + MyObject expected = new MyObject(); - expect(unmarshaller.unmarshal(isA(Source.class))).andReturn(expected); + expect(unmarshaller.unmarshal(isA(Source.class))).andReturn(expected); - replay(marshaller, unmarshaller); - MessageContext messageContext = createMockMessageContext(); + replay(marshaller, unmarshaller); + MessageContext messageContext = createMockMessageContext(); - Object result = processor.resolveArgument(messageContext, supportedParameter); - assertEquals("Invalid return argument", expected, result); + Object result = processor.resolveArgument(messageContext, supportedParameter); + assertEquals("Invalid return argument", expected, result); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test(expected = IllegalStateException.class) - public void resolveArgumentNoUnmarshaller() throws Exception { - processor = new MarshallingPayloadMethodProcessor(); - processor.setMarshaller(marshaller); + @Test(expected = IllegalStateException.class) + public void resolveArgumentNoUnmarshaller() throws Exception { + processor = new MarshallingPayloadMethodProcessor(); + processor.setMarshaller(marshaller); - replay(marshaller, unmarshaller); - MessageContext messageContext = createMockMessageContext(); + replay(marshaller, unmarshaller); + MessageContext messageContext = createMockMessageContext(); - processor.resolveArgument(messageContext, supportedParameter); - } + processor.resolveArgument(messageContext, supportedParameter); + } - @Test - public void handleReturnValue() throws Exception { - MyObject returnValue = new MyObject(); + @Test + public void handleReturnValue() throws Exception { + MyObject returnValue = new MyObject(); - marshaller.marshal(eq(returnValue), isA(Result.class)); + marshaller.marshal(eq(returnValue), isA(Result.class)); - replay(marshaller, unmarshaller); - MessageContext messageContext = createMockMessageContext(); + replay(marshaller, unmarshaller); + MessageContext messageContext = createMockMessageContext(); - processor.handleReturnValue(messageContext, supportedReturnType, returnValue); + processor.handleReturnValue(messageContext, supportedReturnType, returnValue); - verify(marshaller, unmarshaller); - } + verify(marshaller, unmarshaller); + } - @Test(expected = IllegalStateException.class) - public void handleReturnValueNoMarshaller() throws Exception { - processor = new MarshallingPayloadMethodProcessor(); - processor.setUnmarshaller(unmarshaller); + @Test(expected = IllegalStateException.class) + public void handleReturnValueNoMarshaller() throws Exception { + processor = new MarshallingPayloadMethodProcessor(); + processor.setUnmarshaller(unmarshaller); - MyObject returnValue = new MyObject(); + MyObject returnValue = new MyObject(); - replay(marshaller, unmarshaller); - MessageContext messageContext = createMockMessageContext(); + replay(marshaller, unmarshaller); + MessageContext messageContext = createMockMessageContext(); - processor.handleReturnValue(messageContext, supportedReturnType, returnValue); - } + processor.handleReturnValue(messageContext, supportedReturnType, returnValue); + } - @ResponsePayload - public MyObject method(@RequestPayload MyObject object) { - return object; - } + @ResponsePayload + public MyObject method(@RequestPayload MyObject object) { + return object; + } - public static class MyObject { + public static class MyObject { - } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolverTest.java index 7a5fea0b..59f52dc9 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/MessageContextMethodArgumentResolverTest.java @@ -29,30 +29,30 @@ import static org.junit.Assert.assertTrue; public class MessageContextMethodArgumentResolverTest { - private MessageContextMethodArgumentResolver resolver; + private MessageContextMethodArgumentResolver resolver; - private MethodParameter supported; + private MethodParameter supported; - @Before - public void setUp() throws NoSuchMethodException { - resolver = new MessageContextMethodArgumentResolver(); - supported = new MethodParameter(getClass().getMethod("supported", MessageContext.class), 0); - } + @Before + public void setUp() throws NoSuchMethodException { + resolver = new MessageContextMethodArgumentResolver(); + supported = new MethodParameter(getClass().getMethod("supported", MessageContext.class), 0); + } - @Test - public void supportsParameter() throws Exception { - assertTrue("resolver does not support MessageContext", resolver.supportsParameter(supported)); - } + @Test + public void supportsParameter() throws Exception { + assertTrue("resolver does not support MessageContext", resolver.supportsParameter(supported)); + } - @Test - public void resolveArgument() throws Exception { - MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + @Test + public void resolveArgument() throws Exception { + MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - MessageContext result = resolver.resolveArgument(messageContext, supported); - assertSame("Invalid message context returned", messageContext, result); - } + MessageContext result = resolver.resolveArgument(messageContext, supported); + assertSame("Invalid message context returned", messageContext, result); + } - public void supported(MessageContext messageContext) { - } + public void supported(MessageContext messageContext) { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessorTest.java index 16cb6735..74586626 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/SourcePayloadMethodProcessorTest.java @@ -30,56 +30,56 @@ import org.springframework.xml.transform.StringSource; /** @author Arjen Poutsma */ public class SourcePayloadMethodProcessorTest extends AbstractPayloadMethodProcessorTestCase { - @Override - protected AbstractPayloadSourceMethodProcessor createProcessor() { - return new SourcePayloadMethodProcessor(); - } + @Override + protected AbstractPayloadSourceMethodProcessor createProcessor() { + return new SourcePayloadMethodProcessor(); + } - @Override - protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("source", Source.class), 0), - new MethodParameter(getClass().getMethod("dom", DOMSource.class), 0), - new MethodParameter(getClass().getMethod("sax", SAXSource.class), 0), - new MethodParameter(getClass().getMethod("stream", StreamSource.class), 0), - new MethodParameter(getClass().getMethod("stax", StAXSource.class), 0)}; - } + @Override + protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("source", Source.class), 0), + new MethodParameter(getClass().getMethod("dom", DOMSource.class), 0), + new MethodParameter(getClass().getMethod("sax", SAXSource.class), 0), + new MethodParameter(getClass().getMethod("stream", StreamSource.class), 0), + new MethodParameter(getClass().getMethod("stax", StAXSource.class), 0)}; + } - @Override - protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("source", Source.class), -1), - new MethodParameter(getClass().getMethod("dom", DOMSource.class), -1), - new MethodParameter(getClass().getMethod("sax", SAXSource.class), -1), - new MethodParameter(getClass().getMethod("stream", StreamSource.class), -1), - new MethodParameter(getClass().getMethod("stax", StAXSource.class), -1)}; - } + @Override + protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("source", Source.class), -1), + new MethodParameter(getClass().getMethod("dom", DOMSource.class), -1), + new MethodParameter(getClass().getMethod("sax", SAXSource.class), -1), + new MethodParameter(getClass().getMethod("stream", StreamSource.class), -1), + new MethodParameter(getClass().getMethod("stax", StAXSource.class), -1)}; + } - @Override - protected Object getReturnValue(MethodParameter returnType) throws Exception { - return new StringSource(XML); - } + @Override + protected Object getReturnValue(MethodParameter returnType) throws Exception { + return new StringSource(XML); + } - @ResponsePayload - public Source source(@RequestPayload Source source) { - return source; - } + @ResponsePayload + public Source source(@RequestPayload Source source) { + return source; + } - @ResponsePayload - public DOMSource dom(@RequestPayload DOMSource source) { - return source; - } + @ResponsePayload + public DOMSource dom(@RequestPayload DOMSource source) { + return source; + } - @ResponsePayload - public SAXSource sax(@RequestPayload SAXSource source) { - return source; - } + @ResponsePayload + public SAXSource sax(@RequestPayload SAXSource source) { + return source; + } - @ResponsePayload - public StreamSource stream(@RequestPayload StreamSource source) { - return source; - } + @ResponsePayload + public StreamSource stream(@RequestPayload StreamSource source) { + return source; + } - @ResponsePayload - public StAXSource stax(@RequestPayload StAXSource source) { - return source; - } + @ResponsePayload + public StAXSource stax(@RequestPayload StAXSource source) { + return source; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolverTest.java index ff3cfa7f..62b5f9f0 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/StaxPayloadMethodArgumentResolverTest.java @@ -36,129 +36,129 @@ import static org.junit.Assert.*; @SuppressWarnings("Since15") public class StaxPayloadMethodArgumentResolverTest extends AbstractMethodArgumentResolverTestCase { - private StaxPayloadMethodArgumentResolver resolver; + private StaxPayloadMethodArgumentResolver resolver; - private MethodParameter streamParameter; + private MethodParameter streamParameter; - private MethodParameter eventParameter; + private MethodParameter eventParameter; - private MethodParameter invalidParameter; + private MethodParameter invalidParameter; - @Before - public void setUp() throws Exception { - resolver = new StaxPayloadMethodArgumentResolver(); - streamParameter = new MethodParameter(getClass().getMethod("streamReader", XMLStreamReader.class), 0); - eventParameter = new MethodParameter(getClass().getMethod("eventReader", XMLEventReader.class), 0); - invalidParameter = new MethodParameter(getClass().getMethod("invalid", XMLStreamReader.class), 0); - } + @Before + public void setUp() throws Exception { + resolver = new StaxPayloadMethodArgumentResolver(); + streamParameter = new MethodParameter(getClass().getMethod("streamReader", XMLStreamReader.class), 0); + eventParameter = new MethodParameter(getClass().getMethod("eventReader", XMLEventReader.class), 0); + invalidParameter = new MethodParameter(getClass().getMethod("invalid", XMLStreamReader.class), 0); + } - @Test - public void supportsParameter() { - assertTrue("resolver does not support XMLStreamReader", resolver.supportsParameter(streamParameter)); - assertTrue("resolver does not support XMLEventReader", resolver.supportsParameter(eventParameter)); - assertFalse("resolver supports invalid parameter", resolver.supportsParameter(invalidParameter)); - } + @Test + public void supportsParameter() { + assertTrue("resolver does not support XMLStreamReader", resolver.supportsParameter(streamParameter)); + assertTrue("resolver does not support XMLEventReader", resolver.supportsParameter(eventParameter)); + assertFalse("resolver supports invalid parameter", resolver.supportsParameter(invalidParameter)); + } - @Test - public void resolveStreamReaderSaaj() throws Exception { - MessageContext messageContext = createSaajMessageContext(); + @Test + public void resolveStreamReaderSaaj() throws Exception { + MessageContext messageContext = createSaajMessageContext(); - Object result = resolver.resolveArgument(messageContext, streamParameter); + Object result = resolver.resolveArgument(messageContext, streamParameter); - testStreamReader(result); - } + testStreamReader(result); + } - @Test - public void resolveStreamReaderAxiomCaching() throws Exception { - MessageContext messageContext = createCachingAxiomMessageContext(); + @Test + public void resolveStreamReaderAxiomCaching() throws Exception { + MessageContext messageContext = createCachingAxiomMessageContext(); - Object result = resolver.resolveArgument(messageContext, streamParameter); + Object result = resolver.resolveArgument(messageContext, streamParameter); - testStreamReader(result); - } + testStreamReader(result); + } - @Test - public void resolveStreamReaderAxiomNonCaching() throws Exception { - MessageContext messageContext = createNonCachingAxiomMessageContext(); + @Test + public void resolveStreamReaderAxiomNonCaching() throws Exception { + MessageContext messageContext = createNonCachingAxiomMessageContext(); - Object result = resolver.resolveArgument(messageContext, streamParameter); + Object result = resolver.resolveArgument(messageContext, streamParameter); - testStreamReader(result); - } + testStreamReader(result); + } - @Test - public void resolveStreamReaderStream() throws Exception { - MessageContext messageContext = createMockMessageContext(); + @Test + public void resolveStreamReaderStream() throws Exception { + MessageContext messageContext = createMockMessageContext(); - Object result = resolver.resolveArgument(messageContext, streamParameter); + Object result = resolver.resolveArgument(messageContext, streamParameter); - testStreamReader(result); - } + testStreamReader(result); + } - @Test - public void resolveEventReaderSaaj() throws Exception { - MessageContext messageContext = createSaajMessageContext(); + @Test + public void resolveEventReaderSaaj() throws Exception { + MessageContext messageContext = createSaajMessageContext(); - Object result = resolver.resolveArgument(messageContext, eventParameter); + Object result = resolver.resolveArgument(messageContext, eventParameter); - testEventReader(result); - } + testEventReader(result); + } - @Test - public void resolveEventReaderAxiomCaching() throws Exception { - MessageContext messageContext = createCachingAxiomMessageContext(); + @Test + public void resolveEventReaderAxiomCaching() throws Exception { + MessageContext messageContext = createCachingAxiomMessageContext(); - Object result = resolver.resolveArgument(messageContext, eventParameter); + Object result = resolver.resolveArgument(messageContext, eventParameter); - testEventReader(result); - } + testEventReader(result); + } - @Test - public void resolveEventReaderAxiomNonCaching() throws Exception { - MessageContext messageContext = createNonCachingAxiomMessageContext(); + @Test + public void resolveEventReaderAxiomNonCaching() throws Exception { + MessageContext messageContext = createNonCachingAxiomMessageContext(); - Object result = resolver.resolveArgument(messageContext, eventParameter); + Object result = resolver.resolveArgument(messageContext, eventParameter); - testEventReader(result); - } + testEventReader(result); + } - @Test - public void resolveEventReaderStream() throws Exception { - MessageContext messageContext = createMockMessageContext(); + @Test + public void resolveEventReaderStream() throws Exception { + MessageContext messageContext = createMockMessageContext(); - Object result = resolver.resolveArgument(messageContext, eventParameter); + Object result = resolver.resolveArgument(messageContext, eventParameter); - testEventReader(result); - } + testEventReader(result); + } - private void testStreamReader(Object result) throws XMLStreamException { - assertTrue("resolver does not return XMLStreamReader", result instanceof XMLStreamReader); - XMLStreamReader streamReader = (XMLStreamReader) result; - assertTrue("streamReader has no next element", streamReader.hasNext()); - assertEquals(XMLStreamConstants.START_ELEMENT, streamReader.nextTag()); - assertEquals("Invalid namespace", NAMESPACE_URI, streamReader.getNamespaceURI()); - assertEquals("Invalid local name", LOCAL_NAME, streamReader.getLocalName()); - } + private void testStreamReader(Object result) throws XMLStreamException { + assertTrue("resolver does not return XMLStreamReader", result instanceof XMLStreamReader); + XMLStreamReader streamReader = (XMLStreamReader) result; + assertTrue("streamReader has no next element", streamReader.hasNext()); + assertEquals(XMLStreamConstants.START_ELEMENT, streamReader.nextTag()); + assertEquals("Invalid namespace", NAMESPACE_URI, streamReader.getNamespaceURI()); + assertEquals("Invalid local name", LOCAL_NAME, streamReader.getLocalName()); + } - private void testEventReader(Object result) throws XMLStreamException { - assertTrue("resolver does not return XMLEventReader", result instanceof XMLEventReader); - XMLEventReader eventReader = (XMLEventReader) result; - assertTrue("eventReader has no next element", eventReader.hasNext()); - XMLEvent event = eventReader.nextTag(); - assertEquals(XMLStreamConstants.START_ELEMENT, event.getEventType()); - StartElement startElement = (StartElement) event; - assertEquals("Invalid namespace", NAMESPACE_URI, startElement.getName().getNamespaceURI()); - assertEquals("Invalid local name", LOCAL_NAME, startElement.getName().getLocalPart()); - } + private void testEventReader(Object result) throws XMLStreamException { + assertTrue("resolver does not return XMLEventReader", result instanceof XMLEventReader); + XMLEventReader eventReader = (XMLEventReader) result; + assertTrue("eventReader has no next element", eventReader.hasNext()); + XMLEvent event = eventReader.nextTag(); + assertEquals(XMLStreamConstants.START_ELEMENT, event.getEventType()); + StartElement startElement = (StartElement) event; + assertEquals("Invalid namespace", NAMESPACE_URI, startElement.getName().getNamespaceURI()); + assertEquals("Invalid local name", LOCAL_NAME, startElement.getName().getLocalPart()); + } - public void invalid(XMLStreamReader streamReader) { - } + public void invalid(XMLStreamReader streamReader) { + } - public void streamReader(@RequestPayload XMLStreamReader streamReader) { - } + public void streamReader(@RequestPayload XMLStreamReader streamReader) { + } - public void eventReader(@RequestPayload XMLEventReader streamReader) { - } + public void eventReader(@RequestPayload XMLEventReader streamReader) { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolverTest.java index b5562731..c7bd4419 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/XPathParamMethodArgumentResolverTest.java @@ -37,171 +37,171 @@ import static org.junit.Assert.*; @Namespaces(@Namespace(prefix = "tns", uri = "http://springframework.org/spring-ws")) public class XPathParamMethodArgumentResolverTest { - private static final String CONTENTS = "text42"; + private static final String CONTENTS = "text42"; - private XPathParamMethodArgumentResolver resolver; + private XPathParamMethodArgumentResolver resolver; - private MethodParameter booleanParameter; + private MethodParameter booleanParameter; - private MethodParameter doubleParameter; + private MethodParameter doubleParameter; - private MethodParameter nodeParameter; + private MethodParameter nodeParameter; - private MethodParameter nodeListParameter; + private MethodParameter nodeListParameter; - private MethodParameter stringParameter; + private MethodParameter stringParameter; - private MethodParameter convertedParameter; + private MethodParameter convertedParameter; - private MethodParameter unsupportedParameter; + private MethodParameter unsupportedParameter; - private MethodParameter namespaceMethodParameter; + private MethodParameter namespaceMethodParameter; - private MethodParameter namespaceClassParameter; + private MethodParameter namespaceClassParameter; - @Before - public void setUp() throws Exception { - resolver = new XPathParamMethodArgumentResolver(); - Method supportedTypes = getClass() - .getMethod("supportedTypes", Boolean.TYPE, Double.TYPE, Node.class, NodeList.class, String.class); - booleanParameter = new MethodParameter(supportedTypes, 0); - doubleParameter = new MethodParameter(supportedTypes, 1); - nodeParameter = new MethodParameter(supportedTypes, 2); - nodeListParameter = new MethodParameter(supportedTypes, 3); - stringParameter = new MethodParameter(supportedTypes, 4); - convertedParameter = new MethodParameter(getClass().getMethod("convertedType", Integer.TYPE), 0); - unsupportedParameter = new MethodParameter(getClass().getMethod("unsupported", String.class), 0); - namespaceMethodParameter = new MethodParameter(getClass().getMethod("namespacesMethod", String.class), 0); - namespaceClassParameter = new MethodParameter(getClass().getMethod("namespacesClass", String.class), 0); - } + @Before + public void setUp() throws Exception { + resolver = new XPathParamMethodArgumentResolver(); + Method supportedTypes = getClass() + .getMethod("supportedTypes", Boolean.TYPE, Double.TYPE, Node.class, NodeList.class, String.class); + booleanParameter = new MethodParameter(supportedTypes, 0); + doubleParameter = new MethodParameter(supportedTypes, 1); + nodeParameter = new MethodParameter(supportedTypes, 2); + nodeListParameter = new MethodParameter(supportedTypes, 3); + stringParameter = new MethodParameter(supportedTypes, 4); + convertedParameter = new MethodParameter(getClass().getMethod("convertedType", Integer.TYPE), 0); + unsupportedParameter = new MethodParameter(getClass().getMethod("unsupported", String.class), 0); + namespaceMethodParameter = new MethodParameter(getClass().getMethod("namespacesMethod", String.class), 0); + namespaceClassParameter = new MethodParameter(getClass().getMethod("namespacesClass", String.class), 0); + } - @Test - public void supportsParameter() { - assertTrue("resolver does not support boolean parameter", resolver.supportsParameter(booleanParameter)); - assertTrue("resolver does not support double parameter", resolver.supportsParameter(doubleParameter)); - assertTrue("resolver does not support Node parameter", resolver.supportsParameter(nodeParameter)); - assertTrue("resolver does not support NodeList parameter", resolver.supportsParameter(nodeListParameter)); - assertTrue("resolver does not support String parameter", resolver.supportsParameter(stringParameter)); - assertTrue("resolver does not support String parameter", resolver.supportsParameter(convertedParameter)); - assertFalse("resolver supports parameter without @XPathParam", resolver.supportsParameter(unsupportedParameter)); - } + @Test + public void supportsParameter() { + assertTrue("resolver does not support boolean parameter", resolver.supportsParameter(booleanParameter)); + assertTrue("resolver does not support double parameter", resolver.supportsParameter(doubleParameter)); + assertTrue("resolver does not support Node parameter", resolver.supportsParameter(nodeParameter)); + assertTrue("resolver does not support NodeList parameter", resolver.supportsParameter(nodeListParameter)); + assertTrue("resolver does not support String parameter", resolver.supportsParameter(stringParameter)); + assertTrue("resolver does not support String parameter", resolver.supportsParameter(convertedParameter)); + assertFalse("resolver supports parameter without @XPathParam", resolver.supportsParameter(unsupportedParameter)); + } - @Test - public void resolveBoolean() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveBoolean() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, booleanParameter); + Object result = resolver.resolveArgument(messageContext, booleanParameter); - assertTrue("resolver does not return boolean", result instanceof Boolean); - Boolean b = (Boolean) result; - assertTrue("Invalid boolean value", b); - } - @Test - public void resolveDouble() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + assertTrue("resolver does not return boolean", result instanceof Boolean); + Boolean b = (Boolean) result; + assertTrue("Invalid boolean value", b); + } + @Test + public void resolveDouble() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, doubleParameter); + Object result = resolver.resolveArgument(messageContext, doubleParameter); - assertTrue("resolver does not return double", result instanceof Double); - Double d = (Double) result; - assertEquals("Invalid double value", 42D, d, 0D); - } + assertTrue("resolver does not return double", result instanceof Double); + Double d = (Double) result; + assertEquals("Invalid double value", 42D, d, 0D); + } - @Test - public void resolveNode() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveNode() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, nodeParameter); + Object result = resolver.resolveArgument(messageContext, nodeParameter); - assertTrue("resolver does not return Node", result instanceof Node); - Node node = (Node) result; - assertEquals("Invalid node value", "child", node.getLocalName()); - } + assertTrue("resolver does not return Node", result instanceof Node); + Node node = (Node) result; + assertEquals("Invalid node value", "child", node.getLocalName()); + } - @Test - public void resolveNodeList() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveNodeList() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, nodeListParameter); + Object result = resolver.resolveArgument(messageContext, nodeListParameter); - assertTrue("resolver does not return NodeList", result instanceof NodeList); - NodeList nodeList = (NodeList) result; - assertEquals("Invalid NodeList value", 1, nodeList.getLength()); - assertEquals("Invalid Node value", "child", nodeList.item(0).getLocalName()); - } + assertTrue("resolver does not return NodeList", result instanceof NodeList); + NodeList nodeList = (NodeList) result; + assertEquals("Invalid NodeList value", 1, nodeList.getLength()); + assertEquals("Invalid Node value", "child", nodeList.item(0).getLocalName()); + } - @Test - public void resolveString() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveString() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, stringParameter); + Object result = resolver.resolveArgument(messageContext, stringParameter); - assertTrue("resolver does not return String", result instanceof String); - String s = (String) result; - assertEquals("Invalid string value", "text", s); - } - - @Test - public void resolveConvertedType() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + assertTrue("resolver does not return String", result instanceof String); + String s = (String) result; + assertEquals("Invalid string value", "text", s); + } + + @Test + public void resolveConvertedType() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(CONTENTS); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, convertedParameter); + Object result = resolver.resolveArgument(messageContext, convertedParameter); - assertTrue("resolver does not return String", result instanceof Integer); - Integer i = (Integer) result; - assertEquals("Invalid integer value", new Integer(42), i); - } + assertTrue("resolver does not return String", result instanceof Integer); + Integer i = (Integer) result; + assertEquals("Invalid integer value", new Integer(42), i); + } - @Test - public void resolveNamespacesMethod() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage( - "text"); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveNamespacesMethod() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage( + "text"); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, namespaceMethodParameter); + Object result = resolver.resolveArgument(messageContext, namespaceMethodParameter); - assertTrue("resolver does not return String", result instanceof String); - String s = (String) result; - assertEquals("Invalid string value", "text", s); - } - - @Test - public void resolveNamespacesClass() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage( - "text"); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + assertTrue("resolver does not return String", result instanceof String); + String s = (String) result; + assertEquals("Invalid string value", "text", s); + } + + @Test + public void resolveNamespacesClass() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage( + "text"); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = resolver.resolveArgument(messageContext, namespaceClassParameter); + Object result = resolver.resolveArgument(messageContext, namespaceClassParameter); - assertTrue("resolver does not return String", result instanceof String); - String s = (String) result; - assertEquals("Invalid string value", "text", s); - } + assertTrue("resolver does not return String", result instanceof String); + String s = (String) result; + assertEquals("Invalid string value", "text", s); + } - public void unsupported(String s) { - } + public void unsupported(String s) { + } - public void supportedTypes(@XPathParam("/root/child")boolean param1, - @XPathParam("/root/child/number")double param2, - @XPathParam("/root/child") Node param3, - @XPathParam("/root/*") NodeList param4, - @XPathParam("/root/child/text")String param5) { - } + public void supportedTypes(@XPathParam("/root/child")boolean param1, + @XPathParam("/root/child/number")double param2, + @XPathParam("/root/child") Node param3, + @XPathParam("/root/*") NodeList param4, + @XPathParam("/root/child/text")String param5) { + } - public void convertedType(@XPathParam("/root/child/number")int param) { - } + public void convertedType(@XPathParam("/root/child/number")int param) { + } - @Namespaces(@Namespace(prefix = "tns", uri = "http://springframework.org/spring-ws")) - public void namespacesMethod(@XPathParam("/tns:root")String s) { - } + @Namespaces(@Namespace(prefix = "tns", uri = "http://springframework.org/spring-ws")) + public void namespacesMethod(@XPathParam("/tns:root")String s) { + } - public void namespacesClass(@XPathParam("/tns:root")String s) { - } + public void namespacesClass(@XPathParam("/tns:root")String s) { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessorTest.java index 82b9c35a..59a1d893 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/Dom4jPayloadMethodProcessorTest.java @@ -32,38 +32,38 @@ import static org.junit.Assert.assertTrue; public class Dom4jPayloadMethodProcessorTest extends AbstractPayloadMethodProcessorTestCase { @Override - protected AbstractPayloadSourceMethodProcessor createProcessor() { - return new Dom4jPayloadMethodProcessor(); - } + protected AbstractPayloadSourceMethodProcessor createProcessor() { + return new Dom4jPayloadMethodProcessor(); + } - @Override - protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { - return new MethodParameter[]{ - new MethodParameter(getClass().getMethod("element", Element.class), 0)}; - } + @Override + protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { + return new MethodParameter[]{ + new MethodParameter(getClass().getMethod("element", Element.class), 0)}; + } - @Override - protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; - } + @Override + protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; + } - @Override - protected void testArgument(Object argument, MethodParameter parameter) { - assertTrue("argument not a element", argument instanceof Element); - Element element = (Element) argument; - assertEquals("Invalid namespace", NAMESPACE_URI, element.getNamespaceURI()); - assertEquals("Invalid local name", LOCAL_NAME, element.getName()); - } + @Override + protected void testArgument(Object argument, MethodParameter parameter) { + assertTrue("argument not a element", argument instanceof Element); + Element element = (Element) argument; + assertEquals("Invalid namespace", NAMESPACE_URI, element.getNamespaceURI()); + assertEquals("Invalid local name", LOCAL_NAME, element.getName()); + } - @Override - protected Element getReturnValue(MethodParameter returnType) { - Document document = DocumentHelper.createDocument(); - return document.addElement(LOCAL_NAME, NAMESPACE_URI); - } + @Override + protected Element getReturnValue(MethodParameter returnType) { + Document document = DocumentHelper.createDocument(); + return document.addElement(LOCAL_NAME, NAMESPACE_URI); + } - @ResponsePayload - public Element element(@RequestPayload Element element) { - return element; - } + @ResponsePayload + public Element element(@RequestPayload Element element) { + return element; + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessorTest.java index 316cd588..c4a4f21d 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/DomPayloadMethodProcessorTest.java @@ -34,41 +34,41 @@ import static org.junit.Assert.assertTrue; public class DomPayloadMethodProcessorTest extends AbstractPayloadMethodProcessorTestCase { - @Override - protected AbstractPayloadSourceMethodProcessor createProcessor() { - return new DomPayloadMethodProcessor(); - } + @Override + protected AbstractPayloadSourceMethodProcessor createProcessor() { + return new DomPayloadMethodProcessor(); + } - @Override - protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { - return new MethodParameter[]{ - new MethodParameter(getClass().getMethod("element", Element.class), 0)}; - } + @Override + protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { + return new MethodParameter[]{ + new MethodParameter(getClass().getMethod("element", Element.class), 0)}; + } - @Override - protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; - } + @Override + protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; + } - @Override - protected void testArgument(Object argument, MethodParameter parameter) { - assertTrue("argument not a element", argument instanceof Element); - Element element = (Element) argument; - assertEquals("Invalid namespace", NAMESPACE_URI, element.getNamespaceURI()); - assertEquals("Invalid local name", LOCAL_NAME, element.getLocalName()); - } + @Override + protected void testArgument(Object argument, MethodParameter parameter) { + assertTrue("argument not a element", argument instanceof Element); + Element element = (Element) argument; + assertEquals("Invalid namespace", NAMESPACE_URI, element.getNamespaceURI()); + assertEquals("Invalid local name", LOCAL_NAME, element.getLocalName()); + } - @Override - protected Element getReturnValue(MethodParameter returnType) throws ParserConfigurationException { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - return document.createElementNS(NAMESPACE_URI, LOCAL_NAME); - } + @Override + protected Element getReturnValue(MethodParameter returnType) throws ParserConfigurationException { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + return document.createElementNS(NAMESPACE_URI, LOCAL_NAME); + } - @ResponsePayload - public Element element(@RequestPayload Element element) { - return element; - } + @ResponsePayload + public Element element(@RequestPayload Element element) { + return element; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessorTest.java index afee33c6..8c207395 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/JDomPayloadMethodProcessorTest.java @@ -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, @@ -29,36 +29,36 @@ import static org.junit.Assert.assertTrue; public class JDomPayloadMethodProcessorTest extends AbstractPayloadMethodProcessorTestCase { - @Override - protected AbstractPayloadSourceMethodProcessor createProcessor() { - return new JDomPayloadMethodProcessor(); - } + @Override + protected AbstractPayloadSourceMethodProcessor createProcessor() { + return new JDomPayloadMethodProcessor(); + } - @Override - protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), 0)}; - } + @Override + protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), 0)}; + } - @Override - protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; - } + @Override + protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; + } - @Override - protected void testArgument(Object argument, MethodParameter parameter) { - assertTrue("argument not a element", argument instanceof Element); - Element node = (Element) argument; - assertEquals("Invalid namespace", NAMESPACE_URI, node.getNamespaceURI()); - assertEquals("Invalid local name", LOCAL_NAME, node.getName()); - } + @Override + protected void testArgument(Object argument, MethodParameter parameter) { + assertTrue("argument not a element", argument instanceof Element); + Element node = (Element) argument; + assertEquals("Invalid namespace", NAMESPACE_URI, node.getNamespaceURI()); + assertEquals("Invalid local name", LOCAL_NAME, node.getName()); + } - @Override - protected Element getReturnValue(MethodParameter returnType) { - return new Element(LOCAL_NAME, NAMESPACE_URI); - } + @Override + protected Element getReturnValue(MethodParameter returnType) { + return new Element(LOCAL_NAME, NAMESPACE_URI); + } - @ResponsePayload - public Element element(@RequestPayload Element element) { - return element; - } + @ResponsePayload + public Element element(@RequestPayload Element element) { + return element; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessorTest.java index e78d757c..bcde5149 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/dom/XomPayloadMethodProcessorTest.java @@ -29,36 +29,36 @@ import static org.junit.Assert.assertTrue; public class XomPayloadMethodProcessorTest extends AbstractPayloadMethodProcessorTestCase { - @Override - protected AbstractPayloadSourceMethodProcessor createProcessor() { - return new XomPayloadMethodProcessor(); - } + @Override + protected AbstractPayloadSourceMethodProcessor createProcessor() { + return new XomPayloadMethodProcessor(); + } - @Override - protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), 0)}; - } + @Override + protected MethodParameter[] createSupportedParameters() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), 0)}; + } - @Override - protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { - return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; - } + @Override + protected MethodParameter[] createSupportedReturnTypes() throws NoSuchMethodException { + return new MethodParameter[]{new MethodParameter(getClass().getMethod("element", Element.class), -1)}; + } - @Override - protected void testArgument(Object argument, MethodParameter parameter) { - assertTrue("argument not a element", argument instanceof Element); - Element node = (Element) argument; - assertEquals("Invalid namespace", NAMESPACE_URI, node.getNamespaceURI()); - assertEquals("Invalid local name", LOCAL_NAME, node.getLocalName()); - } + @Override + protected void testArgument(Object argument, MethodParameter parameter) { + assertTrue("argument not a element", argument instanceof Element); + Element node = (Element) argument; + assertEquals("Invalid namespace", NAMESPACE_URI, node.getNamespaceURI()); + assertEquals("Invalid local name", LOCAL_NAME, node.getLocalName()); + } - @Override - protected Element getReturnValue(MethodParameter returnType) { - return new Element(LOCAL_NAME, NAMESPACE_URI); - } + @Override + protected Element getReturnValue(MethodParameter returnType) { + return new Element(LOCAL_NAME, NAMESPACE_URI); + } - @ResponsePayload - public Element element(@RequestPayload Element element) { - return element; - } + @ResponsePayload + public Element element(@RequestPayload Element element) { + return element; + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessorTest.java index d28ad21c..c0c8d1ef 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/JaxbElementPayloadMethodProcessorTest.java @@ -44,69 +44,69 @@ import org.springframework.xml.transform.StringResult; public class JaxbElementPayloadMethodProcessorTest { - private JaxbElementPayloadMethodProcessor processor; + private JaxbElementPayloadMethodProcessor processor; - private MethodParameter supportedParameter; + private MethodParameter supportedParameter; - private MethodParameter supportedReturnType; + private MethodParameter supportedReturnType; - private MethodParameter stringReturnType; + private MethodParameter stringReturnType; - @Before - public void setUp() throws Exception { - processor = new JaxbElementPayloadMethodProcessor(); - supportedParameter = new MethodParameter(getClass().getMethod("supported", JAXBElement.class), 0); - supportedReturnType = new MethodParameter(getClass().getMethod("supported", JAXBElement.class), -1); - stringReturnType = new MethodParameter(getClass().getMethod("string"), -1); - } + @Before + public void setUp() throws Exception { + processor = new JaxbElementPayloadMethodProcessor(); + supportedParameter = new MethodParameter(getClass().getMethod("supported", JAXBElement.class), 0); + supportedReturnType = new MethodParameter(getClass().getMethod("supported", JAXBElement.class), -1); + stringReturnType = new MethodParameter(getClass().getMethod("string"), -1); + } - @Test - public void supportsParameter() { - assertTrue("processor does not support @JAXBElement parameter", - processor.supportsParameter(supportedParameter)); - } + @Test + public void supportsParameter() { + assertTrue("processor does not support @JAXBElement parameter", + processor.supportsParameter(supportedParameter)); + } - @Test - public void supportsReturnType() { - assertTrue("processor does not support @JAXBElement return type", - processor.supportsReturnType(supportedReturnType)); - } + @Test + public void supportsReturnType() { + assertTrue("processor does not support @JAXBElement return type", + processor.supportsReturnType(supportedReturnType)); + } - @Test - public void resolveArgument() throws JAXBException { - WebServiceMessage request = new MockWebServiceMessage("Foo"); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveArgument() throws JAXBException { + WebServiceMessage request = new MockWebServiceMessage("Foo"); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - JAXBElement result = processor.resolveArgument(messageContext, supportedParameter); - assertTrue("result not a MyType", result.getValue() instanceof MyType); - MyType type = (MyType) result.getValue(); - assertEquals("invalid result", "Foo", type.getString()); - } + JAXBElement result = processor.resolveArgument(messageContext, supportedParameter); + assertTrue("result not a MyType", result.getValue() instanceof MyType); + MyType type = (MyType) result.getValue(); + assertEquals("invalid result", "Foo", type.getString()); + } - @Test - public void handleReturnValue() throws Exception { - MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + @Test + public void handleReturnValue() throws Exception { + MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - MyType type = new MyType(); - type.setString("Foo"); - JAXBElement element = new JAXBElement(new QName("http://springframework.org", "type"), MyType.class, type); - processor.handleReturnValue(messageContext, supportedReturnType, element); - assertTrue("context has no response", messageContext.hasResponse()); - MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); - assertXMLEqual("Foo", response.getPayloadAsString()); - } + MyType type = new MyType(); + type.setString("Foo"); + JAXBElement element = new JAXBElement(new QName("http://springframework.org", "type"), MyType.class, type); + processor.handleReturnValue(messageContext, supportedReturnType, element); + assertTrue("context has no response", messageContext.hasResponse()); + MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); + assertXMLEqual("Foo", response.getPayloadAsString()); + } - @Test - public void handleReturnValueString() throws Exception { - MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + @Test + public void handleReturnValueString() throws Exception { + MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - String s = "Foo"; - JAXBElement element = new JAXBElement(new QName("http://springframework.org", "string"), String.class, s); - processor.handleReturnValue(messageContext, stringReturnType, element); - assertTrue("context has no response", messageContext.hasResponse()); - MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); - assertXMLEqual("Foo", response.getPayloadAsString()); - } + String s = "Foo"; + JAXBElement element = new JAXBElement(new QName("http://springframework.org", "string"), String.class, s); + processor.handleReturnValue(messageContext, stringReturnType, element); + assertTrue("context has no response", messageContext.hasResponse()); + MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); + assertXMLEqual("Foo", response.getPayloadAsString()); + } @Test public void handleNullReturnValue() throws Exception { @@ -117,60 +117,60 @@ public class JaxbElementPayloadMethodProcessorTest { assertFalse("context has response", messageContext.hasResponse()); } - @Test - public void handleReturnValueAxiom() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - MessageContext messageContext = new DefaultMessageContext(messageFactory); + @Test + public void handleReturnValueAxiom() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + MessageContext messageContext = new DefaultMessageContext(messageFactory); - MyType type = new MyType(); - type.setString("Foo"); - JAXBElement element = new JAXBElement(new QName("http://springframework.org", "type"), MyType.class, type); + MyType type = new MyType(); + type.setString("Foo"); + JAXBElement element = new JAXBElement(new QName("http://springframework.org", "type"), MyType.class, type); - processor.handleReturnValue(messageContext, supportedReturnType, element); - assertTrue("context has no response", messageContext.hasResponse()); - AxiomSoapMessage response = (AxiomSoapMessage) messageContext.getResponse(); + processor.handleReturnValue(messageContext, supportedReturnType, element); + assertTrue("context has no response", messageContext.hasResponse()); + AxiomSoapMessage response = (AxiomSoapMessage) messageContext.getResponse(); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - StringResult payloadResult = new StringResult(); - transformer.transform(response.getPayloadSource(), payloadResult); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + StringResult payloadResult = new StringResult(); + transformer.transform(response.getPayloadSource(), payloadResult); - assertXMLEqual("Foo", - payloadResult.toString()); + assertXMLEqual("Foo", + payloadResult.toString()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - response.writeTo(bos); - String messageResult = bos.toString("UTF-8"); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + response.writeTo(bos); + String messageResult = bos.toString("UTF-8"); - assertXMLEqual("" + - "Foo" + - "", messageResult); + assertXMLEqual("" + + "Foo" + + "", messageResult); - } + } - @ResponsePayload - public JAXBElement supported(@RequestPayload JAXBElement element) { - return element; - } + @ResponsePayload + public JAXBElement supported(@RequestPayload JAXBElement element) { + return element; + } - @ResponsePayload - public JAXBElement string() { - return new JAXBElement(new QName("string"), String.class, "Foo"); - } + @ResponsePayload + public JAXBElement string() { + return new JAXBElement(new QName("string"), String.class, "Foo"); + } - @XmlType(name="myType", namespace = "http://springframework.org") - public static class MyType { + @XmlType(name="myType", namespace = "http://springframework.org") + public static class MyType { - private String string; + private String string; - @XmlElement(name = "string", namespace = "http://springframework.org") - public String getString() { - return string; - } + @XmlElement(name = "string", namespace = "http://springframework.org") + public String getString() { + return string; + } - public void setString(String string) { - this.string = string; - } - } + public void setString(String string) { + this.string = string; + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessorTest.java index e8c1b3f2..09aa7a6e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/adapter/method/jaxb/XmlRootElementPayloadMethodProcessorTest.java @@ -54,225 +54,225 @@ import org.springframework.xml.transform.StringResult; public class XmlRootElementPayloadMethodProcessorTest { - private XmlRootElementPayloadMethodProcessor processor; + private XmlRootElementPayloadMethodProcessor processor; - private MethodParameter rootElementParameter; + private MethodParameter rootElementParameter; - private MethodParameter typeParameter; + private MethodParameter typeParameter; - private MethodParameter rootElementReturnType; + private MethodParameter rootElementReturnType; - @Before - public void setUp() throws Exception { - processor = new XmlRootElementPayloadMethodProcessor(); - rootElementParameter = new MethodParameter(getClass().getMethod("rootElement", MyRootElement.class), 0); - typeParameter = new MethodParameter(getClass().getMethod("type", MyType.class), 0); - rootElementReturnType = new MethodParameter(getClass().getMethod("rootElement", MyRootElement.class), -1); - } + @Before + public void setUp() throws Exception { + processor = new XmlRootElementPayloadMethodProcessor(); + rootElementParameter = new MethodParameter(getClass().getMethod("rootElement", MyRootElement.class), 0); + typeParameter = new MethodParameter(getClass().getMethod("type", MyType.class), 0); + rootElementReturnType = new MethodParameter(getClass().getMethod("rootElement", MyRootElement.class), -1); + } - @Test - public void supportsParameter() { - assertTrue("processor does not support @XmlRootElement parameter", - processor.supportsParameter(rootElementParameter)); - assertTrue("processor does not support @XmlType parameter", processor.supportsParameter( - typeParameter)); - } + @Test + public void supportsParameter() { + assertTrue("processor does not support @XmlRootElement parameter", + processor.supportsParameter(rootElementParameter)); + assertTrue("processor does not support @XmlType parameter", processor.supportsParameter( + typeParameter)); + } - @Test - public void supportsReturnType() { - assertTrue("processor does not support @XmlRootElement return type", - processor.supportsReturnType(rootElementReturnType)); - } + @Test + public void supportsReturnType() { + assertTrue("processor does not support @XmlRootElement return type", + processor.supportsReturnType(rootElementReturnType)); + } - @Test - public void resolveArgumentRootElement() throws JAXBException { - WebServiceMessage request = new MockWebServiceMessage("Foo"); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveArgumentRootElement() throws JAXBException { + WebServiceMessage request = new MockWebServiceMessage("Foo"); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = processor.resolveArgument(messageContext, rootElementParameter); - assertTrue("result not a MyRootElement", result instanceof MyRootElement); - MyRootElement rootElement = (MyRootElement) result; - assertEquals("invalid result", "Foo", rootElement.getString()); - } + Object result = processor.resolveArgument(messageContext, rootElementParameter); + assertTrue("result not a MyRootElement", result instanceof MyRootElement); + MyRootElement rootElement = (MyRootElement) result; + assertEquals("invalid result", "Foo", rootElement.getString()); + } - @Test - public void resolveArgumentType() throws JAXBException { - WebServiceMessage request = new MockWebServiceMessage("Foo"); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void resolveArgumentType() throws JAXBException { + WebServiceMessage request = new MockWebServiceMessage("Foo"); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - Object result = processor.resolveArgument(messageContext, typeParameter); - assertTrue("result not a MyType", result instanceof MyType); - MyType type = (MyType) result; - assertEquals("invalid result", "Foo", type.getString()); - } + Object result = processor.resolveArgument(messageContext, typeParameter); + assertTrue("result not a MyType", result instanceof MyType); + MyType type = (MyType) result; + assertEquals("invalid result", "Foo", type.getString()); + } - @Test - public void resolveArgumentFromCustomSAXSource() throws JAXBException { - // Create a custom SAXSource that generates an appropriate sequence of events. - XMLReader xmlReader = new AbstractXmlReader() { - @Override - public void parse(String systemId) throws IOException, SAXException { - parse(); - } - - @Override - public void parse(InputSource input) throws IOException, SAXException { - parse(); - } - - private void parse() throws SAXException { - ContentHandler handler = getContentHandler(); - // Foo - handler.startDocument(); - handler.startPrefixMapping("", "http://springframework.org"); - handler.startElement("http://springframework.org", "root", "root", new AttributesImpl()); - handler.startElement("http://springframework.org", "string", "string", new AttributesImpl()); - handler.characters("Foo".toCharArray(), 0, 3); - handler.endElement("http://springframework.org", "string", "string"); - handler.endElement("http://springframework.org", "root", "root"); - handler.endPrefixMapping(""); - handler.endDocument(); - } - }; - final SAXSource source = new SAXSource(xmlReader, new InputSource()); - - // Create a mock WebServiceMessage that returns the SAXSource as payload source. - WebServiceMessage request = new WebServiceMessage() { - @Override - public void writeTo(OutputStream outputStream) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public Source getPayloadSource() { - return source; - } - - @Override - public Result getPayloadResult() { - throw new UnsupportedOperationException(); - } - }; - // Create a message context with that request. Note that the message factory doesn't matter here: - // it is required but not used. - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - - Object result = processor.resolveArgument(messageContext, rootElementParameter); - assertTrue("result not a MyRootElement", result instanceof MyRootElement); - MyRootElement rootElement = (MyRootElement) result; - assertEquals("invalid result", "Foo", rootElement.getString()); - } + @Test + public void resolveArgumentFromCustomSAXSource() throws JAXBException { + // Create a custom SAXSource that generates an appropriate sequence of events. + XMLReader xmlReader = new AbstractXmlReader() { + @Override + public void parse(String systemId) throws IOException, SAXException { + parse(); + } + + @Override + public void parse(InputSource input) throws IOException, SAXException { + parse(); + } + + private void parse() throws SAXException { + ContentHandler handler = getContentHandler(); + // Foo + handler.startDocument(); + handler.startPrefixMapping("", "http://springframework.org"); + handler.startElement("http://springframework.org", "root", "root", new AttributesImpl()); + handler.startElement("http://springframework.org", "string", "string", new AttributesImpl()); + handler.characters("Foo".toCharArray(), 0, 3); + handler.endElement("http://springframework.org", "string", "string"); + handler.endElement("http://springframework.org", "root", "root"); + handler.endPrefixMapping(""); + handler.endDocument(); + } + }; + final SAXSource source = new SAXSource(xmlReader, new InputSource()); + + // Create a mock WebServiceMessage that returns the SAXSource as payload source. + WebServiceMessage request = new WebServiceMessage() { + @Override + public void writeTo(OutputStream outputStream) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public Source getPayloadSource() { + return source; + } + + @Override + public Result getPayloadResult() { + throw new UnsupportedOperationException(); + } + }; + // Create a message context with that request. Note that the message factory doesn't matter here: + // it is required but not used. + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + + Object result = processor.resolveArgument(messageContext, rootElementParameter); + assertTrue("result not a MyRootElement", result instanceof MyRootElement); + MyRootElement rootElement = (MyRootElement) result; + assertEquals("invalid result", "Foo", rootElement.getString()); + } - @Test - public void handleReturnValue() throws Exception { - MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + @Test + public void handleReturnValue() throws Exception { + MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - MyRootElement rootElement = new MyRootElement(); - rootElement.setString("Foo"); - processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); - assertTrue("context has no response", messageContext.hasResponse()); - MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); - assertXMLEqual("Foo", response.getPayloadAsString()); - } + MyRootElement rootElement = new MyRootElement(); + rootElement.setString("Foo"); + processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); + assertTrue("context has no response", messageContext.hasResponse()); + MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); + assertXMLEqual("Foo", response.getPayloadAsString()); + } - @Test - public void handleNullReturnValue() throws Exception { - MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + @Test + public void handleNullReturnValue() throws Exception { + MessageContext messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - MyRootElement rootElement = null; - processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); - assertFalse("context has response", messageContext.hasResponse()); - } + MyRootElement rootElement = null; + processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); + assertFalse("context has response", messageContext.hasResponse()); + } - @Test - public void handleReturnValueAxiom() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - MessageContext messageContext = new DefaultMessageContext(messageFactory); + @Test + public void handleReturnValueAxiom() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + MessageContext messageContext = new DefaultMessageContext(messageFactory); - MyRootElement rootElement = new MyRootElement(); - rootElement.setString("Foo"); + MyRootElement rootElement = new MyRootElement(); + rootElement.setString("Foo"); - processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); - assertTrue("context has no response", messageContext.hasResponse()); - AxiomSoapMessage response = (AxiomSoapMessage) messageContext.getResponse(); + processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); + assertTrue("context has no response", messageContext.hasResponse()); + AxiomSoapMessage response = (AxiomSoapMessage) messageContext.getResponse(); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - StringResult payloadResult = new StringResult(); - transformer.transform(response.getPayloadSource(), payloadResult); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + StringResult payloadResult = new StringResult(); + transformer.transform(response.getPayloadSource(), payloadResult); - assertXMLEqual("Foo", - payloadResult.toString()); + assertXMLEqual("Foo", + payloadResult.toString()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - response.writeTo(bos); - String messageResult = bos.toString("UTF-8"); - - assertXMLEqual("" + - "Foo" + - "", messageResult); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + response.writeTo(bos); + String messageResult = bos.toString("UTF-8"); + + assertXMLEqual("" + + "Foo" + + "", messageResult); - } + } - @Test - public void handleReturnValueAxiomNoPayloadCaching() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - MessageContext messageContext = new DefaultMessageContext(messageFactory); + @Test + public void handleReturnValueAxiomNoPayloadCaching() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + MessageContext messageContext = new DefaultMessageContext(messageFactory); - MyRootElement rootElement = new MyRootElement(); - rootElement.setString("Foo"); + MyRootElement rootElement = new MyRootElement(); + rootElement.setString("Foo"); - processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); - assertTrue("context has no response", messageContext.hasResponse()); - AxiomSoapMessage response = (AxiomSoapMessage) messageContext.getResponse(); + processor.handleReturnValue(messageContext, rootElementReturnType, rootElement); + assertTrue("context has no response", messageContext.hasResponse()); + AxiomSoapMessage response = (AxiomSoapMessage) messageContext.getResponse(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - response.writeTo(bos); - String messageResult = bos.toString("UTF-8"); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + response.writeTo(bos); + String messageResult = bos.toString("UTF-8"); - assertXMLEqual("" + - "Foo" + - "", messageResult); + assertXMLEqual("" + + "Foo" + + "", messageResult); - } + } - @ResponsePayload - public MyRootElement rootElement(@RequestPayload MyRootElement rootElement) { - return rootElement; - } + @ResponsePayload + public MyRootElement rootElement(@RequestPayload MyRootElement rootElement) { + return rootElement; + } - public void type(@RequestPayload MyType type) { - } + public void type(@RequestPayload MyType type) { + } - @XmlRootElement(name = "root", namespace = "http://springframework.org") - public static class MyRootElement { + @XmlRootElement(name = "root", namespace = "http://springframework.org") + public static class MyRootElement { - private String string; + private String string; - @XmlElement(name = "string", namespace = "http://springframework.org") - public String getString() { - return string; - } + @XmlElement(name = "string", namespace = "http://springframework.org") + public String getString() { + return string; + } - public void setString(String string) { - this.string = string; - } - } + public void setString(String string) { + this.string = string; + } + } - @XmlType(name = "root", namespace = "http://springframework.org") - public static class MyType { + @XmlType(name = "root", namespace = "http://springframework.org") + public static class MyType { - private String string; + private String string; - @XmlElement(name = "string", namespace = "http://springframework.org") - public String getString() { - return string; - } + @XmlElement(name = "string", namespace = "http://springframework.org") + public String getString() { + return string; + } - public void setString(String string) { - this.string = string; - } - } + public void setString(String string) { + this.string = string; + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptorTest.java index 40c9eea0..1ae6f89b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadLoggingInterceptorTest.java @@ -35,88 +35,88 @@ import org.springframework.ws.context.MessageContext; public class PayloadLoggingInterceptorTest { - private PayloadLoggingInterceptor interceptor; + private PayloadLoggingInterceptor interceptor; - private CountingAppender appender; + private CountingAppender appender; - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() throws Exception { - interceptor = new PayloadLoggingInterceptor(); - appender = new CountingAppender(); - BasicConfigurator.configure(appender); - Logger.getRootLogger().setLevel(Level.DEBUG); - MockWebServiceMessage request = new MockWebServiceMessage(""); - messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - appender.reset(); - } + @Before + public void setUp() throws Exception { + interceptor = new PayloadLoggingInterceptor(); + appender = new CountingAppender(); + BasicConfigurator.configure(appender); + Logger.getRootLogger().setLevel(Level.DEBUG); + MockWebServiceMessage request = new MockWebServiceMessage(""); + messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + appender.reset(); + } - @After - public void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - ClassPathResource resource = new ClassPathResource("log4j.properties"); - PropertyConfigurator.configure(resource.getURL()); - } + @After + public void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + ClassPathResource resource = new ClassPathResource("log4j.properties"); + PropertyConfigurator.configure(resource.getURL()); + } - @Test - public void testHandleRequestDisabled() throws Exception { - interceptor.setLogRequest(false); - int eventCount = appender.getCount(); - interceptor.handleRequest(messageContext, null); - Assert.assertEquals("PayloadLoggingInterceptor logged when disabled", appender.getCount(), eventCount); - } + @Test + public void testHandleRequestDisabled() throws Exception { + interceptor.setLogRequest(false); + int eventCount = appender.getCount(); + interceptor.handleRequest(messageContext, null); + Assert.assertEquals("PayloadLoggingInterceptor logged when disabled", appender.getCount(), eventCount); + } - @Test - public void testHandleRequestEnabled() throws Exception { - int eventCount = appender.getCount(); - interceptor.handleRequest(messageContext, null); - Assert.assertTrue("PayloadLoggingInterceptor did not log", appender.getCount() > eventCount); - } + @Test + public void testHandleRequestEnabled() throws Exception { + int eventCount = appender.getCount(); + interceptor.handleRequest(messageContext, null); + Assert.assertTrue("PayloadLoggingInterceptor did not log", appender.getCount() > eventCount); + } - @Test - public void testHandleResponseDisabled() throws Exception { - MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); - response.setPayload(""); - interceptor.setLogResponse(false); - int eventCount = appender.getCount(); - interceptor.handleResponse(messageContext, null); - Assert.assertEquals("PayloadLoggingInterceptor logged when disabled", appender.getCount(), eventCount); - } + @Test + public void testHandleResponseDisabled() throws Exception { + MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); + response.setPayload(""); + interceptor.setLogResponse(false); + int eventCount = appender.getCount(); + interceptor.handleResponse(messageContext, null); + Assert.assertEquals("PayloadLoggingInterceptor logged when disabled", appender.getCount(), eventCount); + } - @Test - public void testHandleResponseEnabled() throws Exception { - MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); - response.setPayload(""); - int eventCount = appender.getCount(); - interceptor.handleResponse(messageContext, null); - Assert.assertTrue("PayloadLoggingInterceptor did not log", appender.getCount() > eventCount); - } + @Test + public void testHandleResponseEnabled() throws Exception { + MockWebServiceMessage response = (MockWebServiceMessage) messageContext.getResponse(); + response.setPayload(""); + int eventCount = appender.getCount(); + interceptor.handleResponse(messageContext, null); + Assert.assertTrue("PayloadLoggingInterceptor did not log", appender.getCount() > eventCount); + } - private static class CountingAppender extends AppenderSkeleton { + private static class CountingAppender extends AppenderSkeleton { - private int count; + private int count; - public int getCount() { - return count; - } + public int getCount() { + return count; + } - public void reset() { - count = 0; - } + public void reset() { + count = 0; + } - @Override - protected void append(LoggingEvent loggingEvent) { - count++; - } + @Override + protected void append(LoggingEvent loggingEvent) { + count++; + } - @Override - public boolean requiresLayout() { - return false; - } + @Override + public boolean requiresLayout() { + return false; + } - @Override - public void close() { - } - } + @Override + public void close() { + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptorTest.java index 442cd51a..d88cc9d7 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/interceptor/PayloadTransformingInterceptorTest.java @@ -44,131 +44,131 @@ import org.springframework.xml.transform.StringResult; public class PayloadTransformingInterceptorTest { - private PayloadTransformingInterceptor interceptor; + private PayloadTransformingInterceptor interceptor; - private Transformer transformer; + private Transformer transformer; - private Resource input; + private Resource input; - private Resource output; + private Resource output; - private Resource xslt; + private Resource xslt; - @Before - public void setUp() throws Exception { - interceptor = new PayloadTransformingInterceptor(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - input = new ClassPathResource("transformInput.xml", getClass()); - output = new ClassPathResource("transformOutput.xml", getClass()); - xslt = new ClassPathResource("transformation.xslt", getClass()); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public void setUp() throws Exception { + interceptor = new PayloadTransformingInterceptor(); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + input = new ClassPathResource("transformInput.xml", getClass()); + output = new ClassPathResource("transformOutput.xml", getClass()); + xslt = new ClassPathResource("transformation.xslt", getClass()); + XMLUnit.setIgnoreWhitespace(true); + } - @Test - public void testHandleRequest() throws Exception { - interceptor.setRequestXslt(xslt); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(input); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testHandleRequest() throws Exception { + interceptor.setRequestXslt(xslt); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(input); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid interceptor result", result); - StringResult expected = new StringResult(); - transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); - assertXMLEqual(expected.toString(), request.getPayloadAsString()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid interceptor result", result); + StringResult expected = new StringResult(); + transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); + assertXMLEqual(expected.toString(), request.getPayloadAsString()); + } - @Test - public void testHandleRequestNoXslt() throws Exception { - interceptor.setResponseXslt(xslt); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(input); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testHandleRequestNoXslt() throws Exception { + interceptor.setResponseXslt(xslt); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(input); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid interceptor result", result); - StringResult expected = new StringResult(); - transformer.transform(new SAXSource(SaxUtils.createInputSource(input)), expected); - assertXMLEqual(expected.toString(), request.getPayloadAsString()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid interceptor result", result); + StringResult expected = new StringResult(); + transformer.transform(new SAXSource(SaxUtils.createInputSource(input)), expected); + assertXMLEqual(expected.toString(), request.getPayloadAsString()); + } - @Test - public void testHandleResponse() throws Exception { - interceptor.setResponseXslt(xslt); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(input); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(input); + @Test + public void testHandleResponse() throws Exception { + interceptor.setResponseXslt(xslt); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(input); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(input); - boolean result = interceptor.handleResponse(context, null); - Assert.assertTrue("Invalid interceptor result", result); - StringResult expected = new StringResult(); - transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); - assertXMLEqual(expected.toString(), response.getPayloadAsString()); - } + boolean result = interceptor.handleResponse(context, null); + Assert.assertTrue("Invalid interceptor result", result); + StringResult expected = new StringResult(); + transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); + assertXMLEqual(expected.toString(), response.getPayloadAsString()); + } - @Test - public void testHandleResponseNoXslt() throws Exception { - interceptor.setRequestXslt(xslt); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(input); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(input); + @Test + public void testHandleResponseNoXslt() throws Exception { + interceptor.setRequestXslt(xslt); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(input); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(input); - boolean result = interceptor.handleResponse(context, null); - Assert.assertTrue("Invalid interceptor result", result); - StringResult expected = new StringResult(); - transformer.transform(new SAXSource(SaxUtils.createInputSource(input)), expected); - assertXMLEqual(expected.toString(), response.getPayloadAsString()); - } + boolean result = interceptor.handleResponse(context, null); + Assert.assertTrue("Invalid interceptor result", result); + StringResult expected = new StringResult(); + transformer.transform(new SAXSource(SaxUtils.createInputSource(input)), expected); + assertXMLEqual(expected.toString(), response.getPayloadAsString()); + } - @Test - public void testSaaj() throws Exception { - interceptor.setRequestXslt(xslt); - interceptor.afterPropertiesSet(); - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage saajMessage = messageFactory.createMessage(); - SaajSoapMessage message = new SaajSoapMessage(saajMessage); - transformer.transform(new ResourceSource(input), message.getPayloadResult()); - MessageContext context = new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); + @Test + public void testSaaj() throws Exception { + interceptor.setRequestXslt(xslt); + interceptor.afterPropertiesSet(); + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage saajMessage = messageFactory.createMessage(); + SaajSoapMessage message = new SaajSoapMessage(saajMessage); + transformer.transform(new ResourceSource(input), message.getPayloadResult()); + MessageContext context = new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); - Assert.assertTrue("Invalid interceptor result", interceptor.handleRequest(context, null)); - StringResult expected = new StringResult(); - transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); - StringResult result = new StringResult(); - transformer.transform(message.getPayloadSource(), result); - assertXMLEqual(expected.toString(), result.toString()); + Assert.assertTrue("Invalid interceptor result", interceptor.handleRequest(context, null)); + StringResult expected = new StringResult(); + transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); + StringResult result = new StringResult(); + transformer.transform(message.getPayloadSource(), result); + assertXMLEqual(expected.toString(), result.toString()); - } + } - @Test - public void testPox() throws Exception { - interceptor.setRequestXslt(xslt); - interceptor.afterPropertiesSet(); - DomPoxMessageFactory factory = new DomPoxMessageFactory(); - DomPoxMessage message = factory.createWebServiceMessage(); - transformer.transform(new ResourceSource(input), message.getPayloadResult()); - MessageContext context = new DefaultMessageContext(message, factory); + @Test + public void testPox() throws Exception { + interceptor.setRequestXslt(xslt); + interceptor.afterPropertiesSet(); + DomPoxMessageFactory factory = new DomPoxMessageFactory(); + DomPoxMessage message = factory.createWebServiceMessage(); + transformer.transform(new ResourceSource(input), message.getPayloadResult()); + MessageContext context = new DefaultMessageContext(message, factory); - Assert.assertTrue("Invalid interceptor result", interceptor.handleRequest(context, null)); - StringResult expected = new StringResult(); - transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); - StringResult result = new StringResult(); - transformer.transform(message.getPayloadSource(), result); - assertXMLEqual(expected.toString(), result.toString()); + Assert.assertTrue("Invalid interceptor result", interceptor.handleRequest(context, null)); + StringResult expected = new StringResult(); + transformer.transform(new SAXSource(SaxUtils.createInputSource(output)), expected); + StringResult result = new StringResult(); + transformer.transform(message.getPayloadSource(), result); + assertXMLEqual(expected.toString(), result.toString()); - } + } - @Test - public void testNoStylesheetsSet() throws Exception { - try { - interceptor.afterPropertiesSet(); - Assert.fail("Should have thrown an Exception"); - } - catch (IllegalArgumentException ex) { - } - } + @Test + public void testNoStylesheetsSet() throws Exception { + try { + interceptor.afterPropertiesSet(); + Assert.fail("Should have thrown an Exception"); + } + catch (IllegalArgumentException ex) { + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/BridgedMethodRegistrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/BridgedMethodRegistrationTest.java index eeca8449..4d1bdf27 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/BridgedMethodRegistrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/BridgedMethodRegistrationTest.java @@ -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, @@ -37,36 +37,36 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration("bridged-method-registration.xml") public class BridgedMethodRegistrationTest { - @Autowired - private PayloadRootAnnotationMethodEndpointMapping mapping; + @Autowired + private PayloadRootAnnotationMethodEndpointMapping mapping; - @Autowired - private ApplicationContext applicationContext; + @Autowired + private ApplicationContext applicationContext; - @Test - public void registration() throws NoSuchMethodException { - MethodEndpoint bridgedMethod = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); - assertNotNull("bridged method endpoint not registered", bridgedMethod); - Method doIt = B.class.getMethod("doIt"); - MethodEndpoint expected = new MethodEndpoint("bridgedMethodEndpoint", applicationContext, doIt); - assertEquals("Invalid endpoint registered", expected, bridgedMethod); - } + @Test + public void registration() throws NoSuchMethodException { + MethodEndpoint bridgedMethod = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); + assertNotNull("bridged method endpoint not registered", bridgedMethod); + Method doIt = B.class.getMethod("doIt"); + MethodEndpoint expected = new MethodEndpoint("bridgedMethodEndpoint", applicationContext, doIt); + assertEquals("Invalid endpoint registered", expected, bridgedMethod); + } - @Endpoint - public static class A { + @Endpoint + public static class A { - @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") - public A doIt() { - return this; - } - } + @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") + public A doIt() { + return this; + } + } - public static class B extends A { + public static class B extends A { - @Override - public B doIt() { - return this; - } - } + @Override + public B doIt() { + return this; + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/CgLibProxyRegistrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/CgLibProxyRegistrationTest.java index 8b8bda82..830b6c03 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/CgLibProxyRegistrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/CgLibProxyRegistrationTest.java @@ -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,29 +39,29 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration("cglib-proxy-registration.xml") public class CgLibProxyRegistrationTest { - @Autowired - private PayloadRootAnnotationMethodEndpointMapping mapping; + @Autowired + private PayloadRootAnnotationMethodEndpointMapping mapping; - @Autowired - private ApplicationContext applicationContext; + @Autowired + private ApplicationContext applicationContext; - @Test - public void registration() throws NoSuchMethodException { - MethodEndpoint cglibProxy = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); - assertNotNull("cg lib proxy endpoint not registered", cglibProxy); - Method doIt = MyEndpoint.class.getMethod("doIt", Source.class); - MethodEndpoint expected = new MethodEndpoint("cgLibProxyEndpoint", applicationContext, doIt); - assertEquals("Invalid endpoint registered", expected, cglibProxy); - } + @Test + public void registration() throws NoSuchMethodException { + MethodEndpoint cglibProxy = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); + assertNotNull("cg lib proxy endpoint not registered", cglibProxy); + Method doIt = MyEndpoint.class.getMethod("doIt", Source.class); + MethodEndpoint expected = new MethodEndpoint("cgLibProxyEndpoint", applicationContext, doIt); + assertEquals("Invalid endpoint registered", expected, cglibProxy); + } - @Endpoint - public static class MyEndpoint { + @Endpoint + public static class MyEndpoint { - @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") - @Log - public void doIt(@RequestPayload Source payload) { - } + @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") + @Log + public void doIt(@RequestPayload Source payload) { + } - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/EndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/EndpointMappingTest.java index 07df9f2b..7d6b0d87 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/EndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/EndpointMappingTest.java @@ -35,163 +35,163 @@ import static org.junit.Assert.*; */ public class EndpointMappingTest { - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() throws Exception { - messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); - } + @Before + public void setUp() throws Exception { + messageContext = new DefaultMessageContext(new MockWebServiceMessageFactory()); + } - @Test - public void defaultEndpoint() throws Exception { - Object defaultEndpoint = new Object(); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { - assertEquals("Invalid request passed", messageContext, givenRequest); - return null; - } - }; - mapping.setDefaultEndpoint(defaultEndpoint); + @Test + public void defaultEndpoint() throws Exception { + Object defaultEndpoint = new Object(); + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + @Override + protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { + assertEquals("Invalid request passed", messageContext, givenRequest); + return null; + } + }; + mapping.setDefaultEndpoint(defaultEndpoint); - EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertNotNull("No EndpointInvocatioChain returned", result); - assertEquals("Default Endpoint not returned", defaultEndpoint, result.getEndpoint()); - } + EndpointInvocationChain result = mapping.getEndpoint(messageContext); + assertNotNull("No EndpointInvocatioChain returned", result); + assertEquals("Default Endpoint not returned", defaultEndpoint, result.getEndpoint()); + } - @Test - public void endpoint() throws Exception { - final Object endpoint = new Object(); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { - assertEquals("Invalid request passed", messageContext, givenRequest); - return endpoint; - } - }; + @Test + public void endpoint() throws Exception { + final Object endpoint = new Object(); + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + @Override + protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { + assertEquals("Invalid request passed", messageContext, givenRequest); + return endpoint; + } + }; - EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertNotNull("No EndpointInvocationChain returned", result); - assertEquals("Unexpected Endpoint returned", endpoint, result.getEndpoint()); - } + EndpointInvocationChain result = mapping.getEndpoint(messageContext); + assertNotNull("No EndpointInvocationChain returned", result); + assertEquals("Unexpected Endpoint returned", endpoint, result.getEndpoint()); + } - @Test - public void endpointInterceptors() throws Exception { - final Object endpoint = new Object(); - EndpointInterceptor interceptor = new EndpointInterceptorAdapter(); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { - assertEquals("Invalid request passed", messageContext, givenRequest); - return endpoint; - } - }; + @Test + public void endpointInterceptors() throws Exception { + final Object endpoint = new Object(); + EndpointInterceptor interceptor = new EndpointInterceptorAdapter(); + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + @Override + protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { + assertEquals("Invalid request passed", messageContext, givenRequest); + return endpoint; + } + }; - mapping.setInterceptors(new EndpointInterceptor[]{interceptor}); - EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertEquals("Unexpected amount of EndpointInterceptors returned", 1, result.getInterceptors().length); - assertEquals("Unexpected EndpointInterceptor returned", interceptor, result.getInterceptors()[0]); - } + mapping.setInterceptors(new EndpointInterceptor[]{interceptor}); + EndpointInvocationChain result = mapping.getEndpoint(messageContext); + assertEquals("Unexpected amount of EndpointInterceptors returned", 1, result.getInterceptors().length); + assertEquals("Unexpected EndpointInterceptor returned", interceptor, result.getInterceptors()[0]); + } - @Test - public void smartEndpointInterceptors() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("smartInterceptor", MySmartEndpointInterceptor.class); + @Test + public void smartEndpointInterceptors() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("smartInterceptor", MySmartEndpointInterceptor.class); - final Object endpoint = new Object(); - EndpointInterceptor interceptor = new EndpointInterceptorAdapter(); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { - assertEquals("Invalid request passed", messageContext, givenRequest); - return endpoint; - } - }; - mapping.setApplicationContext(applicationContext); - mapping.setInterceptors(new EndpointInterceptor[]{interceptor}); - - EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertEquals("Unexpected amount of EndpointInterceptors returned", 2, result.getInterceptors().length); - assertEquals("Unexpected EndpointInterceptor returned", interceptor, result.getInterceptors()[0]); - assertTrue("Unexpected EndpointInterceptor returned", - result.getInterceptors()[1] instanceof MySmartEndpointInterceptor); - } + final Object endpoint = new Object(); + EndpointInterceptor interceptor = new EndpointInterceptorAdapter(); + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + @Override + protected Object getEndpointInternal(MessageContext givenRequest) throws Exception { + assertEquals("Invalid request passed", messageContext, givenRequest); + return endpoint; + } + }; + mapping.setApplicationContext(applicationContext); + mapping.setInterceptors(new EndpointInterceptor[]{interceptor}); + + EndpointInvocationChain result = mapping.getEndpoint(messageContext); + assertEquals("Unexpected amount of EndpointInterceptors returned", 2, result.getInterceptors().length); + assertEquals("Unexpected EndpointInterceptor returned", interceptor, result.getInterceptors()[0]); + assertTrue("Unexpected EndpointInterceptor returned", + result.getInterceptors()[1] instanceof MySmartEndpointInterceptor); + } - @Test - public void endpointBeanName() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("endpoint", Object.class); + @Test + public void endpointBeanName() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("endpoint", Object.class); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext message) throws Exception { - assertEquals("Invalid request", messageContext, message); - return "endpoint"; - } - }; - mapping.setApplicationContext(applicationContext); + @Override + protected Object getEndpointInternal(MessageContext message) throws Exception { + assertEquals("Invalid request", messageContext, message); + return "endpoint"; + } + }; + mapping.setApplicationContext(applicationContext); - EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertNotNull("No endpoint returned", result); - } + EndpointInvocationChain result = mapping.getEndpoint(messageContext); + assertNotNull("No endpoint returned", result); + } - @Test - public void endpointInvalidBeanName() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("endpoint", Object.class); + @Test + public void endpointInvalidBeanName() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("endpoint", Object.class); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext message) throws Exception { - assertEquals("Invalid request", messageContext, message); - return "noSuchBean"; - } - }; - mapping.setApplicationContext(applicationContext); + @Override + protected Object getEndpointInternal(MessageContext message) throws Exception { + assertEquals("Invalid request", messageContext, message); + return "noSuchBean"; + } + }; + mapping.setApplicationContext(applicationContext); - EndpointInvocationChain result = mapping.getEndpoint(messageContext); + EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertNull("No endpoint returned", result); - } + assertNull("No endpoint returned", result); + } - @Test - public void endpointPrototype() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerPrototype("endpoint", MyEndpoint.class); + @Test + public void endpointPrototype() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerPrototype("endpoint", MyEndpoint.class); - AbstractEndpointMapping mapping = new AbstractEndpointMapping() { + AbstractEndpointMapping mapping = new AbstractEndpointMapping() { - @Override - protected Object getEndpointInternal(MessageContext message) throws Exception { - assertEquals("Invalid request", messageContext, message); - return "endpoint"; - } - }; - mapping.setApplicationContext(applicationContext); + @Override + protected Object getEndpointInternal(MessageContext message) throws Exception { + assertEquals("Invalid request", messageContext, message); + return "endpoint"; + } + }; + mapping.setApplicationContext(applicationContext); - EndpointInvocationChain result = mapping.getEndpoint(messageContext); - assertNotNull("No endpoint returned", result); - result = mapping.getEndpoint(messageContext); - assertNotNull("No endpoint returned", result); - assertEquals("Prototype endpoint was not constructed twice", 2, MyEndpoint.constructorCount); - } + EndpointInvocationChain result = mapping.getEndpoint(messageContext); + assertNotNull("No endpoint returned", result); + result = mapping.getEndpoint(messageContext); + assertNotNull("No endpoint returned", result); + assertEquals("Prototype endpoint was not constructed twice", 2, MyEndpoint.constructorCount); + } - private static class MyEndpoint { + private static class MyEndpoint { - private static int constructorCount; + private static int constructorCount; - private MyEndpoint() { - constructorCount++; - } - } + private MyEndpoint() { + constructorCount++; + } + } - private static class MySmartEndpointInterceptor extends DelegatingSmartEndpointInterceptor { + private static class MySmartEndpointInterceptor extends DelegatingSmartEndpointInterceptor { - private MySmartEndpointInterceptor() { - super(new EndpointInterceptorAdapter()); - } - } + private MySmartEndpointInterceptor() { + super(new EndpointInterceptorAdapter()); + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/JdkProxyRegistrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/JdkProxyRegistrationTest.java index ac01123a..31b4fa92 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/JdkProxyRegistrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/JdkProxyRegistrationTest.java @@ -38,35 +38,35 @@ import org.springframework.ws.server.endpoint.annotation.RequestPayload; @ContextConfiguration("jdk-proxy-registration.xml") public class JdkProxyRegistrationTest { - @Autowired - private PayloadRootAnnotationMethodEndpointMapping mapping; + @Autowired + private PayloadRootAnnotationMethodEndpointMapping mapping; - @Autowired - private ApplicationContext applicationContext; + @Autowired + private ApplicationContext applicationContext; - @Test - public void registration() throws NoSuchMethodException { - MethodEndpoint jdkProxy = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); - assertNotNull("jdk proxy endpoint not registered", jdkProxy); - Method doIt = MyEndpointImpl.class.getMethod("doIt", Source.class); - MethodEndpoint expected = new MethodEndpoint("jdkProxyEndpoint", applicationContext, doIt); - assertEquals("Invalid endpoint registered", expected, jdkProxy); - } + @Test + public void registration() throws NoSuchMethodException { + MethodEndpoint jdkProxy = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); + assertNotNull("jdk proxy endpoint not registered", jdkProxy); + Method doIt = MyEndpointImpl.class.getMethod("doIt", Source.class); + MethodEndpoint expected = new MethodEndpoint("jdkProxyEndpoint", applicationContext, doIt); + assertEquals("Invalid endpoint registered", expected, jdkProxy); + } - @Endpoint - public interface MyEndpoint { + @Endpoint + public interface MyEndpoint { - @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") - @Log - void doIt(Source payload); - } + @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") + @Log + void doIt(Source payload); + } - public static class MyEndpointImpl implements MyEndpoint { + public static class MyEndpointImpl implements MyEndpoint { - @Override - public void doIt(@RequestPayload Source payload) { - } + @Override + public void doIt(@RequestPayload Source payload) { + } - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/LogAspect.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/LogAspect.java index 26477e48..5e3fbb1b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/LogAspect.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/LogAspect.java @@ -26,29 +26,29 @@ import org.aspectj.lang.annotation.Pointcut; @Aspect public class LogAspect { - private static final Log logger = LogFactory.getLog(LogAspect.class); + private static final Log logger = LogFactory.getLog(LogAspect.class); - private boolean logInvoked = false; + private boolean logInvoked = false; - public boolean isLogInvoked() { - return logInvoked; - } + public boolean isLogInvoked() { + return logInvoked; + } - @Pointcut("@annotation(org.springframework.ws.server.endpoint.mapping.Log)") - private void loggedMethod() { + @Pointcut("@annotation(org.springframework.ws.server.endpoint.mapping.Log)") + private void loggedMethod() { - } + } - @Around("loggedMethod()") - public Object log(ProceedingJoinPoint joinPoint) throws Throwable { - logInvoked = true; - logger.info("Before: " + joinPoint.getSignature()); - try { - return joinPoint.proceed(); - } - finally { - logger.info("After: " + joinPoint.getSignature()); - } - } + @Around("loggedMethod()") + public Object log(ProceedingJoinPoint joinPoint) throws Throwable { + logInvoked = true; + logger.info("Before: " + joinPoint.getSignature()); + try { + return joinPoint.proceed(); + } + finally { + logger.info("After: " + joinPoint.getSignature()); + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/MapBasedSoapEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/MapBasedSoapEndpointMappingTest.java index 65f1ccb5..e8e7da1c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/MapBasedSoapEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/MapBasedSoapEndpointMappingTest.java @@ -31,97 +31,97 @@ import org.junit.Test; */ public class MapBasedSoapEndpointMappingTest { - @Test - public void testBeanNames() throws Exception { - StaticApplicationContext context = new StaticApplicationContext(); - context.registerSingleton("endpointMapping", MyMapBasedEndpointMapping.class); - context.registerSingleton("endpoint", Object.class); - context.registerAlias("endpoint", "alias"); - MyMapBasedEndpointMapping mapping = new MyMapBasedEndpointMapping(); - mapping.setValidKeys(new String[]{"endpoint", "alias"}); + @Test + public void testBeanNames() throws Exception { + StaticApplicationContext context = new StaticApplicationContext(); + context.registerSingleton("endpointMapping", MyMapBasedEndpointMapping.class); + context.registerSingleton("endpoint", Object.class); + context.registerAlias("endpoint", "alias"); + MyMapBasedEndpointMapping mapping = new MyMapBasedEndpointMapping(); + mapping.setValidKeys(new String[]{"endpoint", "alias"}); - mapping.setRegisterBeanNames(true); - mapping.setApplicationContext(context); + mapping.setRegisterBeanNames(true); + mapping.setApplicationContext(context); - // try bean - mapping.setKey("endpoint"); - Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); + // try bean + mapping.setKey("endpoint"); + Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); - // try alias - mapping.setKey("alias"); - Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); + // try alias + mapping.setKey("alias"); + Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); - // try non-mapped values - mapping.setKey("endpointMapping"); - Assert.assertNull("Endpoint returned", mapping.getEndpointInternal(null)); + // try non-mapped values + mapping.setKey("endpointMapping"); + Assert.assertNull("Endpoint returned", mapping.getEndpointInternal(null)); - } + } - @Test - public void testDisabledBeanNames() throws Exception { - StaticApplicationContext context = new StaticApplicationContext(); - context.registerSingleton("endpoint", Object.class); + @Test + public void testDisabledBeanNames() throws Exception { + StaticApplicationContext context = new StaticApplicationContext(); + context.registerSingleton("endpoint", Object.class); - MyMapBasedEndpointMapping mapping = new MyMapBasedEndpointMapping(); + MyMapBasedEndpointMapping mapping = new MyMapBasedEndpointMapping(); - mapping.setRegisterBeanNames(true); - mapping.setApplicationContext(context); + mapping.setRegisterBeanNames(true); + mapping.setApplicationContext(context); - mapping.setKey("endpoint"); - Assert.assertNull("Endpoint returned", mapping.getEndpointInternal(null)); - } + mapping.setKey("endpoint"); + Assert.assertNull("Endpoint returned", mapping.getEndpointInternal(null)); + } - @Test - public void testEndpointMap() throws Exception { - Map endpointMap = new TreeMap(); - Object endpoint1 = new Object(); - Object endpoint2 = new Object(); - endpointMap.put("endpoint1", endpoint1); - endpointMap.put("endpoint2", endpoint2); + @Test + public void testEndpointMap() throws Exception { + Map endpointMap = new TreeMap(); + Object endpoint1 = new Object(); + Object endpoint2 = new Object(); + endpointMap.put("endpoint1", endpoint1); + endpointMap.put("endpoint2", endpoint2); - MyMapBasedEndpointMapping mapping = new MyMapBasedEndpointMapping(); - mapping.setValidKeys(new String[]{"endpoint1", "endpoint2"}); + MyMapBasedEndpointMapping mapping = new MyMapBasedEndpointMapping(); + mapping.setValidKeys(new String[]{"endpoint1", "endpoint2"}); - mapping.setEndpointMap(endpointMap); - mapping.setApplicationContext(new StaticApplicationContext()); + mapping.setEndpointMap(endpointMap); + mapping.setApplicationContext(new StaticApplicationContext()); - // try endpoint1 - mapping.setKey("endpoint1"); - Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); + // try endpoint1 + mapping.setKey("endpoint1"); + Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); - // try endpoint2 - mapping.setKey("endpoint2"); - Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); + // try endpoint2 + mapping.setKey("endpoint2"); + Assert.assertNotNull("No endpoint returned", mapping.getEndpointInternal(null)); - // try non-mapped values - mapping.setKey("endpoint3"); - Assert.assertNull("Endpoint returned", mapping.getEndpointInternal(null)); - } + // try non-mapped values + mapping.setKey("endpoint3"); + Assert.assertNull("Endpoint returned", mapping.getEndpointInternal(null)); + } - private static class MyMapBasedEndpointMapping extends AbstractMapBasedEndpointMapping { + private static class MyMapBasedEndpointMapping extends AbstractMapBasedEndpointMapping { - private String key; + private String key; - private String[] validKeys = new String[0]; + private String[] validKeys = new String[0]; - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public void setValidKeys(String[] validKeys) { - this.validKeys = validKeys; - Arrays.sort(this.validKeys); - } + public void setValidKeys(String[] validKeys) { + this.validKeys = validKeys; + Arrays.sort(this.validKeys); + } - @Override - protected boolean validateLookupKey(String key) { - return Arrays.binarySearch(validKeys, key) >= 0; - } + @Override + protected boolean validateLookupKey(String key) { + return Arrays.binarySearch(validKeys, key) >= 0; + } - @Override - protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { - return key; - } - } + @Override + protected String getLookupKeyForMessage(MessageContext messageContext) throws Exception { + return key; + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMappingTest.java index 21e113fd..e11b0d57 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootAnnotationMethodEndpointMappingTest.java @@ -49,123 +49,123 @@ import org.springframework.ws.soap.server.SoapMessageDispatcher; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("payloadRootAnnotationMethodEndpointMapping.xml") -public class PayloadRootAnnotationMethodEndpointMappingTest { +public class PayloadRootAnnotationMethodEndpointMappingTest { - @Autowired - private PayloadRootAnnotationMethodEndpointMapping mapping; + @Autowired + private PayloadRootAnnotationMethodEndpointMapping mapping; - @Autowired - private ApplicationContext applicationContext; + @Autowired + private ApplicationContext applicationContext; - @Test - public void registrationSingle() throws NoSuchMethodException { - MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); - assertNotNull("MethodEndpoint not registered", endpoint); - Method doIt = MyEndpoint.class.getMethod("doIt", Source.class); - MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doIt); - assertEquals("Invalid endpoint registered", expected, endpoint); - } + @Test + public void registrationSingle() throws NoSuchMethodException { + MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request")); + assertNotNull("MethodEndpoint not registered", endpoint); + Method doIt = MyEndpoint.class.getMethod("doIt", Source.class); + MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doIt); + assertEquals("Invalid endpoint registered", expected, endpoint); + } - @Test - public void registrationMultiple() throws NoSuchMethodException { - Method doItMultiple = MyEndpoint.class.getMethod("doItMultiple"); - MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple); + @Test + public void registrationMultiple() throws NoSuchMethodException { + Method doItMultiple = MyEndpoint.class.getMethod("doItMultiple"); + MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple); - MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request1")); - assertNotNull("MethodEndpoint not registered", endpoint); - assertEquals("Invalid endpoint registered", expected, endpoint); + MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request1")); + assertNotNull("MethodEndpoint not registered", endpoint); + assertEquals("Invalid endpoint registered", expected, endpoint); - endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request2")); - assertNotNull("MethodEndpoint not registered", endpoint); - assertEquals("Invalid endpoint registered", expected, endpoint); - } + endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request2")); + assertNotNull("MethodEndpoint not registered", endpoint); + assertEquals("Invalid endpoint registered", expected, endpoint); + } - @Test - public void registrationRepeatable() throws NoSuchMethodException { - Method doItMultiple = MyEndpoint.class.getMethod("doItRepeatable"); - MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple); + @Test + public void registrationRepeatable() throws NoSuchMethodException { + Method doItMultiple = MyEndpoint.class.getMethod("doItRepeatable"); + MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple); - MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request3")); - assertNotNull("MethodEndpoint not registered", endpoint); - assertEquals("Invalid endpoint registered", expected, endpoint); + MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request3")); + assertNotNull("MethodEndpoint not registered", endpoint); + assertEquals("Invalid endpoint registered", expected, endpoint); - endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request4")); - assertNotNull("MethodEndpoint not registered", endpoint); - assertEquals("Invalid endpoint registered", expected, endpoint); - } + endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request4")); + assertNotNull("MethodEndpoint not registered", endpoint); + assertEquals("Invalid endpoint registered", expected, endpoint); + } @Test public void registrationInvalid() { - assertNull("Invalid endpoint registered", - mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Invalid"))); - } + assertNull("Invalid endpoint registered", + mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Invalid"))); + } - @Test - public void invoke() throws Exception { + @Test + public void invoke() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage request = messageFactory.createMessage(); - request.getSOAPBody().addBodyElement(QName.valueOf("{http://springframework.org/spring-ws}Request")); - MessageContext messageContext = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - DefaultMethodEndpointAdapter adapter = new DefaultMethodEndpointAdapter(); - adapter.afterPropertiesSet(); + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage request = messageFactory.createMessage(); + request.getSOAPBody().addBodyElement(QName.valueOf("{http://springframework.org/spring-ws}Request")); + MessageContext messageContext = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + DefaultMethodEndpointAdapter adapter = new DefaultMethodEndpointAdapter(); + adapter.afterPropertiesSet(); - MessageDispatcher messageDispatcher = new SoapMessageDispatcher(); - messageDispatcher.setApplicationContext(applicationContext); - messageDispatcher.setEndpointMappings(Collections.singletonList(mapping)); - messageDispatcher.setEndpointAdapters(Collections.singletonList(adapter)); + MessageDispatcher messageDispatcher = new SoapMessageDispatcher(); + messageDispatcher.setApplicationContext(applicationContext); + messageDispatcher.setEndpointMappings(Collections.singletonList(mapping)); + messageDispatcher.setEndpointAdapters(Collections.singletonList(adapter)); - messageDispatcher.receive(messageContext); + messageDispatcher.receive(messageContext); - MyEndpoint endpoint = applicationContext.getBean("endpoint", MyEndpoint.class); - assertTrue("doIt() not invoked on endpoint", endpoint.isDoItInvoked()); + MyEndpoint endpoint = applicationContext.getBean("endpoint", MyEndpoint.class); + assertTrue("doIt() not invoked on endpoint", endpoint.isDoItInvoked()); - LogAspect aspect = (LogAspect) applicationContext.getBean("logAspect"); - assertTrue("log() not invoked on aspect", aspect.isLogInvoked()); - } + LogAspect aspect = (LogAspect) applicationContext.getBean("logAspect"); + assertTrue("log() not invoked on aspect", aspect.isLogInvoked()); + } - @Endpoint - public static class MyEndpoint { + @Endpoint + public static class MyEndpoint { - private static final org.apache.commons.logging.Log logger = LogFactory.getLog(MyEndpoint.class); + private static final org.apache.commons.logging.Log logger = LogFactory.getLog(MyEndpoint.class); - private boolean doItInvoked = false; + private boolean doItInvoked = false; - public boolean isDoItInvoked() { - return doItInvoked; - } + public boolean isDoItInvoked() { + return doItInvoked; + } - @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") - @Log - public void doIt(@RequestPayload Source payload) { - doItInvoked = true; - logger.info("In doIt()"); - } + @PayloadRoot(localPart = "Request", namespace = "http://springframework.org/spring-ws") + @Log + public void doIt(@RequestPayload Source payload) { + doItInvoked = true; + logger.info("In doIt()"); + } - @PayloadRoots({@PayloadRoot(localPart = "Request1", - namespace = "http://springframework.org/spring-ws"), - @PayloadRoot(localPart = "Request2", - namespace = "http://springframework.org/spring-ws")}) - public void doItMultiple() { - } + @PayloadRoots({@PayloadRoot(localPart = "Request1", + namespace = "http://springframework.org/spring-ws"), + @PayloadRoot(localPart = "Request2", + namespace = "http://springframework.org/spring-ws")}) + public void doItMultiple() { + } - @PayloadRoot(localPart = "Request3", - namespace = "http://springframework.org/spring-ws") - @PayloadRoot(localPart = "Request4", - namespace = "http://springframework.org/spring-ws") - public void doItRepeatable() { + @PayloadRoot(localPart = "Request3", + namespace = "http://springframework.org/spring-ws") + @PayloadRoot(localPart = "Request4", + namespace = "http://springframework.org/spring-ws") + public void doItRepeatable() { - } + } - } + } - static class OtherBean { + static class OtherBean { - @PayloadRoot(localPart = "Invalid", namespace = "http://springframework.org/spring-ws") - public void doIt() { + @PayloadRoot(localPart = "Invalid", namespace = "http://springframework.org/spring-ws") + public void doIt() { - } + } - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMappingTest.java index 2e8962fb..84f1c62b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/PayloadRootQNameEndpointMappingTest.java @@ -29,30 +29,30 @@ import org.junit.Test; public class PayloadRootQNameEndpointMappingTest { - private PayloadRootQNameEndpointMapping mapping; + private PayloadRootQNameEndpointMapping mapping; - @Before - public void setUp() throws Exception { - mapping = new PayloadRootQNameEndpointMapping(); - } + @Before + public void setUp() throws Exception { + mapping = new PayloadRootQNameEndpointMapping(); + } - @Test - public void testResolveQNames() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testResolveQNames() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - QName qName = mapping.resolveQName(context); - Assert.assertNotNull("mapping returns null", qName); - Assert.assertEquals("mapping returns invalid qualified name", new QName("root"), qName); - } + QName qName = mapping.resolveQName(context); + Assert.assertNotNull("mapping returns null", qName); + Assert.assertEquals("mapping returns invalid qualified name", new QName("root"), qName); + } - @Test - public void testGetQNameNameNamespace() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testGetQNameNameNamespace() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - QName qName = mapping.resolveQName(context); - Assert.assertNotNull("mapping returns null", qName); - Assert.assertEquals("mapping returns invalid method name", new QName("namespace", "localname", "prefix"), qName); - } + QName qName = mapping.resolveQName(context); + Assert.assertNotNull("mapping returns null", qName); + Assert.assertEquals("mapping returns invalid method name", new QName("namespace", "localname", "prefix"), qName); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMappingTest.java index b5eea395..94ee1980 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/SimpleMethodEndpointMappingTest.java @@ -27,49 +27,49 @@ import org.junit.Test; public class SimpleMethodEndpointMappingTest { - private SimpleMethodEndpointMapping mapping; + private SimpleMethodEndpointMapping mapping; - @Before - public void setUp() throws Exception { - mapping = new SimpleMethodEndpointMapping(); - mapping.setMethodPrefix("prefix"); - mapping.setMethodSuffix("Suffix"); - MyBean bean = new MyBean(); - mapping.setEndpoints(new Object[]{bean}); - mapping.afterPropertiesSet(); - } + @Before + public void setUp() throws Exception { + mapping = new SimpleMethodEndpointMapping(); + mapping.setMethodPrefix("prefix"); + mapping.setMethodSuffix("Suffix"); + MyBean bean = new MyBean(); + mapping.setEndpoints(new Object[]{bean}); + mapping.afterPropertiesSet(); + } - @Test - public void testRegistration() throws Exception { - Assert.assertNotNull("Endpoint not registered", mapping.lookupEndpoint("MyRequest")); - Assert.assertNull("Endpoint registered", mapping.lookupEndpoint("request")); - } + @Test + public void testRegistration() throws Exception { + Assert.assertNotNull("Endpoint not registered", mapping.lookupEndpoint("MyRequest")); + Assert.assertNull("Endpoint registered", mapping.lookupEndpoint("request")); + } - @Test - public void testGetLookupKeyForMessageNoNamespace() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(""); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - String result = mapping.getLookupKeyForMessage(messageContext); - Assert.assertEquals("Invalid lookup key", "MyRequest", result); - } + @Test + public void testGetLookupKeyForMessageNoNamespace() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(""); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + String result = mapping.getLookupKeyForMessage(messageContext); + Assert.assertEquals("Invalid lookup key", "MyRequest", result); + } - @Test - public void testGetLookupKeyForMessageNamespace() throws Exception { - MockWebServiceMessage request = - new MockWebServiceMessage(""); - MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - String result = mapping.getLookupKeyForMessage(messageContext); - Assert.assertEquals("Invalid lookup key", "MyRequest", result); - } + @Test + public void testGetLookupKeyForMessageNamespace() throws Exception { + MockWebServiceMessage request = + new MockWebServiceMessage(""); + MessageContext messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + String result = mapping.getLookupKeyForMessage(messageContext); + Assert.assertEquals("Invalid lookup key", "MyRequest", result); + } - private static class MyBean { + private static class MyBean { - public void prefixMyRequestSuffix() { + public void prefixMyRequestSuffix() { - } + } - public void request() { + public void request() { - } - } + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMappingTest.java index b9c20422..d384b7dd 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/UriEndpointMappingTest.java @@ -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,56 +34,56 @@ import static org.easymock.EasyMock.*; public class UriEndpointMappingTest { - private UriEndpointMapping mapping; + private UriEndpointMapping mapping; - private MessageContext context; + private MessageContext context; - @Before - public void setUp() throws Exception { - mapping = new UriEndpointMapping(); - context = new DefaultMessageContext(new MockWebServiceMessageFactory()); - } + @Before + public void setUp() throws Exception { + mapping = new UriEndpointMapping(); + context = new DefaultMessageContext(new MockWebServiceMessageFactory()); + } - @After - public void clearContext() { - TransportContextHolder.setTransportContext(null); - } + @After + public void clearContext() { + TransportContextHolder.setTransportContext(null); + } - @Test - public void getLookupKeyForMessage() throws Exception { - WebServiceConnection connectionMock = createMock(WebServiceConnection.class); - TransportContextHolder.setTransportContext(new DefaultTransportContext(connectionMock)); + @Test + public void getLookupKeyForMessage() throws Exception { + WebServiceConnection connectionMock = createMock(WebServiceConnection.class); + TransportContextHolder.setTransportContext(new DefaultTransportContext(connectionMock)); - URI uri = new URI("jms://exampleQueue"); - expect(connectionMock.getUri()).andReturn(uri); + URI uri = new URI("jms://exampleQueue"); + expect(connectionMock.getUri()).andReturn(uri); - replay(connectionMock); + replay(connectionMock); - Assert.assertEquals("Invalid lookup key", uri.toString(), mapping.getLookupKeyForMessage(context)); + Assert.assertEquals("Invalid lookup key", uri.toString(), mapping.getLookupKeyForMessage(context)); - verify(connectionMock); - } + verify(connectionMock); + } - @Test - public void getLookupKeyForMessagePath() throws Exception { - mapping.setUsePath(true); + @Test + public void getLookupKeyForMessagePath() throws Exception { + mapping.setUsePath(true); - WebServiceConnection connectionMock = createMock(WebServiceConnection.class); - TransportContextHolder.setTransportContext(new DefaultTransportContext(connectionMock)); + WebServiceConnection connectionMock = createMock(WebServiceConnection.class); + TransportContextHolder.setTransportContext(new DefaultTransportContext(connectionMock)); - URI uri = new URI("http://example.com/foo/bar"); - expect(connectionMock.getUri()).andReturn(uri); + URI uri = new URI("http://example.com/foo/bar"); + expect(connectionMock.getUri()).andReturn(uri); - replay(connectionMock); + replay(connectionMock); - Assert.assertEquals("Invalid lookup key", "/foo/bar", mapping.getLookupKeyForMessage(context)); + Assert.assertEquals("Invalid lookup key", "/foo/bar", mapping.getLookupKeyForMessage(context)); - verify(connectionMock); - } + verify(connectionMock); + } - @Test - public void testValidateLookupKey() throws Exception { - Assert.assertTrue("URI not valid", mapping.validateLookupKey("http://example.com/services")); - Assert.assertFalse("URI not valid", mapping.validateLookupKey("some string")); - } + @Test + public void testValidateLookupKey() throws Exception { + Assert.assertTrue("URI not valid", mapping.validateLookupKey("http://example.com/services")); + Assert.assertFalse("URI not valid", mapping.validateLookupKey("some string")); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMappingTest.java index 326695c0..b03c26f4 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/XPathPayloadEndpointMappingTest.java @@ -27,23 +27,23 @@ import org.junit.Test; public class XPathPayloadEndpointMappingTest { - private XPathPayloadEndpointMapping mapping; + private XPathPayloadEndpointMapping mapping; - @Before - public void setUp() throws Exception { - mapping = new XPathPayloadEndpointMapping(); - } + @Before + public void setUp() throws Exception { + mapping = new XPathPayloadEndpointMapping(); + } - @Test - public void testGetLookupKeyForMessage() throws Exception { - mapping.setExpression("/root/text()"); - mapping.afterPropertiesSet(); + @Test + public void testGetLookupKeyForMessage() throws Exception { + mapping.setExpression("/root/text()"); + mapping.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage("value"); - MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage request = new MockWebServiceMessage("value"); + MessageContext context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - String result = mapping.getLookupKeyForMessage(context); - Assert.assertNotNull("mapping returns null", result); - Assert.assertEquals("mapping returns invalid result", "value", result); - } + String result = mapping.getLookupKeyForMessage(context); + Assert.assertNotNull("mapping returns null", result); + Assert.assertEquals("mapping returns invalid result", "value", result); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMappingTest.java index a0b91c9b..1f0cb2a5 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/mapping/jaxb/XmlRootElementEndpointMappingTest.java @@ -27,26 +27,26 @@ import static org.junit.Assert.assertEquals; public class XmlRootElementEndpointMappingTest { - private XmlRootElementEndpointMapping mapping; + private XmlRootElementEndpointMapping mapping; - @Before - public void createMapping() throws NoSuchMethodException { - mapping = new XmlRootElementEndpointMapping(); - } + @Before + public void createMapping() throws NoSuchMethodException { + mapping = new XmlRootElementEndpointMapping(); + } - @Test - public void rootElement() throws NoSuchMethodException { - Method rootElement = getClass().getMethod("rootElement", MyRootElement.class); - QName name = mapping.getLookupKeyForMethod(rootElement); - assertEquals(new QName("myNamespace", "myRoot"), name); - } + @Test + public void rootElement() throws NoSuchMethodException { + Method rootElement = getClass().getMethod("rootElement", MyRootElement.class); + QName name = mapping.getLookupKeyForMethod(rootElement); + assertEquals(new QName("myNamespace", "myRoot"), name); + } - public void rootElement(MyRootElement rootElement) { - } + public void rootElement(MyRootElement rootElement) { + } - @XmlRootElement(name = "myRoot", namespace = "myNamespace") - public static class MyRootElement { + @XmlRootElement(name = "myRoot", namespace = "myNamespace") + public static class MyRootElement { - } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/NamespaceUtilsTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/NamespaceUtilsTest.java index 862b4dd8..1ab68c8a 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/NamespaceUtilsTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/NamespaceUtilsTest.java @@ -30,27 +30,27 @@ import static org.junit.Assert.assertEquals; @Namespaces({@Namespace(prefix = "prefix1", uri = "class1"), @Namespace(uri = "class2")}) public class NamespaceUtilsTest { - @Test - public void getNamespaceContextMethod() throws NoSuchMethodException { - Method method = getClass().getMethod("method"); - NamespaceContext namespaceContext = NamespaceUtils.getNamespaceContext(method); - assertEquals("method1", namespaceContext.getNamespaceURI("prefix1")); - assertEquals("method2", namespaceContext.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); + @Test + public void getNamespaceContextMethod() throws NoSuchMethodException { + Method method = getClass().getMethod("method"); + NamespaceContext namespaceContext = NamespaceUtils.getNamespaceContext(method); + assertEquals("method1", namespaceContext.getNamespaceURI("prefix1")); + assertEquals("method2", namespaceContext.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); - } - - @Test - public void getNamespaceContextClass() throws NoSuchMethodException { - Method method = getClass().getMethod("getNamespaceContextClass"); - NamespaceContext namespaceContext = NamespaceUtils.getNamespaceContext(method); - assertEquals("class1", namespaceContext.getNamespaceURI("prefix1")); - assertEquals("class2", namespaceContext.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); + } + + @Test + public void getNamespaceContextClass() throws NoSuchMethodException { + Method method = getClass().getMethod("getNamespaceContextClass"); + NamespaceContext namespaceContext = NamespaceUtils.getNamespaceContext(method); + assertEquals("class1", namespaceContext.getNamespaceURI("prefix1")); + assertEquals("class2", namespaceContext.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); - } + } - @Namespaces({@Namespace(prefix = "prefix1", uri = "method1"), @Namespace(uri = "method2")}) - public void method() { + @Namespaces({@Namespace(prefix = "prefix1", uri = "method1"), @Namespace(uri = "method2")}) + public void method() { - } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/PayloadRootUtilsTest.java b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/PayloadRootUtilsTest.java index a0dfdc6e..f2329f4b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/PayloadRootUtilsTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/server/endpoint/support/PayloadRootUtilsTest.java @@ -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,72 +39,72 @@ import org.xml.sax.InputSource; public class PayloadRootUtilsTest { - @Test - public void testGetQNameForDomSource() throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Element element = document.createElementNS("namespace", "prefix:localname"); - document.appendChild(element); - Source source = new DOMSource(document); - QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); - } + @Test + public void testGetQNameForDomSource() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Element element = document.createElementNS("namespace", "prefix:localname"); + document.appendChild(element); + Source source = new DOMSource(document); + QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); + } - @Test - public void testGetQNameForStaxSourceStreamReader() throws Exception { - String contents = ""; - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(contents)); - Source source = StaxUtils.createStaxSource(streamReader); - QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); - } + @Test + public void testGetQNameForStaxSourceStreamReader() throws Exception { + String contents = ""; + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(contents)); + Source source = StaxUtils.createStaxSource(streamReader); + QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); + } - @Test - public void testGetQNameForStaxSourceEventReader() throws Exception { - String contents = ""; - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(contents)); - Source source = StaxUtils.createStaxSource(eventReader); - QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); - } + @Test + public void testGetQNameForStaxSourceEventReader() throws Exception { + String contents = ""; + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(contents)); + Source source = StaxUtils.createStaxSource(eventReader); + QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); + } - @Test - public void testGetQNameForStreamSource() throws Exception { - String contents = ""; - Source source = new StreamSource(new StringReader(contents)); - QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); - } + @Test + public void testGetQNameForStreamSource() throws Exception { + String contents = ""; + Source source = new StreamSource(new StringReader(contents)); + QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); + } - @Test - public void testGetQNameForSaxSource() throws Exception { - String contents = ""; - Source source = new SAXSource(new InputSource(new StringReader(contents))); - QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); - } + @Test + public void testGetQNameForSaxSource() throws Exception { + String contents = ""; + Source source = new SAXSource(new InputSource(new StringReader(contents))); + QName qName = PayloadRootUtils.getPayloadRootQName(source, TransformerFactory.newInstance()); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); + } - @Test - public void testGetQNameForNullSource() throws Exception { - QName qName = PayloadRootUtils.getPayloadRootQName(null, TransformerFactory.newInstance()); - Assert.assertNull("Qname returned", qName); - } + @Test + public void testGetQNameForNullSource() throws Exception { + QName qName = PayloadRootUtils.getPayloadRootQName(null, TransformerFactory.newInstance()); + Assert.assertNull("Qname returned", qName); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapBodyTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapBodyTestCase.java index e175d09d..aee0c4bf 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapBodyTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapBodyTestCase.java @@ -32,52 +32,52 @@ import static org.junit.Assert.*; public abstract class AbstractSoapBodyTestCase extends AbstractSoapElementTestCase { - protected SoapBody soapBody; + protected SoapBody soapBody; - @Override - protected final SoapElement createSoapElement() throws Exception { - soapBody = createSoapBody(); - return soapBody; - } + @Override + protected final SoapElement createSoapElement() throws Exception { + soapBody = createSoapBody(); + return soapBody; + } - protected abstract SoapBody createSoapBody() throws Exception; + protected abstract SoapBody createSoapBody() throws Exception; - @Test - public void testPayload() throws Exception { - String payload = ""; - transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); - assertPayloadEqual(payload); - } + @Test + public void testPayload() throws Exception { + String payload = ""; + transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); + assertPayloadEqual(payload); + } - @Test - public void testGetPayloadResultTwice() throws Exception { - String payload = ""; - transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); - transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); - DOMResult domResult = new DOMResult(); - transformer.transform(soapBody.getSource(), domResult); - Element bodyElement = ((Document) domResult.getNode()).getDocumentElement(); - NodeList children = bodyElement.getChildNodes(); - assertEquals("Invalid amount of child nodes", 1, children.getLength()); - } + @Test + public void testGetPayloadResultTwice() throws Exception { + String payload = ""; + transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); + transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); + DOMResult domResult = new DOMResult(); + transformer.transform(soapBody.getSource(), domResult); + Element bodyElement = ((Document) domResult.getNode()).getDocumentElement(); + NodeList children = bodyElement.getChildNodes(); + assertEquals("Invalid amount of child nodes", 1, children.getLength()); + } - @Test - public void testNoFault() throws Exception { - assertFalse("body has fault", soapBody.hasFault()); - } + @Test + public void testNoFault() throws Exception { + assertFalse("body has fault", soapBody.hasFault()); + } - @Test - public void testAddFaultWithExistingPayload() throws Exception { - StringSource contents = new StringSource(""); - transformer.transform(contents, soapBody.getPayloadResult()); - soapBody.addMustUnderstandFault("faultString", Locale.ENGLISH); - assertTrue("Body has no fault", soapBody.hasFault()); - } + @Test + public void testAddFaultWithExistingPayload() throws Exception { + StringSource contents = new StringSource(""); + transformer.transform(contents, soapBody.getPayloadResult()); + soapBody.addMustUnderstandFault("faultString", Locale.ENGLISH); + assertTrue("Body has no fault", soapBody.hasFault()); + } - protected void assertPayloadEqual(String expectedPayload) throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapBody.getPayloadSource(), result); - assertXMLEqual("Invalid payload contents", expectedPayload, result.toString()); - } + protected void assertPayloadEqual(String expectedPayload) throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapBody.getPayloadSource(), result); + assertXMLEqual("Invalid payload contents", expectedPayload, result.toString()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapElementTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapElementTestCase.java index f3bd6e85..7a9e426b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapElementTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapElementTestCase.java @@ -27,42 +27,42 @@ import org.junit.Test; public abstract class AbstractSoapElementTestCase { - private SoapElement soapElement; + private SoapElement soapElement; - protected Transformer transformer; + protected Transformer transformer; - @Before - public final void setUp() throws Exception { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - soapElement = createSoapElement(); - } + @Before + public final void setUp() throws Exception { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + soapElement = createSoapElement(); + } - protected abstract SoapElement createSoapElement() throws Exception; + protected abstract SoapElement createSoapElement() throws Exception; - @Test - public void testAttributes() throws Exception { - QName name = new QName("http://springframework.org/spring-ws", "attribute"); - String value = "value"; - soapElement.addAttribute(name, value); - Assert.assertEquals("Invalid attribute value", value, soapElement.getAttributeValue(name)); - Iterator allAttributes = soapElement.getAllAttributes(); - Assert.assertTrue("Iterator is empty", allAttributes.hasNext()); - } + @Test + public void testAttributes() throws Exception { + QName name = new QName("http://springframework.org/spring-ws", "attribute"); + String value = "value"; + soapElement.addAttribute(name, value); + Assert.assertEquals("Invalid attribute value", value, soapElement.getAttributeValue(name)); + Iterator allAttributes = soapElement.getAllAttributes(); + Assert.assertTrue("Iterator is empty", allAttributes.hasNext()); + } - @Test - public void testAddNamespaceDeclaration() throws Exception { - String prefix = "p"; - String namespace = "http://springframework.org/spring-ws"; - soapElement.addNamespaceDeclaration(prefix, namespace); - } + @Test + public void testAddNamespaceDeclaration() throws Exception { + String prefix = "p"; + String namespace = "http://springframework.org/spring-ws"; + soapElement.addNamespaceDeclaration(prefix, namespace); + } - @Test - public void testAddDefaultNamespaceDeclaration() throws Exception { - String prefix = ""; - String namespace = "http://springframework.org/spring-ws"; - soapElement.addNamespaceDeclaration(prefix, namespace); - } + @Test + public void testAddDefaultNamespaceDeclaration() throws Exception { + String prefix = ""; + String namespace = "http://springframework.org/spring-ws"; + soapElement.addNamespaceDeclaration(prefix, namespace); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapEnvelopeTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapEnvelopeTestCase.java index 9d7c02ac..3d37327c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapEnvelopeTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapEnvelopeTestCase.java @@ -22,25 +22,25 @@ import static org.junit.Assert.assertNotNull; public abstract class AbstractSoapEnvelopeTestCase extends AbstractSoapElementTestCase { - protected SoapEnvelope soapEnvelope; + protected SoapEnvelope soapEnvelope; - @Override - protected final SoapElement createSoapElement() throws Exception { - soapEnvelope = createSoapEnvelope(); - return soapEnvelope; - } + @Override + protected final SoapElement createSoapElement() throws Exception { + soapEnvelope = createSoapEnvelope(); + return soapEnvelope; + } - protected abstract SoapEnvelope createSoapEnvelope() throws Exception; + protected abstract SoapEnvelope createSoapEnvelope() throws Exception; - @Test - public void testGetHeader() throws Exception { - SoapHeader header = soapEnvelope.getHeader(); - assertNotNull("No header returned", header); - } + @Test + public void testGetHeader() throws Exception { + SoapHeader header = soapEnvelope.getHeader(); + assertNotNull("No header returned", header); + } - @Test - public void testGetBody() throws Exception { - SoapBody body = soapEnvelope.getBody(); - assertNotNull("No body returned", body); - } + @Test + public void testGetBody() throws Exception { + SoapBody body = soapEnvelope.getBody(); + assertNotNull("No body returned", body); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapHeaderTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapHeaderTestCase.java index b66faa64..3af56a14 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapHeaderTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapHeaderTestCase.java @@ -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, @@ -29,116 +29,116 @@ import static org.junit.Assert.*; public abstract class AbstractSoapHeaderTestCase extends AbstractSoapElementTestCase { - protected SoapHeader soapHeader; + protected SoapHeader soapHeader; - protected static final String NAMESPACE = "http://www.springframework.org"; + protected static final String NAMESPACE = "http://www.springframework.org"; - protected static final String PREFIX = "spring"; + protected static final String PREFIX = "spring"; - @Override - protected final SoapElement createSoapElement() throws Exception { - soapHeader = createSoapHeader(); - return soapHeader; - } + @Override + protected final SoapElement createSoapElement() throws Exception { + soapHeader = createSoapHeader(); + return soapHeader; + } - protected abstract SoapHeader createSoapHeader() throws Exception; + protected abstract SoapHeader createSoapHeader() throws Exception; - @Test - public void testAddHeaderElement() throws Exception { - QName qName = new QName(NAMESPACE, "localName", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - assertNotNull("No SoapHeaderElement returned", headerElement); - assertEquals("Invalid qName for element", qName, headerElement.getName()); - Iterator iterator = soapHeader.examineAllHeaderElements(); - assertTrue("SoapHeader has no elements", iterator.hasNext()); - String payload = ""; - transformer.transform(new StringSource(payload), headerElement.getResult()); - assertHeaderElementEqual(headerElement, - ""); - } + @Test + public void testAddHeaderElement() throws Exception { + QName qName = new QName(NAMESPACE, "localName", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + assertNotNull("No SoapHeaderElement returned", headerElement); + assertEquals("Invalid qName for element", qName, headerElement.getName()); + Iterator iterator = soapHeader.examineAllHeaderElements(); + assertTrue("SoapHeader has no elements", iterator.hasNext()); + String payload = ""; + transformer.transform(new StringSource(payload), headerElement.getResult()); + assertHeaderElementEqual(headerElement, + ""); + } - @Test - public void testRemoveHeaderElement() throws Exception { - QName qName = new QName(NAMESPACE, "localName", PREFIX); - soapHeader.removeHeaderElement(qName); - soapHeader.addHeaderElement(qName); - soapHeader.removeHeaderElement(qName); - Iterator iterator = soapHeader.examineAllHeaderElements(); - assertFalse("SoapHeader has elements", iterator.hasNext()); - } + @Test + public void testRemoveHeaderElement() throws Exception { + QName qName = new QName(NAMESPACE, "localName", PREFIX); + soapHeader.removeHeaderElement(qName); + soapHeader.addHeaderElement(qName); + soapHeader.removeHeaderElement(qName); + Iterator iterator = soapHeader.examineAllHeaderElements(); + assertFalse("SoapHeader has elements", iterator.hasNext()); + } - @Test - public void testExamineAllHeaderElement() throws Exception { - QName qName = new QName(NAMESPACE, "localName", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - assertEquals("Invalid qName for element", qName, headerElement.getName()); - assertNotNull("No SoapHeaderElement returned", headerElement); - String payload = ""; - transformer.transform(new StringSource(payload), headerElement.getResult()); - Iterator iterator = soapHeader.examineAllHeaderElements(); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - headerElement = iterator.next(); - assertEquals("Invalid qName for element", qName, headerElement.getName()); - StringResult result = new StringResult(); - transformer.transform(headerElement.getSource(), result); - assertXMLEqual("Invalid contents of header element", - "", - result.toString()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineAllHeaderElement() throws Exception { + QName qName = new QName(NAMESPACE, "localName", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + assertEquals("Invalid qName for element", qName, headerElement.getName()); + assertNotNull("No SoapHeaderElement returned", headerElement); + String payload = ""; + transformer.transform(new StringSource(payload), headerElement.getResult()); + Iterator iterator = soapHeader.examineAllHeaderElements(); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + headerElement = iterator.next(); + assertEquals("Invalid qName for element", qName, headerElement.getName()); + StringResult result = new StringResult(); + transformer.transform(headerElement.getSource(), result); + assertXMLEqual("Invalid contents of header element", + "", + result.toString()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - @Test - public void testExamineHeaderElementWithName() throws Exception { - QName name1 = new QName(NAMESPACE, "name1", PREFIX); - QName name2 = new QName(NAMESPACE, "name2", PREFIX); - soapHeader.addHeaderElement(name1); - soapHeader.addHeaderElement(name2); - Iterator iterator = soapHeader.examineHeaderElements(name1); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - SoapHeaderElement headerElement = iterator.next(); - assertEquals("Invalid qName for element", name1, headerElement.getName()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineHeaderElementWithName() throws Exception { + QName name1 = new QName(NAMESPACE, "name1", PREFIX); + QName name2 = new QName(NAMESPACE, "name2", PREFIX); + soapHeader.addHeaderElement(name1); + soapHeader.addHeaderElement(name2); + Iterator iterator = soapHeader.examineHeaderElements(name1); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + SoapHeaderElement headerElement = iterator.next(); + assertEquals("Invalid qName for element", name1, headerElement.getName()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - @Test - public void testExamineMustUnderstandHeaderElements() throws Exception { - QName qName1 = new QName(NAMESPACE, "localName1", PREFIX); - SoapHeaderElement headerElement1 = soapHeader.addHeaderElement(qName1); - headerElement1.setMustUnderstand(true); - headerElement1.setActorOrRole("role1"); - QName qName2 = new QName(NAMESPACE, "localName2", PREFIX); - SoapHeaderElement headerElement2 = soapHeader.addHeaderElement(qName2); - headerElement2.setMustUnderstand(true); - headerElement2.setActorOrRole("role2"); - Iterator iterator = soapHeader.examineMustUnderstandHeaderElements("role1"); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - SoapHeaderElement headerElement = iterator.next(); - assertEquals("Invalid name on header element", qName1, headerElement.getName()); - assertTrue("MustUnderstand not set on header element", headerElement.getMustUnderstand()); - assertEquals("Invalid role on header element", "role1", headerElement.getActorOrRole()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineMustUnderstandHeaderElements() throws Exception { + QName qName1 = new QName(NAMESPACE, "localName1", PREFIX); + SoapHeaderElement headerElement1 = soapHeader.addHeaderElement(qName1); + headerElement1.setMustUnderstand(true); + headerElement1.setActorOrRole("role1"); + QName qName2 = new QName(NAMESPACE, "localName2", PREFIX); + SoapHeaderElement headerElement2 = soapHeader.addHeaderElement(qName2); + headerElement2.setMustUnderstand(true); + headerElement2.setActorOrRole("role2"); + Iterator iterator = soapHeader.examineMustUnderstandHeaderElements("role1"); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + SoapHeaderElement headerElement = iterator.next(); + assertEquals("Invalid name on header element", qName1, headerElement.getName()); + assertTrue("MustUnderstand not set on header element", headerElement.getMustUnderstand()); + assertEquals("Invalid role on header element", "role1", headerElement.getActorOrRole()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - @Test - public void testGetResult() throws Exception { - String content = - ""; - transformer.transform(new StringSource(content), soapHeader.getResult()); - Iterator iterator = soapHeader.examineAllHeaderElements(); - assertTrue("Header has no children", iterator.hasNext()); - SoapHeaderElement headerElement = iterator.next(); - assertFalse("Header has too many children", iterator.hasNext()); - assertHeaderElementEqual(headerElement, content); - } + @Test + public void testGetResult() throws Exception { + String content = + ""; + transformer.transform(new StringSource(content), soapHeader.getResult()); + Iterator iterator = soapHeader.examineAllHeaderElements(); + assertTrue("Header has no children", iterator.hasNext()); + SoapHeaderElement headerElement = iterator.next(); + assertFalse("Header has too many children", iterator.hasNext()); + assertHeaderElementEqual(headerElement, content); + } - protected void assertHeaderElementEqual(SoapHeaderElement headerElement, String expected) throws Exception { - StringResult result = new StringResult(); - transformer.transform(headerElement.getSource(), result); - assertXMLEqual("Invalid contents of header element", expected, result.toString()); - } + protected void assertHeaderElementEqual(SoapHeaderElement headerElement, String expected) throws Exception { + StringResult result = new StringResult(); + transformer.transform(headerElement.getSource(), result); + assertXMLEqual("Invalid contents of header element", expected, result.toString()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageFactoryTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageFactoryTestCase.java index 2d7fbd31..681a6d8c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageFactoryTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageFactoryTestCase.java @@ -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,21 +26,21 @@ import static org.junit.Assert.assertTrue; public abstract class AbstractSoapMessageFactoryTestCase extends AbstractWebServiceMessageFactoryTestCase { - @Test - public void testCreateEmptySoapMessage() throws Exception { - WebServiceMessage message = messageFactory.createWebServiceMessage(); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - } + @Test + public void testCreateEmptySoapMessage() throws Exception { + WebServiceMessage message = messageFactory.createWebServiceMessage(); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + } - @Test(expected = InvalidXmlException.class) - public abstract void testCreateSoapMessageIllFormedXml() throws Exception; + @Test(expected = InvalidXmlException.class) + public abstract void testCreateSoapMessageIllFormedXml() throws Exception; - @Test - public abstract void testCreateSoapMessageNoAttachment() throws Exception; + @Test + public abstract void testCreateSoapMessageNoAttachment() throws Exception; - @Test - public abstract void testCreateSoapMessageSwA() throws Exception; + @Test + public abstract void testCreateSoapMessageSwA() throws Exception; - @Test - public abstract void testCreateSoapMessageMtom() throws Exception; + @Test + public abstract void testCreateSoapMessageMtom() throws Exception; } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageTestCase.java index 53a5d922..490121ac 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/AbstractSoapMessageTestCase.java @@ -44,100 +44,100 @@ import static org.junit.Assert.*; public abstract class AbstractSoapMessageTestCase extends AbstractMimeMessageTestCase { - protected SoapMessage soapMessage; + protected SoapMessage soapMessage; - @Override - protected MimeMessage createMimeMessage() throws Exception { - soapMessage = createSoapMessage(); - return soapMessage; - } + @Override + protected MimeMessage createMimeMessage() throws Exception { + soapMessage = createSoapMessage(); + return soapMessage; + } - protected abstract SoapMessage createSoapMessage() throws Exception; + protected abstract SoapMessage createSoapMessage() throws Exception; - @Test - public void testValidate() throws Exception { - XmlValidator validator = - XmlValidatorFactory.createValidator(getSoapSchemas(), XmlValidatorFactory.SCHEMA_W3C_XML); - SAXParseException[] errors = validator.validate(soapMessage.getEnvelope().getSource()); - if (errors.length > 0) { - fail(StringUtils.arrayToCommaDelimitedString(errors)); - } - } + @Test + public void testValidate() throws Exception { + XmlValidator validator = + XmlValidatorFactory.createValidator(getSoapSchemas(), XmlValidatorFactory.SCHEMA_W3C_XML); + SAXParseException[] errors = validator.validate(soapMessage.getEnvelope().getSource()); + if (errors.length > 0) { + fail(StringUtils.arrayToCommaDelimitedString(errors)); + } + } - @Test - public void testSoapAction() throws Exception { - assertEquals("Invalid default SOAP Action", "\"\"", soapMessage.getSoapAction()); - soapMessage.setSoapAction("SoapAction"); - assertEquals("Invalid SOAP Action", "\"SoapAction\"", soapMessage.getSoapAction()); - } + @Test + public void testSoapAction() throws Exception { + assertEquals("Invalid default SOAP Action", "\"\"", soapMessage.getSoapAction()); + soapMessage.setSoapAction("SoapAction"); + assertEquals("Invalid SOAP Action", "\"SoapAction\"", soapMessage.getSoapAction()); + } - @Test - public void testCharsetAttribute() throws Exception { - MockTransportOutputStream outputStream = new MockTransportOutputStream(new ByteArrayOutputStream()); - soapMessage.writeTo(outputStream); - Map headers = outputStream.getHeaders(); - String contentType = headers.get(TransportConstants.HEADER_CONTENT_TYPE); - if (contentType != null) { - Pattern charsetPattern = Pattern.compile("charset\\s*=\\s*([^;]+)"); - Matcher matcher = charsetPattern.matcher(contentType); - if (matcher.find() && matcher.groupCount() == 1) { - String charset = matcher.group(1).trim(); - assertTrue("Invalid charset", charset.indexOf('"') < 0); - } - } - } + @Test + public void testCharsetAttribute() throws Exception { + MockTransportOutputStream outputStream = new MockTransportOutputStream(new ByteArrayOutputStream()); + soapMessage.writeTo(outputStream); + Map headers = outputStream.getHeaders(); + String contentType = headers.get(TransportConstants.HEADER_CONTENT_TYPE); + if (contentType != null) { + Pattern charsetPattern = Pattern.compile("charset\\s*=\\s*([^;]+)"); + Matcher matcher = charsetPattern.matcher(contentType); + if (matcher.find() && matcher.groupCount() == 1) { + String charset = matcher.group(1).trim(); + assertTrue("Invalid charset", charset.indexOf('"') < 0); + } + } + } - @Test - public void testSetStreamingPayload() throws Exception { - if (!(soapMessage instanceof StreamingWebServiceMessage)) { - return; - } - StreamingWebServiceMessage streamingMessage = (StreamingWebServiceMessage) soapMessage; + @Test + public void testSetStreamingPayload() throws Exception { + if (!(soapMessage instanceof StreamingWebServiceMessage)) { + return; + } + StreamingWebServiceMessage streamingMessage = (StreamingWebServiceMessage) soapMessage; - final QName name = new QName("http://springframework.org", "root", "prefix"); - streamingMessage.setStreamingPayload(new StreamingPayload() { - public QName getName() { - return name; - } + final QName name = new QName("http://springframework.org", "root", "prefix"); + streamingMessage.setStreamingPayload(new StreamingPayload() { + public QName getName() { + return name; + } - public void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException { - streamWriter.writeStartElement(name.getPrefix(), name.getLocalPart(), name.getNamespaceURI()); - streamWriter.writeNamespace("prefix", name.getNamespaceURI()); - streamWriter.writeStartElement(name.getNamespaceURI(), "child"); - streamWriter.writeCharacters("Foo"); - streamWriter.writeEndElement(); - streamWriter.writeEndElement(); - } - }); + public void writeTo(XMLStreamWriter streamWriter) throws XMLStreamException { + streamWriter.writeStartElement(name.getPrefix(), name.getLocalPart(), name.getNamespaceURI()); + streamWriter.writeNamespace("prefix", name.getNamespaceURI()); + streamWriter.writeStartElement(name.getNamespaceURI(), "child"); + streamWriter.writeCharacters("Foo"); + streamWriter.writeEndElement(); + streamWriter.writeEndElement(); + } + }); - StringResult result = new StringResult(); - transformer.transform(streamingMessage.getPayloadSource(), result); + StringResult result = new StringResult(); + transformer.transform(streamingMessage.getPayloadSource(), result); - String expected = "Foo"; - assertXMLEqual(expected, result.toString()); + String expected = "Foo"; + assertXMLEqual(expected, result.toString()); - soapMessage.writeTo(new ByteArrayOutputStream()); - } + soapMessage.writeTo(new ByteArrayOutputStream()); + } - protected abstract Resource[] getSoapSchemas(); + protected abstract Resource[] getSoapSchemas(); - @Test - public abstract void testGetVersion() throws Exception; + @Test + public abstract void testGetVersion() throws Exception; - @Test - public abstract void testWriteToTransportOutputStream() throws Exception; + @Test + public abstract void testWriteToTransportOutputStream() throws Exception; - @Test - public abstract void testWriteToTransportResponseAttachment() throws Exception; + @Test + public abstract void testWriteToTransportResponseAttachment() throws Exception; - @Test - public abstract void testToDocument() throws Exception; + @Test + public abstract void testToDocument() throws Exception; - @Test - public abstract void testSetLiveDocument() throws Exception; + @Test + public abstract void testSetLiveDocument() throws Exception; - @Test - public abstract void testSetOtherDocument() throws Exception; + @Test + public abstract void testSetOtherDocument() throws Exception; } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/AbstractWsAddressingTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/AbstractWsAddressingTestCase.java index 931b119d..ae54bc58 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/AbstractWsAddressingTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/AbstractWsAddressingTestCase.java @@ -33,31 +33,31 @@ import static org.junit.Assert.assertNotNull; public abstract class AbstractWsAddressingTestCase { - protected MessageFactory messageFactory; + protected MessageFactory messageFactory; - @Before - public void createMessageFactory() throws Exception { - messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public void createMessageFactory() throws Exception { + messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + XMLUnit.setIgnoreWhitespace(true); + } - protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException { - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader("Content-Type", " application/soap+xml"); - InputStream is = AbstractWsAddressingTestCase.class.getResourceAsStream(fileName); - assertNotNull("Could not load " + fileName, is); - try { - return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is)); - } - finally { - is.close(); - } - } + protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException { + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader("Content-Type", " application/soap+xml"); + InputStream is = AbstractWsAddressingTestCase.class.getResourceAsStream(fileName); + assertNotNull("Could not load " + fileName, is); + try { + return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is)); + } + finally { + is.close(); + } + } - protected void assertXMLEqual(String message, SaajSoapMessage expected, SaajSoapMessage result) { - Document expectedDocument = expected.getSaajMessage().getSOAPPart(); - Document resultDocument = result.getSaajMessage().getSOAPPart(); - org.custommonkey.xmlunit.XMLAssert.assertXMLEqual(message, expectedDocument, resultDocument); - } + protected void assertXMLEqual(String message, SaajSoapMessage expected, SaajSoapMessage result) { + Document expectedDocument = expected.getSaajMessage().getSOAPPart(); + Document resultDocument = result.getSaajMessage().getSOAPPart(); + org.custommonkey.xmlunit.XMLAssert.assertXMLEqual(message, expectedDocument, resultDocument); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/AbstractActionCallbackTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/AbstractActionCallbackTestCase.java index e461b1ac..7f20fc41 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/AbstractActionCallbackTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/AbstractActionCallbackTestCase.java @@ -42,79 +42,79 @@ import static org.easymock.EasyMock.*; public abstract class AbstractActionCallbackTestCase extends AbstractWsAddressingTestCase { - private ActionCallback callback; + private ActionCallback callback; - private MessageIdStrategy strategyMock; + private MessageIdStrategy strategyMock; - private WebServiceConnection connectionMock; + private WebServiceConnection connectionMock; - @Before - public void createMocks() throws Exception { - strategyMock = createMock(MessageIdStrategy.class); + @Before + public void createMocks() throws Exception { + strategyMock = createMock(MessageIdStrategy.class); - connectionMock = createMock(WebServiceConnection.class); + connectionMock = createMock(WebServiceConnection.class); - TransportContext transportContext = new DefaultTransportContext(connectionMock); - TransportContextHolder.setTransportContext(transportContext); - } + TransportContext transportContext = new DefaultTransportContext(connectionMock); + TransportContextHolder.setTransportContext(transportContext); + } - @After - public void clearContext() throws Exception { - TransportContextHolder.setTransportContext(null); - } + @After + public void clearContext() throws Exception { + TransportContextHolder.setTransportContext(null); + } - @Test - public void testValid() throws Exception { - URI action = new URI("http://example.com/fabrikam/mail/Delete"); - URI to = new URI("mailto:fabrikam@example.com"); - callback = new ActionCallback(action, getVersion(), to); - callback.setMessageIdStrategy(strategyMock); - SaajSoapMessage message = createDeleteMessage(); - expect(strategyMock.newMessageId(message)).andReturn(new URI("http://example.com/someuniquestring")); - callback.setReplyTo(new EndpointReference(new URI("http://example.com/business/client1"))); + @Test + public void testValid() throws Exception { + URI action = new URI("http://example.com/fabrikam/mail/Delete"); + URI to = new URI("mailto:fabrikam@example.com"); + callback = new ActionCallback(action, getVersion(), to); + callback.setMessageIdStrategy(strategyMock); + SaajSoapMessage message = createDeleteMessage(); + expect(strategyMock.newMessageId(message)).andReturn(new URI("http://example.com/someuniquestring")); + callback.setReplyTo(new EndpointReference(new URI("http://example.com/business/client1"))); - replay(strategyMock, connectionMock); + replay(strategyMock, connectionMock); - callback.doWithMessage(message); + callback.doWithMessage(message); - SaajSoapMessage expected = loadSaajMessage(getTestPath() + "/valid.xml"); - assertXMLEqual("Invalid message", expected, message); + SaajSoapMessage expected = loadSaajMessage(getTestPath() + "/valid.xml"); + assertXMLEqual("Invalid message", expected, message); - verify(strategyMock, connectionMock); - } + verify(strategyMock, connectionMock); + } - @Test - public void testDefaults() throws Exception { - URI action = new URI("http://example.com/fabrikam/mail/Delete"); - URI connectionUri = new URI("mailto:fabrikam@example.com"); - callback = new ActionCallback(action, getVersion()); - callback.setMessageIdStrategy(strategyMock); - expect(connectionMock.getUri()).andReturn(connectionUri); + @Test + public void testDefaults() throws Exception { + URI action = new URI("http://example.com/fabrikam/mail/Delete"); + URI connectionUri = new URI("mailto:fabrikam@example.com"); + callback = new ActionCallback(action, getVersion()); + callback.setMessageIdStrategy(strategyMock); + expect(connectionMock.getUri()).andReturn(connectionUri); - SaajSoapMessage message = createDeleteMessage(); - expect(strategyMock.newMessageId(message)).andReturn(new URI("http://example.com/someuniquestring")); - callback.setReplyTo(new EndpointReference(new URI("http://example.com/business/client1"))); + SaajSoapMessage message = createDeleteMessage(); + expect(strategyMock.newMessageId(message)).andReturn(new URI("http://example.com/someuniquestring")); + callback.setReplyTo(new EndpointReference(new URI("http://example.com/business/client1"))); - replay(strategyMock, connectionMock); + replay(strategyMock, connectionMock); - callback.doWithMessage(message); + callback.doWithMessage(message); - SaajSoapMessage expected = loadSaajMessage(getTestPath() + "/valid.xml"); - assertXMLEqual("Invalid message", expected, message); - verify(strategyMock, connectionMock); - } + SaajSoapMessage expected = loadSaajMessage(getTestPath() + "/valid.xml"); + assertXMLEqual("Invalid message", expected, message); + verify(strategyMock, connectionMock); + } - private SaajSoapMessage createDeleteMessage() throws SOAPException { - SOAPMessage saajMessage = messageFactory.createMessage(); - SOAPBody saajBody = saajMessage.getSOAPBody(); - SOAPBodyElement delete = saajBody.addBodyElement(new QName("http://example.com/fabrikam", "Delete")); - SOAPElement maxCount = delete.addChildElement(new QName("maxCount")); - maxCount.setTextContent("42"); - return new SaajSoapMessage(saajMessage); - } + private SaajSoapMessage createDeleteMessage() throws SOAPException { + SOAPMessage saajMessage = messageFactory.createMessage(); + SOAPBody saajBody = saajMessage.getSOAPBody(); + SOAPBodyElement delete = saajBody.addBodyElement(new QName("http://example.com/fabrikam", "Delete")); + SOAPElement maxCount = delete.addChildElement(new QName("maxCount")); + maxCount.setTextContent("42"); + return new SaajSoapMessage(saajMessage); + } - protected abstract AddressingVersion getVersion(); + protected abstract AddressingVersion getVersion(); - protected abstract String getTestPath(); + protected abstract String getTestPath(); } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback10Test.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback10Test.java index c33d5d49..1e9a5fd1 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback10Test.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback10Test.java @@ -21,13 +21,13 @@ import org.springframework.ws.soap.addressing.version.AddressingVersion; public class ActionCallback10Test extends AbstractActionCallbackTestCase { - @Override - protected AddressingVersion getVersion() { - return new Addressing10(); - } + @Override + protected AddressingVersion getVersion() { + return new Addressing10(); + } - @Override - protected String getTestPath() { - return "10"; - } + @Override + protected String getTestPath() { + return "10"; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback200408Test.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback200408Test.java index 2eb7067b..c62b49b3 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback200408Test.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/client/ActionCallback200408Test.java @@ -21,13 +21,13 @@ import org.springframework.ws.soap.addressing.version.AddressingVersion; public class ActionCallback200408Test extends AbstractActionCallbackTestCase { - @Override - protected AddressingVersion getVersion() { - return new Addressing200408(); - } + @Override + protected AddressingVersion getVersion() { + return new Addressing200408(); + } - @Override - protected String getTestPath() { - return "200408"; - } + @Override + protected String getTestPath() { + return "200408"; + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategyTest.java index 7b3db612..0b6ddc39 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/messageid/UuidMessageIdStrategyTest.java @@ -24,19 +24,19 @@ import org.junit.Test; public class UuidMessageIdStrategyTest { - private MessageIdStrategy strategy; + private MessageIdStrategy strategy; - @Before - public final void setUp() throws Exception { - strategy = new UuidMessageIdStrategy(); - } + @Before + public final void setUp() throws Exception { + strategy = new UuidMessageIdStrategy(); + } - @Test - public void testStrategy() { - URI messageId1 = strategy.newMessageId(null); - Assert.assertNotNull("Empty messageId", messageId1); - URI messageId2 = strategy.newMessageId(null); - Assert.assertNotNull("Empty messageId", messageId2); - Assert.assertFalse("Equal messageIds", messageId1.equals(messageId2)); - } + @Test + public void testStrategy() { + URI messageId1 = strategy.newMessageId(null); + Assert.assertNotNull("Empty messageId", messageId1); + URI messageId2 = strategy.newMessageId(null); + Assert.assertNotNull("Empty messageId", messageId2); + Assert.assertFalse("Equal messageIds", messageId1.equals(messageId2)); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AbstractAddressingInterceptorTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AbstractAddressingInterceptorTestCase.java index d713d68c..a1a169fd 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AbstractAddressingInterceptorTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AbstractAddressingInterceptorTestCase.java @@ -41,168 +41,168 @@ import static org.junit.Assert.assertTrue; public abstract class AbstractAddressingInterceptorTestCase extends AbstractWsAddressingTestCase { - protected AddressingEndpointInterceptor interceptor; + protected AddressingEndpointInterceptor interceptor; - protected MessageIdStrategy strategyMock; + protected MessageIdStrategy strategyMock; - @Before - public void createMocks() throws Exception { - strategyMock = createMock(MessageIdStrategy.class); - expect(strategyMock.isDuplicate(isA(URI.class))).andReturn(false).anyTimes(); - URI replyAction = new URI("urn:replyAction"); - URI faultAction = new URI("urn:faultAction"); - interceptor = new AddressingEndpointInterceptor(getVersion(), strategyMock, new WebServiceMessageSender[0], - replyAction, faultAction); - } + @Before + public void createMocks() throws Exception { + strategyMock = createMock(MessageIdStrategy.class); + expect(strategyMock.isDuplicate(isA(URI.class))).andReturn(false).anyTimes(); + URI replyAction = new URI("urn:replyAction"); + URI faultAction = new URI("urn:faultAction"); + interceptor = new AddressingEndpointInterceptor(getVersion(), strategyMock, new WebServiceMessageSender[0], + replyAction, faultAction); + } - @Test - public void testUnderstands() throws Exception { - SaajSoapMessage validRequest = loadSaajMessage(getTestPath() + "/valid.xml"); - Iterator iterator = validRequest.getSoapHeader().examineAllHeaderElements(); + @Test + public void testUnderstands() throws Exception { + SaajSoapMessage validRequest = loadSaajMessage(getTestPath() + "/valid.xml"); + Iterator iterator = validRequest.getSoapHeader().examineAllHeaderElements(); - replay(strategyMock); + replay(strategyMock); - while (iterator.hasNext()) { - SoapHeaderElement headerElement = iterator.next(); - assertTrue("Header [" + headerElement.getName() + " not understood", - interceptor.understands(headerElement)); - } + while (iterator.hasNext()) { + SoapHeaderElement headerElement = iterator.next(); + assertTrue("Header [" + headerElement.getName() + " not understood", + interceptor.understands(headerElement)); + } - verify(strategyMock); - } + verify(strategyMock); + } - @Test - public void testValidRequest() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/valid.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + @Test + public void testValidRequest() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/valid.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - replay(strategyMock); + replay(strategyMock); - boolean result = interceptor.handleRequest(context, null); - assertTrue("Valid request not handled", result); - assertFalse("Message Context has response", context.hasResponse()); + boolean result = interceptor.handleRequest(context, null); + assertTrue("Valid request not handled", result); + assertFalse("Message Context has response", context.hasResponse()); - verify(strategyMock); - } + verify(strategyMock); + } - @Test - public void testNoMessageId() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-no-message-id.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + @Test + public void testNoMessageId() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-no-message-id.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - replay(strategyMock); + replay(strategyMock); - boolean result = interceptor.handleRequest(context, null); - assertFalse("Request with no MessageID handled", result); - assertTrue("Message Context has no response", context.hasResponse()); - SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-no-message-id.xml"); - assertXMLEqual("Invalid response for message with no MessageID", expectedResponse, - (SaajSoapMessage) context.getResponse()); + boolean result = interceptor.handleRequest(context, null); + assertFalse("Request with no MessageID handled", result); + assertTrue("Message Context has no response", context.hasResponse()); + SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-no-message-id.xml"); + assertXMLEqual("Invalid response for message with no MessageID", expectedResponse, + (SaajSoapMessage) context.getResponse()); - verify(strategyMock); - } + verify(strategyMock); + } - @Test - public void testNoReplyTo() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-no-reply-to.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - URI messageId = new URI("uid:1234"); + @Test + public void testNoReplyTo() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-no-reply-to.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + URI messageId = new URI("uid:1234"); - expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); - replay(strategyMock); + expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); + replay(strategyMock); - boolean result = interceptor.handleResponse(context, null); - assertTrue("Request with no ReplyTo not handled", result); - assertTrue("Message Context has no response", context.hasResponse()); - SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml"); - assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, - (SaajSoapMessage) context.getResponse()); + boolean result = interceptor.handleResponse(context, null); + assertTrue("Request with no ReplyTo not handled", result); + assertTrue("Message Context has no response", context.hasResponse()); + SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml"); + assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, + (SaajSoapMessage) context.getResponse()); - verify(strategyMock); - } + verify(strategyMock); + } - @Test - public void testAnonymousReplyTo() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-anonymous.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - URI messageId = new URI("uid:1234"); + @Test + public void testAnonymousReplyTo() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-anonymous.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + URI messageId = new URI("uid:1234"); - expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); - replay(strategyMock); + expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); + replay(strategyMock); - boolean result = interceptor.handleResponse(context, null); - assertTrue("Request with anonymous ReplyTo not handled", result); - SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml"); - assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, - (SaajSoapMessage) context.getResponse()); + boolean result = interceptor.handleResponse(context, null); + assertTrue("Request with anonymous ReplyTo not handled", result); + SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml"); + assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, + (SaajSoapMessage) context.getResponse()); - verify(strategyMock); - } + verify(strategyMock); + } - @Test - public void testNoneReplyTo() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-none.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - replay(strategyMock); - boolean result = interceptor.handleResponse(context, null); - assertFalse("None request handled", result); - assertFalse("Message context has response", context.hasResponse()); - verify(strategyMock); - } + @Test + public void testNoneReplyTo() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-none.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + replay(strategyMock); + boolean result = interceptor.handleResponse(context, null); + assertFalse("None request handled", result); + assertFalse("Message context has response", context.hasResponse()); + verify(strategyMock); + } - @Test - public void testFaultTo() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-fault-to.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - SaajSoapMessage response = (SaajSoapMessage) context.getResponse(); - response.getSoapBody().addServerOrReceiverFault("Error", Locale.ENGLISH); - URI messageId = new URI("uid:1234"); - expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); - replay(strategyMock); - boolean result = interceptor.handleFault(context, null); - assertTrue("Request with anonymous FaultTo not handled", result); - SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-fault-to.xml"); - assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, - (SaajSoapMessage) context.getResponse()); - verify(strategyMock); - } + @Test + public void testFaultTo() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-fault-to.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + SaajSoapMessage response = (SaajSoapMessage) context.getResponse(); + response.getSoapBody().addServerOrReceiverFault("Error", Locale.ENGLISH); + URI messageId = new URI("uid:1234"); + expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); + replay(strategyMock); + boolean result = interceptor.handleFault(context, null); + assertTrue("Request with anonymous FaultTo not handled", result); + SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-fault-to.xml"); + assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, + (SaajSoapMessage) context.getResponse()); + verify(strategyMock); + } - @Test - public void testOutOfBandReplyTo() throws Exception { - WebServiceMessageSender senderMock = createMock(WebServiceMessageSender.class); + @Test + public void testOutOfBandReplyTo() throws Exception { + WebServiceMessageSender senderMock = createMock(WebServiceMessageSender.class); - URI replyAction = new URI("urn:replyAction"); - URI faultAction = new URI("urn:replyAction"); - interceptor = - new AddressingEndpointInterceptor(getVersion(), strategyMock, new WebServiceMessageSender[]{senderMock}, - replyAction, faultAction); + URI replyAction = new URI("urn:replyAction"); + URI faultAction = new URI("urn:replyAction"); + interceptor = + new AddressingEndpointInterceptor(getVersion(), strategyMock, new WebServiceMessageSender[]{senderMock}, + replyAction, faultAction); - WebServiceConnection connectionMock = createMock(WebServiceConnection.class); + WebServiceConnection connectionMock = createMock(WebServiceConnection.class); - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/valid.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - SaajSoapMessage response = (SaajSoapMessage) context.getResponse(); + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/valid.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + SaajSoapMessage response = (SaajSoapMessage) context.getResponse(); - URI messageId = new URI("uid:1234"); - expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); + URI messageId = new URI("uid:1234"); + expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); - URI uri = new URI("http://example.com/business/client1"); - expect(senderMock.supports(uri)).andReturn(true); - expect(senderMock.createConnection(uri)).andReturn(connectionMock); - connectionMock.send(response); - connectionMock.close(); + URI uri = new URI("http://example.com/business/client1"); + expect(senderMock.supports(uri)).andReturn(true); + expect(senderMock.createConnection(uri)).andReturn(connectionMock); + connectionMock.send(response); + connectionMock.close(); - replay(strategyMock, senderMock, connectionMock); + replay(strategyMock, senderMock, connectionMock); - boolean result = interceptor.handleResponse(context, null); - assertFalse("Out of Band request handled", result); - assertFalse("Message context has response", context.hasResponse()); + boolean result = interceptor.handleResponse(context, null); + assertFalse("Out of Band request handled", result); + assertFalse("Message context has response", context.hasResponse()); - verify(strategyMock, senderMock, connectionMock); - } + verify(strategyMock, senderMock, connectionMock); + } - protected abstract AddressingVersion getVersion(); + protected abstract AddressingVersion getVersion(); - protected abstract String getTestPath(); + protected abstract String getTestPath(); } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor10Test.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor10Test.java index 09c0b3ca..e59d0f98 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor10Test.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor10Test.java @@ -31,29 +31,29 @@ import static org.junit.Assert.assertTrue; public class AddressingInterceptor10Test extends AbstractAddressingInterceptorTestCase { - @Override - protected AddressingVersion getVersion() { - return new Addressing10(); - } + @Override + protected AddressingVersion getVersion() { + return new Addressing10(); + } - @Override - protected String getTestPath() { - return "10"; - } + @Override + protected String getTestPath() { + return "10"; + } - public void testNoTo() throws Exception { - SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-no-to.xml"); - MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); - URI messageId = new URI("uid:1234"); - expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); - replay(strategyMock); - boolean result = interceptor.handleResponse(context, null); - assertTrue("Request with no To not handled", result); - assertTrue("Message Context has no response", context.hasResponse()); - SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml"); - assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, - (SaajSoapMessage) context.getResponse()); - verify(strategyMock); - } + public void testNoTo() throws Exception { + SaajSoapMessage valid = loadSaajMessage(getTestPath() + "/request-no-to.xml"); + MessageContext context = new DefaultMessageContext(valid, new SaajSoapMessageFactory(messageFactory)); + URI messageId = new URI("uid:1234"); + expect(strategyMock.newMessageId((SoapMessage) context.getResponse())).andReturn(messageId); + replay(strategyMock); + boolean result = interceptor.handleResponse(context, null); + assertTrue("Request with no To not handled", result); + assertTrue("Message Context has no response", context.hasResponse()); + SaajSoapMessage expectedResponse = loadSaajMessage(getTestPath() + "/response-anonymous.xml"); + assertXMLEqual("Invalid response for message with invalid MAP", expectedResponse, + (SaajSoapMessage) context.getResponse()); + verify(strategyMock); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor200408Test.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor200408Test.java index 9dc70603..4825e45f 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor200408Test.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AddressingInterceptor200408Test.java @@ -21,18 +21,18 @@ import org.springframework.ws.soap.addressing.version.AddressingVersion; public class AddressingInterceptor200408Test extends AbstractAddressingInterceptorTestCase { - @Override - protected AddressingVersion getVersion() { - return new Addressing200408(); - } + @Override + protected AddressingVersion getVersion() { + return new Addressing200408(); + } - @Override - protected String getTestPath() { - return "200408"; - } + @Override + protected String getTestPath() { + return "200408"; + } - @Override - public void testNoneReplyTo() throws Exception { - // This version of the spec does not have none addresses - } + @Override + public void testNoneReplyTo() throws Exception { + // This version of the spec does not have none addresses + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AnnotationActionMethodEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AnnotationActionMethodEndpointMappingTest.java index 8c0da52a..13ab060b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AnnotationActionMethodEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/AnnotationActionMethodEndpointMappingTest.java @@ -47,61 +47,61 @@ import static org.junit.Assert.*; */ public class AnnotationActionMethodEndpointMappingTest { - private StaticApplicationContext applicationContext; + private StaticApplicationContext applicationContext; - private AnnotationActionEndpointMapping mapping; + private AnnotationActionEndpointMapping mapping; - private MessageFactory messageFactory; + private MessageFactory messageFactory; - @Before - public void setUp() throws Exception { - messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - XMLUnit.setIgnoreWhitespace(true); - applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("mapping", AnnotationActionEndpointMapping.class); - applicationContext.registerSingleton("interceptor", MyInterceptor.class); - applicationContext.registerSingleton("smartIntercepter", MySmartInterceptor.class); - applicationContext.registerSingleton("endpoint", MyEndpoint.class); - applicationContext.refresh(); - mapping = (AnnotationActionEndpointMapping) applicationContext.getBean("mapping"); - } + @Before + public void setUp() throws Exception { + messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + XMLUnit.setIgnoreWhitespace(true); + applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("mapping", AnnotationActionEndpointMapping.class); + applicationContext.registerSingleton("interceptor", MyInterceptor.class); + applicationContext.registerSingleton("smartIntercepter", MySmartInterceptor.class); + applicationContext.registerSingleton("endpoint", MyEndpoint.class); + applicationContext.refresh(); + mapping = (AnnotationActionEndpointMapping) applicationContext.getBean("mapping"); + } - @Test - public void mapping() throws Exception { - MessageContext messageContext = createMessageContext(); + @Test + public void mapping() throws Exception { + MessageContext messageContext = createMessageContext(); - EndpointInvocationChain chain = mapping.getEndpoint(messageContext); - assertNotNull("MethodEndpoint not registered", chain); - MethodEndpoint expected = new MethodEndpoint(applicationContext.getBean("endpoint"), "doIt"); - assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); - assertEquals("No smart interceptors registered", 2, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[0] instanceof AddressingEndpointInterceptor); - assertTrue(chain.getInterceptors()[1] instanceof MyInterceptor); - } + EndpointInvocationChain chain = mapping.getEndpoint(messageContext); + assertNotNull("MethodEndpoint not registered", chain); + MethodEndpoint expected = new MethodEndpoint(applicationContext.getBean("endpoint"), "doIt"); + assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); + assertEquals("No smart interceptors registered", 2, chain.getInterceptors().length); + assertTrue(chain.getInterceptors()[0] instanceof AddressingEndpointInterceptor); + assertTrue(chain.getInterceptors()[1] instanceof MyInterceptor); + } - private MessageContext createMessageContext() throws SOAPException, IOException { - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader("Content-Type", " application/soap+xml"); - InputStream is = getClass().getResourceAsStream("valid.xml"); - assertNotNull("Could not load valid.xml", is); - try { - SaajSoapMessage message = new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is)); - return new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); - } - finally { - is.close(); - } - } + private MessageContext createMessageContext() throws SOAPException, IOException { + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader("Content-Type", " application/soap+xml"); + InputStream is = getClass().getResourceAsStream("valid.xml"); + assertNotNull("Could not load valid.xml", is); + try { + SaajSoapMessage message = new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is)); + return new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); + } + finally { + is.close(); + } + } - @Endpoint - @Address("mailto:joe@fabrikam123.example") - private static class MyEndpoint { + @Endpoint + @Address("mailto:joe@fabrikam123.example") + private static class MyEndpoint { - @Action("http://fabrikam123.example/mail/Delete") - public void doIt() { + @Action("http://fabrikam123.example/mail/Delete") + public void doIt() { - } - } + } + } private static class MyInterceptor extends DelegatingSmartEndpointInterceptor { @@ -110,14 +110,14 @@ public class AnnotationActionMethodEndpointMappingTest { } } - private static class MySmartInterceptor extends DelegatingSmartEndpointInterceptor { + private static class MySmartInterceptor extends DelegatingSmartEndpointInterceptor { - public MySmartInterceptor() { - super(new PayloadLoggingInterceptor()); - } + public MySmartInterceptor() { + super(new PayloadLoggingInterceptor()); + } - public boolean shouldIntercept(MessageContext messageContext, Object endpoint) { - return false; - } - } + public boolean shouldIntercept(MessageContext messageContext, Object endpoint) { + return false; + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMappingTest.java index a0521603..b1387fd7 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/addressing/server/SimpleActionEndpointMappingTest.java @@ -37,54 +37,54 @@ import static org.junit.Assert.*; public class SimpleActionEndpointMappingTest extends AbstractWsAddressingTestCase { - private SimpleActionEndpointMapping mapping; + private SimpleActionEndpointMapping mapping; - private Endpoint1 endpoint1; + private Endpoint1 endpoint1; - @Before - public void createMappings() throws Exception { - mapping = new SimpleActionEndpointMapping(); - Map map = new HashMap(); - endpoint1 = new Endpoint1(); - Endpoint2 endpoint2 = new Endpoint2(); - map.put("http://example.com/fabrikam/mail/Delete", endpoint1); - map.put("http://example.com/fabrikam/mail/Add", endpoint2); - mapping.setPreInterceptors(new EndpointInterceptor[]{new PayloadLoggingInterceptor()}); - mapping.setPostInterceptors(new EndpointInterceptor[]{new PayloadValidatingInterceptor()}); - mapping.setAddress(new URI("mailto:fabrikam@example.com")); - mapping.setActionMap(map); - mapping.afterPropertiesSet(); - } + @Before + public void createMappings() throws Exception { + mapping = new SimpleActionEndpointMapping(); + Map map = new HashMap(); + endpoint1 = new Endpoint1(); + Endpoint2 endpoint2 = new Endpoint2(); + map.put("http://example.com/fabrikam/mail/Delete", endpoint1); + map.put("http://example.com/fabrikam/mail/Add", endpoint2); + mapping.setPreInterceptors(new EndpointInterceptor[]{new PayloadLoggingInterceptor()}); + mapping.setPostInterceptors(new EndpointInterceptor[]{new PayloadValidatingInterceptor()}); + mapping.setAddress(new URI("mailto:fabrikam@example.com")); + mapping.setActionMap(map); + mapping.afterPropertiesSet(); + } - @Test - public void testMatch() throws Exception { - SaajSoapMessage message = loadSaajMessage("200408/valid.xml"); - MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); + @Test + public void testMatch() throws Exception { + SaajSoapMessage message = loadSaajMessage("200408/valid.xml"); + MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); - EndpointInvocationChain endpoint = mapping.getEndpoint(messageContext); - assertNotNull("No endpoint returned", endpoint); - assertEquals("Invalid endpoint returned", endpoint1, endpoint.getEndpoint()); - EndpointInterceptor[] interceptors = endpoint.getInterceptors(); - assertEquals("Invalid amount of interceptors returned", 3, interceptors.length); - assertTrue("Invalid first interceptor", interceptors[0] instanceof PayloadLoggingInterceptor); - assertTrue("Invalid first interceptor", interceptors[1] instanceof AddressingEndpointInterceptor); - assertTrue("Invalid first interceptor", interceptors[2] instanceof PayloadValidatingInterceptor); - } + EndpointInvocationChain endpoint = mapping.getEndpoint(messageContext); + assertNotNull("No endpoint returned", endpoint); + assertEquals("Invalid endpoint returned", endpoint1, endpoint.getEndpoint()); + EndpointInterceptor[] interceptors = endpoint.getInterceptors(); + assertEquals("Invalid amount of interceptors returned", 3, interceptors.length); + assertTrue("Invalid first interceptor", interceptors[0] instanceof PayloadLoggingInterceptor); + assertTrue("Invalid first interceptor", interceptors[1] instanceof AddressingEndpointInterceptor); + assertTrue("Invalid first interceptor", interceptors[2] instanceof PayloadValidatingInterceptor); + } - @Test - public void testNoMatch() throws Exception { - SaajSoapMessage message = loadSaajMessage("200408/response-no-message-id.xml"); - MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); + @Test + public void testNoMatch() throws Exception { + SaajSoapMessage message = loadSaajMessage("200408/response-no-message-id.xml"); + MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(messageFactory)); - EndpointInvocationChain endpoint = mapping.getEndpoint(messageContext); - assertNull("Endpoint returned", endpoint); - } + EndpointInvocationChain endpoint = mapping.getEndpoint(messageContext); + assertNull("Endpoint returned", endpoint); + } - private static class Endpoint1 { + private static class Endpoint1 { - } + } - private static class Endpoint2 { + private static class Endpoint2 { - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomHandlerTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomHandlerTest.java index b0d2017e..6612eade 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomHandlerTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomHandlerTest.java @@ -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, @@ -46,127 +46,127 @@ import org.xml.sax.helpers.XMLReaderFactory; public class AxiomHandlerTest { - private static final String XML_1 = - "" + "" + "" + - "content" + - ""; + private static final String XML_1 = + "" + "" + "" + + "content" + + ""; - private static final String XML_2_EXPECTED = - "" + "" + "" + - ""; + private static final String XML_2_EXPECTED = + "" + "" + "" + + ""; - private static final String XML_2_SNIPPET = - "" + ""; + private static final String XML_2_SNIPPET = + "" + ""; - private static final String XML_3_ENTITY = - "<>&"'"; + private static final String XML_3_ENTITY = + "<>&"'"; - private static final String XML_4_SNIPPET = "" + ""; - - private static final String XML_5_SNIPPET = "" + ""; + private static final String XML_4_SNIPPET = "" + ""; + + private static final String XML_5_SNIPPET = "" + ""; - private AxiomHandler handler; + private AxiomHandler handler; - private OMDocument result; + private OMDocument result; - private XMLReader xmlReader; + private XMLReader xmlReader; - private OMFactory factory; + private OMFactory factory; - @Before - public void setUp() throws Exception { - factory = OMAbstractFactory.getOMFactory(); - result = factory.createOMDocument(); - xmlReader = XMLReaderFactory.createXMLReader(); - } + @Before + public void setUp() throws Exception { + factory = OMAbstractFactory.getOMFactory(); + result = factory.createOMDocument(); + xmlReader = XMLReaderFactory.createXMLReader(); + } - @Test - public void testContentHandlerDocumentNamespacePrefixes() throws Exception { - xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); - handler = new AxiomHandler(result, factory); - xmlReader.setContentHandler(handler); - xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); - xmlReader.parse(new InputSource(new StringReader(XML_1))); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - result.serialize(bos); - assertXMLEqual("Invalid result", XML_1, bos.toString("UTF-8")); - } + @Test + public void testContentHandlerDocumentNamespacePrefixes() throws Exception { + xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + handler = new AxiomHandler(result, factory); + xmlReader.setContentHandler(handler); + xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); + xmlReader.parse(new InputSource(new StringReader(XML_1))); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + result.serialize(bos); + assertXMLEqual("Invalid result", XML_1, bos.toString("UTF-8")); + } - @Test - public void testContentHandlerDocumentNoNamespacePrefixes() throws Exception { - xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); - handler = new AxiomHandler(result, factory); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_1))); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - result.serialize(bos); - assertXMLEqual("Invalid result", XML_1, bos.toString("UTF-8")); - } + @Test + public void testContentHandlerDocumentNoNamespacePrefixes() throws Exception { + xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); + handler = new AxiomHandler(result, factory); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_1))); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + result.serialize(bos); + assertXMLEqual("Invalid result", XML_1, bos.toString("UTF-8")); + } - @Test - public void testContentHandlerElement() throws Exception { - OMNamespace namespace = factory.createOMNamespace("namespace", ""); - OMElement rootElement = factory.createOMElement("root", namespace, result); - handler = new AxiomHandler(rootElement, factory); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - result.serialize(bos); - assertXMLEqual("Invalid result", XML_2_EXPECTED, bos.toString("UTF-8")); - } - - @Test - public void testContentHandlerElementWithSamePrefixAndDifferentNamespace() throws Exception { - OMNamespace namespace = factory.createOMNamespace("namespace1", ""); - OMElement rootElement = factory.createOMElement("root", namespace, result); - handler = new AxiomHandler(rootElement, factory); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); - Iterator it = result.getOMDocumentElement().getChildrenWithLocalName("child"); - assertTrue(it.hasNext()); - OMElement child = (OMElement) it.next(); - assertEquals("", child.getQName().getPrefix()); - assertEquals("namespace2", child.getQName().getNamespaceURI()); - } + @Test + public void testContentHandlerElement() throws Exception { + OMNamespace namespace = factory.createOMNamespace("namespace", ""); + OMElement rootElement = factory.createOMElement("root", namespace, result); + handler = new AxiomHandler(rootElement, factory); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + result.serialize(bos); + assertXMLEqual("Invalid result", XML_2_EXPECTED, bos.toString("UTF-8")); + } + + @Test + public void testContentHandlerElementWithSamePrefixAndDifferentNamespace() throws Exception { + OMNamespace namespace = factory.createOMNamespace("namespace1", ""); + OMElement rootElement = factory.createOMElement("root", namespace, result); + handler = new AxiomHandler(rootElement, factory); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); + Iterator it = result.getOMDocumentElement().getChildrenWithLocalName("child"); + assertTrue(it.hasNext()); + OMElement child = (OMElement) it.next(); + assertEquals("", child.getQName().getPrefix()); + assertEquals("namespace2", child.getQName().getNamespaceURI()); + } - @Test - public void testContentHandlerElementWithSameNamespacesAndPrefix() throws Exception { - OMNamespace namespace = factory.createOMNamespace("namespace1", ""); - OMElement rootElement = factory.createOMElement("root", namespace, result); - handler = new AxiomHandler(rootElement, factory); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_4_SNIPPET))); - Iterator it = result.getOMDocumentElement().getChildrenWithLocalName("child"); - assertTrue(it.hasNext()); - OMElement child = (OMElement) it.next(); - assertEquals("", child.getQName().getPrefix()); - assertEquals("namespace1", child.getQName().getNamespaceURI()); - } + @Test + public void testContentHandlerElementWithSameNamespacesAndPrefix() throws Exception { + OMNamespace namespace = factory.createOMNamespace("namespace1", ""); + OMElement rootElement = factory.createOMElement("root", namespace, result); + handler = new AxiomHandler(rootElement, factory); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_4_SNIPPET))); + Iterator it = result.getOMDocumentElement().getChildrenWithLocalName("child"); + assertTrue(it.hasNext()); + OMElement child = (OMElement) it.next(); + assertEquals("", child.getQName().getPrefix()); + assertEquals("namespace1", child.getQName().getNamespaceURI()); + } - @Test - public void testContentHandlerElementWithSameNamespacesAndDifferentPrefix() throws Exception { - OMNamespace namespace = factory.createOMNamespace("namespace1", ""); - OMElement rootElement = factory.createOMElement("root", namespace, result); - handler = new AxiomHandler(rootElement, factory); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_5_SNIPPET))); - Iterator it = result.getOMDocumentElement().getChildrenWithLocalName("child"); - assertTrue(it.hasNext()); - OMElement child = (OMElement) it.next(); - assertEquals("x", child.getQName().getPrefix()); - assertEquals("namespace1", child.getQName().getNamespaceURI()); - } + @Test + public void testContentHandlerElementWithSameNamespacesAndDifferentPrefix() throws Exception { + OMNamespace namespace = factory.createOMNamespace("namespace1", ""); + OMElement rootElement = factory.createOMElement("root", namespace, result); + handler = new AxiomHandler(rootElement, factory); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_5_SNIPPET))); + Iterator it = result.getOMDocumentElement().getChildrenWithLocalName("child"); + assertTrue(it.hasNext()); + OMElement child = (OMElement) it.next(); + assertEquals("x", child.getQName().getPrefix()); + assertEquals("namespace1", child.getQName().getNamespaceURI()); + } - @Test - public void testContentHandlerPredefinedEntityReference() throws Exception { - handler = new AxiomHandler(result, factory); - xmlReader.setContentHandler(handler); - xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); - xmlReader.parse(new InputSource(new StringReader(XML_3_ENTITY))); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - result.serialize(bos); - assertXMLEqual("Invalid result", XML_3_ENTITY, bos.toString("UTF-8")); - } + @Test + public void testContentHandlerPredefinedEntityReference() throws Exception { + handler = new AxiomHandler(result, factory); + xmlReader.setContentHandler(handler); + xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); + xmlReader.parse(new InputSource(new StringReader(XML_3_ENTITY))); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + result.serialize(bos); + assertXMLEqual("Invalid result", XML_3_ENTITY, bos.toString("UTF-8")); + } @Test public void testTransformDom() throws Exception { diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11BodyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11BodyTest.java index 3d4fc618..19e75473 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11BodyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11BodyTest.java @@ -27,25 +27,25 @@ import org.springframework.xml.transform.StringSource; public class AxiomSoap11BodyTest extends AbstractSoap11BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); - return axiomSoapMessage.getSoapBody(); - } + @Override + protected SoapBody createSoapBody() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); + return axiomSoapMessage.getSoapBody(); + } - @Test - public void testPayloadNoCaching() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.setSoapVersion(SoapVersion.SOAP_11); + @Test + public void testPayloadNoCaching() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.setSoapVersion(SoapVersion.SOAP_11); - AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); - soapBody = axiomSoapMessage.getSoapBody(); + AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); + soapBody = axiomSoapMessage.getSoapBody(); - String payload = ""; - transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); - assertPayloadEqual(payload); - } + String payload = ""; + transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); + assertPayloadEqual(payload); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11EnvelopeTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11EnvelopeTest.java index 3ff63fa8..27e0af70 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11EnvelopeTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11EnvelopeTest.java @@ -23,10 +23,10 @@ import org.springframework.ws.soap.soap11.AbstractSoap11EnvelopeTestCase; public class AxiomSoap11EnvelopeTest extends AbstractSoap11EnvelopeTestCase { - @Override - protected SoapEnvelope createSoapEnvelope() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); - return axiomSoapMessage.getEnvelope(); - } + @Override + protected SoapEnvelope createSoapEnvelope() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); + return axiomSoapMessage.getEnvelope(); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11HeaderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11HeaderTest.java index ec6ce6e9..766a42dd 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11HeaderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11HeaderTest.java @@ -23,14 +23,14 @@ import org.springframework.ws.soap.soap11.AbstractSoap11HeaderTestCase; public class AxiomSoap11HeaderTest extends AbstractSoap11HeaderTestCase { - @Override - protected SoapHeader createSoapHeader() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); - return axiomSoapMessage.getSoapHeader(); - } + @Override + protected SoapHeader createSoapHeader() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); + return axiomSoapMessage.getSoapHeader(); + } - @Override - public void testGetResult() throws Exception { - } + @Override + public void testGetResult() throws Exception { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageFactoryTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageFactoryTest.java index 6677d7f2..457c5d8e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageFactoryTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageFactoryTest.java @@ -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,107 +39,107 @@ import static org.junit.Assert.fail; public class AxiomSoap11MessageFactoryTest extends AbstractSoap11MessageFactoryTestCase { - private Transformer transformer; + private Transformer transformer; - @Override - protected WebServiceMessageFactory createMessageFactory() throws Exception { - transformer = TransformerFactory.newInstance().newTransformer(); + @Override + protected WebServiceMessageFactory createMessageFactory() throws Exception { + transformer = TransformerFactory.newInstance().newTransformer(); - AxiomSoapMessageFactory factory = new AxiomSoapMessageFactory(); - factory.afterPropertiesSet(); - return factory; - } + AxiomSoapMessageFactory factory = new AxiomSoapMessageFactory(); + factory.afterPropertiesSet(); + return factory; + } - @Override - public void testCreateSoapMessageIllFormedXml() throws Exception { - // Axiom parses the contents of XML lazily, so it will not throw an InvalidXmlException when a message is parsed - throw new InvalidXmlException(null, null); - } + @Override + public void testCreateSoapMessageIllFormedXml() throws Exception { + // Axiom parses the contents of XML lazily, so it will not throw an InvalidXmlException when a message is parsed + throw new InvalidXmlException(null, null); + } - @Test - public void testGetCharsetEncoding() { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + @Test + public void testGetCharsetEncoding() { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - assertEquals("Invalid charset", "utf-8", messageFactory.getCharSetEncoding("text/html; charset=utf-8")); - assertEquals("Invalid charset", "utf-8", messageFactory.getCharSetEncoding("application/xop+xml;type=text/xml; charset=utf-8")); - assertEquals("Invalid charset", "utf-8", messageFactory.getCharSetEncoding("application/xop+xml;type=\"text/xml; charset=utf-8\"")); - } + assertEquals("Invalid charset", "utf-8", messageFactory.getCharSetEncoding("text/html; charset=utf-8")); + assertEquals("Invalid charset", "utf-8", messageFactory.getCharSetEncoding("application/xop+xml;type=text/xml; charset=utf-8")); + assertEquals("Invalid charset", "utf-8", messageFactory.getCharSetEncoding("application/xop+xml;type=\"text/xml; charset=utf-8\"")); + } - @Test - public void testRepetitiveReadCaching() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(true); - messageFactory.afterPropertiesSet(); + @Test + public void testRepetitiveReadCaching() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(true); + messageFactory.afterPropertiesSet(); - String xml = "" + - "" + - ""; - TransportInputStream tis = new MockTransportInputStream(new ByteArrayInputStream(xml.getBytes())); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + String xml = "" + + "" + + ""; + TransportInputStream tis = new MockTransportInputStream(new ByteArrayInputStream(xml.getBytes())); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - StringResult result = new StringResult(); - transformer.transform(message.getPayloadSource(), result); - transformer.transform(message.getPayloadSource(), result); - } + StringResult result = new StringResult(); + transformer.transform(message.getPayloadSource(), result); + transformer.transform(message.getPayloadSource(), result); + } - @Test - public void testRepetitiveReadNoCaching() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.afterPropertiesSet(); + @Test + public void testRepetitiveReadNoCaching() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.afterPropertiesSet(); - String xml = "" + - "" + - ""; - TransportInputStream tis = new MockTransportInputStream(new ByteArrayInputStream(xml.getBytes())); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + String xml = "" + + "" + + ""; + TransportInputStream tis = new MockTransportInputStream(new ByteArrayInputStream(xml.getBytes())); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - StringResult result = new StringResult(); - transformer.transform(message.getPayloadSource(), result); - try { - transformer.transform(message.getPayloadSource(), result); - fail("TransformerException expected"); - } - catch (TransformerException expected) { - // ignore - } - } + StringResult result = new StringResult(); + transformer.transform(message.getPayloadSource(), result); + try { + transformer.transform(message.getPayloadSource(), result); + fail("TransformerException expected"); + } + catch (TransformerException expected) { + // ignore + } + } - /** - * See http://jira.springframework.org/browse/SWS-502 - */ - @Test - public void testSWS502() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.afterPropertiesSet(); + /** + * See http://jira.springframework.org/browse/SWS-502 + */ + @Test + public void testSWS502() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.afterPropertiesSet(); - String envelope = - "" + - "" + - "" + - "" + "" + - "true" + "0" + - "ok]]]]>>" + - "]]>" + "" + - ""; + String envelope = + "" + + "" + + "" + + "" + "" + + "true" + "0" + + "ok]]]]>>" + + "]]>" + "" + + ""; - InputStream inputStream = new ByteArrayInputStream(envelope.getBytes("UTF-8")); - AxiomSoapMessage message = messageFactory.createWebServiceMessage(new MockTransportInputStream(inputStream)); + InputStream inputStream = new ByteArrayInputStream(envelope.getBytes("UTF-8")); + AxiomSoapMessage message = messageFactory.createWebServiceMessage(new MockTransportInputStream(inputStream)); - StringResult result = new StringResult(); - transformer.transform(message.getPayloadSource(), result); + StringResult result = new StringResult(); + transformer.transform(message.getPayloadSource(), result); - XMLUnit.setIgnoreWhitespace(true); - String expectedPayload = - "" + - "" + - "" + "" + - "true" + "0" + - "ok]]]]>>" + - "]]>" + ""; - XMLAssert.assertXMLEqual(expectedPayload, result.toString()); + XMLUnit.setIgnoreWhitespace(true); + String expectedPayload = + "" + + "" + + "" + "" + + "true" + "0" + + "ok]]]]>>" + + "]]>" + ""; + XMLAssert.assertXMLEqual(expectedPayload, result.toString()); - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageTest.java index 51b55822..9f7c936b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11MessageTest.java @@ -23,10 +23,10 @@ import org.springframework.ws.soap.soap11.AbstractSoap11MessageTestCase; public class AxiomSoap11MessageTest extends AbstractSoap11MessageTestCase { - @Override - protected SoapMessage createSoapMessage() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); - return new AxiomSoapMessage(axiomFactory); - } + @Override + protected SoapMessage createSoapMessage() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP11Factory(); + return new AxiomSoapMessage(axiomFactory); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingBodyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingBodyTest.java index 36f2de7d..13891891 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingBodyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingBodyTest.java @@ -22,14 +22,14 @@ import org.springframework.ws.soap.soap11.AbstractSoap11BodyTestCase; public class AxiomSoap11NonCachingBodyTest extends AbstractSoap11BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.setSoapVersion(SoapVersion.SOAP_11); + @Override + protected SoapBody createSoapBody() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.setSoapVersion(SoapVersion.SOAP_11); - AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); - return axiomSoapMessage.getSoapBody(); - } + AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); + return axiomSoapMessage.getSoapBody(); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingMessageTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingMessageTest.java index 50e481e4..0457a7b0 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingMessageTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap11NonCachingMessageTest.java @@ -26,25 +26,25 @@ import org.springframework.ws.soap.soap11.AbstractSoap11MessageTestCase; public class AxiomSoap11NonCachingMessageTest extends AbstractSoap11MessageTestCase { - @Override - protected SoapMessage createSoapMessage() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.setSoapVersion(SoapVersion.SOAP_11); + @Override + protected SoapMessage createSoapMessage() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.setSoapVersion(SoapVersion.SOAP_11); - return messageFactory.createWebServiceMessage(); - } + return messageFactory.createWebServiceMessage(); + } - @Override - public void testWriteToTransportOutputStream() throws Exception { - super.testWriteToTransportOutputStream(); + @Override + public void testWriteToTransportOutputStream() throws Exception { + super.testWriteToTransportOutputStream(); - SoapBody body = soapMessage.getSoapBody(); - OMSourcedElementImpl axiomPayloadEle = - (OMSourcedElementImpl) ((AxiomSoapBody) body).getAxiomElement().getFirstElement(); - assertFalse("Non-cached body should not be expanded now", axiomPayloadEle.isExpanded()); - axiomPayloadEle.getFirstElement(); - assertTrue("Non-cached body should now be expanded", axiomPayloadEle.isExpanded()); - assertEquals("Invalid payload", "payload", axiomPayloadEle.getLocalName()); - } + SoapBody body = soapMessage.getSoapBody(); + OMSourcedElementImpl axiomPayloadEle = + (OMSourcedElementImpl) ((AxiomSoapBody) body).getAxiomElement().getFirstElement(); + assertFalse("Non-cached body should not be expanded now", axiomPayloadEle.isExpanded()); + axiomPayloadEle.getFirstElement(); + assertTrue("Non-cached body should now be expanded", axiomPayloadEle.isExpanded()); + assertEquals("Invalid payload", "payload", axiomPayloadEle.getLocalName()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12BodyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12BodyTest.java index b5a29811..c1f78409 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12BodyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12BodyTest.java @@ -27,24 +27,24 @@ import org.springframework.xml.transform.StringSource; public class AxiomSoap12BodyTest extends AbstractSoap12BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); - AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); - return axiomSoapMessage.getSoapBody(); - } + @Override + protected SoapBody createSoapBody() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); + AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); + return axiomSoapMessage.getSoapBody(); + } - @Test - public void testPayloadNoCaching() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.setSoapVersion(SoapVersion.SOAP_12); + @Test + public void testPayloadNoCaching() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.setSoapVersion(SoapVersion.SOAP_12); - AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); - soapBody = axiomSoapMessage.getSoapBody(); + AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); + soapBody = axiomSoapMessage.getSoapBody(); - String payload = ""; - transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); - assertPayloadEqual(payload); - } + String payload = ""; + transformer.transform(new StringSource(payload), soapBody.getPayloadResult()); + assertPayloadEqual(payload); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12EnvelopeTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12EnvelopeTest.java index 6d82e890..7565989a 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12EnvelopeTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12EnvelopeTest.java @@ -23,10 +23,10 @@ import org.springframework.ws.soap.soap12.AbstractSoap12EnvelopeTestCase; public class AxiomSoap12EnvelopeTest extends AbstractSoap12EnvelopeTestCase { - @Override - protected SoapEnvelope createSoapEnvelope() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); - AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); - return axiomSoapMessage.getEnvelope(); - } + @Override + protected SoapEnvelope createSoapEnvelope() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); + AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); + return axiomSoapMessage.getEnvelope(); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12HeaderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12HeaderTest.java index fd083e1e..0aeba450 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12HeaderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12HeaderTest.java @@ -23,14 +23,14 @@ import org.springframework.ws.soap.soap12.AbstractSoap12HeaderTestCase; public class AxiomSoap12HeaderTest extends AbstractSoap12HeaderTestCase { - @Override - protected SoapHeader createSoapHeader() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); - AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); - return axiomSoapMessage.getSoapHeader(); - } + @Override + protected SoapHeader createSoapHeader() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); + AxiomSoapMessage axiomSoapMessage = new AxiomSoapMessage(axiomFactory); + return axiomSoapMessage.getSoapHeader(); + } - @Override - public void testGetResult() throws Exception { - } + @Override + public void testGetResult() throws Exception { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageFactoryTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageFactoryTest.java index f93161ac..9f4c60f4 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageFactoryTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageFactoryTest.java @@ -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, @@ -23,18 +23,18 @@ import org.springframework.ws.soap.soap12.AbstractSoap12MessageFactoryTestCase; public class AxiomSoap12MessageFactoryTest extends AbstractSoap12MessageFactoryTestCase { - @Override - protected WebServiceMessageFactory createMessageFactory() throws Exception { - AxiomSoapMessageFactory factory = new AxiomSoapMessageFactory(); - factory.setSoapVersion(SoapVersion.SOAP_12); - factory.afterPropertiesSet(); - return factory; - } + @Override + protected WebServiceMessageFactory createMessageFactory() throws Exception { + AxiomSoapMessageFactory factory = new AxiomSoapMessageFactory(); + factory.setSoapVersion(SoapVersion.SOAP_12); + factory.afterPropertiesSet(); + return factory; + } - @Override - public void testCreateSoapMessageIllFormedXml() throws Exception { - // Axiom parses the contents of XML lazily, so it will not throw an InvalidXmlException when a message is parsed - throw new InvalidXmlException(null, null); - } + @Override + public void testCreateSoapMessageIllFormedXml() throws Exception { + // Axiom parses the contents of XML lazily, so it will not throw an InvalidXmlException when a message is parsed + throw new InvalidXmlException(null, null); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageTest.java index 49f623dc..21c9ed96 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12MessageTest.java @@ -23,10 +23,10 @@ import org.springframework.ws.soap.soap12.AbstractSoap12MessageTestCase; public class AxiomSoap12MessageTest extends AbstractSoap12MessageTestCase { - @Override - protected SoapMessage createSoapMessage() throws Exception { - SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); - return new AxiomSoapMessage(axiomFactory); - } + @Override + protected SoapMessage createSoapMessage() throws Exception { + SOAPFactory axiomFactory = OMAbstractFactory.getSOAP12Factory(); + return new AxiomSoapMessage(axiomFactory); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingBodyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingBodyTest.java index fb20ccbb..c06bb87e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingBodyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingBodyTest.java @@ -22,14 +22,14 @@ import org.springframework.ws.soap.soap12.AbstractSoap12BodyTestCase; public class AxiomSoap12NonCachingBodyTest extends AbstractSoap12BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.setSoapVersion(SoapVersion.SOAP_12); + @Override + protected SoapBody createSoapBody() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.setSoapVersion(SoapVersion.SOAP_12); - AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); - return axiomSoapMessage.getSoapBody(); - } + AxiomSoapMessage axiomSoapMessage = messageFactory.createWebServiceMessage(); + return axiomSoapMessage.getSoapBody(); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingMessageTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingMessageTest.java index 54e0490e..84defa95 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingMessageTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoap12NonCachingMessageTest.java @@ -27,25 +27,25 @@ import static org.junit.Assert.*; public class AxiomSoap12NonCachingMessageTest extends AbstractSoap12MessageTestCase { - @Override - protected SoapMessage createSoapMessage() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(false); - messageFactory.setSoapVersion(SoapVersion.SOAP_12); + @Override + protected SoapMessage createSoapMessage() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(false); + messageFactory.setSoapVersion(SoapVersion.SOAP_12); - return messageFactory.createWebServiceMessage(); - } + return messageFactory.createWebServiceMessage(); + } - @Override - public void testWriteToTransportOutputStream() throws Exception { - super.testWriteToTransportOutputStream(); + @Override + public void testWriteToTransportOutputStream() throws Exception { + super.testWriteToTransportOutputStream(); - SoapBody body = soapMessage.getSoapBody(); - OMSourcedElementImpl axiomPayloadEle = - (OMSourcedElementImpl) ((AxiomSoapBody) body).getAxiomElement().getFirstElement(); - assertFalse("Non-cached body should not be expanded now", axiomPayloadEle.isExpanded()); - axiomPayloadEle.getFirstElement(); - assertTrue("Non-cached body should now be expanded", axiomPayloadEle.isExpanded()); - assertEquals("Invalid payload", "payload", axiomPayloadEle.getLocalName()); - } + SoapBody body = soapMessage.getSoapBody(); + OMSourcedElementImpl axiomPayloadEle = + (OMSourcedElementImpl) ((AxiomSoapBody) body).getAxiomElement().getFirstElement(); + assertFalse("Non-cached body should not be expanded now", axiomPayloadEle.isExpanded()); + axiomPayloadEle.getFirstElement(); + assertTrue("Non-cached body should now be expanded", axiomPayloadEle.isExpanded()); + assertEquals("Invalid payload", "payload", axiomPayloadEle.getLocalName()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailTest.java index 07051a07..f3595593 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/AxiomSoapFaultDetailTest.java @@ -32,65 +32,65 @@ import org.junit.Test; @SuppressWarnings("Since15") public class AxiomSoapFaultDetailTest { - private static final String FAILING_FAULT = - "\n " + "\n " + - "\n " + "Client\n " + - "Client Error\n " + "\n " + - "\n " + - "\n " + "" + "" + - "" + "" + ""; + private static final String FAILING_FAULT = + "\n " + "\n " + + "\n " + "Client\n " + + "Client Error\n " + "\n " + + "\n " + + "\n " + "" + "" + + "" + "" + ""; - private static final String SUCCEEDING_FAULT = - "\n " + "\n " + - "\n " + "Client\n " + - "Client Error\n " + "" + - "\n " + - "\n " + "" + "" + - "" + "" + ""; + private static final String SUCCEEDING_FAULT = + "\n " + "\n " + + "\n " + "Client\n " + + "Client Error\n " + "" + + "\n " + + "\n " + "" + "" + + "" + "" + ""; - private AxiomSoapMessage failingMessage; + private AxiomSoapMessage failingMessage; - private AxiomSoapMessage succeedingMessage; + private AxiomSoapMessage succeedingMessage; - @Before - public void setUp() throws Exception { - XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(FAILING_FAULT)); - StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser); - SOAPMessage soapMessage = builder.getSoapMessage(); + @Before + public void setUp() throws Exception { + XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(FAILING_FAULT)); + StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser); + SOAPMessage soapMessage = builder.getSoapMessage(); - failingMessage = new AxiomSoapMessage(soapMessage, null, false, true); + failingMessage = new AxiomSoapMessage(soapMessage, null, false, true); - parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(SUCCEEDING_FAULT)); - builder = new StAXSOAPModelBuilder(parser); - soapMessage = builder.getSoapMessage(); + parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(SUCCEEDING_FAULT)); + builder = new StAXSOAPModelBuilder(parser); + soapMessage = builder.getSoapMessage(); - succeedingMessage = new AxiomSoapMessage(soapMessage, null, false, true); + succeedingMessage = new AxiomSoapMessage(soapMessage, null, false, true); - } + } - @Test - public void testGetDetailEntriesWorksWithWhitespaceNodes() throws Exception { - SoapFault fault = failingMessage.getSoapBody().getFault(); - Assert.assertNotNull("Fault is null", fault); - Assert.assertNotNull("Fault detail is null", fault.getFaultDetail()); - SoapFaultDetail detail = fault.getFaultDetail(); - Assert.assertTrue("No next detail entry present", detail.getDetailEntries().hasNext()); - detail.getDetailEntries().next(); + @Test + public void testGetDetailEntriesWorksWithWhitespaceNodes() throws Exception { + SoapFault fault = failingMessage.getSoapBody().getFault(); + Assert.assertNotNull("Fault is null", fault); + Assert.assertNotNull("Fault detail is null", fault.getFaultDetail()); + SoapFaultDetail detail = fault.getFaultDetail(); + Assert.assertTrue("No next detail entry present", detail.getDetailEntries().hasNext()); + detail.getDetailEntries().next(); - } + } - @Test - public void testGetDetailEntriesWorksWithoutWhitespaceNodes() throws Exception { - SoapFault fault = succeedingMessage.getSoapBody().getFault(); - Assert.assertNotNull("Fault is null", fault); - Assert.assertNotNull("Fault detail is null", fault.getFaultDetail()); - SoapFaultDetail detail = fault.getFaultDetail(); - Assert.assertTrue("No next detail entry present", detail.getDetailEntries().hasNext()); - detail.getDetailEntries().next(); - } + @Test + public void testGetDetailEntriesWorksWithoutWhitespaceNodes() throws Exception { + SoapFault fault = succeedingMessage.getSoapBody().getFault(); + Assert.assertNotNull("Fault is null", fault); + Assert.assertNotNull("Fault detail is null", fault.getFaultDetail()); + SoapFaultDetail detail = fault.getFaultDetail(); + Assert.assertTrue("No next detail entry present", detail.getDetailEntries().hasNext()); + detail.getDetailEntries().next(); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/NonCachingPayloadTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/NonCachingPayloadTest.java index 6298855b..fa096d3f 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/NonCachingPayloadTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/NonCachingPayloadTest.java @@ -32,79 +32,79 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; @SuppressWarnings("Since15") public class NonCachingPayloadTest { - private Payload payload; + private Payload payload; - private SOAPBody body; + private SOAPBody body; - @Before - public final void setUp() { - SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory(); - body = soapFactory.createSOAPBody(); - payload = new NonCachingPayload(body, soapFactory); - } + @Before + public final void setUp() { + SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory(); + body = soapFactory.createSOAPBody(); + payload = new NonCachingPayload(body, soapFactory); + } - @Test - public void testDelegatingStreamWriter() throws Exception { - XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(payload.getResult()); + @Test + public void testDelegatingStreamWriter() throws Exception { + XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(payload.getResult()); - String namespace = "http://springframework.org/spring-ws"; - streamWriter.setDefaultNamespace(namespace); - streamWriter.writeStartElement(namespace, "root"); - streamWriter.writeDefaultNamespace(namespace); - streamWriter.writeStartElement(namespace, "child"); - streamWriter.writeCharacters("text"); - streamWriter.writeEndElement(); - streamWriter.writeEndElement(); - streamWriter.flush(); + String namespace = "http://springframework.org/spring-ws"; + streamWriter.setDefaultNamespace(namespace); + streamWriter.writeStartElement(namespace, "root"); + streamWriter.writeDefaultNamespace(namespace); + streamWriter.writeStartElement(namespace, "child"); + streamWriter.writeCharacters("text"); + streamWriter.writeEndElement(); + streamWriter.writeEndElement(); + streamWriter.flush(); - StringWriter writer = new StringWriter(); - body.serialize(writer); + StringWriter writer = new StringWriter(); + body.serialize(writer); - String expected = "" + - "" + "text" + "" - ; - assertXMLEqual(expected, writer.toString()); - } + String expected = "" + + "" + "text" + "" + ; + assertXMLEqual(expected, writer.toString()); + } - @Test - public void testDelegatingStreamWriterWriteEndDocument() throws Exception { - XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(payload.getResult()); + @Test + public void testDelegatingStreamWriterWriteEndDocument() throws Exception { + XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(payload.getResult()); - String namespace = "http://springframework.org/spring-ws"; - streamWriter.setDefaultNamespace(namespace); - streamWriter.writeStartElement(namespace, "root"); - streamWriter.writeDefaultNamespace(namespace); - streamWriter.writeStartElement(namespace, "child"); - streamWriter.writeCharacters("text"); - streamWriter.writeEndDocument(); - streamWriter.flush(); + String namespace = "http://springframework.org/spring-ws"; + streamWriter.setDefaultNamespace(namespace); + streamWriter.writeStartElement(namespace, "root"); + streamWriter.writeDefaultNamespace(namespace); + streamWriter.writeStartElement(namespace, "child"); + streamWriter.writeCharacters("text"); + streamWriter.writeEndDocument(); + streamWriter.flush(); - StringWriter writer = new StringWriter(); - body.serialize(writer); + StringWriter writer = new StringWriter(); + body.serialize(writer); - String expected = "" + - "" + "text" + "" - ; - assertXMLEqual(expected, writer.toString()); - } + String expected = "" + + "" + "text" + "" + ; + assertXMLEqual(expected, writer.toString()); + } - @Test - public void testDelegatingStreamWriterWriteEmptyElement() throws Exception { - XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(payload.getResult()); + @Test + public void testDelegatingStreamWriterWriteEmptyElement() throws Exception { + XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(payload.getResult()); - String namespace = "http://springframework.org/spring-ws"; - streamWriter.setDefaultNamespace(namespace); - streamWriter.writeStartElement(namespace, "root"); - streamWriter.writeDefaultNamespace(namespace); - streamWriter.writeEmptyElement(namespace, "child"); - streamWriter.writeEndElement(); - streamWriter.flush(); + String namespace = "http://springframework.org/spring-ws"; + streamWriter.setDefaultNamespace(namespace); + streamWriter.writeStartElement(namespace, "root"); + streamWriter.writeDefaultNamespace(namespace); + streamWriter.writeEmptyElement(namespace, "child"); + streamWriter.writeEndElement(); + streamWriter.flush(); - StringWriter writer = new StringWriter(); - body.serialize(writer); + StringWriter writer = new StringWriter(); + body.serialize(writer); - String expected = "" + - "" + "" + ""; - assertXMLEqual(expected, writer.toString()); - } + String expected = "" + + "" + "" + ""; + assertXMLEqual(expected, writer.toString()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/support/AxiomUtilsTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/support/AxiomUtilsTest.java index 8746035a..4dc28fdf 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/support/AxiomUtilsTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/axiom/support/AxiomUtilsTest.java @@ -47,101 +47,101 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class AxiomUtilsTest { - private OMElement element; + private OMElement element; - @Before - public void setUp() throws Exception { - OMFactory factory = OMAbstractFactory.getOMFactory(); - OMNamespace namespace = factory.createOMNamespace("http://www.springframework.org", "prefix"); - element = factory.createOMElement("element", namespace); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public void setUp() throws Exception { + OMFactory factory = OMAbstractFactory.getOMFactory(); + OMNamespace namespace = factory.createOMNamespace("http://www.springframework.org", "prefix"); + element = factory.createOMElement("element", namespace); + XMLUnit.setIgnoreWhitespace(true); + } - @Test - public void testToNamespaceDeclared() throws Exception { - QName qName = new QName(element.getNamespace().getNamespaceURI(), "localPart"); - OMNamespace namespace = AxiomUtils.toNamespace(qName, element); - Assert.assertNotNull("Invalid namespace", namespace); - Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); - } + @Test + public void testToNamespaceDeclared() throws Exception { + QName qName = new QName(element.getNamespace().getNamespaceURI(), "localPart"); + OMNamespace namespace = AxiomUtils.toNamespace(qName, element); + Assert.assertNotNull("Invalid namespace", namespace); + Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); + } - @Test - public void testToNamespaceUndeclared() throws Exception { - QName qName = new QName("http://www.example.com", "localPart"); - OMNamespace namespace = AxiomUtils.toNamespace(qName, element); - Assert.assertNotNull("Invalid namespace", namespace); - Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); - Assert.assertFalse("Invalid prefix", "prefix".equals(namespace.getPrefix())); - } + @Test + public void testToNamespaceUndeclared() throws Exception { + QName qName = new QName("http://www.example.com", "localPart"); + OMNamespace namespace = AxiomUtils.toNamespace(qName, element); + Assert.assertNotNull("Invalid namespace", namespace); + Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); + Assert.assertFalse("Invalid prefix", "prefix".equals(namespace.getPrefix())); + } - @Test - public void testToNamespacePrefixDeclared() throws Exception { - QName qName = new QName(element.getNamespace().getNamespaceURI(), "localPart", "prefix"); - OMNamespace namespace = AxiomUtils.toNamespace(qName, element); - Assert.assertNotNull("Invalid namespace", namespace); - Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); - Assert.assertEquals("Invalid prefix", "prefix", namespace.getPrefix()); - } + @Test + public void testToNamespacePrefixDeclared() throws Exception { + QName qName = new QName(element.getNamespace().getNamespaceURI(), "localPart", "prefix"); + OMNamespace namespace = AxiomUtils.toNamespace(qName, element); + Assert.assertNotNull("Invalid namespace", namespace); + Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); + Assert.assertEquals("Invalid prefix", "prefix", namespace.getPrefix()); + } - @Test - public void testToNamespacePrefixUndeclared() throws Exception { - QName qName = new QName("http://www.example.com", "localPart", "otherPrefix"); - OMNamespace namespace = AxiomUtils.toNamespace(qName, element); - Assert.assertNotNull("Invalid namespace", namespace); - Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); - Assert.assertEquals("Invalid prefix", qName.getPrefix(), namespace.getPrefix()); - } + @Test + public void testToNamespacePrefixUndeclared() throws Exception { + QName qName = new QName("http://www.example.com", "localPart", "otherPrefix"); + OMNamespace namespace = AxiomUtils.toNamespace(qName, element); + Assert.assertNotNull("Invalid namespace", namespace); + Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), namespace.getNamespaceURI()); + Assert.assertEquals("Invalid prefix", qName.getPrefix(), namespace.getPrefix()); + } - @Test - public void testToLanguage() throws Exception { - Assert.assertEquals("Invalid conversion", "fr-CA", AxiomUtils.toLanguage(Locale.CANADA_FRENCH)); - Assert.assertEquals("Invalid conversion", "en", AxiomUtils.toLanguage(Locale.ENGLISH)); - } + @Test + public void testToLanguage() throws Exception { + Assert.assertEquals("Invalid conversion", "fr-CA", AxiomUtils.toLanguage(Locale.CANADA_FRENCH)); + Assert.assertEquals("Invalid conversion", "en", AxiomUtils.toLanguage(Locale.ENGLISH)); + } - @Test - public void testToLocale() throws Exception { - Assert.assertEquals("Invalid conversion", Locale.CANADA_FRENCH, AxiomUtils.toLocale("fr-CA")); - Assert.assertEquals("Invalid conversion", Locale.ENGLISH, AxiomUtils.toLocale("en")); - } + @Test + public void testToLocale() throws Exception { + Assert.assertEquals("Invalid conversion", Locale.CANADA_FRENCH, AxiomUtils.toLocale("fr-CA")); + Assert.assertEquals("Invalid conversion", Locale.ENGLISH, AxiomUtils.toLocale("en")); + } - @Test - @SuppressWarnings("Since15") - public void testToDocument() throws Exception { - Resource resource = new ClassPathResource("org/springframework/ws/soap/soap11/soap11.xml"); + @Test + @SuppressWarnings("Since15") + public void testToDocument() throws Exception { + Resource resource = new ClassPathResource("org/springframework/ws/soap/soap11/soap11.xml"); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLStreamReader reader = inputFactory.createXMLStreamReader(resource.getInputStream()); - StAXSOAPModelBuilder builder = - new StAXSOAPModelBuilder(reader, OMAbstractFactory.getSOAP11Factory(), SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); - SOAPMessage soapMessage = builder.getSoapMessage(); + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader reader = inputFactory.createXMLStreamReader(resource.getInputStream()); + StAXSOAPModelBuilder builder = + new StAXSOAPModelBuilder(reader, OMAbstractFactory.getSOAP11Factory(), SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); + SOAPMessage soapMessage = builder.getSoapMessage(); - Document result = AxiomUtils.toDocument(soapMessage.getSOAPEnvelope()); + Document result = AxiomUtils.toDocument(soapMessage.getSOAPEnvelope()); - assertXMLEqual("Invalid document generated from SOAPEnvelope", expected, result); - } + assertXMLEqual("Invalid document generated from SOAPEnvelope", expected, result); + } - @Test - public void testToEnvelope() throws Exception { - Resource resource = new ClassPathResource("org/springframework/ws/soap/soap11/soap11.xml"); + @Test + public void testToEnvelope() throws Exception { + Resource resource = new ClassPathResource("org/springframework/ws/soap/soap11/soap11.xml"); - byte[] buf = FileCopyUtils.copyToByteArray(resource.getFile()); - String expected = new String(buf, "UTF-8"); + byte[] buf = FileCopyUtils.copyToByteArray(resource.getFile()); + String expected = new String(buf, "UTF-8"); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.parse(SaxUtils.createInputSource(resource)); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.parse(SaxUtils.createInputSource(resource)); - SOAPEnvelope envelope = AxiomUtils.toEnvelope(document); - StringWriter writer = new StringWriter(); - envelope.serialize(writer); - String result = writer.toString(); + SOAPEnvelope envelope = AxiomUtils.toEnvelope(document); + StringWriter writer = new StringWriter(); + envelope.serialize(writer); + String result = writer.toString(); - assertXMLEqual("Invalid SOAPEnvelope generated from document", expected, result); - } + assertXMLEqual("Invalid SOAPEnvelope generated from document", expected, result); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11BodyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11BodyTest.java index 9b1eb70e..39fa04a7 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11BodyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11BodyTest.java @@ -32,30 +32,30 @@ import static org.junit.Assert.assertNull; public class SaajSoap11BodyTest extends AbstractSoap11BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); - return new SaajSoap11Body(saajMessage.getSOAPPart().getEnvelope().getBody(), true); - } + @Override + protected SoapBody createSoapBody() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); + return new SaajSoap11Body(saajMessage.getSOAPPart().getEnvelope().getBody(), true); + } - @Test - public void testLangAttributeOnSoap11FaultString() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); + @Test + public void testLangAttributeOnSoap11FaultString() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); - SOAPBody saajSoapBody = saajMessage.getSOAPPart().getEnvelope().getBody(); - SaajSoap11Body soapBody = new SaajSoap11Body(saajSoapBody, true); + SOAPBody saajSoapBody = saajMessage.getSOAPPart().getEnvelope().getBody(); + SaajSoap11Body soapBody = new SaajSoap11Body(saajSoapBody, true); - soapBody.addClientOrSenderFault("Foo", Locale.ENGLISH); - assertNotNull("No Language set", saajSoapBody.getFault().getFaultStringLocale()); + soapBody.addClientOrSenderFault("Foo", Locale.ENGLISH); + assertNotNull("No Language set", saajSoapBody.getFault().getFaultStringLocale()); - saajSoapBody = saajMessage.getSOAPPart().getEnvelope().getBody(); - soapBody = new SaajSoap11Body(saajSoapBody, false); + saajSoapBody = saajMessage.getSOAPPart().getEnvelope().getBody(); + soapBody = new SaajSoap11Body(saajSoapBody, false); - soapBody.addClientOrSenderFault("Foo", Locale.ENGLISH); - assertNull("Language set", saajSoapBody.getFault().getFaultStringLocale()); - } + soapBody.addClientOrSenderFault("Foo", Locale.ENGLISH); + assertNull("Language set", saajSoapBody.getFault().getFaultStringLocale()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11EnvelopeTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11EnvelopeTest.java index 1a6963e2..acb9dad3 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11EnvelopeTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11EnvelopeTest.java @@ -25,10 +25,10 @@ import org.springframework.ws.soap.soap11.AbstractSoap11EnvelopeTestCase; public class SaajSoap11EnvelopeTest extends AbstractSoap11EnvelopeTestCase { - @Override - protected SoapEnvelope createSoapEnvelope() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); - return new SaajSoapEnvelope(saajMessage.getSOAPPart().getEnvelope(), true); - } + @Override + protected SoapEnvelope createSoapEnvelope() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); + return new SaajSoapEnvelope(saajMessage.getSOAPPart().getEnvelope(), true); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11HeaderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11HeaderTest.java index 2d878373..8be7399f 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11HeaderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11HeaderTest.java @@ -25,10 +25,10 @@ import org.springframework.ws.soap.soap11.AbstractSoap11HeaderTestCase; public class SaajSoap11HeaderTest extends AbstractSoap11HeaderTestCase { - @Override - protected SoapHeader createSoapHeader() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); - return new SaajSoap11Header(saajMessage.getSOAPPart().getEnvelope().getHeader()); - } + @Override + protected SoapHeader createSoapHeader() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); + return new SaajSoap11Header(saajMessage.getSOAPPart().getEnvelope().getHeader()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11MessageFactoryTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11MessageFactoryTest.java index 788abd38..88ece505 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11MessageFactoryTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap11MessageFactoryTest.java @@ -34,22 +34,22 @@ import static org.junit.Assert.assertTrue; public class SaajSoap11MessageFactoryTest extends AbstractSoap11MessageFactoryTestCase { - @Override - protected WebServiceMessageFactory createMessageFactory() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - return new SaajSoapMessageFactory(messageFactory); - } + @Override + protected WebServiceMessageFactory createMessageFactory() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + return new SaajSoapMessageFactory(messageFactory); + } - @Test - public void properties() throws IOException { - Map properties = Collections.singletonMap(SOAPMessage.WRITE_XML_DECLARATION, "true"); - ((SaajSoapMessageFactory)messageFactory).setMessageProperties(properties); - SoapMessage soapMessage = (SoapMessage) messageFactory.createWebServiceMessage(); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - soapMessage.writeTo(os); - String result = os.toString("UTF-8"); - assertTrue("XML declaration not written", result.startsWith(" properties = Collections.singletonMap(SOAPMessage.WRITE_XML_DECLARATION, "true"); + ((SaajSoapMessageFactory)messageFactory).setMessageProperties(properties); + SoapMessage soapMessage = (SoapMessage) messageFactory.createWebServiceMessage(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + soapMessage.writeTo(os); + String result = os.toString("UTF-8"); + assertTrue("XML declaration not written", result.startsWith("", result.toString()); - } + @Test + public void testGetPayloadSource() throws Exception { + saajMessage.getSOAPPart().getEnvelope().getBody().addChildElement("child"); + Source source = soapMessage.getPayloadSource(); + StringResult result = new StringResult(); + transformer.transform(source, result); + assertXMLEqual("Invalid source", "", result.toString()); + } - @Test - public void testGetPayloadSourceText() throws Exception { - SOAPBody body = saajMessage.getSOAPPart().getEnvelope().getBody(); - body.addTextNode(" "); - body.addChildElement("child"); - Source source = soapMessage.getPayloadSource(); - StringResult result = new StringResult(); - transformer.transform(source, result); - assertXMLEqual("Invalid source", "", result.toString()); - } + @Test + public void testGetPayloadSourceText() throws Exception { + SOAPBody body = saajMessage.getSOAPPart().getEnvelope().getBody(); + body.addTextNode(" "); + body.addChildElement("child"); + Source source = soapMessage.getPayloadSource(); + StringResult result = new StringResult(); + transformer.transform(source, result); + assertXMLEqual("Invalid source", "", result.toString()); + } - @Test - public void testGetPayloadResult() throws Exception { - StringSource source = new StringSource(""); - Result result = soapMessage.getPayloadResult(); - transformer.transform(source, result); - SOAPBody body = saajMessage.getSOAPPart().getEnvelope().getBody(); - Iterator iterator = body.getChildElements(); - assertTrue("No child nodes created", iterator.hasNext()); - SOAPBodyElement bodyElement = (SOAPBodyElement) iterator.next(); - assertEquals("Invalid child node created", "child", bodyElement.getElementName().getLocalName()); - } + @Test + public void testGetPayloadResult() throws Exception { + StringSource source = new StringSource(""); + Result result = soapMessage.getPayloadResult(); + transformer.transform(source, result); + SOAPBody body = saajMessage.getSOAPPart().getEnvelope().getBody(); + Iterator iterator = body.getChildElements(); + assertTrue("No child nodes created", iterator.hasNext()); + SOAPBodyElement bodyElement = (SOAPBodyElement) iterator.next(); + assertEquals("Invalid child node created", "child", bodyElement.getElementName().getLocalName()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12BodyTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12BodyTest.java index 756d5461..47bd68bd 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12BodyTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12BodyTest.java @@ -25,11 +25,11 @@ import org.springframework.ws.soap.soap12.AbstractSoap12BodyTestCase; public class SaajSoap12BodyTest extends AbstractSoap12BodyTestCase { - @Override - protected SoapBody createSoapBody() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); - return new SaajSoap12Body(saajMessage.getSOAPBody()); - } + @Override + protected SoapBody createSoapBody() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); + return new SaajSoap12Body(saajMessage.getSOAPBody()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12EnvelopeTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12EnvelopeTest.java index 30ad81be..88c9a5e9 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12EnvelopeTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12EnvelopeTest.java @@ -25,10 +25,10 @@ import org.springframework.ws.soap.soap12.AbstractSoap12EnvelopeTestCase; public class SaajSoap12EnvelopeTest extends AbstractSoap12EnvelopeTestCase { - @Override - protected SoapEnvelope createSoapEnvelope() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); - return new SaajSoapEnvelope(saajMessage.getSOAPPart().getEnvelope(), true); - } + @Override + protected SoapEnvelope createSoapEnvelope() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); + return new SaajSoapEnvelope(saajMessage.getSOAPPart().getEnvelope(), true); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12HeaderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12HeaderTest.java index 3e5bf7ec..36751b1b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12HeaderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12HeaderTest.java @@ -25,10 +25,10 @@ import org.springframework.ws.soap.soap12.AbstractSoap12HeaderTestCase; public class SaajSoap12HeaderTest extends AbstractSoap12HeaderTestCase { - @Override - protected SoapHeader createSoapHeader() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage saajMessage = messageFactory.createMessage(); - return new SaajSoap12Header(saajMessage.getSOAPHeader()); - } + @Override + protected SoapHeader createSoapHeader() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage saajMessage = messageFactory.createMessage(); + return new SaajSoap12Header(saajMessage.getSOAPHeader()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageFactoryTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageFactoryTest.java index 21b97ac6..8a957f15 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageFactoryTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageFactoryTest.java @@ -24,9 +24,9 @@ import org.springframework.ws.soap.soap12.AbstractSoap12MessageFactoryTestCase; public class SaajSoap12MessageFactoryTest extends AbstractSoap12MessageFactoryTestCase { - @Override - protected WebServiceMessageFactory createMessageFactory() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - return new SaajSoapMessageFactory(messageFactory); - } + @Override + protected WebServiceMessageFactory createMessageFactory() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + return new SaajSoapMessageFactory(messageFactory); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageTest.java index 8e17051c..4e778ad4 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/SaajSoap12MessageTest.java @@ -33,39 +33,39 @@ import static org.junit.Assert.assertTrue; public class SaajSoap12MessageTest extends AbstractSoap12MessageTestCase { - private SOAPMessage saajMessage; + private SOAPMessage saajMessage; - @Override - protected SoapMessage createSoapMessage() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - saajMessage = messageFactory.createMessage(); - saajMessage.getSOAPHeader().detachNode(); - return new SaajSoapMessage(saajMessage, true, messageFactory); - } + @Override + protected SoapMessage createSoapMessage() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + saajMessage = messageFactory.createMessage(); + saajMessage.getSOAPHeader().detachNode(); + return new SaajSoapMessage(saajMessage, true, messageFactory); + } - public void testGetPayloadSource() throws Exception { - saajMessage.getSOAPBody().addChildElement("child"); - Source source = soapMessage.getPayloadSource(); - StringResult result = new StringResult(); - transformer.transform(source, result); - assertXMLEqual("Invalid source", "", result.toString()); - } + public void testGetPayloadSource() throws Exception { + saajMessage.getSOAPBody().addChildElement("child"); + Source source = soapMessage.getPayloadSource(); + StringResult result = new StringResult(); + transformer.transform(source, result); + assertXMLEqual("Invalid source", "", result.toString()); + } - public void testGetPayloadSourceText() throws Exception { - saajMessage.getSOAPBody().addTextNode(" "); - saajMessage.getSOAPBody().addChildElement("child"); - Source source = soapMessage.getPayloadSource(); - StringResult result = new StringResult(); - transformer.transform(source, result); - assertXMLEqual("Invalid source", "", result.toString()); - } + public void testGetPayloadSourceText() throws Exception { + saajMessage.getSOAPBody().addTextNode(" "); + saajMessage.getSOAPBody().addChildElement("child"); + Source source = soapMessage.getPayloadSource(); + StringResult result = new StringResult(); + transformer.transform(source, result); + assertXMLEqual("Invalid source", "", result.toString()); + } - public void testGetPayloadResult() throws Exception { - StringSource source = new StringSource(""); - Result result = soapMessage.getPayloadResult(); - transformer.transform(source, result); - assertTrue("No child nodes created", saajMessage.getSOAPBody().hasChildNodes()); - assertEquals("Invalid child node created", "child", saajMessage.getSOAPBody().getFirstChild().getLocalName()); - } + public void testGetPayloadResult() throws Exception { + StringSource source = new StringSource(""); + Result result = soapMessage.getPayloadResult(); + transformer.transform(source, result); + assertTrue("No child nodes created", saajMessage.getSOAPBody().hasChildNodes()); + assertEquals("Invalid child node created", "child", saajMessage.getSOAPBody().getFirstChild().getLocalName()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajContentHandlerTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajContentHandlerTest.java index 8a0a9f55..17cc157c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajContentHandlerTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajContentHandlerTest.java @@ -37,39 +37,39 @@ import org.junit.Test; public class SaajContentHandlerTest { - private SaajContentHandler handler; + private SaajContentHandler handler; - private Transformer transformer; + private Transformer transformer; - private SOAPEnvelope envelope; + private SOAPEnvelope envelope; - @Before - public void setUp() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage message = messageFactory.createMessage(); - envelope = message.getSOAPPart().getEnvelope(); - handler = new SaajContentHandler(envelope.getBody()); - transformer = TransformerFactory.newInstance().newTransformer(); - } + @Before + public void setUp() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage message = messageFactory.createMessage(); + envelope = message.getSOAPPart().getEnvelope(); + handler = new SaajContentHandler(envelope.getBody()); + transformer = TransformerFactory.newInstance().newTransformer(); + } - @Test - public void testHandler() throws Exception { - String content = "" + - "Content"; - Source source = new StringSource(content); - Result result = new SAXResult(handler); - transformer.transform(source, result); - Name rootName = envelope.createName("Root", "", "http://springframework.org/spring-ws/1"); - Iterator iterator = envelope.getBody().getChildElements(rootName); - Assert.assertTrue("No child found", iterator.hasNext()); - SOAPBodyElement rootElement = (SOAPBodyElement) iterator.next(); - Name childName = envelope.createName("Child", "child", "http://springframework.org/spring-ws/2"); - iterator = rootElement.getChildElements(childName); - Assert.assertTrue("No child found", iterator.hasNext()); - SOAPElement childElement = (SOAPElement) iterator.next(); - Assert.assertEquals("Invalid contents", "Content", childElement.getValue()); - Name attributeName = envelope.createName("attribute"); - Assert.assertEquals("Invalid attribute value", "value", childElement.getAttributeValue(attributeName)); - } + @Test + public void testHandler() throws Exception { + String content = "" + + "Content"; + Source source = new StringSource(content); + Result result = new SAXResult(handler); + transformer.transform(source, result); + Name rootName = envelope.createName("Root", "", "http://springframework.org/spring-ws/1"); + Iterator iterator = envelope.getBody().getChildElements(rootName); + Assert.assertTrue("No child found", iterator.hasNext()); + SOAPBodyElement rootElement = (SOAPBodyElement) iterator.next(); + Name childName = envelope.createName("Child", "child", "http://springframework.org/spring-ws/2"); + iterator = rootElement.getChildElements(childName); + Assert.assertTrue("No child found", iterator.hasNext()); + SOAPElement childElement = (SOAPElement) iterator.next(); + Assert.assertEquals("Invalid contents", "Content", childElement.getValue()); + Name attributeName = envelope.createName("attribute"); + Assert.assertEquals("Invalid attribute value", "value", childElement.getAttributeValue(attributeName)); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajUtilsTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajUtilsTest.java index cdb0c5b6..998bd13b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajUtilsTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajUtilsTest.java @@ -40,106 +40,106 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class SaajUtilsTest { - private MessageFactory messageFactory; + private MessageFactory messageFactory; - @Before - public void setUp() throws Exception { - messageFactory = MessageFactory.newInstance(); - } + @Before + public void setUp() throws Exception { + messageFactory = MessageFactory.newInstance(); + } - @Test - public void testToName() throws Exception { - SOAPMessage message = messageFactory.createMessage(); - QName qName = new QName("localPart"); - SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); - Name name = SaajUtils.toName(qName, envelope); - Assert.assertNotNull("Invalid name", name); - Assert.assertEquals("Invalid local part", qName.getLocalPart(), name.getLocalName()); - Assert.assertFalse("Invalid prefix", StringUtils.hasLength(name.getPrefix())); - Assert.assertFalse("Invalid namespace", StringUtils.hasLength(name.getURI())); - } + @Test + public void testToName() throws Exception { + SOAPMessage message = messageFactory.createMessage(); + QName qName = new QName("localPart"); + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + Name name = SaajUtils.toName(qName, envelope); + Assert.assertNotNull("Invalid name", name); + Assert.assertEquals("Invalid local part", qName.getLocalPart(), name.getLocalName()); + Assert.assertFalse("Invalid prefix", StringUtils.hasLength(name.getPrefix())); + Assert.assertFalse("Invalid namespace", StringUtils.hasLength(name.getURI())); + } - @Test - public void testToNameNamespace() throws Exception { - SOAPMessage message = messageFactory.createMessage(); - QName qName = new QName("namespace", "localPart"); - SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); - envelope.addNamespaceDeclaration("prefix", "namespace"); - Name name = SaajUtils.toName(qName, envelope); - Assert.assertNotNull("Invalid name", name); - Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), name.getURI()); - Assert.assertEquals("Invalid local part", qName.getLocalPart(), name.getLocalName()); - Assert.assertEquals("Invalid prefix", "prefix", name.getPrefix()); - } + @Test + public void testToNameNamespace() throws Exception { + SOAPMessage message = messageFactory.createMessage(); + QName qName = new QName("namespace", "localPart"); + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + envelope.addNamespaceDeclaration("prefix", "namespace"); + Name name = SaajUtils.toName(qName, envelope); + Assert.assertNotNull("Invalid name", name); + Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), name.getURI()); + Assert.assertEquals("Invalid local part", qName.getLocalPart(), name.getLocalName()); + Assert.assertEquals("Invalid prefix", "prefix", name.getPrefix()); + } - @Test - public void testToNameNamespacePrefix() throws Exception { - SOAPMessage message = messageFactory.createMessage(); - QName qName = new QName("namespace", "localPart", "prefix"); - SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); - Name name = SaajUtils.toName(qName, envelope); - Assert.assertNotNull("Invalid name", name); - Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), name.getURI()); - Assert.assertEquals("Invalid local part", qName.getLocalPart(), name.getLocalName()); - Assert.assertEquals("Invalid prefix", qName.getPrefix(), name.getPrefix()); - } + @Test + public void testToNameNamespacePrefix() throws Exception { + SOAPMessage message = messageFactory.createMessage(); + QName qName = new QName("namespace", "localPart", "prefix"); + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + Name name = SaajUtils.toName(qName, envelope); + Assert.assertNotNull("Invalid name", name); + Assert.assertEquals("Invalid namespace", qName.getNamespaceURI(), name.getURI()); + Assert.assertEquals("Invalid local part", qName.getLocalPart(), name.getLocalName()); + Assert.assertEquals("Invalid prefix", qName.getPrefix(), name.getPrefix()); + } - @Test - public void testToQName() throws Exception { - SOAPMessage message = messageFactory.createMessage(); - Name name = message.getSOAPPart().getEnvelope().createName("localPart", null, null); - QName qName = SaajUtils.toQName(name); - Assert.assertNotNull("Invalid qName", qName); - Assert.assertEquals("Invalid namespace", name.getURI(), qName.getNamespaceURI()); - Assert.assertFalse("Invalid prefix", StringUtils.hasLength(qName.getPrefix())); - Assert.assertFalse("Invalid namespace", StringUtils.hasLength(qName.getNamespaceURI())); - } + @Test + public void testToQName() throws Exception { + SOAPMessage message = messageFactory.createMessage(); + Name name = message.getSOAPPart().getEnvelope().createName("localPart", null, null); + QName qName = SaajUtils.toQName(name); + Assert.assertNotNull("Invalid qName", qName); + Assert.assertEquals("Invalid namespace", name.getURI(), qName.getNamespaceURI()); + Assert.assertFalse("Invalid prefix", StringUtils.hasLength(qName.getPrefix())); + Assert.assertFalse("Invalid namespace", StringUtils.hasLength(qName.getNamespaceURI())); + } - @Test - public void testToQNameNamespace() throws Exception { - SOAPMessage message = messageFactory.createMessage(); - Name name = message.getSOAPPart().getEnvelope().createName("localPart", null, "namespace"); - QName qName = SaajUtils.toQName(name); - Assert.assertNotNull("Invalid qName", qName); - Assert.assertEquals("Invalid namespace", name.getURI(), qName.getNamespaceURI()); - Assert.assertEquals("Invalid local part", name.getLocalName(), qName.getLocalPart()); - Assert.assertFalse("Invalid prefix", StringUtils.hasLength(qName.getPrefix())); - } + @Test + public void testToQNameNamespace() throws Exception { + SOAPMessage message = messageFactory.createMessage(); + Name name = message.getSOAPPart().getEnvelope().createName("localPart", null, "namespace"); + QName qName = SaajUtils.toQName(name); + Assert.assertNotNull("Invalid qName", qName); + Assert.assertEquals("Invalid namespace", name.getURI(), qName.getNamespaceURI()); + Assert.assertEquals("Invalid local part", name.getLocalName(), qName.getLocalPart()); + Assert.assertFalse("Invalid prefix", StringUtils.hasLength(qName.getPrefix())); + } - @Test - public void testToQNamePrefixNamespace() throws Exception { - SOAPMessage message = messageFactory.createMessage(); - Name name = message.getSOAPPart().getEnvelope().createName("localPart", "prefix", "namespace"); - QName qName = SaajUtils.toQName(name); - Assert.assertNotNull("Invalid qName", qName); - Assert.assertEquals("Invalid namespace", name.getURI(), qName.getNamespaceURI()); - Assert.assertEquals("Invalid local part", name.getLocalName(), qName.getLocalPart()); - Assert.assertEquals("Invalid prefix", name.getPrefix(), qName.getPrefix()); - } + @Test + public void testToQNamePrefixNamespace() throws Exception { + SOAPMessage message = messageFactory.createMessage(); + Name name = message.getSOAPPart().getEnvelope().createName("localPart", "prefix", "namespace"); + QName qName = SaajUtils.toQName(name); + Assert.assertNotNull("Invalid qName", qName); + Assert.assertEquals("Invalid namespace", name.getURI(), qName.getNamespaceURI()); + Assert.assertEquals("Invalid local part", name.getLocalName(), qName.getLocalPart()); + Assert.assertEquals("Invalid prefix", name.getPrefix(), qName.getPrefix()); + } - @Test - public void testLoadMessage() throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(getClass().getResourceAsStream("soapMessage.xml")); - SOAPMessage soapMessage = - SaajUtils.loadMessage(new ClassPathResource("soapMessage.xml", getClass()), messageFactory); - assertXMLEqual(soapMessage.getSOAPPart(), document); - } + @Test + public void testLoadMessage() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(getClass().getResourceAsStream("soapMessage.xml")); + SOAPMessage soapMessage = + SaajUtils.loadMessage(new ClassPathResource("soapMessage.xml", getClass()), messageFactory); + assertXMLEqual(soapMessage.getSOAPPart(), document); + } - @Test - public void testGetSaajVersion() throws Exception { - Assert.assertEquals("Invalid SAAJ version", SaajUtils.SAAJ_13, SaajUtils.getSaajVersion()); - } + @Test + public void testGetSaajVersion() throws Exception { + Assert.assertEquals("Invalid SAAJ version", SaajUtils.SAAJ_13, SaajUtils.getSaajVersion()); + } - @Test(expected = SOAPException.class) - public void testGetSaajVersionInvalidEnvelope() throws Exception { - Resource resource = new ClassPathResource("invalidNamespaceReferenceSoapMessage.xml", getClass()); - InputStream in = resource.getInputStream(); - MimeHeaders headers = new MimeHeaders(); - SOAPMessage soapMessage = messageFactory.createMessage(headers, in); - SaajUtils.getSaajVersion(soapMessage); - } + @Test(expected = SOAPException.class) + public void testGetSaajVersionInvalidEnvelope() throws Exception { + Resource resource = new ClassPathResource("invalidNamespaceReferenceSoapMessage.xml", getClass()); + InputStream in = resource.getInputStream(); + MimeHeaders headers = new MimeHeaders(); + SOAPMessage soapMessage = messageFactory.createMessage(headers, in); + SaajUtils.getSaajVersion(soapMessage); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajXmlReaderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajXmlReaderTest.java index fd78ead1..63991ffd 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajXmlReaderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/saaj/support/SaajXmlReaderTest.java @@ -35,42 +35,42 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class SaajXmlReaderTest { - private SaajXmlReader saajReader; + private SaajXmlReader saajReader; - private SOAPMessage message; + private SOAPMessage message; - private Transformer transformer; + private Transformer transformer; - @Before - public void setUp() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - message = messageFactory.createMessage(); - SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); - saajReader = new SaajXmlReader(envelope); - transformer = TransformerFactory.newInstance().newTransformer(); - } + @Before + public void setUp() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(); + message = messageFactory.createMessage(); + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + saajReader = new SaajXmlReader(envelope); + transformer = TransformerFactory.newInstance().newTransformer(); + } - @Test - public void testNamespacesPrefixes() throws Exception { - saajReader.setFeature("http://xml.org/sax/features/namespaces", true); - saajReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); - DOMResult result = new DOMResult(); - Source source = new SAXSource(saajReader, new InputSource()); - transformer.transform(source, result); - DOMResult expected = new DOMResult(); - transformer.transform(new DOMSource(message.getSOAPPart().getEnvelope()), expected); - assertXMLEqual((Document) expected.getNode(), (Document) result.getNode()); - } + @Test + public void testNamespacesPrefixes() throws Exception { + saajReader.setFeature("http://xml.org/sax/features/namespaces", true); + saajReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + DOMResult result = new DOMResult(); + Source source = new SAXSource(saajReader, new InputSource()); + transformer.transform(source, result); + DOMResult expected = new DOMResult(); + transformer.transform(new DOMSource(message.getSOAPPart().getEnvelope()), expected); + assertXMLEqual((Document) expected.getNode(), (Document) result.getNode()); + } - @Test - public void testNamespacesNoPrefixes() throws Exception { - saajReader.setFeature("http://xml.org/sax/features/namespaces", true); - saajReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); - DOMResult result = new DOMResult(); - Source source = new SAXSource(saajReader, new InputSource()); - transformer.transform(source, result); - DOMResult expected = new DOMResult(); - transformer.transform(new DOMSource(message.getSOAPPart().getEnvelope()), expected); - assertXMLEqual((Document) expected.getNode(), (Document) result.getNode()); - } + @Test + public void testNamespacesNoPrefixes() throws Exception { + saajReader.setFeature("http://xml.org/sax/features/namespaces", true); + saajReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); + DOMResult result = new DOMResult(); + Source source = new SAXSource(saajReader, new InputSource()); + transformer.transform(source, result); + DOMResult expected = new DOMResult(); + transformer.transform(new DOMSource(message.getSOAPPart().getEnvelope()), expected); + assertXMLEqual((Document) expected.getNode(), (Document) result.getNode()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/SoapMessageDispatcherTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/SoapMessageDispatcherTest.java index 7f971abf..6003566c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/SoapMessageDispatcherTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/SoapMessageDispatcherTest.java @@ -44,214 +44,214 @@ import static org.easymock.EasyMock.*; public class SoapMessageDispatcherTest { - private SoapMessageDispatcher dispatcher; + private SoapMessageDispatcher dispatcher; - private SoapEndpointInterceptor interceptorMock; + private SoapEndpointInterceptor interceptorMock; - @Before - public void setUp() throws Exception { - interceptorMock = createMock(SoapEndpointInterceptor.class); - dispatcher = new SoapMessageDispatcher(); - } + @Before + public void setUp() throws Exception { + interceptorMock = createMock(SoapEndpointInterceptor.class); + dispatcher = new SoapMessageDispatcher(); + } - @Test - public void testProcessMustUnderstandHeadersUnderstoodSoap11() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = - request.getSOAPHeader().addHeaderElement(new QName("http://www.springframework.org", "Header")); - header.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); - header.setMustUnderstand(true); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); + @Test + public void testProcessMustUnderstandHeadersUnderstoodSoap11() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = + request.getSOAPHeader().addHeaderElement(new QName("http://www.springframework.org", "Header")); + header.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); + header.setMustUnderstand(true); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); - replay(interceptorMock); + replay(interceptorMock); - SoapEndpointInvocationChain chain = - new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); + SoapEndpointInvocationChain chain = + new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertTrue("Header not understood", result); + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertTrue("Header not understood", result); - verify(interceptorMock); - } + verify(interceptorMock); + } - @Test - public void testProcessMustUnderstandHeadersUnderstoodSoap12() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = - request.getSOAPHeader().addHeaderElement(new QName("http://www.springframework.org", "Header")); - header.setMustUnderstand(true); - header.setRole(SOAPConstants.URI_SOAP_1_2_ROLE_NEXT); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); + @Test + public void testProcessMustUnderstandHeadersUnderstoodSoap12() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = + request.getSOAPHeader().addHeaderElement(new QName("http://www.springframework.org", "Header")); + header.setMustUnderstand(true); + header.setRole(SOAPConstants.URI_SOAP_1_2_ROLE_NEXT); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); - replay(interceptorMock); + replay(interceptorMock); - SoapEndpointInvocationChain chain = - new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); + SoapEndpointInvocationChain chain = + new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertTrue("Header not understood", result); + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertTrue("Header not understood", result); - verify(interceptorMock); - } + verify(interceptorMock); + } - @Test - public void testProcessMustUnderstandHeadersNotUnderstoodSoap11() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = request.getSOAPHeader() - .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); - header.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); - header.setMustUnderstand(true); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(false); + @Test + public void testProcessMustUnderstandHeadersNotUnderstoodSoap11() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = request.getSOAPHeader() + .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); + header.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); + header.setMustUnderstand(true); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(false); - replay(interceptorMock); + replay(interceptorMock); - SoapEndpointInvocationChain chain = - new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); + SoapEndpointInvocationChain chain = + new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertFalse("Header understood", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapBody responseBody = ((SoapMessage) context.getResponse()).getSoapBody(); - Assert.assertTrue("Response body has no fault", responseBody.hasFault()); - Soap11Fault fault = (Soap11Fault) responseBody.getFault(); - Assert.assertEquals("Invalid fault code", new QName(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "MustUnderstand"), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string", SoapMessageDispatcher.DEFAULT_MUST_UNDERSTAND_FAULT_STRING, - fault.getFaultStringOrReason()); - Assert.assertEquals("Invalid fault string locale", Locale.ENGLISH, fault.getFaultStringLocale()); + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertFalse("Header understood", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapBody responseBody = ((SoapMessage) context.getResponse()).getSoapBody(); + Assert.assertTrue("Response body has no fault", responseBody.hasFault()); + Soap11Fault fault = (Soap11Fault) responseBody.getFault(); + Assert.assertEquals("Invalid fault code", new QName(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "MustUnderstand"), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string", SoapMessageDispatcher.DEFAULT_MUST_UNDERSTAND_FAULT_STRING, + fault.getFaultStringOrReason()); + Assert.assertEquals("Invalid fault string locale", Locale.ENGLISH, fault.getFaultStringLocale()); - verify(interceptorMock); - } + verify(interceptorMock); + } - @Test - public void testProcessMustUnderstandHeadersNotUnderstoodSoap12() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = request.getSOAPHeader() - .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); - header.setMustUnderstand(true); - header.setRole(SOAPConstants.URI_SOAP_1_2_ROLE_NEXT); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(false); + @Test + public void testProcessMustUnderstandHeadersNotUnderstoodSoap12() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = request.getSOAPHeader() + .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); + header.setMustUnderstand(true); + header.setRole(SOAPConstants.URI_SOAP_1_2_ROLE_NEXT); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(false); - replay(interceptorMock); + replay(interceptorMock); - SoapEndpointInvocationChain chain = - new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); + SoapEndpointInvocationChain chain = + new SoapEndpointInvocationChain(new Object(), new SoapEndpointInterceptor[]{interceptorMock}); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertFalse("Header understood", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - SoapBody responseBody = response.getSoapBody(); - Assert.assertTrue("Response body has no fault", responseBody.hasFault()); - Soap12Fault fault = (Soap12Fault) responseBody.getFault(); - Assert.assertEquals("Invalid fault code", new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "MustUnderstand"), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string", SoapMessageDispatcher.DEFAULT_MUST_UNDERSTAND_FAULT_STRING, - fault.getFaultReasonText(Locale.ENGLISH)); - SoapHeader responseHeader = response.getSoapHeader(); - Iterator iterator = responseHeader.examineAllHeaderElements(); - Assert.assertTrue("Response header has no elements", iterator.hasNext()); - SoapHeaderElement headerElement = iterator.next(); - Assert.assertEquals("No NotUnderstood header", - new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "NotUnderstood"), headerElement.getName()); + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertFalse("Header understood", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + SoapBody responseBody = response.getSoapBody(); + Assert.assertTrue("Response body has no fault", responseBody.hasFault()); + Soap12Fault fault = (Soap12Fault) responseBody.getFault(); + Assert.assertEquals("Invalid fault code", new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "MustUnderstand"), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string", SoapMessageDispatcher.DEFAULT_MUST_UNDERSTAND_FAULT_STRING, + fault.getFaultReasonText(Locale.ENGLISH)); + SoapHeader responseHeader = response.getSoapHeader(); + Iterator iterator = responseHeader.examineAllHeaderElements(); + Assert.assertTrue("Response header has no elements", iterator.hasNext()); + SoapHeaderElement headerElement = iterator.next(); + Assert.assertEquals("No NotUnderstood header", + new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "NotUnderstood"), headerElement.getName()); - verify(interceptorMock); - } + verify(interceptorMock); + } - @Test - public void testProcessMustUnderstandHeadersForActorSoap11() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = request.getSOAPHeader() - .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); - String headerActor = "http://www/springframework.org/role"; - header.setActor(headerActor); - header.setMustUnderstand(true); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); + @Test + public void testProcessMustUnderstandHeadersForActorSoap11() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = request.getSOAPHeader() + .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); + String headerActor = "http://www/springframework.org/role"; + header.setActor(headerActor); + header.setMustUnderstand(true); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); - replay(interceptorMock); + replay(interceptorMock); - SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), - new SoapEndpointInterceptor[]{interceptorMock}, new String[]{headerActor}, true); + SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), + new SoapEndpointInterceptor[]{interceptorMock}, new String[]{headerActor}, true); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertTrue("actor-specific header not understood", result); + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertTrue("actor-specific header not understood", result); - verify(interceptorMock); - } + verify(interceptorMock); + } - @Test - public void testProcessMustUnderstandHeadersForRoleSoap12() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = request.getSOAPHeader() - .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); - String headerRole = "http://www/springframework.org/role"; - header.setRole(headerRole); - header.setMustUnderstand(true); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); + @Test + public void testProcessMustUnderstandHeadersForRoleSoap12() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = request.getSOAPHeader() + .addHeaderElement(new QName("http://www.springframework.org", "Header", "spring-ws")); + String headerRole = "http://www/springframework.org/role"; + header.setRole(headerRole); + header.setMustUnderstand(true); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + expect(interceptorMock.understands(isA(SoapHeaderElement.class))).andReturn(true); - replay(interceptorMock); + replay(interceptorMock); - SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), - new SoapEndpointInterceptor[]{interceptorMock}, new String[]{headerRole}, true); + SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), + new SoapEndpointInterceptor[]{interceptorMock}, new String[]{headerRole}, true); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertTrue("role-specific header not understood", result); + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertTrue("role-specific header not understood", result); - verify(interceptorMock); - } + verify(interceptorMock); + } - @Test - public void testProcessNoHeader() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - request.getSOAPHeader().detachNode(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - replay(interceptorMock); + @Test + public void testProcessNoHeader() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + request.getSOAPHeader().detachNode(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + replay(interceptorMock); - SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), - new SoapEndpointInterceptor[]{interceptorMock}, new String[]{"role"}, true); + SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), + new SoapEndpointInterceptor[]{interceptorMock}, new String[]{"role"}, true); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertTrue("Invalid result", result); - verify(interceptorMock); - } + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertTrue("Invalid result", result); + verify(interceptorMock); + } - @Test - public void testProcessMustUnderstandHeadersNoInterceptors() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage request = messageFactory.createMessage(); - SOAPHeaderElement header = - request.getSOAPHeader().addHeaderElement(new QName("http://www.springframework.org", "Header")); - header.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); - header.setMustUnderstand(true); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); - replay(interceptorMock); + @Test + public void testProcessMustUnderstandHeadersNoInterceptors() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage request = messageFactory.createMessage(); + SOAPHeaderElement header = + request.getSOAPHeader().addHeaderElement(new QName("http://www.springframework.org", "Header")); + header.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); + header.setMustUnderstand(true); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(request), factory); + replay(interceptorMock); - SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), null); + SoapEndpointInvocationChain chain = new SoapEndpointInvocationChain(new Object(), null); - boolean result = dispatcher.handleRequest(chain, context); - Assert.assertFalse("Header understood", result); - verify(interceptorMock); - } + boolean result = dispatcher.handleRequest(chain, context); + Assert.assertFalse("Header understood", result); + verify(interceptorMock); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/FaultCreatingValidatingMarshallingPayloadEndpointTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/FaultCreatingValidatingMarshallingPayloadEndpointTest.java index 728d475b..a190d6db 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/FaultCreatingValidatingMarshallingPayloadEndpointTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/FaultCreatingValidatingMarshallingPayloadEndpointTest.java @@ -45,160 +45,160 @@ import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; public class FaultCreatingValidatingMarshallingPayloadEndpointTest { - private MessageContext messageContext; + private MessageContext messageContext; - private ResourceBundleMessageSource messageSource; + private ResourceBundleMessageSource messageSource; - @Before - public void setUp() throws Exception { - this.messageSource = new ResourceBundleMessageSource(); - this.messageSource.setBasename("org.springframework.ws.soap.server.endpoint.messages"); - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage request = messageFactory.createMessage(); - request.getSOAPBody().addBodyElement(new QName("http://www.springframework.org/spring-ws", "request")); - messageContext = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - } + @Before + public void setUp() throws Exception { + this.messageSource = new ResourceBundleMessageSource(); + this.messageSource.setBasename("org.springframework.ws.soap.server.endpoint.messages"); + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage request = messageFactory.createMessage(); + request.getSOAPBody().addBodyElement(new QName("http://www.springframework.org/spring-ws", "request")); + messageContext = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + } - @Test - public void testValidationIncorrect() throws Exception { - Person p = new Person("", -1); - PersonMarshaller marshaller = new PersonMarshaller(p); + @Test + public void testValidationIncorrect() throws Exception { + Person p = new Person("", -1); + PersonMarshaller marshaller = new PersonMarshaller(p); - AbstractFaultCreatingValidatingMarshallingPayloadEndpoint endpoint = - new AbstractFaultCreatingValidatingMarshallingPayloadEndpoint() { + AbstractFaultCreatingValidatingMarshallingPayloadEndpoint endpoint = + new AbstractFaultCreatingValidatingMarshallingPayloadEndpoint() { - @Override - protected Object invokeInternal(Object requestObject) throws Exception { - Assert.fail("No expected"); - return null; - } - }; - endpoint.setValidator(new PersonValidator()); - endpoint.setMessageSource(messageSource); - endpoint.setMarshaller(marshaller); - endpoint.setUnmarshaller(marshaller); + @Override + protected Object invokeInternal(Object requestObject) throws Exception { + Assert.fail("No expected"); + return null; + } + }; + endpoint.setValidator(new PersonValidator()); + endpoint.setMessageSource(messageSource); + endpoint.setMarshaller(marshaller); + endpoint.setUnmarshaller(marshaller); - endpoint.invoke(messageContext); + endpoint.invoke(messageContext); - SOAPMessage response = ((SaajSoapMessage) messageContext.getResponse()).getSaajMessage(); - Assert.assertTrue("Response has no fault", response.getSOAPBody().hasFault()); - SOAPFault fault = response.getSOAPBody().getFault(); - Assert.assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "Client"), - fault.getFaultCodeAsQName()); - Assert.assertEquals("Invalid fault string", endpoint.getFaultStringOrReason(), fault.getFaultString()); - Detail detail = fault.getDetail(); - Assert.assertNotNull("No detail", detail); - Iterator iterator = detail.getDetailEntries(); - Assert.assertTrue("No detail entry", iterator.hasNext()); - DetailEntry detailEntry = (DetailEntry) iterator.next(); - Assert.assertEquals("Invalid detail entry name", - new QName("http://springframework.org/spring-ws", "ValidationError"), detailEntry.getElementQName()); - Assert.assertEquals("Invalid detail entry text", "Name is required", detailEntry.getTextContent()); - Assert.assertTrue("No detail entry", iterator.hasNext()); - detailEntry = (DetailEntry) iterator.next(); - Assert.assertEquals("Invalid detail entry name", - new QName("http://springframework.org/spring-ws", "ValidationError"), detailEntry.getElementQName()); - Assert.assertEquals("Invalid detail entry text", "Age Cannot be negative", detailEntry.getTextContent()); - Assert.assertFalse("Too many detail entries", iterator.hasNext()); - } + SOAPMessage response = ((SaajSoapMessage) messageContext.getResponse()).getSaajMessage(); + Assert.assertTrue("Response has no fault", response.getSOAPBody().hasFault()); + SOAPFault fault = response.getSOAPBody().getFault(); + Assert.assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "Client"), + fault.getFaultCodeAsQName()); + Assert.assertEquals("Invalid fault string", endpoint.getFaultStringOrReason(), fault.getFaultString()); + Detail detail = fault.getDetail(); + Assert.assertNotNull("No detail", detail); + Iterator iterator = detail.getDetailEntries(); + Assert.assertTrue("No detail entry", iterator.hasNext()); + DetailEntry detailEntry = (DetailEntry) iterator.next(); + Assert.assertEquals("Invalid detail entry name", + new QName("http://springframework.org/spring-ws", "ValidationError"), detailEntry.getElementQName()); + Assert.assertEquals("Invalid detail entry text", "Name is required", detailEntry.getTextContent()); + Assert.assertTrue("No detail entry", iterator.hasNext()); + detailEntry = (DetailEntry) iterator.next(); + Assert.assertEquals("Invalid detail entry name", + new QName("http://springframework.org/spring-ws", "ValidationError"), detailEntry.getElementQName()); + Assert.assertEquals("Invalid detail entry text", "Age Cannot be negative", detailEntry.getTextContent()); + Assert.assertFalse("Too many detail entries", iterator.hasNext()); + } - @Test - public void testValidationCorrect() throws Exception { - Person p = new Person("John", 42); - PersonMarshaller marshaller = new PersonMarshaller(p); - AbstractFaultCreatingValidatingMarshallingPayloadEndpoint endpoint = - new AbstractFaultCreatingValidatingMarshallingPayloadEndpoint() { + @Test + public void testValidationCorrect() throws Exception { + Person p = new Person("John", 42); + PersonMarshaller marshaller = new PersonMarshaller(p); + AbstractFaultCreatingValidatingMarshallingPayloadEndpoint endpoint = + new AbstractFaultCreatingValidatingMarshallingPayloadEndpoint() { - @Override - protected Object invokeInternal(Object requestObject) throws Exception { - return null; - } - }; - endpoint.setValidator(new PersonValidator()); - endpoint.setMessageSource(messageSource); - endpoint.setMarshaller(marshaller); - endpoint.setUnmarshaller(marshaller); + @Override + protected Object invokeInternal(Object requestObject) throws Exception { + return null; + } + }; + endpoint.setValidator(new PersonValidator()); + endpoint.setMessageSource(messageSource); + endpoint.setMarshaller(marshaller); + endpoint.setUnmarshaller(marshaller); - endpoint.invoke(messageContext); + endpoint.invoke(messageContext); - SOAPMessage response = ((SaajSoapMessage) messageContext.getResponse()).getSaajMessage(); - Assert.assertFalse("Response has fault", response.getSOAPBody().hasFault()); - } + SOAPMessage response = ((SaajSoapMessage) messageContext.getResponse()).getSaajMessage(); + Assert.assertFalse("Response has fault", response.getSOAPBody().hasFault()); + } - private static class PersonValidator implements Validator { + private static class PersonValidator implements Validator { - @Override - public boolean supports(Class clazz) { - return Person.class.equals(clazz); - } + @Override + public boolean supports(Class clazz) { + return Person.class.equals(clazz); + } - @Override - public void validate(Object obj, Errors e) { - ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); - Person p = (Person) obj; - if (p.getAge() < 0) { - e.rejectValue("age", "age.negativevalue"); - } - else if (p.getAge() > 110) { - e.rejectValue("age", "too.darn.old"); - } - } - } + @Override + public void validate(Object obj, Errors e) { + ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); + Person p = (Person) obj; + if (p.getAge() < 0) { + e.rejectValue("age", "age.negativevalue"); + } + else if (p.getAge() > 110) { + e.rejectValue("age", "too.darn.old"); + } + } + } - private static class Person { + private static class Person { - private String name; + private String name; - private int age; + private int age; - private Person(String name, int age) { - this.name = name; - this.age = age; - } + private Person(String name, int age) { + this.name = name; + this.age = age; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; + } - public String toString() { - return "Person{" + name + "," + age + "}"; - } - } + public String toString() { + return "Person{" + name + "," + age + "}"; + } + } - private static class PersonMarshaller implements Unmarshaller, Marshaller { + private static class PersonMarshaller implements Unmarshaller, Marshaller { - private final Person person; + private final Person person; - private PersonMarshaller(Person person) { - this.person = person; - } + private PersonMarshaller(Person person) { + this.person = person; + } - @Override - public Object unmarshal(Source source) throws XmlMappingException, IOException { - return person; - } + @Override + public Object unmarshal(Source source) throws XmlMappingException, IOException { + return person; + } - @Override - public boolean supports(Class clazz) { - return Person.class.equals(clazz); - } + @Override + public boolean supports(Class clazz) { + return Person.class.equals(clazz); + } - @Override - public void marshal(Object graph, Result result) throws XmlMappingException, IOException { - } - } + @Override + public void marshal(Object graph, Result result) throws XmlMappingException, IOException { + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolverTest.java index 566280c0..b94927ac 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SimpleSoapExceptionResolverTest.java @@ -33,37 +33,37 @@ import static org.easymock.EasyMock.*; public class SimpleSoapExceptionResolverTest { - private SimpleSoapExceptionResolver exceptionResolver; + private SimpleSoapExceptionResolver exceptionResolver; - private MessageContext messageContext; + private MessageContext messageContext; - private SoapMessage messageMock; + private SoapMessage messageMock; - private Soap11Body bodyMock; + private Soap11Body bodyMock; - private WebServiceMessageFactory factoryMock; + private WebServiceMessageFactory factoryMock; - @Before - public void setUp() throws Exception { - exceptionResolver = new SimpleSoapExceptionResolver(); - factoryMock = createMock(WebServiceMessageFactory.class); - messageContext = new DefaultMessageContext(new MockWebServiceMessage(), factoryMock); - messageMock = createMock(SoapMessage.class); - bodyMock = createMock(Soap11Body.class); - } + @Before + public void setUp() throws Exception { + exceptionResolver = new SimpleSoapExceptionResolver(); + factoryMock = createMock(WebServiceMessageFactory.class); + messageContext = new DefaultMessageContext(new MockWebServiceMessage(), factoryMock); + messageMock = createMock(SoapMessage.class); + bodyMock = createMock(Soap11Body.class); + } - @Test - public void testResolveExceptionInternal() throws Exception { - Exception exception = new Exception("message"); - expect(factoryMock.createWebServiceMessage()).andReturn(messageMock); - expect(messageMock.getSoapBody()).andReturn(bodyMock); - expect(bodyMock.addServerOrReceiverFault(exception.getMessage(), Locale.ENGLISH)).andReturn(null); + @Test + public void testResolveExceptionInternal() throws Exception { + Exception exception = new Exception("message"); + expect(factoryMock.createWebServiceMessage()).andReturn(messageMock); + expect(messageMock.getSoapBody()).andReturn(bodyMock); + expect(bodyMock.addServerOrReceiverFault(exception.getMessage(), Locale.ENGLISH)).andReturn(null); - replay(factoryMock, messageMock, bodyMock); + replay(factoryMock, messageMock, bodyMock); - boolean result = exceptionResolver.resolveExceptionInternal(messageContext, null, exception); - Assert.assertTrue("Invalid result", result); + boolean result = exceptionResolver.resolveExceptionInternal(messageContext, null, exception); + Assert.assertTrue("Invalid result", result); - verify(factoryMock, messageMock, bodyMock); - } + verify(factoryMock, messageMock, bodyMock); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolverTest.java index ae4cd12c..cd2e8ff3 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultAnnotationExceptionResolverTest.java @@ -40,211 +40,211 @@ import org.springframework.ws.soap.soap12.Soap12Fault; public class SoapFaultAnnotationExceptionResolverTest { - private SoapFaultAnnotationExceptionResolver resolver; + private SoapFaultAnnotationExceptionResolver resolver; - @Before - public void setUp() throws Exception { - resolver = new SoapFaultAnnotationExceptionResolver(); - } + @Before + public void setUp() throws Exception { + resolver = new SoapFaultAnnotationExceptionResolver(); + } - @Test - public void testResolveExceptionClientSoap11() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionClientSoap11() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new MyClientException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Client error", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new MyClientException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Client error", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionSenderSoap12() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionSenderSoap12() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new MySenderException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Sender error", fault.getFaultReasonText(Locale.ENGLISH)); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new MySenderException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Sender error", fault.getFaultReasonText(Locale.ENGLISH)); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionServerSoap11() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionServerSoap11() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new MyServerException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getServerOrReceiverFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Server error", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new MyServerException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getServerOrReceiverFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Server error", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionReceiverSoap12() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage message = saajFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + @Test + public void testResolveExceptionReceiverSoap12() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage message = saajFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new MyReceiverException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getServerOrReceiverFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Receiver error", fault.getFaultReasonText(Locale.ENGLISH)); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new MyReceiverException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getServerOrReceiverFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Receiver error", fault.getFaultReasonText(Locale.ENGLISH)); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionDefault() throws Exception { - SoapFaultDefinition defaultFault = new SoapFaultDefinition(); - defaultFault.setFaultCode(SoapFaultDefinition.CLIENT); - defaultFault.setFaultStringOrReason("faultstring"); - resolver.setDefaultFault(defaultFault); - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionDefault() throws Exception { + SoapFaultDefinition defaultFault = new SoapFaultDefinition(); + defaultFault.setFaultCode(SoapFaultDefinition.CLIENT); + defaultFault.setFaultStringOrReason("faultstring"); + resolver.setDefaultFault(defaultFault); + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new NonAnnotatedException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "faultstring", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new NonAnnotatedException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "faultstring", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionCustom() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionCustom() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new MyCustomException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", new QName("http://springframework.org/spring-ws", "Fault"), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "MyCustomException thrown", fault.getFaultStringOrReason()); - Assert.assertEquals("Invalid fault locale on fault", new Locale("nl"), fault.getFaultStringLocale()); - } + boolean result = resolver.resolveException(context, null, new MyCustomException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", new QName("http://springframework.org/spring-ws", "Fault"), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "MyCustomException thrown", fault.getFaultStringOrReason()); + Assert.assertEquals("Invalid fault locale on fault", new Locale("nl"), fault.getFaultStringLocale()); + } - @Test - public void testResolveExceptionInheritance() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionInheritance() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new MySubClientException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Client error", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new MySubClientException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Client error", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionExceptionMessage() throws Exception { - MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); - MessageContext context = new DefaultMessageContext(factory); + @Test + public void testResolveExceptionExceptionMessage() throws Exception { + MessageFactory saajFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SoapMessageFactory factory = new SaajSoapMessageFactory(saajFactory); + MessageContext context = new DefaultMessageContext(factory); - boolean result = resolver.resolveException(context, null, new NoStringOrReasonException("Exception message")); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Exception message", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new NoStringOrReasonException("Exception message")); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Resonse has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Exception message", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @SoapFault(faultCode = FaultCode.CLIENT, faultStringOrReason = "Client error") - @SuppressWarnings("serial") - public class MyClientException extends Exception { + @SoapFault(faultCode = FaultCode.CLIENT, faultStringOrReason = "Client error") + @SuppressWarnings("serial") + public class MyClientException extends Exception { - } + } @SuppressWarnings("serial") - public class MySubClientException extends MyClientException { + public class MySubClientException extends MyClientException { - } + } - @SoapFault(faultCode = FaultCode.CLIENT) - @SuppressWarnings("serial") - public class NoStringOrReasonException extends Exception { + @SoapFault(faultCode = FaultCode.CLIENT) + @SuppressWarnings("serial") + public class NoStringOrReasonException extends Exception { - public NoStringOrReasonException(String message) { - super(message); - } - } + public NoStringOrReasonException(String message) { + super(message); + } + } - @SoapFault(faultCode = FaultCode.SENDER, faultStringOrReason = "Sender error") - @SuppressWarnings("serial") - public class MySenderException extends Exception { + @SoapFault(faultCode = FaultCode.SENDER, faultStringOrReason = "Sender error") + @SuppressWarnings("serial") + public class MySenderException extends Exception { - } + } - @SoapFault(faultCode = FaultCode.SERVER, faultStringOrReason = "Server error") - @SuppressWarnings("serial") - public class MyServerException extends Exception { + @SoapFault(faultCode = FaultCode.SERVER, faultStringOrReason = "Server error") + @SuppressWarnings("serial") + public class MyServerException extends Exception { - } + } - @SoapFault(faultCode = FaultCode.RECEIVER, faultStringOrReason = "Receiver error") - @SuppressWarnings("serial") - public class MyReceiverException extends Exception { + @SoapFault(faultCode = FaultCode.RECEIVER, faultStringOrReason = "Receiver error") + @SuppressWarnings("serial") + public class MyReceiverException extends Exception { - } + } - @SoapFault(faultCode = FaultCode.CUSTOM, customFaultCode = "{http://springframework.org/spring-ws}Fault", - faultStringOrReason = "MyCustomException thrown", locale = "nl") - @SuppressWarnings("serial") - public class MyCustomException extends Exception { + @SoapFault(faultCode = FaultCode.CUSTOM, customFaultCode = "{http://springframework.org/spring-ws}Fault", + faultStringOrReason = "MyCustomException thrown", locale = "nl") + @SuppressWarnings("serial") + public class MyCustomException extends Exception { - } + } @SuppressWarnings("serial") - public class NonAnnotatedException extends Exception { + public class NonAnnotatedException extends Exception { - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditorTest.java index 8b62c942..f047252f 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultDefinitionEditorTest.java @@ -25,63 +25,63 @@ import org.junit.Test; public class SoapFaultDefinitionEditorTest { - private SoapFaultDefinitionEditor editor; + private SoapFaultDefinitionEditor editor; - @Before - public void setUp() throws Exception { - editor = new SoapFaultDefinitionEditor(); - } + @Before + public void setUp() throws Exception { + editor = new SoapFaultDefinitionEditor(); + } - @Test - public void testSetAsTextNoLocale() throws Exception { - editor.setAsText("Server, Server error"); - SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); - Assert.assertNotNull("fault not set", definition); - Assert.assertEquals("Invalid fault code", new QName("Server"), definition.getFaultCode()); - Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); - Assert.assertEquals("Invalid fault string locale", Locale.ENGLISH, definition.getLocale()); - } + @Test + public void testSetAsTextNoLocale() throws Exception { + editor.setAsText("Server, Server error"); + SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); + Assert.assertNotNull("fault not set", definition); + Assert.assertEquals("Invalid fault code", new QName("Server"), definition.getFaultCode()); + Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); + Assert.assertEquals("Invalid fault string locale", Locale.ENGLISH, definition.getLocale()); + } - @Test - public void testSetAsTextLocale() throws Exception { - editor.setAsText("Server, Server error, nl"); - SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); - Assert.assertNotNull("fault not set", definition); - Assert.assertEquals("Invalid fault code", new QName("Server"), definition.getFaultCode()); - Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); - Assert.assertEquals("Invalid fault string locale", new Locale("nl"), definition.getLocale()); - } + @Test + public void testSetAsTextLocale() throws Exception { + editor.setAsText("Server, Server error, nl"); + SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); + Assert.assertNotNull("fault not set", definition); + Assert.assertEquals("Invalid fault code", new QName("Server"), definition.getFaultCode()); + Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); + Assert.assertEquals("Invalid fault string locale", new Locale("nl"), definition.getLocale()); + } - @Test - public void testSetAsTextSender() throws Exception { - editor.setAsText("SENDER, Server error"); - SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); - Assert.assertNotNull("fault not set", definition); - Assert.assertEquals("Invalid fault code", SoapFaultDefinition.SENDER, definition.getFaultCode()); - Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); - } + @Test + public void testSetAsTextSender() throws Exception { + editor.setAsText("SENDER, Server error"); + SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); + Assert.assertNotNull("fault not set", definition); + Assert.assertEquals("Invalid fault code", SoapFaultDefinition.SENDER, definition.getFaultCode()); + Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); + } - @Test - public void testSetAsTextReceiver() throws Exception { - editor.setAsText("RECEIVER, Server error"); - SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); - Assert.assertNotNull("fault not set", definition); - Assert.assertEquals("Invalid fault code", SoapFaultDefinition.RECEIVER, definition.getFaultCode()); - Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); - } + @Test + public void testSetAsTextReceiver() throws Exception { + editor.setAsText("RECEIVER, Server error"); + SoapFaultDefinition definition = (SoapFaultDefinition) editor.getValue(); + Assert.assertNotNull("fault not set", definition); + Assert.assertEquals("Invalid fault code", SoapFaultDefinition.RECEIVER, definition.getFaultCode()); + Assert.assertEquals("Invalid fault string", "Server error", definition.getFaultStringOrReason()); + } - @Test - public void testSetAsTextIllegalArgument() throws Exception { - try { - editor.setAsText("SOAP-ENV:Server"); - } - catch (IllegalArgumentException ex) { - } - } + @Test + public void testSetAsTextIllegalArgument() throws Exception { + try { + editor.setAsText("SOAP-ENV:Server"); + } + catch (IllegalArgumentException ex) { + } + } - @Test - public void testSetAsTextEmpty() throws Exception { - editor.setAsText(""); - Assert.assertNull("definition not set to null", editor.getValue()); - } + @Test + public void testSetAsTextEmpty() throws Exception { + editor.setAsText(""); + Assert.assertNull("definition not set to null", editor.getValue()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolverTest.java index 0d9e8c69..6fb8fd61 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/SoapFaultMappingExceptionResolverTest.java @@ -40,178 +40,178 @@ import org.junit.Test; public class SoapFaultMappingExceptionResolverTest { - private SoapFaultMappingExceptionResolver resolver; + private SoapFaultMappingExceptionResolver resolver; - @Before - public void setUp() throws Exception { - resolver = new SoapFaultMappingExceptionResolver(); - } + @Before + public void setUp() throws Exception { + resolver = new SoapFaultMappingExceptionResolver(); + } - @Test - public void testGetDepth() throws Exception { - Assert.assertEquals("Invalid depth for Exception", 0, resolver.getDepth("java.lang.Exception", new Exception())); - Assert.assertEquals("Invalid depth for IllegalArgumentException", 2, - resolver.getDepth("java.lang.Exception", new IllegalArgumentException())); - Assert.assertEquals("Invalid depth for IllegalStateException", -1, - resolver.getDepth("IllegalArgumentException", new IllegalStateException())); - } + @Test + public void testGetDepth() throws Exception { + Assert.assertEquals("Invalid depth for Exception", 0, resolver.getDepth("java.lang.Exception", new Exception())); + Assert.assertEquals("Invalid depth for IllegalArgumentException", 2, + resolver.getDepth("java.lang.Exception", new IllegalArgumentException())); + Assert.assertEquals("Invalid depth for IllegalStateException", -1, + resolver.getDepth("IllegalArgumentException", new IllegalStateException())); + } - @Test - public void testResolveExceptionClientSoap11() throws Exception { - Properties mappings = new Properties(); - mappings.setProperty(Exception.class.getName(), "SERVER, Server error"); - mappings.setProperty(RuntimeException.class.getName(), "CLIENT, Client error"); - resolver.setExceptionMappings(mappings); + @Test + public void testResolveExceptionClientSoap11() throws Exception { + Properties mappings = new Properties(); + mappings.setProperty(Exception.class.getName(), "SERVER, Server error"); + mappings.setProperty(RuntimeException.class.getName(), "CLIENT, Client error"); + resolver.setExceptionMappings(mappings); - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage message = messageFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage message = messageFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Client error", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Client error", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionSenderSoap12() throws Exception { - Properties mappings = new Properties(); - mappings.setProperty(Exception.class.getName(), "RECEIVER, Receiver error, en"); - mappings.setProperty(RuntimeException.class.getName(), "SENDER, Sender error, en"); - resolver.setExceptionMappings(mappings); + @Test + public void testResolveExceptionSenderSoap12() throws Exception { + Properties mappings = new Properties(); + mappings.setProperty(Exception.class.getName(), "RECEIVER, Receiver error, en"); + mappings.setProperty(RuntimeException.class.getName(), "SENDER, Sender error, en"); + resolver.setExceptionMappings(mappings); - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage message = messageFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage message = messageFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Sender error", fault.getFaultReasonText(Locale.ENGLISH)); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Sender error", fault.getFaultReasonText(Locale.ENGLISH)); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionServerSoap11() throws Exception { - Properties mappings = new Properties(); - mappings.setProperty(Exception.class.getName(), "CLIENT, Client error"); - mappings.setProperty(RuntimeException.class.getName(), "SERVER, Server error"); - resolver.setExceptionMappings(mappings); + @Test + public void testResolveExceptionServerSoap11() throws Exception { + Properties mappings = new Properties(); + mappings.setProperty(Exception.class.getName(), "CLIENT, Client error"); + mappings.setProperty(RuntimeException.class.getName(), "SERVER, Server error"); + resolver.setExceptionMappings(mappings); - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage message = messageFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage message = messageFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getServerOrReceiverFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Server error", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getServerOrReceiverFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Server error", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionReceiverSoap12() throws Exception { - Properties mappings = new Properties(); - mappings.setProperty(Exception.class.getName(), "SENDER, Sender error"); - mappings.setProperty(RuntimeException.class.getName(), "RECEIVER, Receiver error"); - resolver.setExceptionMappings(mappings); + @Test + public void testResolveExceptionReceiverSoap12() throws Exception { + Properties mappings = new Properties(); + mappings.setProperty(Exception.class.getName(), "SENDER, Sender error"); + mappings.setProperty(RuntimeException.class.getName(), "RECEIVER, Receiver error"); + resolver.setExceptionMappings(mappings); - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - SOAPMessage message = messageFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage message = messageFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getServerOrReceiverFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "Receiver error", fault.getFaultReasonText(Locale.ENGLISH)); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getServerOrReceiverFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "Receiver error", fault.getFaultReasonText(Locale.ENGLISH)); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveExceptionDefault() throws Exception { - Properties mappings = new Properties(); - mappings.setProperty(SoapMessageException.class.getName(), "SERVER,Server error"); - resolver.setExceptionMappings(mappings); - SoapFaultDefinition defaultFault = new SoapFaultDefinition(); - defaultFault.setFaultCode(SoapFaultDefinition.CLIENT); - resolver.setDefaultFault(defaultFault); - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage message = messageFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + @Test + public void testResolveExceptionDefault() throws Exception { + Properties mappings = new Properties(); + mappings.setProperty(SoapMessageException.class.getName(), "SERVER,Server error"); + resolver.setExceptionMappings(mappings); + SoapFaultDefinition defaultFault = new SoapFaultDefinition(); + defaultFault.setFaultCode(SoapFaultDefinition.CLIENT); + resolver.setDefaultFault(defaultFault); + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage message = messageFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "bla", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); + boolean result = resolver.resolveException(context, null, new IllegalArgumentException("bla")); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "bla", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); - // SWS-226 - result = resolver.resolveException(context, null, new IllegalArgumentException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "java.lang.IllegalArgumentException", - fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + // SWS-226 + result = resolver.resolveException(context, null, new IllegalArgumentException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "java.lang.IllegalArgumentException", + fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testResolveNoMessageException() throws Exception { - Properties mappings = new Properties(); - mappings.setProperty(IOException.class.getName(), "SERVER"); - resolver.setExceptionMappings(mappings); + @Test + public void testResolveNoMessageException() throws Exception { + Properties mappings = new Properties(); + mappings.setProperty(IOException.class.getName(), "SERVER"); + resolver.setExceptionMappings(mappings); - MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - SOAPMessage message = messageFactory.createMessage(); - SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); - MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); + MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage message = messageFactory.createMessage(); + SoapMessageFactory factory = new SaajSoapMessageFactory(messageFactory); + MessageContext context = new DefaultMessageContext(new SaajSoapMessage(message), factory); - boolean result = resolver.resolveException(context, null, new IOException()); - Assert.assertTrue("resolveException returns false", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getServerOrReceiverFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", "java.io.IOException", fault.getFaultStringOrReason()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = resolver.resolveException(context, null, new IOException()); + Assert.assertTrue("resolveException returns false", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getServerOrReceiverFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", "java.io.IOException", fault.getFaultStringOrReason()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolverTest.java index c4621b3c..5ea5a289 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapHeaderElementMethodArgumentResolverTest.java @@ -36,116 +36,116 @@ import static org.junit.Assert.*; */ public class SoapHeaderElementMethodArgumentResolverTest extends AbstractMethodArgumentResolverTestCase { - private static final QName HEADER_QNAME = new QName(NAMESPACE_URI, "header"); + private static final QName HEADER_QNAME = new QName(NAMESPACE_URI, "header"); - private static final String HEADER_CONTENT = "content"; + private static final String HEADER_CONTENT = "content"; - private SoapHeaderElementMethodArgumentResolver resolver; + private SoapHeaderElementMethodArgumentResolver resolver; - private MessageContext messageContext; + private MessageContext messageContext; - private MethodParameter soapHeaderWithEmptyValue; + private MethodParameter soapHeaderWithEmptyValue; - private MethodParameter soapHeaderElementParameter; + private MethodParameter soapHeaderElementParameter; - private MethodParameter soapHeaderElementListParameter; + private MethodParameter soapHeaderElementListParameter; - private MethodParameter soapHeaderMismatch; + private MethodParameter soapHeaderMismatch; - private MethodParameter soapHeaderMismatchList; + private MethodParameter soapHeaderMismatchList; - @Before - public void setUp() throws Exception { - resolver = new SoapHeaderElementMethodArgumentResolver(); - messageContext = createSaajMessageContext(); - SoapMessage message = (SoapMessage) messageContext.getRequest(); - for (int i = 0; i < 3; i++) { - SoapHeaderElement element = message.getSoapHeader().addHeaderElement(HEADER_QNAME); - element.setText(HEADER_CONTENT + i); - } - soapHeaderWithEmptyValue = - new MethodParameter(getClass().getMethod("soapHeaderWithEmptyValue", SoapHeaderElement.class), 0); - soapHeaderElementParameter = - new MethodParameter(getClass().getMethod("soapHeaderElement", SoapHeaderElement.class), 0); - soapHeaderElementListParameter = - new MethodParameter(getClass().getMethod("soapHeaderElementList", List.class), 0); - soapHeaderMismatch = - new MethodParameter(getClass().getMethod("soapHeaderMismatch", SoapHeaderElement.class), 0); - soapHeaderMismatchList = new MethodParameter(getClass().getMethod("soapHeaderMismatchList", List.class), 0); - } + @Before + public void setUp() throws Exception { + resolver = new SoapHeaderElementMethodArgumentResolver(); + messageContext = createSaajMessageContext(); + SoapMessage message = (SoapMessage) messageContext.getRequest(); + for (int i = 0; i < 3; i++) { + SoapHeaderElement element = message.getSoapHeader().addHeaderElement(HEADER_QNAME); + element.setText(HEADER_CONTENT + i); + } + soapHeaderWithEmptyValue = + new MethodParameter(getClass().getMethod("soapHeaderWithEmptyValue", SoapHeaderElement.class), 0); + soapHeaderElementParameter = + new MethodParameter(getClass().getMethod("soapHeaderElement", SoapHeaderElement.class), 0); + soapHeaderElementListParameter = + new MethodParameter(getClass().getMethod("soapHeaderElementList", List.class), 0); + soapHeaderMismatch = + new MethodParameter(getClass().getMethod("soapHeaderMismatch", SoapHeaderElement.class), 0); + soapHeaderMismatchList = new MethodParameter(getClass().getMethod("soapHeaderMismatchList", List.class), 0); + } - @Test - public void supportsParameter() throws Exception { - assertTrue("resolver does not support soapHeaderElement", - resolver.supportsParameter(soapHeaderElementParameter)); - assertTrue("resolver does not support List", - resolver.supportsParameter(soapHeaderElementListParameter)); - } + @Test + public void supportsParameter() throws Exception { + assertTrue("resolver does not support soapHeaderElement", + resolver.supportsParameter(soapHeaderElementParameter)); + assertTrue("resolver does not support List", + resolver.supportsParameter(soapHeaderElementListParameter)); + } - @Test(expected = IllegalArgumentException.class) - public void failOnEmptyValue() throws Exception { - resolver.resolveArgument(messageContext, soapHeaderWithEmptyValue); - } + @Test(expected = IllegalArgumentException.class) + public void failOnEmptyValue() throws Exception { + resolver.resolveArgument(messageContext, soapHeaderWithEmptyValue); + } - @Test - public void resolveSoapHeaderElement() throws Exception { - Object result = resolver.resolveArgument(messageContext, soapHeaderElementParameter); + @Test + public void resolveSoapHeaderElement() throws Exception { + Object result = resolver.resolveArgument(messageContext, soapHeaderElementParameter); - assertTrue("result must be a SoapHeaderElement", SoapHeaderElement.class.isAssignableFrom(result.getClass())); + assertTrue("result must be a SoapHeaderElement", SoapHeaderElement.class.isAssignableFrom(result.getClass())); - SoapHeaderElement element = (SoapHeaderElement) result; + SoapHeaderElement element = (SoapHeaderElement) result; - assertTrue("headers must be equal", element.getName().equals(HEADER_QNAME)); - assertEquals("header text must be equal to [" + HEADER_CONTENT + "0]", HEADER_CONTENT + "0", element.getText()); - } + assertTrue("headers must be equal", element.getName().equals(HEADER_QNAME)); + assertEquals("header text must be equal to [" + HEADER_CONTENT + "0]", HEADER_CONTENT + "0", element.getText()); + } - @Test - @SuppressWarnings("unchecked") - public void resolveSoapHeaderElementList() throws Exception { - Object result = resolver.resolveArgument(messageContext, soapHeaderElementListParameter); + @Test + @SuppressWarnings("unchecked") + public void resolveSoapHeaderElementList() throws Exception { + Object result = resolver.resolveArgument(messageContext, soapHeaderElementListParameter); - assertTrue("result must be a List", List.class.isAssignableFrom(result.getClass())); + assertTrue("result must be a List", List.class.isAssignableFrom(result.getClass())); - List elements = (List) result; + List elements = (List) result; - assertTrue("size", elements.size() > 1); - for (int i = 0; i < elements.size(); i++) { - SoapHeaderElement element = elements.get(i); - assertTrue("headers must be equal", element.getName().equals(HEADER_QNAME)); - assertEquals("header must be equal to [" + HEADER_CONTENT + i + "]", HEADER_CONTENT + i, - elements.get(i).getText()); - } - } + assertTrue("size", elements.size() > 1); + for (int i = 0; i < elements.size(); i++) { + SoapHeaderElement element = elements.get(i); + assertTrue("headers must be equal", element.getName().equals(HEADER_QNAME)); + assertEquals("header must be equal to [" + HEADER_CONTENT + i + "]", HEADER_CONTENT + i, + elements.get(i).getText()); + } + } - @Test - public void resolveSoapHeaderMismatch() throws Exception { - Object result = resolver.resolveArgument(messageContext, soapHeaderMismatch); - assertNull(result); - } + @Test + public void resolveSoapHeaderMismatch() throws Exception { + Object result = resolver.resolveArgument(messageContext, soapHeaderMismatch); + assertNull(result); + } - @Test - public void resolveSoapHeaderMismatchList() throws Exception { - Object result = resolver.resolveArgument(messageContext, soapHeaderMismatchList); - assertTrue("result must be a List", List.class.isAssignableFrom(result.getClass())); - assertTrue("result List must be empty", ((List) result).isEmpty()); - } + @Test + public void resolveSoapHeaderMismatchList() throws Exception { + Object result = resolver.resolveArgument(messageContext, soapHeaderMismatchList); + assertTrue("result must be a List", List.class.isAssignableFrom(result.getClass())); + assertTrue("result List must be empty", ((List) result).isEmpty()); + } - public void soapHeaderWithEmptyValue(@SoapHeader("") SoapHeaderElement element) { - } + public void soapHeaderWithEmptyValue(@SoapHeader("") SoapHeaderElement element) { + } - public void soapHeaderElement(@SoapHeader("{http://springframework.org/ws}header") SoapHeaderElement element) { - } + public void soapHeaderElement(@SoapHeader("{http://springframework.org/ws}header") SoapHeaderElement element) { + } - public void soapHeaderElementList(@SoapHeader( - "{http://springframework.org/ws}header") List elements) { - } + public void soapHeaderElementList(@SoapHeader( + "{http://springframework.org/ws}header") List elements) { + } - public void soapHeaderMismatch(@SoapHeader("{http://springframework.org/ws}xxx") SoapHeaderElement element) { - } + public void soapHeaderMismatch(@SoapHeader("{http://springframework.org/ws}xxx") SoapHeaderElement element) { + } - public void soapHeaderMismatchList(@SoapHeader( - "{http://springframework.org/ws}xxx") List elements) { - } + public void soapHeaderMismatchList(@SoapHeader( + "{http://springframework.org/ws}xxx") List elements) { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolverTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolverTest.java index ee3d1223..b99f830c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolverTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/adapter/method/SoapMethodArgumentResolverTest.java @@ -33,79 +33,79 @@ import static org.junit.Assert.assertTrue; /** @author Arjen Poutsma */ public class SoapMethodArgumentResolverTest extends AbstractMethodArgumentResolverTestCase { - private SoapMethodArgumentResolver resolver; + private SoapMethodArgumentResolver resolver; - private MethodParameter soapMessageParameter; + private MethodParameter soapMessageParameter; - private MethodParameter soapEnvelopeParameter; + private MethodParameter soapEnvelopeParameter; - private MethodParameter soapBodyParameter; + private MethodParameter soapBodyParameter; - private MethodParameter soapHeaderParameter; + private MethodParameter soapHeaderParameter; - @Before - public void setUp() throws Exception { - resolver = new SoapMethodArgumentResolver(); - soapMessageParameter = new MethodParameter(getClass().getMethod("soapMessage", SoapMessage.class), 0); - soapEnvelopeParameter = new MethodParameter(getClass().getMethod("soapEnvelope", SoapEnvelope.class), 0); - soapBodyParameter = new MethodParameter(getClass().getMethod("soapBody", SoapBody.class), 0); - soapHeaderParameter = new MethodParameter(getClass().getMethod("soapHeader", SoapHeader.class), 0); - } + @Before + public void setUp() throws Exception { + resolver = new SoapMethodArgumentResolver(); + soapMessageParameter = new MethodParameter(getClass().getMethod("soapMessage", SoapMessage.class), 0); + soapEnvelopeParameter = new MethodParameter(getClass().getMethod("soapEnvelope", SoapEnvelope.class), 0); + soapBodyParameter = new MethodParameter(getClass().getMethod("soapBody", SoapBody.class), 0); + soapHeaderParameter = new MethodParameter(getClass().getMethod("soapHeader", SoapHeader.class), 0); + } - @Test - public void supportsParameter() throws Exception { - assertTrue("resolver does not support SoapMessage", resolver.supportsParameter(soapMessageParameter)); - assertTrue("resolver does not support SoapEnvelope", resolver.supportsParameter(soapEnvelopeParameter)); - assertTrue("resolver does not support SoapBody", resolver.supportsParameter(soapBodyParameter)); - assertTrue("resolver does not support SoapHeader", resolver.supportsParameter(soapHeaderParameter)); - } + @Test + public void supportsParameter() throws Exception { + assertTrue("resolver does not support SoapMessage", resolver.supportsParameter(soapMessageParameter)); + assertTrue("resolver does not support SoapEnvelope", resolver.supportsParameter(soapEnvelopeParameter)); + assertTrue("resolver does not support SoapBody", resolver.supportsParameter(soapBodyParameter)); + assertTrue("resolver does not support SoapHeader", resolver.supportsParameter(soapHeaderParameter)); + } - @Test - public void resolveSoapMessageSaaj() throws Exception { - MessageContext messageContext = createSaajMessageContext(); + @Test + public void resolveSoapMessageSaaj() throws Exception { + MessageContext messageContext = createSaajMessageContext(); - Object result = resolver.resolveArgument(messageContext, soapMessageParameter); + Object result = resolver.resolveArgument(messageContext, soapMessageParameter); - assertEquals(messageContext.getRequest(), result); - } + assertEquals(messageContext.getRequest(), result); + } - @Test - public void resolveSoapEnvelopeSaaj() throws Exception { - MessageContext messageContext = createSaajMessageContext(); + @Test + public void resolveSoapEnvelopeSaaj() throws Exception { + MessageContext messageContext = createSaajMessageContext(); - Object result = resolver.resolveArgument(messageContext, soapEnvelopeParameter); + Object result = resolver.resolveArgument(messageContext, soapEnvelopeParameter); - assertEquals(((SoapMessage)messageContext.getRequest()).getEnvelope(), result); - } + assertEquals(((SoapMessage)messageContext.getRequest()).getEnvelope(), result); + } - @Test - public void resolveSoapBodySaaj() throws Exception { - MessageContext messageContext = createSaajMessageContext(); + @Test + public void resolveSoapBodySaaj() throws Exception { + MessageContext messageContext = createSaajMessageContext(); - Object result = resolver.resolveArgument(messageContext, soapBodyParameter); + Object result = resolver.resolveArgument(messageContext, soapBodyParameter); - assertEquals(((SoapMessage)messageContext.getRequest()).getSoapBody(), result); - } + assertEquals(((SoapMessage)messageContext.getRequest()).getSoapBody(), result); + } - @Test - public void resolveSoapHeaderSaaj() throws Exception { - MessageContext messageContext = createSaajMessageContext(); + @Test + public void resolveSoapHeaderSaaj() throws Exception { + MessageContext messageContext = createSaajMessageContext(); - Object result = resolver.resolveArgument(messageContext, soapHeaderParameter); + Object result = resolver.resolveArgument(messageContext, soapHeaderParameter); - assertEquals(((SoapMessage)messageContext.getRequest()).getSoapHeader(), result); - } + assertEquals(((SoapMessage)messageContext.getRequest()).getSoapHeader(), result); + } - public void soapMessage(SoapMessage soapMessage) { + public void soapMessage(SoapMessage soapMessage) { - } + } - public void soapEnvelope(SoapEnvelope soapEnvelope) { - } + public void soapEnvelope(SoapEnvelope soapEnvelope) { + } - public void soapBody(SoapBody soapBody) { - } + public void soapBody(SoapBody soapBody) { + } - public void soapHeader(SoapHeader soapHeader) { - } + public void soapHeader(SoapHeader soapHeader) { + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptorTest.java index 4e1b419c..48491e87 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadRootSmartSoapEndpointInterceptorTest.java @@ -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,64 +31,64 @@ import static org.junit.Assert.assertTrue; public class PayloadRootSmartSoapEndpointInterceptorTest { - private EndpointInterceptor delegate; + private EndpointInterceptor delegate; - private String namespaceUri; + private String namespaceUri; - private String localPart; + private String localPart; - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() { - delegate = new EndpointInterceptorAdapter(); + @Before + public void setUp() { + delegate = new EndpointInterceptorAdapter(); - namespaceUri = "http://springframework.org/spring-ws"; - localPart = "element"; + namespaceUri = "http://springframework.org/spring-ws"; + localPart = "element"; - MockWebServiceMessage request = new MockWebServiceMessage("<" + localPart + " xmlns=\"" + namespaceUri + "\" />"); - messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - } + MockWebServiceMessage request = new MockWebServiceMessage("<" + localPart + " xmlns=\"" + namespaceUri + "\" />"); + messageContext = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + } - @Test(expected = IllegalArgumentException.class) - public void neitherNamespaceNorLocalPart() { - new PayloadRootSmartSoapEndpointInterceptor(delegate, null, null); - } + @Test(expected = IllegalArgumentException.class) + public void neitherNamespaceNorLocalPart() { + new PayloadRootSmartSoapEndpointInterceptor(delegate, null, null); + } - @Test - public void shouldInterceptFullMatch() throws Exception { - PayloadRootSmartSoapEndpointInterceptor interceptor = - new PayloadRootSmartSoapEndpointInterceptor(delegate, namespaceUri, localPart); + @Test + public void shouldInterceptFullMatch() throws Exception { + PayloadRootSmartSoapEndpointInterceptor interceptor = + new PayloadRootSmartSoapEndpointInterceptor(delegate, namespaceUri, localPart); - boolean result = interceptor.shouldIntercept(messageContext, null); - assertTrue("Interceptor should apply", result); - } + boolean result = interceptor.shouldIntercept(messageContext, null); + assertTrue("Interceptor should apply", result); + } - @Test - public void shouldInterceptFullNonMatch() throws Exception { - PayloadRootSmartSoapEndpointInterceptor interceptor = - new PayloadRootSmartSoapEndpointInterceptor(delegate, "http://springframework.org/other", localPart); + @Test + public void shouldInterceptFullNonMatch() throws Exception { + PayloadRootSmartSoapEndpointInterceptor interceptor = + new PayloadRootSmartSoapEndpointInterceptor(delegate, "http://springframework.org/other", localPart); - boolean result = interceptor.shouldIntercept(messageContext, null); - assertFalse("Interceptor should not apply", result); - } + boolean result = interceptor.shouldIntercept(messageContext, null); + assertFalse("Interceptor should not apply", result); + } - @Test - public void shouldInterceptNamespaceUriMatch() throws Exception { - PayloadRootSmartSoapEndpointInterceptor interceptor = - new PayloadRootSmartSoapEndpointInterceptor(delegate, namespaceUri, null); + @Test + public void shouldInterceptNamespaceUriMatch() throws Exception { + PayloadRootSmartSoapEndpointInterceptor interceptor = + new PayloadRootSmartSoapEndpointInterceptor(delegate, namespaceUri, null); - boolean result = interceptor.shouldIntercept(messageContext, null); - assertTrue("Interceptor should apply", result); - } - - @Test - public void shouldInterceptNamespaceUriNonMatch() throws Exception { - PayloadRootSmartSoapEndpointInterceptor interceptor = - new PayloadRootSmartSoapEndpointInterceptor(delegate, "http://springframework.org/other", null); + boolean result = interceptor.shouldIntercept(messageContext, null); + assertTrue("Interceptor should apply", result); + } + + @Test + public void shouldInterceptNamespaceUriNonMatch() throws Exception { + PayloadRootSmartSoapEndpointInterceptor interceptor = + new PayloadRootSmartSoapEndpointInterceptor(delegate, "http://springframework.org/other", null); - boolean result = interceptor.shouldIntercept(messageContext, null); - assertFalse("Interceptor should not apply", result); - } + boolean result = interceptor.shouldIntercept(messageContext, null); + assertFalse("Interceptor should not apply", result); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptorTest.java index 075ff0eb..a451fa64 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/PayloadValidatingInterceptorTest.java @@ -57,340 +57,340 @@ import org.springframework.xml.xsd.SimpleXsdSchema; public class PayloadValidatingInterceptorTest { - private PayloadValidatingInterceptor interceptor; + private PayloadValidatingInterceptor interceptor; - private MessageContext context; + private MessageContext context; - private SaajSoapMessageFactory soap11Factory; + private SaajSoapMessageFactory soap11Factory; - private SaajSoapMessageFactory soap12Factory; + private SaajSoapMessageFactory soap12Factory; - private Transformer transformer; + private Transformer transformer; - private static final String INVALID_MESSAGE = "invalidMessage.xml"; + private static final String INVALID_MESSAGE = "invalidMessage.xml"; - private static final String SCHEMA = "schema.xsd"; + private static final String SCHEMA = "schema.xsd"; - private static final String VALID_MESSAGE = "validMessage.xml"; + private static final String VALID_MESSAGE = "validMessage.xml"; - private static final String PRODUCT_SCHEMA = "productSchema.xsd"; + private static final String PRODUCT_SCHEMA = "productSchema.xsd"; - private static final String SIZE_SCHEMA = "sizeSchema.xsd"; + private static final String SIZE_SCHEMA = "sizeSchema.xsd"; - private static final String VALID_SOAP_MESSAGE = "validSoapMessage.xml"; + private static final String VALID_SOAP_MESSAGE = "validSoapMessage.xml"; - private static final String SCHEMA2 = "schema2.xsd"; + private static final String SCHEMA2 = "schema2.xsd"; - @Before - public void setUp() throws Exception { - interceptor = new PayloadValidatingInterceptor(); - interceptor.setSchema(new ClassPathResource(SCHEMA, getClass())); - interceptor.setValidateRequest(true); - interceptor.setValidateResponse(true); - interceptor.afterPropertiesSet(); + @Before + public void setUp() throws Exception { + interceptor = new PayloadValidatingInterceptor(); + interceptor.setSchema(new ClassPathResource(SCHEMA, getClass())); + interceptor.setValidateRequest(true); + interceptor.setValidateResponse(true); + interceptor.afterPropertiesSet(); - soap11Factory = new SaajSoapMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL)); - soap12Factory = new SaajSoapMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL)); - transformer = TransformerFactory.newInstance().newTransformer(); - } + soap11Factory = new SaajSoapMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL)); + soap12Factory = new SaajSoapMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL)); + transformer = TransformerFactory.newInstance().newTransformer(); + } - @Test - public void testHandleInvalidRequestSoap11() throws Exception { - SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); - InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); - transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); - context = new DefaultMessageContext(invalidMessage, soap11Factory); + @Test + public void testHandleInvalidRequestSoap11() throws Exception { + SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); + InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); + transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); + context = new DefaultMessageContext(invalidMessage, soap11Factory); - boolean result = interceptor.handleRequest(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", PayloadValidatingInterceptor.DEFAULT_FAULTSTRING_OR_REASON, - fault.getFaultStringOrReason()); - Assert.assertNotNull("No Detail on fault", fault.getFaultDetail()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", PayloadValidatingInterceptor.DEFAULT_FAULTSTRING_OR_REASON, + fault.getFaultStringOrReason()); + Assert.assertNotNull("No Detail on fault", fault.getFaultDetail()); + } - @Test - public void testHandleInvalidRequestSoap12() throws Exception { - SoapMessage invalidMessage = soap12Factory.createWebServiceMessage(); - InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); - transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); - context = new DefaultMessageContext(invalidMessage, soap12Factory); + @Test + public void testHandleInvalidRequestSoap12() throws Exception { + SoapMessage invalidMessage = soap12Factory.createWebServiceMessage(); + InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); + transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); + context = new DefaultMessageContext(invalidMessage, soap12Factory); - boolean result = interceptor.handleRequest(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", PayloadValidatingInterceptor.DEFAULT_FAULTSTRING_OR_REASON, - fault.getFaultReasonText(Locale.ENGLISH)); - Assert.assertNotNull("No Detail on fault", fault.getFaultDetail()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap12Fault fault = (Soap12Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_12.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", PayloadValidatingInterceptor.DEFAULT_FAULTSTRING_OR_REASON, + fault.getFaultReasonText(Locale.ENGLISH)); + Assert.assertNotNull("No Detail on fault", fault.getFaultDetail()); + } - @Test - public void testHandleInvalidRequestOverridenProperties() throws Exception { - String faultString = "fout"; - Locale locale = new Locale("nl"); - interceptor.setFaultStringOrReason(faultString); - interceptor.setFaultStringOrReasonLocale(locale); - interceptor.setAddValidationErrorDetail(false); + @Test + public void testHandleInvalidRequestOverridenProperties() throws Exception { + String faultString = "fout"; + Locale locale = new Locale("nl"); + interceptor.setFaultStringOrReason(faultString); + interceptor.setFaultStringOrReasonLocale(locale); + interceptor.setAddValidationErrorDetail(false); - SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); - InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); - transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); - context = new DefaultMessageContext(invalidMessage, soap11Factory); + SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); + InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); + transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); + context = new DefaultMessageContext(invalidMessage, soap11Factory); - boolean result = interceptor.handleRequest(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - Assert.assertTrue("Context has no response", context.hasResponse()); - SoapMessage response = (SoapMessage) context.getResponse(); - Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); - Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); - Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), - fault.getFaultCode()); - Assert.assertEquals("Invalid fault string on fault", faultString, fault.getFaultStringOrReason()); - Assert.assertEquals("Invalid fault string locale on fault", locale, fault.getFaultStringLocale()); - Assert.assertNull("Detail on fault", fault.getFaultDetail()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + Assert.assertTrue("Context has no response", context.hasResponse()); + SoapMessage response = (SoapMessage) context.getResponse(); + Assert.assertTrue("Response has no fault", response.getSoapBody().hasFault()); + Soap11Fault fault = (Soap11Fault) response.getSoapBody().getFault(); + Assert.assertEquals("Invalid fault code on fault", SoapVersion.SOAP_11.getClientOrSenderFaultName(), + fault.getFaultCode()); + Assert.assertEquals("Invalid fault string on fault", faultString, fault.getFaultStringOrReason()); + Assert.assertEquals("Invalid fault string locale on fault", locale, fault.getFaultStringLocale()); + Assert.assertNull("Detail on fault", fault.getFaultDetail()); + } - @Test - public void testHandlerInvalidRequest() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - request.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - } + @Test + public void testHandlerInvalidRequest() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + request.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + boolean result = interceptor.handleRequest(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + } - @Test - public void testHandleValidRequest() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } + @Test + public void testHandleValidRequest() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } - @Test - public void testHandleInvalidResponse() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - } + @Test + public void testHandleInvalidResponse() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + } - @Test - public void testHandleValidResponse() throws Exception { - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - } + @Test + public void testHandleValidResponse() throws Exception { + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + } - @Test - public void testNamespacesInType() throws Exception { - // Make sure we use Xerces for this testcase: the JAXP implementation used internally by JDK 1.5 has a bug - // See http://opensource.atlassian.com/projects/spring/browse/SWS-35 - String previousSchemaFactory = - System.getProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, ""); - System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, - "org.apache.xerces.jaxp.validation.XMLSchemaFactory"); - try { - PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); - interceptor.setSchema(new ClassPathResource(SCHEMA2, PayloadValidatingInterceptorTest.class)); - interceptor.afterPropertiesSet(); - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage saajMessage = - SaajUtils.loadMessage(new ClassPathResource(VALID_SOAP_MESSAGE, getClass()), messageFactory); - context = new DefaultMessageContext(new SaajSoapMessage(saajMessage), - new SaajSoapMessageFactory(messageFactory)); + @Test + public void testNamespacesInType() throws Exception { + // Make sure we use Xerces for this testcase: the JAXP implementation used internally by JDK 1.5 has a bug + // See http://opensource.atlassian.com/projects/spring/browse/SWS-35 + String previousSchemaFactory = + System.getProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, ""); + System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, + "org.apache.xerces.jaxp.validation.XMLSchemaFactory"); + try { + PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); + interceptor.setSchema(new ClassPathResource(SCHEMA2, PayloadValidatingInterceptorTest.class)); + interceptor.afterPropertiesSet(); + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage saajMessage = + SaajUtils.loadMessage(new ClassPathResource(VALID_SOAP_MESSAGE, getClass()), messageFactory); + context = new DefaultMessageContext(new SaajSoapMessage(saajMessage), + new SaajSoapMessageFactory(messageFactory)); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } - finally { - // Reset the property - System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, - previousSchemaFactory); - } - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } + finally { + // Reset the property + System.setProperty("javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI, + previousSchemaFactory); + } + } - @Test - public void testNonExistingSchema() throws Exception { - try { - interceptor.setSchema(new ClassPathResource("invalid")); - interceptor.afterPropertiesSet(); - Assert.fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + @Test + public void testNonExistingSchema() throws Exception { + try { + interceptor.setSchema(new ClassPathResource("invalid")); + interceptor.afterPropertiesSet(); + Assert.fail("IllegalArgumentException expected"); + } + catch (IllegalArgumentException ex) { + // expected + } + } - @Test - public void testHandlerInvalidRequestMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(INVALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - } + @Test + public void testHandlerInvalidRequestMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(INVALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + boolean result = interceptor.handleRequest(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + } - @Test - public void testHandleValidRequestMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(VALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + @Test + public void testHandleValidRequestMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(new ClassPathResource(VALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } - @Test - public void testHandleInvalidResponseMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context, null); - Assert.assertFalse("Invalid response from interceptor", result); - } + @Test + public void testHandleInvalidResponseMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(INVALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context, null); + Assert.assertFalse("Invalid response from interceptor", result); + } - @Test - public void testHandleValidResponseMultipleSchemas() throws Exception { - interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), - new ClassPathResource(SIZE_SCHEMA, getClass())}); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); - response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - boolean result = interceptor.handleResponse(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - } + @Test + public void testHandleValidResponseMultipleSchemas() throws Exception { + interceptor.setSchemas(new Resource[]{new ClassPathResource(PRODUCT_SCHEMA, getClass()), + new ClassPathResource(SIZE_SCHEMA, getClass())}); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + MockWebServiceMessage response = (MockWebServiceMessage) context.getResponse(); + response.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + boolean result = interceptor.handleResponse(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + } - @Test - public void testCreateRequestValidationFaultAxiom() throws Exception { - LocatorImpl locator = new LocatorImpl(); - locator.setLineNumber(0); - locator.setColumnNumber(0); - SAXParseException[] exceptions = new SAXParseException[]{new SAXParseException("Message 1", locator), - new SAXParseException("Message 2", locator),}; - MessageContext messageContext = new DefaultMessageContext(new AxiomSoapMessageFactory()); - interceptor.handleRequestValidationErrors(messageContext, exceptions); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - messageContext.getResponse().writeTo(os); - assertXMLEqual( - "" + "" + - "" + "soapenv:Client" + - "Validation error" + "" + - "Message 1" + - "Message 2" + - "" + "" + "" + "", os.toString()); + @Test + public void testCreateRequestValidationFaultAxiom() throws Exception { + LocatorImpl locator = new LocatorImpl(); + locator.setLineNumber(0); + locator.setColumnNumber(0); + SAXParseException[] exceptions = new SAXParseException[]{new SAXParseException("Message 1", locator), + new SAXParseException("Message 2", locator),}; + MessageContext messageContext = new DefaultMessageContext(new AxiomSoapMessageFactory()); + interceptor.handleRequestValidationErrors(messageContext, exceptions); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + messageContext.getResponse().writeTo(os); + assertXMLEqual( + "" + "" + + "" + "soapenv:Client" + + "Validation error" + "" + + "Message 1" + + "Message 2" + + "" + "" + "" + "", os.toString()); - } + } - @Test - public void testXsdSchema() throws Exception { - PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); - SimpleXsdSchema schema = new SimpleXsdSchema(new ClassPathResource(SCHEMA, getClass())); - schema.afterPropertiesSet(); - interceptor.setXsdSchema(schema); - interceptor.setValidateRequest(true); - interceptor.setValidateResponse(true); - interceptor.afterPropertiesSet(); - MockWebServiceMessage request = new MockWebServiceMessage(); - request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); - context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Response set", context.hasResponse()); - } + @Test + public void testXsdSchema() throws Exception { + PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); + SimpleXsdSchema schema = new SimpleXsdSchema(new ClassPathResource(SCHEMA, getClass())); + schema.afterPropertiesSet(); + interceptor.setXsdSchema(schema); + interceptor.setValidateRequest(true); + interceptor.setValidateResponse(true); + interceptor.afterPropertiesSet(); + MockWebServiceMessage request = new MockWebServiceMessage(); + request.setPayload(new ClassPathResource(VALID_MESSAGE, getClass())); + context = new DefaultMessageContext(request, new MockWebServiceMessageFactory()); + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Response set", context.hasResponse()); + } - @Test - public void testAxiom() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(true); - messageFactory.afterPropertiesSet(); + @Test + public void testAxiom() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(true); + messageFactory.afterPropertiesSet(); - PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); - interceptor.setSchema(new ClassPathResource("codexws.xsd", getClass())); - interceptor.afterPropertiesSet(); + PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); + interceptor.setSchema(new ClassPathResource("codexws.xsd", getClass())); + interceptor.afterPropertiesSet(); - Resource resource = new ClassPathResource("axiom.xml", getClass()); - TransportInputStream tis = new MockTransportInputStream(resource.getInputStream()); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - MessageContext context = new DefaultMessageContext(message, messageFactory); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); + Resource resource = new ClassPathResource("axiom.xml", getClass()); + TransportInputStream tis = new MockTransportInputStream(resource.getInputStream()); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + MessageContext context = new DefaultMessageContext(message, messageFactory); + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); - } + } - @Test - public void testMultipleNamespacesAxiom() throws Exception { - AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); - messageFactory.setPayloadCaching(true); - messageFactory.afterPropertiesSet(); + @Test + public void testMultipleNamespacesAxiom() throws Exception { + AxiomSoapMessageFactory messageFactory = new AxiomSoapMessageFactory(); + messageFactory.setPayloadCaching(true); + messageFactory.afterPropertiesSet(); - PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); - interceptor.setSchema(new ClassPathResource("multipleNamespaces.xsd", getClass())); - interceptor.afterPropertiesSet(); + PayloadValidatingInterceptor interceptor = new PayloadValidatingInterceptor(); + interceptor.setSchema(new ClassPathResource("multipleNamespaces.xsd", getClass())); + interceptor.afterPropertiesSet(); - Resource resource = new ClassPathResource("multipleNamespaces.xml", getClass()); - TransportInputStream tis = new MockTransportInputStream(resource.getInputStream()); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - MessageContext context = new DefaultMessageContext(message, messageFactory); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); + Resource resource = new ClassPathResource("multipleNamespaces.xml", getClass()); + TransportInputStream tis = new MockTransportInputStream(resource.getInputStream()); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + MessageContext context = new DefaultMessageContext(message, messageFactory); + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); - } + } - @Test - public void customErrorHandler() throws Exception { - ValidationErrorHandler errorHandler = new ValidationErrorHandler() { - public SAXParseException[] getErrors() { - return new SAXParseException[0]; - } + @Test + public void customErrorHandler() throws Exception { + ValidationErrorHandler errorHandler = new ValidationErrorHandler() { + public SAXParseException[] getErrors() { + return new SAXParseException[0]; + } - public void warning(SAXParseException exception) throws SAXException { - } + public void warning(SAXParseException exception) throws SAXException { + } - public void error(SAXParseException exception) throws SAXException { - } + public void error(SAXParseException exception) throws SAXException { + } - public void fatalError(SAXParseException exception) throws SAXException { - } - }; - interceptor.setErrorHandler(errorHandler); - SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); - InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); - transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); - context = new DefaultMessageContext(invalidMessage, soap11Factory); + public void fatalError(SAXParseException exception) throws SAXException { + } + }; + interceptor.setErrorHandler(errorHandler); + SoapMessage invalidMessage = soap11Factory.createWebServiceMessage(); + InputStream inputStream = getClass().getResourceAsStream(INVALID_MESSAGE); + transformer.transform(new StreamSource(inputStream), invalidMessage.getPayloadResult()); + context = new DefaultMessageContext(invalidMessage, soap11Factory); - boolean result = interceptor.handleRequest(context, null); - Assert.assertTrue("Invalid response from interceptor", result); - Assert.assertFalse("Context has response", context.hasResponse()); - } + boolean result = interceptor.handleRequest(context, null); + Assert.assertTrue("Invalid response from interceptor", result); + Assert.assertFalse("Context has response", context.hasResponse()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptorTest.java index cb9f0150..79c47a73 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapActionSmartEndpointInterceptorTest.java @@ -31,46 +31,46 @@ import static org.junit.Assert.assertTrue; public class SoapActionSmartEndpointInterceptorTest { - private EndpointInterceptor delegate; + private EndpointInterceptor delegate; - private String soapAction; + private String soapAction; - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() { - delegate = new EndpointInterceptorAdapter(); + @Before + public void setUp() { + delegate = new EndpointInterceptorAdapter(); - soapAction = "http://springframework.org/spring-ws"; + soapAction = "http://springframework.org/spring-ws"; - SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(); - messageFactory.afterPropertiesSet(); - SaajSoapMessage request = messageFactory.createWebServiceMessage(); - request.setSoapAction(soapAction); - messageContext = new DefaultMessageContext(request, messageFactory); - } + SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(); + messageFactory.afterPropertiesSet(); + SaajSoapMessage request = messageFactory.createWebServiceMessage(); + request.setSoapAction(soapAction); + messageContext = new DefaultMessageContext(request, messageFactory); + } - @Test(expected = IllegalArgumentException.class) - public void neitherNamespaceNorLocalPart() { - new SoapActionSmartEndpointInterceptor(delegate, null); - } + @Test(expected = IllegalArgumentException.class) + public void neitherNamespaceNorLocalPart() { + new SoapActionSmartEndpointInterceptor(delegate, null); + } - @Test - public void shouldInterceptMatch() throws Exception { - SoapActionSmartEndpointInterceptor interceptor = new SoapActionSmartEndpointInterceptor(delegate, soapAction); + @Test + public void shouldInterceptMatch() throws Exception { + SoapActionSmartEndpointInterceptor interceptor = new SoapActionSmartEndpointInterceptor(delegate, soapAction); - boolean result = interceptor.shouldIntercept(messageContext, null); - assertTrue("Interceptor should apply", result); - } + boolean result = interceptor.shouldIntercept(messageContext, null); + assertTrue("Interceptor should apply", result); + } - @Test - public void shouldInterceptNonMatch() throws Exception { - SoapActionSmartEndpointInterceptor interceptor = - new SoapActionSmartEndpointInterceptor(delegate, "http://springframework.org/other"); + @Test + public void shouldInterceptNonMatch() throws Exception { + SoapActionSmartEndpointInterceptor interceptor = + new SoapActionSmartEndpointInterceptor(delegate, "http://springframework.org/other"); - boolean result = interceptor.shouldIntercept(messageContext, null); - assertFalse("Interceptor should apply", result); - } + boolean result = interceptor.shouldIntercept(messageContext, null); + assertFalse("Interceptor should apply", result); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptorTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptorTest.java index bfd5d405..50b4ea9b 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptorTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/interceptor/SoapEnvelopeLoggingInterceptorTest.java @@ -34,104 +34,104 @@ import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; public class SoapEnvelopeLoggingInterceptorTest { - private SoapEnvelopeLoggingInterceptor interceptor; + private SoapEnvelopeLoggingInterceptor interceptor; - private CountingAppender appender; + private CountingAppender appender; - private MessageContext messageContext; + private MessageContext messageContext; - @Before - public void setUp() throws Exception { - interceptor = new SoapEnvelopeLoggingInterceptor(); - appender = new SoapEnvelopeLoggingInterceptorTest.CountingAppender(); - BasicConfigurator.configure(appender); - Logger.getRootLogger().setLevel(Level.DEBUG); - SaajSoapMessageFactory factory = new SaajSoapMessageFactory(); - factory.afterPropertiesSet(); - messageContext = new DefaultMessageContext(factory); - appender.reset(); - } + @Before + public void setUp() throws Exception { + interceptor = new SoapEnvelopeLoggingInterceptor(); + appender = new SoapEnvelopeLoggingInterceptorTest.CountingAppender(); + BasicConfigurator.configure(appender); + Logger.getRootLogger().setLevel(Level.DEBUG); + SaajSoapMessageFactory factory = new SaajSoapMessageFactory(); + factory.afterPropertiesSet(); + messageContext = new DefaultMessageContext(factory); + appender.reset(); + } - @After - public void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - ClassPathResource resource = new ClassPathResource("log4j.properties"); - PropertyConfigurator.configure(resource.getURL()); - } + @After + public void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + ClassPathResource resource = new ClassPathResource("log4j.properties"); + PropertyConfigurator.configure(resource.getURL()); + } - @Test - public void testHandleRequestDisabled() throws Exception { - interceptor.setLogRequest(false); - int eventCount = appender.getCount(); - interceptor.handleRequest(messageContext, null); - Assert.assertEquals("interceptor logged when disabled", appender.getCount(), eventCount); - } + @Test + public void testHandleRequestDisabled() throws Exception { + interceptor.setLogRequest(false); + int eventCount = appender.getCount(); + interceptor.handleRequest(messageContext, null); + Assert.assertEquals("interceptor logged when disabled", appender.getCount(), eventCount); + } - @Test - public void testHandleRequestEnabled() throws Exception { - int eventCount = appender.getCount(); - interceptor.handleRequest(messageContext, null); - Assert.assertTrue("interceptor did not log", appender.getCount() > eventCount); - } + @Test + public void testHandleRequestEnabled() throws Exception { + int eventCount = appender.getCount(); + interceptor.handleRequest(messageContext, null); + Assert.assertTrue("interceptor did not log", appender.getCount() > eventCount); + } - @Test - public void testHandleResponseDisabled() throws Exception { - messageContext.getResponse(); - interceptor.setLogResponse(false); - int eventCount = appender.getCount(); - interceptor.handleResponse(messageContext, null); - Assert.assertEquals("interceptor logged when disabled", appender.getCount(), eventCount); - } + @Test + public void testHandleResponseDisabled() throws Exception { + messageContext.getResponse(); + interceptor.setLogResponse(false); + int eventCount = appender.getCount(); + interceptor.handleResponse(messageContext, null); + Assert.assertEquals("interceptor logged when disabled", appender.getCount(), eventCount); + } - @Test - public void testHandleResponseEnabled() throws Exception { - messageContext.getResponse(); - int eventCount = appender.getCount(); - interceptor.handleResponse(messageContext, null); - Assert.assertTrue("interceptor did not log", appender.getCount() > eventCount); - } + @Test + public void testHandleResponseEnabled() throws Exception { + messageContext.getResponse(); + int eventCount = appender.getCount(); + interceptor.handleResponse(messageContext, null); + Assert.assertTrue("interceptor did not log", appender.getCount() > eventCount); + } - @Test - public void testHandleFaultDisabled() throws Exception { - messageContext.getResponse(); - interceptor.setLogFault(false); - int eventCount = appender.getCount(); - interceptor.handleFault(messageContext, null); - Assert.assertEquals("interceptor logged when disabled", appender.getCount(), eventCount); - } + @Test + public void testHandleFaultDisabled() throws Exception { + messageContext.getResponse(); + interceptor.setLogFault(false); + int eventCount = appender.getCount(); + interceptor.handleFault(messageContext, null); + Assert.assertEquals("interceptor logged when disabled", appender.getCount(), eventCount); + } - @Test - public void testHandleFaultEnabled() throws Exception { - messageContext.getResponse(); - int eventCount = appender.getCount(); - interceptor.handleResponse(messageContext, null); - Assert.assertTrue("interceptor did not log", appender.getCount() > eventCount); - } + @Test + public void testHandleFaultEnabled() throws Exception { + messageContext.getResponse(); + int eventCount = appender.getCount(); + interceptor.handleResponse(messageContext, null); + Assert.assertTrue("interceptor did not log", appender.getCount() > eventCount); + } - private static class CountingAppender extends AppenderSkeleton { + private static class CountingAppender extends AppenderSkeleton { - private int count; + private int count; - public int getCount() { - return count; - } + public int getCount() { + return count; + } - public void reset() { - count = 0; - } + public void reset() { + count = 0; + } - @Override - protected void append(LoggingEvent loggingEvent) { - count++; - } + @Override + protected void append(LoggingEvent loggingEvent) { + count++; + } - @Override - public boolean requiresLayout() { - return false; - } + @Override + public boolean requiresLayout() { + return false; + } - @Override - public void close() { - } - } + @Override + public void close() { + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMappingTest.java index af2ccb88..9e2fbb4d 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/DelegatingSoapEndpointMappingTest.java @@ -31,32 +31,32 @@ import static org.easymock.EasyMock.*; public class DelegatingSoapEndpointMappingTest { - private DelegatingSoapEndpointMapping endpointMapping; + private DelegatingSoapEndpointMapping endpointMapping; - private EndpointMapping mock; + private EndpointMapping mock; - @Before - public void setUp() throws Exception { - endpointMapping = new DelegatingSoapEndpointMapping(); - mock = createMock(EndpointMapping.class); - endpointMapping.setDelegate(mock); - } + @Before + public void setUp() throws Exception { + endpointMapping = new DelegatingSoapEndpointMapping(); + mock = createMock(EndpointMapping.class); + endpointMapping.setDelegate(mock); + } - @Test - public void testGetEndpointMapping() throws Exception { - String role = "http://www.springframework.org/spring-ws/role"; - endpointMapping.setActorOrRole(role); - MessageContext context = new DefaultMessageContext(new MockWebServiceMessageFactory()); - EndpointInvocationChain delegateChain = new EndpointInvocationChain(new Object()); - expect(mock.getEndpoint(context)).andReturn(delegateChain); + @Test + public void testGetEndpointMapping() throws Exception { + String role = "http://www.springframework.org/spring-ws/role"; + endpointMapping.setActorOrRole(role); + MessageContext context = new DefaultMessageContext(new MockWebServiceMessageFactory()); + EndpointInvocationChain delegateChain = new EndpointInvocationChain(new Object()); + expect(mock.getEndpoint(context)).andReturn(delegateChain); - replay(mock); + replay(mock); - SoapEndpointInvocationChain resultChain = (SoapEndpointInvocationChain) endpointMapping.getEndpoint(context); - Assert.assertNotNull("No chain returned", resultChain); - Assert.assertEquals("Invalid ampount of roles returned", 1, resultChain.getActorsOrRoles().length); - Assert.assertEquals("Invalid role returned", role, resultChain.getActorsOrRoles()[0]); + SoapEndpointInvocationChain resultChain = (SoapEndpointInvocationChain) endpointMapping.getEndpoint(context); + Assert.assertNotNull("No chain returned", resultChain); + Assert.assertEquals("Invalid ampount of roles returned", 1, resultChain.getActorsOrRoles().length); + Assert.assertEquals("Invalid role returned", role, resultChain.getActorsOrRoles()[0]); - verify(mock); - } + verify(mock); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMappingTest.java index 292ec54f..b2af407d 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionAnnotationMethodEndpointMappingTest.java @@ -36,101 +36,101 @@ import org.springframework.ws.soap.server.endpoint.annotation.SoapActions; public class SoapActionAnnotationMethodEndpointMappingTest { - private SoapActionAnnotationMethodEndpointMapping mapping; + private SoapActionAnnotationMethodEndpointMapping mapping; - private StaticApplicationContext applicationContext; + private StaticApplicationContext applicationContext; - @Before - public void setUp() throws Exception { - applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("mapping", SoapActionAnnotationMethodEndpointMapping.class); - applicationContext.registerSingleton("endpoint", MyEndpoint.class); - applicationContext.refresh(); - mapping = (SoapActionAnnotationMethodEndpointMapping) applicationContext.getBean("mapping"); - } + @Before + public void setUp() throws Exception { + applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("mapping", SoapActionAnnotationMethodEndpointMapping.class); + applicationContext.registerSingleton("endpoint", MyEndpoint.class); + applicationContext.refresh(); + mapping = (SoapActionAnnotationMethodEndpointMapping) applicationContext.getBean("mapping"); + } - @Test - public void registrationSingle() throws Exception { - SoapMessage requestMock = createMock(SoapMessage.class); - expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction"); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - replay(requestMock, factoryMock); + @Test + public void registrationSingle() throws Exception { + SoapMessage requestMock = createMock(SoapMessage.class); + expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction"); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + replay(requestMock, factoryMock); - MessageContext context = new DefaultMessageContext(requestMock, factoryMock); - EndpointInvocationChain chain = mapping.getEndpoint(context); - Assert.assertNotNull("MethodEndpoint not registered", chain); - Method doIt = MyEndpoint.class.getMethod("doIt", new Class[0]); - MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doIt); - Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); + MessageContext context = new DefaultMessageContext(requestMock, factoryMock); + EndpointInvocationChain chain = mapping.getEndpoint(context); + Assert.assertNotNull("MethodEndpoint not registered", chain); + Method doIt = MyEndpoint.class.getMethod("doIt", new Class[0]); + MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doIt); + Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); - verify(requestMock, factoryMock); - } + verify(requestMock, factoryMock); + } - @Test - public void registrationMultiple() throws Exception { - SoapMessage requestMock = createMock(SoapMessage.class); - expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction1"); - expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction2"); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - replay(requestMock, factoryMock); + @Test + public void registrationMultiple() throws Exception { + SoapMessage requestMock = createMock(SoapMessage.class); + expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction1"); + expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction2"); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + replay(requestMock, factoryMock); - Method doItMultiple = MyEndpoint.class.getMethod("doItMultiple"); - MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple); + Method doItMultiple = MyEndpoint.class.getMethod("doItMultiple"); + MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple); - MessageContext context = new DefaultMessageContext(requestMock, factoryMock); - EndpointInvocationChain chain = mapping.getEndpoint(context); - Assert.assertNotNull("MethodEndpoint not registered", chain); - Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); + MessageContext context = new DefaultMessageContext(requestMock, factoryMock); + EndpointInvocationChain chain = mapping.getEndpoint(context); + Assert.assertNotNull("MethodEndpoint not registered", chain); + Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); - chain = mapping.getEndpoint(context); - Assert.assertNotNull("MethodEndpoint not registered", chain); - Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); + chain = mapping.getEndpoint(context); + Assert.assertNotNull("MethodEndpoint not registered", chain); + Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); - verify(requestMock, factoryMock); - } + verify(requestMock, factoryMock); + } - @Test - public void registrationRepeatable() throws Exception { - SoapMessage requestMock = createMock(SoapMessage.class); - expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction3"); - expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction4"); - WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); - replay(requestMock, factoryMock); + @Test + public void registrationRepeatable() throws Exception { + SoapMessage requestMock = createMock(SoapMessage.class); + expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction3"); + expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction4"); + WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class); + replay(requestMock, factoryMock); - Method doItRepeatable = MyEndpoint.class.getMethod("doItRepeatable"); - MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItRepeatable); + Method doItRepeatable = MyEndpoint.class.getMethod("doItRepeatable"); + MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItRepeatable); - MessageContext context = new DefaultMessageContext(requestMock, factoryMock); - EndpointInvocationChain chain = mapping.getEndpoint(context); - Assert.assertNotNull("MethodEndpoint not registered", chain); - Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); + MessageContext context = new DefaultMessageContext(requestMock, factoryMock); + EndpointInvocationChain chain = mapping.getEndpoint(context); + Assert.assertNotNull("MethodEndpoint not registered", chain); + Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); - chain = mapping.getEndpoint(context); - Assert.assertNotNull("MethodEndpoint not registered", chain); - Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); + chain = mapping.getEndpoint(context); + Assert.assertNotNull("MethodEndpoint not registered", chain); + Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint()); - verify(requestMock, factoryMock); - } + verify(requestMock, factoryMock); + } - @Endpoint - private static class MyEndpoint { + @Endpoint + private static class MyEndpoint { - @SoapAction("http://springframework.org/spring-ws/SoapAction") - public void doIt() { + @SoapAction("http://springframework.org/spring-ws/SoapAction") + public void doIt() { - } + } - @SoapActions({@SoapAction("http://springframework.org/spring-ws/SoapAction1"), - @SoapAction("http://springframework.org/spring-ws/SoapAction2")}) - public void doItMultiple() { - } + @SoapActions({@SoapAction("http://springframework.org/spring-ws/SoapAction1"), + @SoapAction("http://springframework.org/spring-ws/SoapAction2")}) + public void doItMultiple() { + } @SoapAction("http://springframework.org/spring-ws/SoapAction3") @SoapAction("http://springframework.org/spring-ws/SoapAction4") public void doItRepeatable() { - } + } - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMappingTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMappingTest.java index 9c8a3e3e..d07bfaa4 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMappingTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/server/endpoint/mapping/SoapActionEndpointMappingTest.java @@ -29,32 +29,32 @@ import org.junit.Test; public class SoapActionEndpointMappingTest { - private SoapActionEndpointMapping mapping; + private SoapActionEndpointMapping mapping; - private MessageContext context; + private MessageContext context; - @Before - public void setUp() throws Exception { - mapping = new SoapActionEndpointMapping(); - context = new DefaultMessageContext(new SaajSoapMessageFactory(MessageFactory.newInstance())); - } + @Before + public void setUp() throws Exception { + mapping = new SoapActionEndpointMapping(); + context = new DefaultMessageContext(new SaajSoapMessageFactory(MessageFactory.newInstance())); + } - @Test - public void testGetLookupKeyForMessage() throws Exception { - String soapAction = "http://springframework.org/spring-ws/SoapAction"; - ((SoapMessage) context.getRequest()).setSoapAction(soapAction); - Assert.assertEquals("Invalid lookup key", soapAction, mapping.getLookupKeyForMessage(context)); - } + @Test + public void testGetLookupKeyForMessage() throws Exception { + String soapAction = "http://springframework.org/spring-ws/SoapAction"; + ((SoapMessage) context.getRequest()).setSoapAction(soapAction); + Assert.assertEquals("Invalid lookup key", soapAction, mapping.getLookupKeyForMessage(context)); + } - @Test - public void testGetLookupKeyForMessageQuoted() throws Exception { - String soapAction = "http://springframework.org/spring-ws/SoapAction"; - ((SoapMessage) context.getRequest()).setSoapAction(soapAction); - Assert.assertEquals("Invalid lookup key", soapAction, mapping.getLookupKeyForMessage(context)); - } + @Test + public void testGetLookupKeyForMessageQuoted() throws Exception { + String soapAction = "http://springframework.org/spring-ws/SoapAction"; + ((SoapMessage) context.getRequest()).setSoapAction(soapAction); + Assert.assertEquals("Invalid lookup key", soapAction, mapping.getLookupKeyForMessage(context)); + } - @Test - public void testValidateLookupKey() throws Exception { - Assert.assertTrue("Soapaction not valid", mapping.validateLookupKey("SoapAction")); - } + @Test + public void testValidateLookupKey() throws Exception { + Assert.assertTrue("Soapaction not valid", mapping.validateLookupKey("SoapAction")); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11BodyTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11BodyTestCase.java index e4f85a7a..f60c321c 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11BodyTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11BodyTestCase.java @@ -34,124 +34,124 @@ import static org.junit.Assert.*; public abstract class AbstractSoap11BodyTestCase extends AbstractSoapBodyTestCase { - @Test - public void testGetType() { - assertTrue("Invalid type returned", soapBody instanceof Soap11Body); - } + @Test + public void testGetType() { + assertTrue("Invalid type returned", soapBody instanceof Soap11Body); + } - @Test - public void testGetName() throws Exception { - assertEquals("Invalid qualified name", SoapVersion.SOAP_11.getBodyName(), soapBody.getName()); - } + @Test + public void testGetName() throws Exception { + assertEquals("Invalid qualified name", SoapVersion.SOAP_11.getBodyName(), soapBody.getName()); + } - @Test - public void testGetSource() throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapBody.getSource(), result); - assertXMLEqual("Invalid contents of body", "", - result.toString()); - } + @Test + public void testGetSource() throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapBody.getSource(), result); + assertXMLEqual("Invalid contents of body", "", + result.toString()); + } - @Test - public void testAddMustUnderstandFault() throws Exception { - SoapFault fault = soapBody.addMustUnderstandFault("SOAP Must Understand Error", null); - assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "MustUnderstand"), - fault.getFaultCode()); - assertPayloadEqual("" + - "" + soapBody.getName().getPrefix() + ":MustUnderstand" + - "SOAP Must Understand Error"); - } + @Test + public void testAddMustUnderstandFault() throws Exception { + SoapFault fault = soapBody.addMustUnderstandFault("SOAP Must Understand Error", null); + assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "MustUnderstand"), + fault.getFaultCode()); + assertPayloadEqual("" + + "" + soapBody.getName().getPrefix() + ":MustUnderstand" + + "SOAP Must Understand Error"); + } - @Test - public void testAddClientFault() throws Exception { - SoapFault fault = soapBody.addClientOrSenderFault("faultString", null); - assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "Client"), - fault.getFaultCode()); - assertPayloadEqual("" + - "" + soapBody.getName().getPrefix() + ":Client" + - "faultString" + ""); - } + @Test + public void testAddClientFault() throws Exception { + SoapFault fault = soapBody.addClientOrSenderFault("faultString", null); + assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "Client"), + fault.getFaultCode()); + assertPayloadEqual("" + + "" + soapBody.getName().getPrefix() + ":Client" + + "faultString" + ""); + } - @Test - public void testAddServerFault() throws Exception { - SoapFault fault = soapBody.addServerOrReceiverFault("faultString", null); - assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"), - fault.getFaultCode()); - assertPayloadEqual("" + - "" + soapBody.getName().getPrefix() + ":Server" + - "faultString" + ""); - } + @Test + public void testAddServerFault() throws Exception { + SoapFault fault = soapBody.addServerOrReceiverFault("faultString", null); + assertEquals("Invalid fault code", new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"), + fault.getFaultCode()); + assertPayloadEqual("" + + "" + soapBody.getName().getPrefix() + ":Server" + + "faultString" + ""); + } - @Test - public void testAddFault() throws Exception { - QName faultCode = new QName("http://www.springframework.org", "fault", "spring"); - String faultString = "faultString"; - Soap11Fault fault = ((Soap11Body) soapBody).addFault(faultCode, faultString, Locale.ENGLISH); - assertNotNull("Null returned", fault); - assertTrue("SoapBody has no fault", soapBody.hasFault()); - assertNotNull("SoapBody has no fault", soapBody.getFault()); - assertEquals("Invalid fault code", faultCode, fault.getFaultCode()); - assertEquals("Invalid fault string", faultString, fault.getFaultStringOrReason()); - assertEquals("Invalid fault string locale", Locale.ENGLISH, fault.getFaultStringLocale()); - String actor = "http://www.springframework.org/actor"; - fault.setFaultActorOrRole(actor); - assertEquals("Invalid fault actor", actor, fault.getFaultActorOrRole()); - assertPayloadEqual("" + "spring:fault" + - "" + faultString + "" + "" + actor + - "" + ""); - } + @Test + public void testAddFault() throws Exception { + QName faultCode = new QName("http://www.springframework.org", "fault", "spring"); + String faultString = "faultString"; + Soap11Fault fault = ((Soap11Body) soapBody).addFault(faultCode, faultString, Locale.ENGLISH); + assertNotNull("Null returned", fault); + assertTrue("SoapBody has no fault", soapBody.hasFault()); + assertNotNull("SoapBody has no fault", soapBody.getFault()); + assertEquals("Invalid fault code", faultCode, fault.getFaultCode()); + assertEquals("Invalid fault string", faultString, fault.getFaultStringOrReason()); + assertEquals("Invalid fault string locale", Locale.ENGLISH, fault.getFaultStringLocale()); + String actor = "http://www.springframework.org/actor"; + fault.setFaultActorOrRole(actor); + assertEquals("Invalid fault actor", actor, fault.getFaultActorOrRole()); + assertPayloadEqual("" + "spring:fault" + + "" + faultString + "" + "" + actor + + "" + ""); + } - @Test - public void testAddFaultNoPrefix() throws Exception { - QName faultCode = new QName("http://www.springframework.org", "fault"); - String faultString = "faultString"; - Soap11Fault fault = ((Soap11Body) soapBody).addFault(faultCode, faultString, Locale.ENGLISH); - assertNotNull("Null returned", fault); - assertTrue("SoapBody has no fault", soapBody.hasFault()); - assertNotNull("SoapBody has no fault", soapBody.getFault()); - assertEquals("Invalid fault code", faultCode, fault.getFaultCode()); - assertEquals("Invalid fault string", faultString, fault.getFaultStringOrReason()); - assertEquals("Invalid fault string locale", Locale.ENGLISH, fault.getFaultStringLocale()); - String actor = "http://www.springframework.org/actor"; - fault.setFaultActorOrRole(actor); - assertEquals("Invalid fault actor", actor, fault.getFaultActorOrRole()); - } + @Test + public void testAddFaultNoPrefix() throws Exception { + QName faultCode = new QName("http://www.springframework.org", "fault"); + String faultString = "faultString"; + Soap11Fault fault = ((Soap11Body) soapBody).addFault(faultCode, faultString, Locale.ENGLISH); + assertNotNull("Null returned", fault); + assertTrue("SoapBody has no fault", soapBody.hasFault()); + assertNotNull("SoapBody has no fault", soapBody.getFault()); + assertEquals("Invalid fault code", faultCode, fault.getFaultCode()); + assertEquals("Invalid fault string", faultString, fault.getFaultStringOrReason()); + assertEquals("Invalid fault string locale", Locale.ENGLISH, fault.getFaultStringLocale()); + String actor = "http://www.springframework.org/actor"; + fault.setFaultActorOrRole(actor); + assertEquals("Invalid fault actor", actor, fault.getFaultActorOrRole()); + } - @Test - public void testAddFaultWithDetail() throws Exception { - QName faultCode = new QName("http://www.springframework.org", "fault", "spring"); - String faultString = "faultString"; - SoapFault fault = ((Soap11Body) soapBody).addFault(faultCode, faultString, null); - SoapFaultDetail detail = fault.addFaultDetail(); - QName detailName = new QName("http://www.springframework.org", "detailEntry", "spring"); - SoapFaultDetailElement detailElement1 = detail.addFaultDetailElement(detailName); - StringSource detailContents = new StringSource(""); - transformer.transform(detailContents, detailElement1.getResult()); - SoapFaultDetailElement detailElement2 = detail.addFaultDetailElement(detailName); - detailContents = new StringSource(""); - transformer.transform(detailContents, detailElement2.getResult()); - assertPayloadEqual( - "" + - "spring:fault" + "" + faultString + "" + - "" + - "" + - "" + - "" + ""); + @Test + public void testAddFaultWithDetail() throws Exception { + QName faultCode = new QName("http://www.springframework.org", "fault", "spring"); + String faultString = "faultString"; + SoapFault fault = ((Soap11Body) soapBody).addFault(faultCode, faultString, null); + SoapFaultDetail detail = fault.addFaultDetail(); + QName detailName = new QName("http://www.springframework.org", "detailEntry", "spring"); + SoapFaultDetailElement detailElement1 = detail.addFaultDetailElement(detailName); + StringSource detailContents = new StringSource(""); + transformer.transform(detailContents, detailElement1.getResult()); + SoapFaultDetailElement detailElement2 = detail.addFaultDetailElement(detailName); + detailContents = new StringSource(""); + transformer.transform(detailContents, detailElement2.getResult()); + assertPayloadEqual( + "" + + "spring:fault" + "" + faultString + "" + + "" + + "" + + "" + + "" + ""); - } + } - @Test - public void testAddFaultWithDetailResult() throws Exception { - SoapFault fault = ((Soap11Body) soapBody) - .addFault(new QName("namespace", "localPart", "prefix"), "Fault", null); - SoapFaultDetail detail = fault.addFaultDetail(); - transformer.transform(new StringSource(""), detail.getResult()); - transformer.transform(new StringSource(""), detail.getResult()); - assertPayloadEqual("" + - "prefix:localPart" + - "Fault" + "" + "" + - "" + ""); - } + @Test + public void testAddFaultWithDetailResult() throws Exception { + SoapFault fault = ((Soap11Body) soapBody) + .addFault(new QName("namespace", "localPart", "prefix"), "Fault", null); + SoapFaultDetail detail = fault.addFaultDetail(); + transformer.transform(new StringSource(""), detail.getResult()); + transformer.transform(new StringSource(""), detail.getResult()); + assertPayloadEqual("" + + "prefix:localPart" + + "Fault" + "" + "" + + "" + ""); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11EnvelopeTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11EnvelopeTestCase.java index f7d99ad5..ad22fe06 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11EnvelopeTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11EnvelopeTestCase.java @@ -29,19 +29,19 @@ import static org.junit.Assert.assertEquals; public abstract class AbstractSoap11EnvelopeTestCase extends AbstractSoapEnvelopeTestCase { - @Test - public void testGetName() throws Exception { - assertEquals("Invalid qualified name", - new QName(SoapVersion.SOAP_11.getEnvelopeNamespaceUri(), "Envelope"), - soapEnvelope.getName()); - } + @Test + public void testGetName() throws Exception { + assertEquals("Invalid qualified name", + new QName(SoapVersion.SOAP_11.getEnvelopeNamespaceUri(), "Envelope"), + soapEnvelope.getName()); + } - @Test - public void testGetContent() throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapEnvelope.getSource(), result); - assertXMLEqual("

", - result.toString()); - } + @Test + public void testGetContent() throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapEnvelope.getSource(), result); + assertXMLEqual("
", + result.toString()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11HeaderTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11HeaderTestCase.java index 2d8c05a4..dccac032 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11HeaderTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11HeaderTestCase.java @@ -30,71 +30,71 @@ import org.springframework.xml.transform.StringResult; public abstract class AbstractSoap11HeaderTestCase extends AbstractSoapHeaderTestCase { - private static final String PREFIX = "spring"; + private static final String PREFIX = "spring"; - @Test - public void testGetType() { - assertTrue("Invalid type returned", soapHeader instanceof Soap11Header); - } + @Test + public void testGetType() { + assertTrue("Invalid type returned", soapHeader instanceof Soap11Header); + } - @Test - public void testGetName() throws Exception { - assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_11.getEnvelopeNamespaceUri(), "Header"), - soapHeader.getName()); - } + @Test + public void testGetName() throws Exception { + assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_11.getEnvelopeNamespaceUri(), "Header"), + soapHeader.getName()); + } - @Test - public void testGetSource() throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapHeader.getSource(), result); - assertXMLEqual("Invalid contents of header", - "", result.toString()); - } + @Test + public void testGetSource() throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapHeader.getSource(), result); + assertXMLEqual("Invalid contents of header", + "", result.toString()); + } - @Test - public void testExamineHeaderElementsToProcessActors() throws Exception { - QName qName = new QName(NAMESPACE, "localName1", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole("role1"); - qName = new QName(NAMESPACE, "localName2", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole("role2"); - qName = new QName(NAMESPACE, "localName3", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(SoapVersion.SOAP_11.getNextActorOrRoleUri()); - Iterator iterator = ((Soap11Header) soapHeader).examineHeaderElementsToProcess(new String[]{"role1"}); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineHeaderElementsToProcessActors() throws Exception { + QName qName = new QName(NAMESPACE, "localName1", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole("role1"); + qName = new QName(NAMESPACE, "localName2", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole("role2"); + qName = new QName(NAMESPACE, "localName3", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(SoapVersion.SOAP_11.getNextActorOrRoleUri()); + Iterator iterator = ((Soap11Header) soapHeader).examineHeaderElementsToProcess(new String[]{"role1"}); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - @Test - public void testExamineHeaderElementsToProcessNoActors() throws Exception { - QName qName = new QName(NAMESPACE, "localName1", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(""); - qName = new QName(NAMESPACE, "localName2", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole("role1"); - qName = new QName(NAMESPACE, "localName3", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(SoapVersion.SOAP_11.getNextActorOrRoleUri()); - Iterator iterator = ((Soap11Header) soapHeader).examineHeaderElementsToProcess(new String[0]); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineHeaderElementsToProcessNoActors() throws Exception { + QName qName = new QName(NAMESPACE, "localName1", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(""); + qName = new QName(NAMESPACE, "localName2", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole("role1"); + qName = new QName(NAMESPACE, "localName3", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(SoapVersion.SOAP_11.getNextActorOrRoleUri()); + Iterator iterator = ((Soap11Header) soapHeader).examineHeaderElementsToProcess(new String[0]); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - private void checkHeaderElement(SoapHeaderElement headerElement) { - QName name = headerElement.getName(); - assertTrue("Invalid name on header element", new QName(NAMESPACE, "localName1", PREFIX).equals(name) || - new QName(NAMESPACE, "localName3", PREFIX).equals(name)); - } + private void checkHeaderElement(SoapHeaderElement headerElement) { + QName name = headerElement.getName(); + assertTrue("Invalid name on header element", new QName(NAMESPACE, "localName1", PREFIX).equals(name) || + new QName(NAMESPACE, "localName3", PREFIX).equals(name)); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageFactoryTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageFactoryTestCase.java index dd8e0679..d9c3a160 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageFactoryTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageFactoryTestCase.java @@ -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, @@ -35,135 +35,135 @@ import static org.junit.Assert.*; public abstract class AbstractSoap11MessageFactoryTestCase extends AbstractSoapMessageFactoryTestCase { - @Test - public void testCreateEmptySoap11Message() throws Exception { - WebServiceMessage message = messageFactory.createWebServiceMessage(); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); - } + @Test + public void testCreateEmptySoap11Message() throws Exception { + WebServiceMessage message = messageFactory.createWebServiceMessage(); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); + } - @Override - public void testCreateSoapMessageNoAttachment() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11.xml"); - Map headers = new HashMap(); - headers.put("Content-Type", "text/xml"); - String soapAction = "\"http://springframework.org/spring-ws/Action\""; - headers.put("SOAPAction", soapAction); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageNoAttachment() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11.xml"); + Map headers = new HashMap(); + headers.put("Content-Type", "text/xml"); + String soapAction = "\"http://springframework.org/spring-ws/Action\""; + headers.put("SOAPAction", soapAction); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); - assertEquals("Invalid soap action", soapAction, soapMessage.getSoapAction()); - assertFalse("Message a XOP pacakge", soapMessage.isXopPackage()); - } + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); + assertEquals("Invalid soap action", soapAction, soapMessage.getSoapAction()); + assertFalse("Message a XOP pacakge", soapMessage.isXopPackage()); + } - @Override - public void testCreateSoapMessageIllFormedXml() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-ill-formed.xml"); - Map headers = new HashMap(); - headers.put("Content-Type", "text/xml"); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageIllFormedXml() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-ill-formed.xml"); + Map headers = new HashMap(); + headers.put("Content-Type", "text/xml"); + TransportInputStream tis = new MockTransportInputStream(is, headers); - messageFactory.createWebServiceMessage(tis); - } + messageFactory.createWebServiceMessage(tis); + } - @Override - public void testCreateSoapMessageSwA() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-attachment.bin"); - Map headers = new HashMap(); - headers.put("Content-Type", - "multipart/related;" + "type=\"text/xml\";" + "boundary=\"----=_Part_0_11416420.1149699787554\""); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageSwA() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-attachment.bin"); + Map headers = new HashMap(); + headers.put("Content-Type", + "multipart/related;" + "type=\"text/xml\";" + "boundary=\"----=_Part_0_11416420.1149699787554\""); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); - assertFalse("Message a XOP package", soapMessage.isXopPackage()); - Iterator iter = soapMessage.getAttachments(); - assertTrue("No attachments read", iter.hasNext()); - Attachment attachment = soapMessage.getAttachment("interface21"); - assertNotNull("No attachment read", attachment); - assertEquals("Invalid content id", "interface21", attachment.getContentId()); - } + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); + assertFalse("Message a XOP package", soapMessage.isXopPackage()); + Iterator iter = soapMessage.getAttachments(); + assertTrue("No attachments read", iter.hasNext()); + Attachment attachment = soapMessage.getAttachment("interface21"); + assertNotNull("No attachment read", attachment); + assertEquals("Invalid content id", "interface21", attachment.getContentId()); + } - @Override - public void testCreateSoapMessageMtom() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-mtom.bin"); - Map headers = new HashMap(); - headers.put("Content-Type", "multipart/related;" + "start-info=\"text/xml\";" + - "type=\"application/xop+xml\";" + "start=\"<0.urn:uuid:492264AB42E57108E01176731445508@apache.org>\";" + - "boundary=\"MIMEBoundaryurn_uuid_492264AB42E57108E01176731445507\""); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageMtom() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-mtom.bin"); + Map headers = new HashMap(); + headers.put("Content-Type", "multipart/related;" + "start-info=\"text/xml\";" + + "type=\"application/xop+xml\";" + "start=\"<0.urn:uuid:492264AB42E57108E01176731445508@apache.org>\";" + + "boundary=\"MIMEBoundaryurn_uuid_492264AB42E57108E01176731445507\""); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); - assertTrue("Message not a XOP package", soapMessage.isXopPackage()); - Iterator iter = soapMessage.getAttachments(); - assertTrue("No attachments read", iter.hasNext()); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); + assertTrue("Message not a XOP package", soapMessage.isXopPackage()); + Iterator iter = soapMessage.getAttachments(); + assertTrue("No attachments read", iter.hasNext()); - Attachment attachment = soapMessage.getAttachment("<1.urn:uuid:492264AB42E57108E01176731445504@apache.org>"); - assertNotNull("No attachment read", attachment); - } + Attachment attachment = soapMessage.getAttachment("<1.urn:uuid:492264AB42E57108E01176731445504@apache.org>"); + assertNotNull("No attachment read", attachment); + } - @Test - public void testCreateSoapMessageMtomWeirdStartInfo() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-mtom.bin"); - Map headers = new HashMap(); - headers.put("Content-Type", "multipart/related;" + "startinfo=\"text/xml\";" + - "type=\"application/xop+xml\";" + "start=\"<0.urn:uuid:492264AB42E57108E01176731445508@apache.org>\";" + - "boundary=\"MIMEBoundaryurn_uuid_492264AB42E57108E01176731445507\""); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Test + public void testCreateSoapMessageMtomWeirdStartInfo() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-mtom.bin"); + Map headers = new HashMap(); + headers.put("Content-Type", "multipart/related;" + "startinfo=\"text/xml\";" + + "type=\"application/xop+xml\";" + "start=\"<0.urn:uuid:492264AB42E57108E01176731445508@apache.org>\";" + + "boundary=\"MIMEBoundaryurn_uuid_492264AB42E57108E01176731445507\""); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); - assertTrue("Message not a XOP package", soapMessage.isXopPackage()); - Iterator iter = soapMessage.getAttachments(); - assertTrue("No attachments read", iter.hasNext()); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_11, soapMessage.getVersion()); + assertTrue("Message not a XOP package", soapMessage.isXopPackage()); + Iterator iter = soapMessage.getAttachments(); + assertTrue("No attachments read", iter.hasNext()); - Attachment attachment = soapMessage.getAttachment("<1.urn:uuid:492264AB42E57108E01176731445504@apache.org>"); - assertNotNull("No attachment read", attachment); - } + Attachment attachment = soapMessage.getAttachment("<1.urn:uuid:492264AB42E57108E01176731445504@apache.org>"); + assertNotNull("No attachment read", attachment); + } - @Test - public void testCreateSoapMessageUtf8ByteOrderMark() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-utf8-bom.xml"); - Map headers = new HashMap(); - headers.put("Content-Type", "text/xml; charset=UTF-8"); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Test + public void testCreateSoapMessageUtf8ByteOrderMark() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-utf8-bom.xml"); + Map headers = new HashMap(); + headers.put("Content-Type", "text/xml; charset=UTF-8"); + TransportInputStream tis = new MockTransportInputStream(is, headers); - SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(tis); - assertEquals("Invalid soap version", SoapVersion.SOAP_11, message.getVersion()); - } + SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(tis); + assertEquals("Invalid soap version", SoapVersion.SOAP_11, message.getVersion()); + } - @Test - public void testCreateSoapMessageUtf16BigEndianByteOrderMark() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-utf16-be-bom.xml"); - Map headers = new HashMap(); - headers.put("Content-Type", "text/xml; charset=UTF-16"); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Test + public void testCreateSoapMessageUtf16BigEndianByteOrderMark() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-utf16-be-bom.xml"); + Map headers = new HashMap(); + headers.put("Content-Type", "text/xml; charset=UTF-16"); + TransportInputStream tis = new MockTransportInputStream(is, headers); - SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(tis); - assertEquals("Invalid soap version", SoapVersion.SOAP_11, message.getVersion()); - } + SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(tis); + assertEquals("Invalid soap version", SoapVersion.SOAP_11, message.getVersion()); + } - @Test - public void testCreateSoapMessageUtf16LittleEndianByteOrderMark() throws Exception { - InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-utf16-le-bom.xml"); - Map headers = new HashMap(); - headers.put("Content-Type", "text/xml; charset=UTF-16"); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Test + public void testCreateSoapMessageUtf16LittleEndianByteOrderMark() throws Exception { + InputStream is = AbstractSoap11MessageFactoryTestCase.class.getResourceAsStream("soap11-utf16-le-bom.xml"); + Map headers = new HashMap(); + headers.put("Content-Type", "text/xml; charset=UTF-16"); + TransportInputStream tis = new MockTransportInputStream(is, headers); - SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(tis); - assertEquals("Invalid soap version", SoapVersion.SOAP_11, message.getVersion()); - } + SoapMessage message = (SoapMessage) messageFactory.createWebServiceMessage(tis); + assertEquals("Invalid soap version", SoapVersion.SOAP_11, message.getVersion()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageTestCase.java index f77c863d..3f405f1f 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap11/AbstractSoap11MessageTestCase.java @@ -41,115 +41,115 @@ import org.springframework.xml.transform.StringSource; public abstract class AbstractSoap11MessageTestCase extends AbstractSoapMessageTestCase { - @Override - protected final Resource[] getSoapSchemas() { - return new Resource[]{new ClassPathResource("soap11.xsd", AbstractSoap11MessageTestCase.class)}; - } + @Override + protected final Resource[] getSoapSchemas() { + return new Resource[]{new ClassPathResource("soap11.xsd", AbstractSoap11MessageTestCase.class)}; + } - @Override - public void testGetVersion() throws Exception { - Assert.assertEquals("Invalid SOAP version", SoapVersion.SOAP_11, soapMessage.getVersion()); - } + @Override + public void testGetVersion() throws Exception { + Assert.assertEquals("Invalid SOAP version", SoapVersion.SOAP_11, soapMessage.getVersion()); + } - @Override - public void testWriteToTransportOutputStream() throws Exception { - SoapBody body = soapMessage.getSoapBody(); - String payload = ""; - transformer.transform(new StringSource(payload), body.getPayloadResult()); + @Override + public void testWriteToTransportOutputStream() throws Exception { + SoapBody body = soapMessage.getSoapBody(); + String payload = ""; + transformer.transform(new StringSource(payload), body.getPayloadResult()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - MockTransportOutputStream tos = new MockTransportOutputStream(bos); - String soapAction = "http://springframework.org/spring-ws/Action"; - soapMessage.setSoapAction(soapAction); - soapMessage.writeTo(tos); - String result = bos.toString("UTF-8"); - assertXMLEqual( - "", - result); - String contentType = tos.getHeaders().get("Content-Type"); - assertTrue("Invalid Content-Type set", contentType.indexOf(SoapVersion.SOAP_11.getContentType()) != -1); - String resultSoapAction = tos.getHeaders().get("SOAPAction"); - assertEquals("Invalid soap action", "\"" + soapAction + "\"", resultSoapAction); - String resultAccept = tos.getHeaders().get("Accept"); - assertNotNull("Invalid accept header", resultAccept); - } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + MockTransportOutputStream tos = new MockTransportOutputStream(bos); + String soapAction = "http://springframework.org/spring-ws/Action"; + soapMessage.setSoapAction(soapAction); + soapMessage.writeTo(tos); + String result = bos.toString("UTF-8"); + assertXMLEqual( + "", + result); + String contentType = tos.getHeaders().get("Content-Type"); + assertTrue("Invalid Content-Type set", contentType.indexOf(SoapVersion.SOAP_11.getContentType()) != -1); + String resultSoapAction = tos.getHeaders().get("SOAPAction"); + assertEquals("Invalid soap action", "\"" + soapAction + "\"", resultSoapAction); + String resultAccept = tos.getHeaders().get("Accept"); + assertNotNull("Invalid accept header", resultAccept); + } - @Override - public void testWriteToTransportResponseAttachment() throws Exception { - InputStreamSource inputStreamSource = new ByteArrayResource("contents".getBytes("UTF-8")); - soapMessage.addAttachment("contentId", inputStreamSource, "text/plain"); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - MockTransportOutputStream tos = new MockTransportOutputStream(bos); - soapMessage.writeTo(tos); - String contentType = tos.getHeaders().get("Content-Type"); - assertTrue("Content-Type for attachment message does not contains multipart/related", - contentType.indexOf("multipart/related") != -1); - assertTrue("Content-Type for attachment message does not contains type=\"text/xml\"", - contentType.indexOf("type=\"text/xml\"") != -1); - } + @Override + public void testWriteToTransportResponseAttachment() throws Exception { + InputStreamSource inputStreamSource = new ByteArrayResource("contents".getBytes("UTF-8")); + soapMessage.addAttachment("contentId", inputStreamSource, "text/plain"); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + MockTransportOutputStream tos = new MockTransportOutputStream(bos); + soapMessage.writeTo(tos); + String contentType = tos.getHeaders().get("Content-Type"); + assertTrue("Content-Type for attachment message does not contains multipart/related", + contentType.indexOf("multipart/related") != -1); + assertTrue("Content-Type for attachment message does not contains type=\"text/xml\"", + contentType.indexOf("type=\"text/xml\"") != -1); + } - @Override - public void testToDocument() throws Exception { - transformer.transform(new StringSource(""), - soapMessage.getSoapBody().getPayloadResult()); + @Override + public void testToDocument() throws Exception { + transformer.transform(new StringSource(""), + soapMessage.getSoapBody().getPayloadResult()); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expected = documentBuilder.newDocument(); - Element envelope = expected.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "Envelope"); - expected.appendChild(envelope); - Element body = expected.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "Body"); - envelope.appendChild(body); - Element payload = expected.createElementNS("http://www.springframework.org", "payload"); - body.appendChild(payload); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expected = documentBuilder.newDocument(); + Element envelope = expected.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "Envelope"); + expected.appendChild(envelope); + Element body = expected.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "Body"); + envelope.appendChild(body); + Element payload = expected.createElementNS("http://www.springframework.org", "payload"); + body.appendChild(payload); - Document result = soapMessage.getDocument(); + Document result = soapMessage.getDocument(); - assertXMLEqual(expected, result); - } + assertXMLEqual(expected, result); + } - @Override - public void testSetLiveDocument() throws Exception { - transformer.transform(new StringSource(""), - soapMessage.getSoapBody().getPayloadResult()); + @Override + public void testSetLiveDocument() throws Exception { + transformer.transform(new StringSource(""), + soapMessage.getSoapBody().getPayloadResult()); - Document document = soapMessage.getDocument(); + Document document = soapMessage.getDocument(); - soapMessage.setDocument(document); + soapMessage.setDocument(document); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - soapMessage.writeTo(bos); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + soapMessage.writeTo(bos); - String result = bos.toString("UTF-8"); - assertXMLEqual( - "", - result); - } + String result = bos.toString("UTF-8"); + assertXMLEqual( + "", + result); + } - @Override - public void testSetOtherDocument() throws Exception { - transformer.transform(new StringSource(""), - soapMessage.getSoapBody().getPayloadResult()); + @Override + public void testSetOtherDocument() throws Exception { + transformer.transform(new StringSource(""), + soapMessage.getSoapBody().getPayloadResult()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - soapMessage.writeTo(bos); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + soapMessage.writeTo(bos); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - DOMResult domResult = new DOMResult(); - transformer.transform(new StreamSource(bis), domResult); + DOMResult domResult = new DOMResult(); + transformer.transform(new StreamSource(bis), domResult); - Document document = (Document) domResult.getNode(); + Document document = (Document) domResult.getNode(); - soapMessage.setDocument(document); + soapMessage.setDocument(document); - bos = new ByteArrayOutputStream(); - soapMessage.writeTo(bos); + bos = new ByteArrayOutputStream(); + soapMessage.writeTo(bos); - String result = bos.toString("UTF-8"); - assertXMLEqual( - "", - result); - } + String result = bos.toString("UTF-8"); + assertXMLEqual( + "", + result); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12BodyTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12BodyTestCase.java index 0383a715..a2ce13e1 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12BodyTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12BodyTestCase.java @@ -35,129 +35,129 @@ import static org.junit.Assert.*; public abstract class AbstractSoap12BodyTestCase extends AbstractSoapBodyTestCase { - @Test - public void testGetType() { - assertTrue("Invalid type returned", soapBody instanceof Soap12Body); - } + @Test + public void testGetType() { + assertTrue("Invalid type returned", soapBody instanceof Soap12Body); + } - @Test - public void testGetName() throws Exception { - assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "Body"), - soapBody.getName()); - } + @Test + public void testGetName() throws Exception { + assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "Body"), + soapBody.getName()); + } - @Test - public void testGetSource() throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapBody.getSource(), result); - assertXMLEqual("Invalid contents of body", "", - result.toString()); - } + @Test + public void testGetSource() throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapBody.getSource(), result); + assertXMLEqual("Invalid contents of body", "", + result.toString()); + } - @Test - public void testAddMustUnderstandFault() throws Exception { - SoapFault fault = soapBody.addMustUnderstandFault("SOAP Must Understand Error", Locale.ENGLISH); - assertEquals("Invalid fault code", new QName("http://www.w3.org/2003/05/soap-envelope", "MustUnderstand"), - fault.getFaultCode()); - StringResult result = new StringResult(); - transformer.transform(fault.getSource(), result); - assertXMLEqual("Invalid contents of body", - "" + - "" + soapBody.getName().getPrefix() + - ":MustUnderstand" + - "SOAP Must Understand Error" + - "", result.toString()); - } + @Test + public void testAddMustUnderstandFault() throws Exception { + SoapFault fault = soapBody.addMustUnderstandFault("SOAP Must Understand Error", Locale.ENGLISH); + assertEquals("Invalid fault code", new QName("http://www.w3.org/2003/05/soap-envelope", "MustUnderstand"), + fault.getFaultCode()); + StringResult result = new StringResult(); + transformer.transform(fault.getSource(), result); + assertXMLEqual("Invalid contents of body", + "" + + "" + soapBody.getName().getPrefix() + + ":MustUnderstand" + + "SOAP Must Understand Error" + + "", result.toString()); + } - @Test - public void testAddSenderFault() throws Exception { - SoapFault fault = soapBody.addClientOrSenderFault("faultString", Locale.ENGLISH); - assertEquals("Invalid fault code", new QName("http://www.w3.org/2003/05/soap-envelope", "Sender"), - fault.getFaultCode()); - StringResult result = new StringResult(); - transformer.transform(fault.getSource(), result); - assertXMLEqual("Invalid contents of body", - "" + - "" + soapBody.getName().getPrefix() + - ":Sender" + - "faultString" + - "", result.toString()); - } + @Test + public void testAddSenderFault() throws Exception { + SoapFault fault = soapBody.addClientOrSenderFault("faultString", Locale.ENGLISH); + assertEquals("Invalid fault code", new QName("http://www.w3.org/2003/05/soap-envelope", "Sender"), + fault.getFaultCode()); + StringResult result = new StringResult(); + transformer.transform(fault.getSource(), result); + assertXMLEqual("Invalid contents of body", + "" + + "" + soapBody.getName().getPrefix() + + ":Sender" + + "faultString" + + "", result.toString()); + } - @Test - public void testAddReceiverFault() throws Exception { - SoapFault fault = soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); - assertEquals("Invalid fault code", new QName("http://www.w3.org/2003/05/soap-envelope", "Receiver"), - fault.getFaultCode()); - StringResult result = new StringResult(); - transformer.transform(fault.getSource(), result); - assertXMLEqual("Invalid contents of body", - "" + - "" + soapBody.getName().getPrefix() + - ":Receiver" + - "faultString" + - "", result.toString()); - } + @Test + public void testAddReceiverFault() throws Exception { + SoapFault fault = soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); + assertEquals("Invalid fault code", new QName("http://www.w3.org/2003/05/soap-envelope", "Receiver"), + fault.getFaultCode()); + StringResult result = new StringResult(); + transformer.transform(fault.getSource(), result); + assertXMLEqual("Invalid contents of body", + "" + + "" + soapBody.getName().getPrefix() + + ":Receiver" + + "faultString" + + "", result.toString()); + } - @Test - public void testAddFaultWithDetail() throws Exception { - SoapFault fault = soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); - SoapFaultDetail detail = fault.addFaultDetail(); - SoapFaultDetailElement detailElement = - detail.addFaultDetailElement(new QName("namespace", "localPart", "prefix")); - StringSource detailContents = new StringSource(""); - transformer.transform(detailContents, detailElement.getResult()); - StringResult result = new StringResult(); - transformer.transform(fault.getSource(), result); - assertXMLEqual("Invalid source for body", - "" + - "" + soapBody.getName().getPrefix() + ":Receiver" + - "" + - "faultString" + - "" + - "", result.toString()); - } + @Test + public void testAddFaultWithDetail() throws Exception { + SoapFault fault = soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); + SoapFaultDetail detail = fault.addFaultDetail(); + SoapFaultDetailElement detailElement = + detail.addFaultDetailElement(new QName("namespace", "localPart", "prefix")); + StringSource detailContents = new StringSource(""); + transformer.transform(detailContents, detailElement.getResult()); + StringResult result = new StringResult(); + transformer.transform(fault.getSource(), result); + assertXMLEqual("Invalid source for body", + "" + + "" + soapBody.getName().getPrefix() + ":Receiver" + + "" + + "faultString" + + "" + + "", result.toString()); + } - @Test - public void testAddFaultWithDetailResult() throws Exception { - SoapFault fault = soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); - SoapFaultDetail detail = fault.addFaultDetail(); - transformer.transform(new StringSource(""), detail.getResult()); - transformer.transform(new StringSource(""), detail.getResult()); - StringResult result = new StringResult(); - transformer.transform(fault.getSource(), result); - assertXMLEqual("Invalid source for body", - "" + - "" + soapBody.getName().getPrefix() + ":Receiver" + - "" + - "faultString" + - "" + "" + - "" + "", result.toString()); - } + @Test + public void testAddFaultWithDetailResult() throws Exception { + SoapFault fault = soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); + SoapFaultDetail detail = fault.addFaultDetail(); + transformer.transform(new StringSource(""), detail.getResult()); + transformer.transform(new StringSource(""), detail.getResult()); + StringResult result = new StringResult(); + transformer.transform(fault.getSource(), result); + assertXMLEqual("Invalid source for body", + "" + + "" + soapBody.getName().getPrefix() + ":Receiver" + + "" + + "faultString" + + "" + "" + + "" + "", result.toString()); + } - @Test - public void testAddFaultWithSubcode() throws Exception { - Soap12Fault fault = (Soap12Fault) soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); - QName subcode1 = new QName("http://www.springframework.org", "Subcode1", "spring-ws"); - fault.addFaultSubcode(subcode1); - QName subcode2 = new QName("http://www.springframework.org", "Subcode2", "spring-ws"); - fault.addFaultSubcode(subcode2); - Iterator iterator = fault.getFaultSubcodes(); - assertTrue("No subcode found", iterator.hasNext()); - assertEquals("Invalid subcode", subcode1, iterator.next()); - assertTrue("No subcode found", iterator.hasNext()); - assertEquals("Invalid subcode", subcode2, iterator.next()); - assertFalse("Subcode found", iterator.hasNext()); - StringResult result = new StringResult(); - transformer.transform(fault.getSource(), result); - assertXMLEqual("Invalid source for body", - "" + - "" + soapBody.getName().getPrefix() + ":Receiver" + - "spring-ws:Subcode1" + - "spring-ws:Subcode2" + - "" + - "faultString" + - "", result.toString()); - } + @Test + public void testAddFaultWithSubcode() throws Exception { + Soap12Fault fault = (Soap12Fault) soapBody.addServerOrReceiverFault("faultString", Locale.ENGLISH); + QName subcode1 = new QName("http://www.springframework.org", "Subcode1", "spring-ws"); + fault.addFaultSubcode(subcode1); + QName subcode2 = new QName("http://www.springframework.org", "Subcode2", "spring-ws"); + fault.addFaultSubcode(subcode2); + Iterator iterator = fault.getFaultSubcodes(); + assertTrue("No subcode found", iterator.hasNext()); + assertEquals("Invalid subcode", subcode1, iterator.next()); + assertTrue("No subcode found", iterator.hasNext()); + assertEquals("Invalid subcode", subcode2, iterator.next()); + assertFalse("Subcode found", iterator.hasNext()); + StringResult result = new StringResult(); + transformer.transform(fault.getSource(), result); + assertXMLEqual("Invalid source for body", + "" + + "" + soapBody.getName().getPrefix() + ":Receiver" + + "spring-ws:Subcode1" + + "spring-ws:Subcode2" + + "" + + "faultString" + + "", result.toString()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12EnvelopeTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12EnvelopeTestCase.java index a97656ea..4e836e29 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12EnvelopeTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12EnvelopeTestCase.java @@ -29,18 +29,18 @@ import static org.junit.Assert.assertEquals; public abstract class AbstractSoap12EnvelopeTestCase extends AbstractSoapEnvelopeTestCase { - @Test - public void testGetName() throws Exception { - assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "Envelope"), - soapEnvelope.getName()); - } + @Test + public void testGetName() throws Exception { + assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "Envelope"), + soapEnvelope.getName()); + } - @Test - public void testGetSource() throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapEnvelope.getSource(), result); - assertXMLEqual("
" + "", - result.toString()); - } + @Test + public void testGetSource() throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapEnvelope.getSource(), result); + assertXMLEqual("
" + "", + result.toString()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12HeaderTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12HeaderTestCase.java index fc6d3fc6..df16127e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12HeaderTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12HeaderTestCase.java @@ -30,114 +30,114 @@ import org.springframework.xml.transform.StringResult; public abstract class AbstractSoap12HeaderTestCase extends AbstractSoapHeaderTestCase { - @Test - public void testGetType() { - assertTrue("Invalid type returned", soapHeader instanceof Soap12Header); - } + @Test + public void testGetType() { + assertTrue("Invalid type returned", soapHeader instanceof Soap12Header); + } - @Test - public void testGetName() throws Exception { - assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "Header"), - soapHeader.getName()); - } + @Test + public void testGetName() throws Exception { + assertEquals("Invalid qualified name", new QName(SoapVersion.SOAP_12.getEnvelopeNamespaceUri(), "Header"), + soapHeader.getName()); + } - @Test - public void testGetSource() throws Exception { - StringResult result = new StringResult(); - transformer.transform(soapHeader.getSource(), result); - assertXMLEqual("Invalid contents of header", "
", - result.toString()); - } + @Test + public void testGetSource() throws Exception { + StringResult result = new StringResult(); + transformer.transform(soapHeader.getSource(), result); + assertXMLEqual("Invalid contents of header", "
", + result.toString()); + } - @Test - public void testAddNotUnderstood() throws Exception { - Soap12Header soap12Header = (Soap12Header) soapHeader; - QName headerName = new QName("http://www.springframework.org", "NotUnderstood", "spring-ws"); - soap12Header.addNotUnderstoodHeaderElement(headerName); - StringResult result = new StringResult(); - transformer.transform(soapHeader.getSource(), result); - assertXMLEqual("Invalid contents of header", "
" + - "" + - "
", result.toString()); - } + @Test + public void testAddNotUnderstood() throws Exception { + Soap12Header soap12Header = (Soap12Header) soapHeader; + QName headerName = new QName("http://www.springframework.org", "NotUnderstood", "spring-ws"); + soap12Header.addNotUnderstoodHeaderElement(headerName); + StringResult result = new StringResult(); + transformer.transform(soapHeader.getSource(), result); + assertXMLEqual("Invalid contents of header", "
" + + "" + + "
", result.toString()); + } - @Test - public void testAddUpgrade() throws Exception { - String[] supportedUris = - new String[]{"http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/2003/05/soap-envelope"}; - Soap12Header soap12Header = (Soap12Header) soapHeader; - SoapHeaderElement header = soap12Header.addUpgradeHeaderElement(supportedUris); - StringResult result = new StringResult(); - transformer.transform(soapHeader.getSource(), result); - assertEquals("Invalid name", header.getName(), new QName("http://www.w3.org/2003/05/soap-envelope", "Upgrade")); - // XMLUnit can't test this: + @Test + public void testAddUpgrade() throws Exception { + String[] supportedUris = + new String[]{"http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/2003/05/soap-envelope"}; + Soap12Header soap12Header = (Soap12Header) soapHeader; + SoapHeaderElement header = soap12Header.addUpgradeHeaderElement(supportedUris); + StringResult result = new StringResult(); + transformer.transform(soapHeader.getSource(), result); + assertEquals("Invalid name", header.getName(), new QName("http://www.w3.org/2003/05/soap-envelope", "Upgrade")); + // XMLUnit can't test this: /* - assertXMLEqual("Invalid contents of header", "
" + - "" + - "" + - "" + - "" + - "
", result.toString()); + assertXMLEqual("Invalid contents of header", "
" + + "" + + "" + + "" + + "" + + "
", result.toString()); */ - } + } - @Test - public void testExamineHeaderElementsToProcessActors() throws Exception { - QName qName = new QName(NAMESPACE, "localName1", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole("role1"); - qName = new QName(NAMESPACE, "localName2", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole("role2"); - qName = new QName(NAMESPACE, "localName3", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(SoapVersion.SOAP_12.getNextActorOrRoleUri()); - Iterator iterator = ((Soap12Header) soapHeader).examineHeaderElementsToProcess(new String[]{"role1"}, false); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineHeaderElementsToProcessActors() throws Exception { + QName qName = new QName(NAMESPACE, "localName1", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole("role1"); + qName = new QName(NAMESPACE, "localName2", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole("role2"); + qName = new QName(NAMESPACE, "localName3", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(SoapVersion.SOAP_12.getNextActorOrRoleUri()); + Iterator iterator = ((Soap12Header) soapHeader).examineHeaderElementsToProcess(new String[]{"role1"}, false); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - @Test - public void testExamineHeaderElementsToProcessNoActors() throws Exception { - QName qName = new QName(NAMESPACE, "localName1", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(""); - qName = new QName(NAMESPACE, "localName2", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole("role1"); - qName = new QName(NAMESPACE, "localName3", PREFIX); - headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(SoapVersion.SOAP_12.getNextActorOrRoleUri()); - Iterator iterator = ((Soap12Header) soapHeader).examineHeaderElementsToProcess(new String[0], false); - assertNotNull("header element iterator is null", iterator); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertTrue("header element iterator has no elements", iterator.hasNext()); - checkHeaderElement(iterator.next()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineHeaderElementsToProcessNoActors() throws Exception { + QName qName = new QName(NAMESPACE, "localName1", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(""); + qName = new QName(NAMESPACE, "localName2", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole("role1"); + qName = new QName(NAMESPACE, "localName3", PREFIX); + headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(SoapVersion.SOAP_12.getNextActorOrRoleUri()); + Iterator iterator = ((Soap12Header) soapHeader).examineHeaderElementsToProcess(new String[0], false); + assertNotNull("header element iterator is null", iterator); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertTrue("header element iterator has no elements", iterator.hasNext()); + checkHeaderElement(iterator.next()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - @Test - public void testExamineHeaderElementsToProcessUltimateDestination() throws Exception { - QName qName = new QName(NAMESPACE, "localName", PREFIX); - SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); - headerElement.setActorOrRole(SoapVersion.SOAP_12.getUltimateReceiverRoleUri()); - Iterator iterator = ((Soap12Header) soapHeader).examineHeaderElementsToProcess(new String[]{"role"}, true); - assertNotNull("header element iterator is null", iterator); - headerElement = iterator.next(); - assertEquals("Invalid name on header element", new QName(NAMESPACE, "localName", PREFIX), - headerElement.getName()); - assertFalse("header element iterator has too many elements", iterator.hasNext()); - } + @Test + public void testExamineHeaderElementsToProcessUltimateDestination() throws Exception { + QName qName = new QName(NAMESPACE, "localName", PREFIX); + SoapHeaderElement headerElement = soapHeader.addHeaderElement(qName); + headerElement.setActorOrRole(SoapVersion.SOAP_12.getUltimateReceiverRoleUri()); + Iterator iterator = ((Soap12Header) soapHeader).examineHeaderElementsToProcess(new String[]{"role"}, true); + assertNotNull("header element iterator is null", iterator); + headerElement = iterator.next(); + assertEquals("Invalid name on header element", new QName(NAMESPACE, "localName", PREFIX), + headerElement.getName()); + assertFalse("header element iterator has too many elements", iterator.hasNext()); + } - private void checkHeaderElement(SoapHeaderElement headerElement) { - QName name = headerElement.getName(); - assertTrue("Invalid name on header element", new QName(NAMESPACE, "localName1", PREFIX).equals(name) || - new QName(NAMESPACE, "localName3", PREFIX).equals(name)); - } + private void checkHeaderElement(SoapHeaderElement headerElement) { + QName name = headerElement.getName(); + assertTrue("Invalid name on header element", new QName(NAMESPACE, "localName1", PREFIX).equals(name) || + new QName(NAMESPACE, "localName3", PREFIX).equals(name)); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageFactoryTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageFactoryTestCase.java index 2b3f7f17..b46bb6aa 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageFactoryTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageFactoryTestCase.java @@ -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,78 +34,78 @@ import static org.junit.Assert.*; public abstract class AbstractSoap12MessageFactoryTestCase extends AbstractSoapMessageFactoryTestCase { - @Override - public void testCreateEmptyMessage() throws Exception { - WebServiceMessage message = messageFactory.createWebServiceMessage(); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); - } + @Override + public void testCreateEmptyMessage() throws Exception { + WebServiceMessage message = messageFactory.createWebServiceMessage(); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); + } - @Override - public void testCreateSoapMessageNoAttachment() throws Exception { - InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12.xml"); - Map headers = new HashMap(); - String soapAction = "\"http://springframework.org/spring-ws/Action\""; - headers.put(TransportConstants.HEADER_CONTENT_TYPE, "application/soap+xml; action=" + soapAction); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageNoAttachment() throws Exception { + InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12.xml"); + Map headers = new HashMap(); + String soapAction = "\"http://springframework.org/spring-ws/Action\""; + headers.put(TransportConstants.HEADER_CONTENT_TYPE, "application/soap+xml; action=" + soapAction); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); - assertEquals("Invalid soap action", soapAction, soapMessage.getSoapAction()); - assertFalse("Message is a XOP pacakge", soapMessage.isXopPackage()); - } + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); + assertEquals("Invalid soap action", soapAction, soapMessage.getSoapAction()); + assertFalse("Message is a XOP pacakge", soapMessage.isXopPackage()); + } - @Override - public void testCreateSoapMessageIllFormedXml() throws Exception { - InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12-ill-formed.xml"); - Map headers = new HashMap(); - headers.put(TransportConstants.HEADER_CONTENT_TYPE, "application/soap+xml"); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageIllFormedXml() throws Exception { + InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12-ill-formed.xml"); + Map headers = new HashMap(); + headers.put(TransportConstants.HEADER_CONTENT_TYPE, "application/soap+xml"); + TransportInputStream tis = new MockTransportInputStream(is, headers); - messageFactory.createWebServiceMessage(tis); - } + messageFactory.createWebServiceMessage(tis); + } - @Override - public void testCreateSoapMessageSwA() throws Exception { - InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12-attachment.bin"); - Map headers = new HashMap(); - headers.put("Content-Type", "multipart/related;" + "type=\"application/soap+xml\";" + - "boundary=\"----=_Part_0_11416420.1149699787554\""); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageSwA() throws Exception { + InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12-attachment.bin"); + Map headers = new HashMap(); + headers.put("Content-Type", "multipart/related;" + "type=\"application/soap+xml\";" + + "boundary=\"----=_Part_0_11416420.1149699787554\""); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); - assertFalse("Message is a XOP package", soapMessage.isXopPackage()); - Attachment attachment = soapMessage.getAttachment("interface21"); - assertNotNull("No attachment read", attachment); - } + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); + assertFalse("Message is a XOP package", soapMessage.isXopPackage()); + Attachment attachment = soapMessage.getAttachment("interface21"); + assertNotNull("No attachment read", attachment); + } - @Override - public void testCreateSoapMessageMtom() throws Exception { - InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12-mtom.bin"); - Map headers = new HashMap(); - headers.put("Content-Type", "multipart/related;" + "start-info=\"application/soap+xml\";" + - "type=\"application/xop+xml\";" + "start=\"<0.urn:uuid:40864869929B855F971176851454456@apache.org>\";" + - "boundary=\"MIMEBoundaryurn_uuid_40864869929B855F971176851454455\""); - TransportInputStream tis = new MockTransportInputStream(is, headers); + @Override + public void testCreateSoapMessageMtom() throws Exception { + InputStream is = AbstractSoap12MessageFactoryTestCase.class.getResourceAsStream("soap12-mtom.bin"); + Map headers = new HashMap(); + headers.put("Content-Type", "multipart/related;" + "start-info=\"application/soap+xml\";" + + "type=\"application/xop+xml\";" + "start=\"<0.urn:uuid:40864869929B855F971176851454456@apache.org>\";" + + "boundary=\"MIMEBoundaryurn_uuid_40864869929B855F971176851454455\""); + TransportInputStream tis = new MockTransportInputStream(is, headers); - WebServiceMessage message = messageFactory.createWebServiceMessage(tis); - assertTrue("Not a SoapMessage", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; - assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); - assertTrue("Message is not a XOP package", soapMessage.isXopPackage()); - Iterator iter = soapMessage.getAttachments(); - assertTrue("No attachments read", iter.hasNext()); + WebServiceMessage message = messageFactory.createWebServiceMessage(tis); + assertTrue("Not a SoapMessage", message instanceof SoapMessage); + SoapMessage soapMessage = (SoapMessage) message; + assertEquals("Invalid soap version", SoapVersion.SOAP_12, soapMessage.getVersion()); + assertTrue("Message is not a XOP package", soapMessage.isXopPackage()); + Iterator iter = soapMessage.getAttachments(); + assertTrue("No attachments read", iter.hasNext()); - Attachment attachment = soapMessage.getAttachment("<1.urn:uuid:40864869929B855F971176851454452@apache.org>"); - assertNotNull("No attachment read", attachment); - } + Attachment attachment = soapMessage.getAttachment("<1.urn:uuid:40864869929B855F971176851454452@apache.org>"); + assertNotNull("No attachment read", attachment); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageTestCase.java index 3ad2d15a..d4528d47 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/soap12/AbstractSoap12MessageTestCase.java @@ -47,119 +47,119 @@ import static org.junit.Assert.*; public abstract class AbstractSoap12MessageTestCase extends AbstractSoapMessageTestCase { - @Override - public void testGetVersion() throws Exception { - Assert.assertEquals("Invalid SOAP version", SoapVersion.SOAP_12, soapMessage.getVersion()); - } + @Override + public void testGetVersion() throws Exception { + Assert.assertEquals("Invalid SOAP version", SoapVersion.SOAP_12, soapMessage.getVersion()); + } - @Override - protected final Resource[] getSoapSchemas() { - return new Resource[]{new ClassPathResource("xml.xsd", AbstractSoap12MessageTestCase.class), - new ClassPathResource("soap12.xsd", AbstractSoap12MessageTestCase.class)}; - } + @Override + protected final Resource[] getSoapSchemas() { + return new Resource[]{new ClassPathResource("xml.xsd", AbstractSoap12MessageTestCase.class), + new ClassPathResource("soap12.xsd", AbstractSoap12MessageTestCase.class)}; + } - @Override - public void testWriteToTransportOutputStream() throws Exception { - SoapBody body = soapMessage.getSoapBody(); - String payload = ""; - transformer.transform(new StringSource(payload), body.getPayloadResult()); + @Override + public void testWriteToTransportOutputStream() throws Exception { + SoapBody body = soapMessage.getSoapBody(); + String payload = ""; + transformer.transform(new StringSource(payload), body.getPayloadResult()); - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - MockTransportOutputStream tos = new MockTransportOutputStream(bos); - String soapAction = "http://springframework.org/spring-ws/Action"; - soapMessage.setSoapAction(soapAction); - soapMessage.writeTo(tos); - String result = bos.toString("UTF-8"); - assertXMLEqual( - "", - result); - String contentType = tos.getHeaders().get(TransportConstants.HEADER_CONTENT_TYPE); - assertTrue("Invalid Content-Type set", - contentType.contains(SoapVersion.SOAP_12.getContentType())); - assertNull(TransportConstants.HEADER_SOAP_ACTION + " header must not be found", - tos.getHeaders().get(TransportConstants.HEADER_SOAP_ACTION)); - assertTrue("Invalid Content-Type set", contentType.contains(soapAction)); - String resultAccept = tos.getHeaders().get("Accept"); - assertNotNull("Invalid accept header", resultAccept); - } + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + MockTransportOutputStream tos = new MockTransportOutputStream(bos); + String soapAction = "http://springframework.org/spring-ws/Action"; + soapMessage.setSoapAction(soapAction); + soapMessage.writeTo(tos); + String result = bos.toString("UTF-8"); + assertXMLEqual( + "", + result); + String contentType = tos.getHeaders().get(TransportConstants.HEADER_CONTENT_TYPE); + assertTrue("Invalid Content-Type set", + contentType.contains(SoapVersion.SOAP_12.getContentType())); + assertNull(TransportConstants.HEADER_SOAP_ACTION + " header must not be found", + tos.getHeaders().get(TransportConstants.HEADER_SOAP_ACTION)); + assertTrue("Invalid Content-Type set", contentType.contains(soapAction)); + String resultAccept = tos.getHeaders().get("Accept"); + assertNotNull("Invalid accept header", resultAccept); + } - @Override - public void testWriteToTransportResponseAttachment() throws Exception { - InputStreamSource inputStreamSource = new ByteArrayResource("contents".getBytes("UTF-8")); - soapMessage.addAttachment("contentId", inputStreamSource, "text/plain"); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - MockTransportOutputStream tos = new MockTransportOutputStream(bos); - soapMessage.writeTo(tos); - String contentType = tos.getHeaders().get("Content-Type"); - assertTrue("Content-Type for attachment message does not contains multipart/related", - contentType.contains("multipart/related")); - assertTrue("Content-Type for attachment message does not contains type=\"application/soap+xml\"", - contentType.contains("type=\"application/soap+xml\"")); - } + @Override + public void testWriteToTransportResponseAttachment() throws Exception { + InputStreamSource inputStreamSource = new ByteArrayResource("contents".getBytes("UTF-8")); + soapMessage.addAttachment("contentId", inputStreamSource, "text/plain"); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + MockTransportOutputStream tos = new MockTransportOutputStream(bos); + soapMessage.writeTo(tos); + String contentType = tos.getHeaders().get("Content-Type"); + assertTrue("Content-Type for attachment message does not contains multipart/related", + contentType.contains("multipart/related")); + assertTrue("Content-Type for attachment message does not contains type=\"application/soap+xml\"", + contentType.contains("type=\"application/soap+xml\"")); + } - @Override - public void testToDocument() throws Exception { - transformer.transform(new StringSource(""), - soapMessage.getSoapBody().getPayloadResult()); + @Override + public void testToDocument() throws Exception { + transformer.transform(new StringSource(""), + soapMessage.getSoapBody().getPayloadResult()); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expected = documentBuilder.newDocument(); - Element envelope = expected.createElementNS("http://www.w3.org/2003/05/soap-envelope", "Envelope"); - expected.appendChild(envelope); - Element body = expected.createElementNS("http://www.w3.org/2003/05/soap-envelope", "Body"); - envelope.appendChild(body); - Element payload = expected.createElementNS("http://www.springframework.org", "payload"); - body.appendChild(payload); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expected = documentBuilder.newDocument(); + Element envelope = expected.createElementNS("http://www.w3.org/2003/05/soap-envelope", "Envelope"); + expected.appendChild(envelope); + Element body = expected.createElementNS("http://www.w3.org/2003/05/soap-envelope", "Body"); + envelope.appendChild(body); + Element payload = expected.createElementNS("http://www.springframework.org", "payload"); + body.appendChild(payload); - Document result = soapMessage.getDocument(); + Document result = soapMessage.getDocument(); - assertXMLEqual(expected, result); - } + assertXMLEqual(expected, result); + } - @Override - public void testSetLiveDocument() throws Exception { - transformer.transform(new StringSource(""), - soapMessage.getSoapBody().getPayloadResult()); + @Override + public void testSetLiveDocument() throws Exception { + transformer.transform(new StringSource(""), + soapMessage.getSoapBody().getPayloadResult()); - Document document = soapMessage.getDocument(); + Document document = soapMessage.getDocument(); - soapMessage.setDocument(document); + soapMessage.setDocument(document); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - soapMessage.writeTo(bos); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + soapMessage.writeTo(bos); - String result = bos.toString("UTF-8"); - assertXMLEqual( - "", - result); - } + String result = bos.toString("UTF-8"); + assertXMLEqual( + "", + result); + } - @Override - public void testSetOtherDocument() throws Exception { - transformer.transform(new StringSource(""), - soapMessage.getSoapBody().getPayloadResult()); + @Override + public void testSetOtherDocument() throws Exception { + transformer.transform(new StringSource(""), + soapMessage.getSoapBody().getPayloadResult()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - soapMessage.writeTo(bos); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + soapMessage.writeTo(bos); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - DOMResult domResult = new DOMResult(); - transformer.transform(new StreamSource(bis), domResult); + DOMResult domResult = new DOMResult(); + transformer.transform(new StreamSource(bis), domResult); - Document document = (Document) domResult.getNode(); + Document document = (Document) domResult.getNode(); - soapMessage.setDocument(document); + soapMessage.setDocument(document); - bos = new ByteArrayOutputStream(); - soapMessage.writeTo(bos); + bos = new ByteArrayOutputStream(); + soapMessage.writeTo(bos); - String result = bos.toString("UTF-8"); - assertXMLEqual( - "", - result); - } + String result = bos.toString("UTF-8"); + assertXMLEqual( + "", + result); + } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/soap/support/SoapUtilsTest.java b/spring-ws-core/src/test/java/org/springframework/ws/soap/support/SoapUtilsTest.java index 5e88cc35..59e4df08 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/soap/support/SoapUtilsTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/soap/support/SoapUtilsTest.java @@ -21,56 +21,56 @@ import org.junit.Test; public class SoapUtilsTest { - @Test - public void testExtractActionFromContentType() throws Exception { - String soapAction = "http://springframework.org/spring-ws/Action"; + @Test + public void testExtractActionFromContentType() throws Exception { + String soapAction = "http://springframework.org/spring-ws/Action"; - String contentType = "application/soap+xml; action=" + soapAction; - String result = SoapUtils.extractActionFromContentType(contentType); - Assert.assertEquals("Invalid SOAP action", soapAction, result); + String contentType = "application/soap+xml; action=" + soapAction; + String result = SoapUtils.extractActionFromContentType(contentType); + Assert.assertEquals("Invalid SOAP action", soapAction, result); - contentType = "application/soap+xml; action = " + soapAction; - result = SoapUtils.extractActionFromContentType(contentType); - Assert.assertEquals("Invalid SOAP action", soapAction, result); + contentType = "application/soap+xml; action = " + soapAction; + result = SoapUtils.extractActionFromContentType(contentType); + Assert.assertEquals("Invalid SOAP action", soapAction, result); - contentType = "application/soap+xml; action=" + soapAction + " ; charset=UTF-8"; - result = SoapUtils.extractActionFromContentType(contentType); - Assert.assertEquals("Invalid SOAP action", soapAction, result); + contentType = "application/soap+xml; action=" + soapAction + " ; charset=UTF-8"; + result = SoapUtils.extractActionFromContentType(contentType); + Assert.assertEquals("Invalid SOAP action", soapAction, result); - contentType = "application/soap+xml; charset=UTF-8; action=" + soapAction; - result = SoapUtils.extractActionFromContentType(contentType); - Assert.assertEquals("Invalid SOAP action", soapAction, result); - } + contentType = "application/soap+xml; charset=UTF-8; action=" + soapAction; + result = SoapUtils.extractActionFromContentType(contentType); + Assert.assertEquals("Invalid SOAP action", soapAction, result); + } - @Test - public void testEscapeAction() throws Exception { - String result = SoapUtils.escapeAction("action"); - Assert.assertEquals("Invalid SOAP action", "\"action\"", result); + @Test + public void testEscapeAction() throws Exception { + String result = SoapUtils.escapeAction("action"); + Assert.assertEquals("Invalid SOAP action", "\"action\"", result); - result = SoapUtils.escapeAction("\"action\""); - Assert.assertEquals("Invalid SOAP action", "\"action\"", result); + result = SoapUtils.escapeAction("\"action\""); + Assert.assertEquals("Invalid SOAP action", "\"action\"", result); - result = SoapUtils.escapeAction(""); - Assert.assertEquals("Invalid SOAP action", "\"\"", result); + result = SoapUtils.escapeAction(""); + Assert.assertEquals("Invalid SOAP action", "\"\"", result); - result = SoapUtils.escapeAction(null); - Assert.assertEquals("Invalid SOAP action", "\"\"", result); + result = SoapUtils.escapeAction(null); + Assert.assertEquals("Invalid SOAP action", "\"\"", result); - } + } - @Test - public void testSetActionInContentType() throws Exception { - String soapAction = "http://springframework.org/spring-ws/Action"; - String contentType = "application/soap+xml"; + @Test + public void testSetActionInContentType() throws Exception { + String soapAction = "http://springframework.org/spring-ws/Action"; + String contentType = "application/soap+xml"; - String result = SoapUtils.setActionInContentType(contentType, soapAction); - Assert.assertEquals("Invalid SOAP action", soapAction, SoapUtils.extractActionFromContentType(result)); + String result = SoapUtils.setActionInContentType(contentType, soapAction); + Assert.assertEquals("Invalid SOAP action", soapAction, SoapUtils.extractActionFromContentType(result)); - String anotherSoapAction = "http://springframework.org/spring-ws/AnotherAction"; - String contentTypeWithAction = "application/soap+xml; action=http://springframework.org/spring-ws/Action"; - result = SoapUtils.setActionInContentType(contentTypeWithAction, anotherSoapAction); - Assert.assertEquals("Invalid SOAP action", anotherSoapAction, SoapUtils.extractActionFromContentType(result)); + String anotherSoapAction = "http://springframework.org/spring-ws/AnotherAction"; + String contentTypeWithAction = "application/soap+xml; action=http://springframework.org/spring-ws/Action"; + result = SoapUtils.setActionInContentType(contentTypeWithAction, anotherSoapAction); + Assert.assertEquals("Invalid SOAP action", anotherSoapAction, SoapUtils.extractActionFromContentType(result)); - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/support/DefaultStrategiesHelperTest.java b/spring-ws-core/src/test/java/org/springframework/ws/support/DefaultStrategiesHelperTest.java index 945052ee..8adbb9be 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/support/DefaultStrategiesHelperTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/support/DefaultStrategiesHelperTest.java @@ -32,90 +32,90 @@ import org.springframework.core.io.Resource; public class DefaultStrategiesHelperTest { - @Test - public void testGetDefaultStrategies() throws Exception { + @Test + public void testGetDefaultStrategies() throws Exception { - Properties strategies = new Properties(); - strategies.put(Strategy.class.getName(), - StrategyImpl.class.getName() + "," + ContextAwareStrategyImpl.class.getName()); - DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies); + Properties strategies = new Properties(); + strategies.put(Strategy.class.getName(), + StrategyImpl.class.getName() + "," + ContextAwareStrategyImpl.class.getName()); + DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies); - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("strategy1", StrategyImpl.class); - applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class); + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("strategy1", StrategyImpl.class); + applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class); - List result = helper.getDefaultStrategies(Strategy.class, applicationContext); - Assert.assertNotNull("No result", result); - Assert.assertEquals("Invalid amount of strategies", 2, result.size()); - Assert.assertTrue("Result not a Strategy implementation", result.get(0) != null); - Assert.assertTrue("Result not a Strategy implementation", result.get(1) != null); - Assert.assertTrue("Result not a StrategyImpl implementation", result.get(0) instanceof StrategyImpl); - Assert.assertTrue("Result not a StrategyImpl implementation", result.get(1) instanceof ContextAwareStrategyImpl); - ContextAwareStrategyImpl impl = (ContextAwareStrategyImpl) result.get(1); - Assert.assertNotNull("No application context injected", impl.getApplicationContext()); - } + List result = helper.getDefaultStrategies(Strategy.class, applicationContext); + Assert.assertNotNull("No result", result); + Assert.assertEquals("Invalid amount of strategies", 2, result.size()); + Assert.assertTrue("Result not a Strategy implementation", result.get(0) != null); + Assert.assertTrue("Result not a Strategy implementation", result.get(1) != null); + Assert.assertTrue("Result not a StrategyImpl implementation", result.get(0) instanceof StrategyImpl); + Assert.assertTrue("Result not a StrategyImpl implementation", result.get(1) instanceof ContextAwareStrategyImpl); + ContextAwareStrategyImpl impl = (ContextAwareStrategyImpl) result.get(1); + Assert.assertNotNull("No application context injected", impl.getApplicationContext()); + } - @Test - public void testGetDefaultStrategy() throws Exception { - Properties strategies = new Properties(); - strategies.put(Strategy.class.getName(), StrategyImpl.class.getName()); - DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies); + @Test + public void testGetDefaultStrategy() throws Exception { + Properties strategies = new Properties(); + strategies.put(Strategy.class.getName(), StrategyImpl.class.getName()); + DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies); - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("strategy1", StrategyImpl.class); - applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class); + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("strategy1", StrategyImpl.class); + applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class); - Object result = helper.getDefaultStrategy(Strategy.class, applicationContext); - Assert.assertNotNull("No result", result); - Assert.assertTrue("Result not a Strategy implementation", result instanceof Strategy); - Assert.assertTrue("Result not a StrategyImpl implementation", result instanceof StrategyImpl); - } + Object result = helper.getDefaultStrategy(Strategy.class, applicationContext); + Assert.assertNotNull("No result", result); + Assert.assertTrue("Result not a Strategy implementation", result instanceof Strategy); + Assert.assertTrue("Result not a StrategyImpl implementation", result instanceof StrategyImpl); + } - @Test - public void testGetDefaultStrategyMoreThanOne() throws Exception { - Properties strategies = new Properties(); - strategies.put(Strategy.class.getName(), - StrategyImpl.class.getName() + "," + ContextAwareStrategyImpl.class.getName()); - DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies); + @Test + public void testGetDefaultStrategyMoreThanOne() throws Exception { + Properties strategies = new Properties(); + strategies.put(Strategy.class.getName(), + StrategyImpl.class.getName() + "," + ContextAwareStrategyImpl.class.getName()); + DefaultStrategiesHelper helper = new DefaultStrategiesHelper(strategies); - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("strategy1", StrategyImpl.class); - applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class); + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("strategy1", StrategyImpl.class); + applicationContext.registerSingleton("strategy2", ContextAwareStrategyImpl.class); - try { - helper.getDefaultStrategy(Strategy.class, applicationContext); - Assert.fail("Expected BeanInitializationException"); - } - catch (BeanInitializationException ex) { - // expected - } - } + try { + helper.getDefaultStrategy(Strategy.class, applicationContext); + Assert.fail("Expected BeanInitializationException"); + } + catch (BeanInitializationException ex) { + // expected + } + } - @Test - public void testResourceConstructor() throws Exception { - Resource resource = new ClassPathResource("strategies.properties", getClass()); - new DefaultStrategiesHelper(resource); - } + @Test + public void testResourceConstructor() throws Exception { + Resource resource = new ClassPathResource("strategies.properties", getClass()); + new DefaultStrategiesHelper(resource); + } - public interface Strategy { + public interface Strategy { - } + } - private static class StrategyImpl implements Strategy { + private static class StrategyImpl implements Strategy { - } + } - private static class ContextAwareStrategyImpl implements Strategy, ApplicationContextAware { + private static class ContextAwareStrategyImpl implements Strategy, ApplicationContextAware { - private ApplicationContext applicationContext; + private ApplicationContext applicationContext; - public ApplicationContext getApplicationContext() { - return applicationContext; - } + public ApplicationContext getApplicationContext() { + return applicationContext; + } - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/support/MarshallingUtilsTest.java b/spring-ws-core/src/test/java/org/springframework/ws/support/MarshallingUtilsTest.java index 8ee65394..4d91d67e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/support/MarshallingUtilsTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/support/MarshallingUtilsTest.java @@ -36,90 +36,90 @@ import static org.easymock.EasyMock.*; public class MarshallingUtilsTest { - @Test - public void testUnmarshal() throws Exception { - Unmarshaller unmarshallerMock = createMock(Unmarshaller.class); - WebServiceMessage messageMock = createMock(WebServiceMessage.class); + @Test + public void testUnmarshal() throws Exception { + Unmarshaller unmarshallerMock = createMock(Unmarshaller.class); + WebServiceMessage messageMock = createMock(WebServiceMessage.class); - Source source = new StringSource(""); - Object unmarshalled = new Object(); - expect(messageMock.getPayloadSource()).andReturn(source); - expect(unmarshallerMock.unmarshal(source)).andReturn(unmarshalled); + Source source = new StringSource(""); + Object unmarshalled = new Object(); + expect(messageMock.getPayloadSource()).andReturn(source); + expect(unmarshallerMock.unmarshal(source)).andReturn(unmarshalled); - replay(unmarshallerMock, messageMock); + replay(unmarshallerMock, messageMock); - Object result = MarshallingUtils.unmarshal(unmarshallerMock, messageMock); - Assert.assertEquals("Invalid unmarshalled object", unmarshalled, result); + Object result = MarshallingUtils.unmarshal(unmarshallerMock, messageMock); + Assert.assertEquals("Invalid unmarshalled object", unmarshalled, result); - verify(unmarshallerMock, messageMock); - } + verify(unmarshallerMock, messageMock); + } - @Test - public void testUnmarshalMime() throws Exception { - MimeUnmarshaller unmarshallerMock = createMock(MimeUnmarshaller.class); - MimeMessage messageMock = createMock(MimeMessage.class); + @Test + public void testUnmarshalMime() throws Exception { + MimeUnmarshaller unmarshallerMock = createMock(MimeUnmarshaller.class); + MimeMessage messageMock = createMock(MimeMessage.class); - Source source = new StringSource(""); - Object unmarshalled = new Object(); - expect(messageMock.getPayloadSource()).andReturn(source); - expect(unmarshallerMock.unmarshal(eq(source), isA(MimeContainer.class))).andReturn(unmarshalled); + Source source = new StringSource(""); + Object unmarshalled = new Object(); + expect(messageMock.getPayloadSource()).andReturn(source); + expect(unmarshallerMock.unmarshal(eq(source), isA(MimeContainer.class))).andReturn(unmarshalled); - replay(unmarshallerMock, messageMock); + replay(unmarshallerMock, messageMock); - Object result = MarshallingUtils.unmarshal(unmarshallerMock, messageMock); - Assert.assertEquals("Invalid unmarshalled object", unmarshalled, result); + Object result = MarshallingUtils.unmarshal(unmarshallerMock, messageMock); + Assert.assertEquals("Invalid unmarshalled object", unmarshalled, result); - verify(unmarshallerMock, messageMock); - } + verify(unmarshallerMock, messageMock); + } - @Test - public void testUnmarshalNoPayload() throws Exception { - Unmarshaller unmarshallerMock = createMock(Unmarshaller.class); - MimeMessage messageMock = createMock(MimeMessage.class); + @Test + public void testUnmarshalNoPayload() throws Exception { + Unmarshaller unmarshallerMock = createMock(Unmarshaller.class); + MimeMessage messageMock = createMock(MimeMessage.class); - expect(messageMock.getPayloadSource()).andReturn(null); + expect(messageMock.getPayloadSource()).andReturn(null); - replay(unmarshallerMock, messageMock); + replay(unmarshallerMock, messageMock); - Object result = MarshallingUtils.unmarshal(unmarshallerMock, messageMock); - Assert.assertNull("Invalid unmarshalled object", result); + Object result = MarshallingUtils.unmarshal(unmarshallerMock, messageMock); + Assert.assertNull("Invalid unmarshalled object", result); - verify(unmarshallerMock, messageMock); - } + verify(unmarshallerMock, messageMock); + } - @Test - public void testMarshal() throws Exception { - Marshaller marshallerMock = createMock(Marshaller.class); - WebServiceMessage messageMock = createMock(WebServiceMessage.class); + @Test + public void testMarshal() throws Exception { + Marshaller marshallerMock = createMock(Marshaller.class); + WebServiceMessage messageMock = createMock(WebServiceMessage.class); - Result result = new StringResult(); - Object marshalled = new Object(); - expect(messageMock.getPayloadResult()).andReturn(result); - marshallerMock.marshal(marshalled, result); + Result result = new StringResult(); + Object marshalled = new Object(); + expect(messageMock.getPayloadResult()).andReturn(result); + marshallerMock.marshal(marshalled, result); - replay(marshallerMock, messageMock); + replay(marshallerMock, messageMock); - MarshallingUtils.marshal(marshallerMock, marshalled, messageMock); + MarshallingUtils.marshal(marshallerMock, marshalled, messageMock); - verify(marshallerMock, messageMock); - } + verify(marshallerMock, messageMock); + } - @Test - public void testMarshalMime() throws Exception { - MimeMarshaller marshallerMock = createMock(MimeMarshaller.class); - MimeMessage messageMock = createMock(MimeMessage.class); + @Test + public void testMarshalMime() throws Exception { + MimeMarshaller marshallerMock = createMock(MimeMarshaller.class); + MimeMessage messageMock = createMock(MimeMessage.class); - Result result = new StringResult(); - Object marshalled = new Object(); - expect(messageMock.getPayloadResult()).andReturn(result); - marshallerMock.marshal(eq(marshalled), eq(result), isA(MimeContainer.class)); + Result result = new StringResult(); + Object marshalled = new Object(); + expect(messageMock.getPayloadResult()).andReturn(result); + marshallerMock.marshal(eq(marshalled), eq(result), isA(MimeContainer.class)); - replay(marshallerMock, messageMock); + replay(marshallerMock, messageMock); - MarshallingUtils.marshal(marshallerMock, marshalled, messageMock); + MarshallingUtils.marshal(marshallerMock, marshalled, messageMock); - verify(marshallerMock, messageMock); - } + verify(marshallerMock, messageMock); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportInputStream.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportInputStream.java index 664b3ae5..1c3ba1a2 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportInputStream.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportInputStream.java @@ -28,36 +28,36 @@ import org.springframework.util.StringUtils; public class MockTransportInputStream extends TransportInputStream { - private Map headers; + private Map headers; - private InputStream inputStream; + private InputStream inputStream; - public MockTransportInputStream(InputStream inputStream, Map headers) { - Assert.notNull(inputStream, "inputStream must not be null"); - Assert.notNull(headers, "headers must not be null"); - this.inputStream = inputStream; - this.headers = headers; - } + public MockTransportInputStream(InputStream inputStream, Map headers) { + Assert.notNull(inputStream, "inputStream must not be null"); + Assert.notNull(headers, "headers must not be null"); + this.inputStream = inputStream; + this.headers = headers; + } - public MockTransportInputStream(InputStream inputStream) { - Assert.notNull(inputStream, "inputStream must not be null"); - this.inputStream = inputStream; - headers = new HashMap(); - } + public MockTransportInputStream(InputStream inputStream) { + Assert.notNull(inputStream, "inputStream must not be null"); + this.inputStream = inputStream; + headers = new HashMap(); + } - @Override - protected InputStream createInputStream() throws IOException { - return inputStream; - } + @Override + protected InputStream createInputStream() throws IOException { + return inputStream; + } - @Override - public Iterator getHeaderNames() throws IOException { - return headers.keySet().iterator(); - } + @Override + public Iterator getHeaderNames() throws IOException { + return headers.keySet().iterator(); + } - @Override - public Iterator getHeaders(String name) throws IOException { - String[] values = StringUtils.delimitedListToStringArray(headers.get(name), ", "); - return Arrays.asList(values).iterator(); - } + @Override + public Iterator getHeaders(String name) throws IOException { + String[] values = StringUtils.delimitedListToStringArray(headers.get(name), ", "); + return Arrays.asList(values).iterator(); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportOutputStream.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportOutputStream.java index 9c2f325e..effa737e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportOutputStream.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/MockTransportOutputStream.java @@ -25,26 +25,26 @@ import org.springframework.util.Assert; public class MockTransportOutputStream extends TransportOutputStream { - private Map headers = new HashMap(); + private Map headers = new HashMap(); - private OutputStream outputStream; + private OutputStream outputStream; - public MockTransportOutputStream(OutputStream outputStream) { - Assert.notNull(outputStream, "outputStream must not be null"); - this.outputStream = outputStream; - } + public MockTransportOutputStream(OutputStream outputStream) { + Assert.notNull(outputStream, "outputStream must not be null"); + this.outputStream = outputStream; + } - @Override - protected OutputStream createOutputStream() throws IOException { - return outputStream; - } + @Override + protected OutputStream createOutputStream() throws IOException { + return outputStream; + } - public Map getHeaders() { - return headers; - } + public Map getHeaders() { + return headers; + } - @Override - public void addHeader(String name, String value) throws IOException { - headers.put(name, value); - } + @Override + public void addHeader(String name, String value) throws IOException { + headers.put(name, value); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSenderIntegrationTestCase.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSenderIntegrationTestCase.java index abd799eb..0baa5c3e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSenderIntegrationTestCase.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/AbstractHttpWebServiceMessageSenderIntegrationTestCase.java @@ -61,250 +61,250 @@ import org.springframework.xml.transform.StringSource; public abstract class AbstractHttpWebServiceMessageSenderIntegrationTestCase { - private Server jettyServer; + private Server jettyServer; - private static final String REQUEST_HEADER_NAME = "RequestHeader"; + private static final String REQUEST_HEADER_NAME = "RequestHeader"; - private static final String REQUEST_HEADER_VALUE = "RequestHeaderValue"; + private static final String REQUEST_HEADER_VALUE = "RequestHeaderValue"; - private static final String RESPONSE_HEADER_NAME = "ResponseHeader"; + private static final String RESPONSE_HEADER_NAME = "ResponseHeader"; - private static final String RESPONSE_HEADER_VALUE = "ResponseHeaderValue"; + private static final String RESPONSE_HEADER_VALUE = "ResponseHeaderValue"; - private static final String REQUEST = ""; + private static final String REQUEST = ""; - private static final String SOAP_REQUEST = - "" + - REQUEST + ""; + private static final String SOAP_REQUEST = + "" + + REQUEST + ""; - private static final String RESPONSE = ""; + private static final String RESPONSE = ""; - private static final String SOAP_RESPONSE = - "" + - RESPONSE + ""; + private static final String SOAP_RESPONSE = + "" + + RESPONSE + ""; - private AbstractHttpWebServiceMessageSender messageSender; + private AbstractHttpWebServiceMessageSender messageSender; - private Context jettyContext; + private Context jettyContext; - private MessageFactory saajMessageFactory; + private MessageFactory saajMessageFactory; - private TransformerFactory transformerFactory; + private TransformerFactory transformerFactory; - private WebServiceMessageFactory messageFactory; + private WebServiceMessageFactory messageFactory; - private URI connectionUri; + private URI connectionUri; - @Before - public final void setUp() throws Exception { - int port = FreePortScanner.getFreePort(); - connectionUri = new URI("http", null, "localhost", port, null, null, null); - jettyServer = new Server(port); - jettyContext = new Context(jettyServer, "/"); - messageSender = createMessageSender(); - if (messageSender instanceof InitializingBean) { - ((InitializingBean) messageSender).afterPropertiesSet(); - } - XMLUnit.setIgnoreWhitespace(true); - saajMessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - messageFactory = new SaajSoapMessageFactory(saajMessageFactory); - transformerFactory = TransformerFactory.newInstance(); - } + @Before + public final void setUp() throws Exception { + int port = FreePortScanner.getFreePort(); + connectionUri = new URI("http", null, "localhost", port, null, null, null); + jettyServer = new Server(port); + jettyContext = new Context(jettyServer, "/"); + messageSender = createMessageSender(); + if (messageSender instanceof InitializingBean) { + ((InitializingBean) messageSender).afterPropertiesSet(); + } + XMLUnit.setIgnoreWhitespace(true); + saajMessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + messageFactory = new SaajSoapMessageFactory(saajMessageFactory); + transformerFactory = TransformerFactory.newInstance(); + } - protected abstract AbstractHttpWebServiceMessageSender createMessageSender(); + protected abstract AbstractHttpWebServiceMessageSender createMessageSender(); - @After - public final void tearDown() throws Exception { - if (jettyServer.isRunning()) { - jettyServer.stop(); - } - } + @After + public final void tearDown() throws Exception { + if (jettyServer.isRunning()) { + jettyServer.stop(); + } + } - @Test - public void testSupports() throws URISyntaxException { - Assert.assertTrue("Message sender does not support HTTP url", messageSender.supports(connectionUri)); - } + @Test + public void testSupports() throws URISyntaxException { + Assert.assertTrue("Message sender does not support HTTP url", messageSender.supports(connectionUri)); + } - @Test - public void testSendAndReceiveResponse() throws Exception { - MyServlet servlet = new MyServlet(); - servlet.setResponse(true); - validateResponse(servlet); - } + @Test + public void testSendAndReceiveResponse() throws Exception { + MyServlet servlet = new MyServlet(); + servlet.setResponse(true); + validateResponse(servlet); + } - @Test - public void testSendAndReceiveNoResponse() throws Exception { - validateNonResponse(new MyServlet()); - } + @Test + public void testSendAndReceiveNoResponse() throws Exception { + validateNonResponse(new MyServlet()); + } - @Test - public void testSendAndReceiveNoResponseAccepted() throws Exception { - MyServlet servlet = new MyServlet(); - servlet.setResponseStatus(HttpServletResponse.SC_ACCEPTED); - validateNonResponse(servlet); - } + @Test + public void testSendAndReceiveNoResponseAccepted() throws Exception { + MyServlet servlet = new MyServlet(); + servlet.setResponseStatus(HttpServletResponse.SC_ACCEPTED); + validateNonResponse(servlet); + } - @Test - public void testSendAndReceiveCompressed() throws Exception { - MyServlet servlet = new MyServlet(); - servlet.setResponse(true); - servlet.setGzip(true); - validateResponse(servlet); - } + @Test + public void testSendAndReceiveCompressed() throws Exception { + MyServlet servlet = new MyServlet(); + servlet.setResponse(true); + servlet.setGzip(true); + validateResponse(servlet); + } - @Test - public void testSendAndReceiveInvalidContentSize() throws Exception { - MyServlet servlet = new MyServlet(); - servlet.setResponse(true); - servlet.setContentLength(-1); - validateResponse(servlet); - } + @Test + public void testSendAndReceiveInvalidContentSize() throws Exception { + MyServlet servlet = new MyServlet(); + servlet.setResponse(true); + servlet.setContentLength(-1); + validateResponse(servlet); + } - @Test - public void testSendAndReceiveCompressedInvalidContentSize() throws Exception { - MyServlet servlet = new MyServlet(); - servlet.setResponse(true); - servlet.setGzip(true); - servlet.setContentLength(-1); - validateResponse(servlet); - } + @Test + public void testSendAndReceiveCompressedInvalidContentSize() throws Exception { + MyServlet servlet = new MyServlet(); + servlet.setResponse(true); + servlet.setGzip(true); + servlet.setContentLength(-1); + validateResponse(servlet); + } - @Test - public void testSendAndReceiveFault() throws Exception { - MyServlet servlet = new MyServlet(); - servlet.setResponseStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - servlet.setResponse(true); - jettyContext.addServlet(new ServletHolder(servlet), "/"); - jettyServer.start(); - FaultAwareWebServiceConnection connection = - (FaultAwareWebServiceConnection) messageSender.createConnection(connectionUri); - SOAPMessage request = createRequest(); - try { - connection.send(new SaajSoapMessage(request)); - connection.receive(messageFactory); - Assert.assertTrue("Response has no fault", connection.hasFault()); - } - finally { - connection.close(); - } - } + @Test + public void testSendAndReceiveFault() throws Exception { + MyServlet servlet = new MyServlet(); + servlet.setResponseStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + servlet.setResponse(true); + jettyContext.addServlet(new ServletHolder(servlet), "/"); + jettyServer.start(); + FaultAwareWebServiceConnection connection = + (FaultAwareWebServiceConnection) messageSender.createConnection(connectionUri); + SOAPMessage request = createRequest(); + try { + connection.send(new SaajSoapMessage(request)); + connection.receive(messageFactory); + Assert.assertTrue("Response has no fault", connection.hasFault()); + } + finally { + connection.close(); + } + } - private void validateResponse(Servlet servlet) throws Exception { - jettyContext.addServlet(new ServletHolder(servlet), "/"); - jettyServer.start(); - FaultAwareWebServiceConnection connection = - (FaultAwareWebServiceConnection) messageSender.createConnection(connectionUri); - SOAPMessage request = createRequest(); - try { - connection.send(new SaajSoapMessage(request)); - SaajSoapMessage response = (SaajSoapMessage) connection.receive(messageFactory); - Assert.assertNotNull("No response", response); - Assert.assertFalse("Response has fault", connection.hasFault()); - SOAPMessage saajResponse = response.getSaajMessage(); - String[] headerValues = saajResponse.getMimeHeaders().getHeader(RESPONSE_HEADER_NAME); - Assert.assertNotNull("Response has no header", headerValues); - Assert.assertEquals("Response has invalid header", 1, headerValues.length); - Assert.assertEquals("Response has invalid header values", RESPONSE_HEADER_VALUE, headerValues[0]); - StringResult result = new StringResult(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.transform(response.getPayloadSource(), result); - assertXMLEqual("Invalid response", RESPONSE, result.toString()); - } - finally { - connection.close(); - } - } + private void validateResponse(Servlet servlet) throws Exception { + jettyContext.addServlet(new ServletHolder(servlet), "/"); + jettyServer.start(); + FaultAwareWebServiceConnection connection = + (FaultAwareWebServiceConnection) messageSender.createConnection(connectionUri); + SOAPMessage request = createRequest(); + try { + connection.send(new SaajSoapMessage(request)); + SaajSoapMessage response = (SaajSoapMessage) connection.receive(messageFactory); + Assert.assertNotNull("No response", response); + Assert.assertFalse("Response has fault", connection.hasFault()); + SOAPMessage saajResponse = response.getSaajMessage(); + String[] headerValues = saajResponse.getMimeHeaders().getHeader(RESPONSE_HEADER_NAME); + Assert.assertNotNull("Response has no header", headerValues); + Assert.assertEquals("Response has invalid header", 1, headerValues.length); + Assert.assertEquals("Response has invalid header values", RESPONSE_HEADER_VALUE, headerValues[0]); + StringResult result = new StringResult(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(response.getPayloadSource(), result); + assertXMLEqual("Invalid response", RESPONSE, result.toString()); + } + finally { + connection.close(); + } + } - private void validateNonResponse(Servlet servlet) throws Exception { - jettyContext.addServlet(new ServletHolder(servlet), "/"); - jettyServer.start(); + private void validateNonResponse(Servlet servlet) throws Exception { + jettyContext.addServlet(new ServletHolder(servlet), "/"); + jettyServer.start(); - WebServiceConnection connection = messageSender.createConnection(connectionUri); - SOAPMessage request = createRequest(); - try { - connection.send(new SaajSoapMessage(request)); - WebServiceMessage response = connection.receive(messageFactory); - Assert.assertNull("Response", response); - } - finally { - connection.close(); - } - } + WebServiceConnection connection = messageSender.createConnection(connectionUri); + SOAPMessage request = createRequest(); + try { + connection.send(new SaajSoapMessage(request)); + WebServiceMessage response = connection.receive(messageFactory); + Assert.assertNull("Response", response); + } + finally { + connection.close(); + } + } - private SOAPMessage createRequest() throws TransformerException, SOAPException { - SOAPMessage request = saajMessageFactory.createMessage(); - MimeHeaders mimeHeaders = request.getMimeHeaders(); - mimeHeaders.addHeader(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE); - Transformer transformer = transformerFactory.newTransformer(); - transformer.transform(new StringSource(REQUEST), new DOMResult(request.getSOAPBody())); - return request; - } + private SOAPMessage createRequest() throws TransformerException, SOAPException { + SOAPMessage request = saajMessageFactory.createMessage(); + MimeHeaders mimeHeaders = request.getMimeHeaders(); + mimeHeaders.addHeader(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(new StringSource(REQUEST), new DOMResult(request.getSOAPBody())); + return request; + } @SuppressWarnings("serial") - private class MyServlet extends HttpServlet { + private class MyServlet extends HttpServlet { - private int responseStatus = HttpServletResponse.SC_OK; + private int responseStatus = HttpServletResponse.SC_OK; - private Integer contentLength; + private Integer contentLength; - private boolean response; + private boolean response; - private boolean gzip; + private boolean gzip; - public void setResponseStatus(int responseStatus) { - this.responseStatus = responseStatus; - } + public void setResponseStatus(int responseStatus) { + this.responseStatus = responseStatus; + } - public void setContentLength(int contentLength) { - this.contentLength = contentLength; - } + public void setContentLength(int contentLength) { + this.contentLength = contentLength; + } - public void setResponse(boolean response) { - this.response = response; - } + public void setResponse(boolean response) { + this.response = response; + } - public void setGzip(boolean gzip) { - this.gzip = gzip; - } + public void setGzip(boolean gzip) { + this.gzip = gzip; + } - @Override - protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) - throws ServletException, IOException { - try { - assertEquals("Invalid header value received on server side", REQUEST_HEADER_VALUE, - httpServletRequest.getHeader(REQUEST_HEADER_NAME)); - String receivedRequest = - new String(FileCopyUtils.copyToByteArray(httpServletRequest.getInputStream()), "UTF-8"); - assertXMLEqual("Invalid request received", SOAP_REQUEST, receivedRequest); - if (gzip) { - assertEquals("Invalid Accept-Encoding header value received on server side", "gzip", - httpServletRequest.getHeader("Accept-Encoding")); - } + @Override + protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) + throws ServletException, IOException { + try { + assertEquals("Invalid header value received on server side", REQUEST_HEADER_VALUE, + httpServletRequest.getHeader(REQUEST_HEADER_NAME)); + String receivedRequest = + new String(FileCopyUtils.copyToByteArray(httpServletRequest.getInputStream()), "UTF-8"); + assertXMLEqual("Invalid request received", SOAP_REQUEST, receivedRequest); + if (gzip) { + assertEquals("Invalid Accept-Encoding header value received on server side", "gzip", + httpServletRequest.getHeader("Accept-Encoding")); + } - httpServletResponse.setStatus(responseStatus); - if (response) { - httpServletResponse.setContentType("text/xml"); - if (contentLength != null) { - httpServletResponse.setContentLength(contentLength); - } - if (gzip) { - httpServletResponse.addHeader("Content-Encoding", "gzip"); - } - httpServletResponse.setHeader(RESPONSE_HEADER_NAME, RESPONSE_HEADER_VALUE); - OutputStream os; - if (gzip) { - os = new GZIPOutputStream(httpServletResponse.getOutputStream()); - } - else { - os = httpServletResponse.getOutputStream(); - } - FileCopyUtils.copy(SOAP_RESPONSE.getBytes("UTF-8"), os); - } - } - catch (Exception ex) { - throw new ServletException(ex); - } - } - } + httpServletResponse.setStatus(responseStatus); + if (response) { + httpServletResponse.setContentType("text/xml"); + if (contentLength != null) { + httpServletResponse.setContentLength(contentLength); + } + if (gzip) { + httpServletResponse.addHeader("Content-Encoding", "gzip"); + } + httpServletResponse.setHeader(RESPONSE_HEADER_NAME, RESPONSE_HEADER_VALUE); + OutputStream os; + if (gzip) { + os = new GZIPOutputStream(httpServletResponse.getOutputStream()); + } + else { + os = httpServletResponse.getOutputStream(); + } + FileCopyUtils.copy(SOAP_RESPONSE.getBytes("UTF-8"), os); + } + } + catch (Exception ex) { + throw new ServletException(ex); + } + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/ClientHttpRequestMessageSenderIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/ClientHttpRequestMessageSenderIntegrationTest.java index 7da6aa25..2cfb4a26 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/ClientHttpRequestMessageSenderIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/ClientHttpRequestMessageSenderIntegrationTest.java @@ -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, @@ -17,10 +17,10 @@ package org.springframework.ws.transport.http; public class ClientHttpRequestMessageSenderIntegrationTest - extends AbstractHttpWebServiceMessageSenderIntegrationTestCase { + extends AbstractHttpWebServiceMessageSenderIntegrationTestCase { - @Override - protected AbstractHttpWebServiceMessageSender createMessageSender() { - return new ClientHttpRequestMessageSender(); - } + @Override + protected AbstractHttpWebServiceMessageSender createMessageSender() { + return new ClientHttpRequestMessageSender(); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/CommonsHttpMessageSenderIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/CommonsHttpMessageSenderIntegrationTest.java index b95c7ec2..7d8f9bc0 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/CommonsHttpMessageSenderIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/CommonsHttpMessageSenderIntegrationTest.java @@ -42,73 +42,73 @@ import org.springframework.ws.transport.support.FreePortScanner; public class CommonsHttpMessageSenderIntegrationTest extends AbstractHttpWebServiceMessageSenderIntegrationTestCase { - @Override - protected AbstractHttpWebServiceMessageSender createMessageSender() { - return new CommonsHttpMessageSender(); - } + @Override + protected AbstractHttpWebServiceMessageSender createMessageSender() { + return new CommonsHttpMessageSender(); + } - @Test - public void testMaxConnections() throws URISyntaxException, URIException { - CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(); - messageSender.setMaxTotalConnections(2); - Map maxConnectionsPerHost = new HashMap(); - maxConnectionsPerHost.put("https://www.example.com", "1"); - maxConnectionsPerHost.put("http://www.example.com:8080", "7"); - maxConnectionsPerHost.put("www.springframework.org", "10"); - maxConnectionsPerHost.put("*", "5"); - messageSender.setMaxConnectionsPerHost(maxConnectionsPerHost); - } + @Test + public void testMaxConnections() throws URISyntaxException, URIException { + CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(); + messageSender.setMaxTotalConnections(2); + Map maxConnectionsPerHost = new HashMap(); + maxConnectionsPerHost.put("https://www.example.com", "1"); + maxConnectionsPerHost.put("http://www.example.com:8080", "7"); + maxConnectionsPerHost.put("www.springframework.org", "10"); + maxConnectionsPerHost.put("*", "5"); + messageSender.setMaxConnectionsPerHost(maxConnectionsPerHost); + } - @Test - public void testContextClose() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - int port = FreePortScanner.getFreePort(); - Server jettyServer = new Server(port); - Context jettyContext = new Context(jettyServer, "/"); - jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/"); - jettyServer.start(); - WebServiceConnection connection = null; - try { + @Test + public void testContextClose() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(); + int port = FreePortScanner.getFreePort(); + Server jettyServer = new Server(port); + Context jettyContext = new Context(jettyServer, "/"); + jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/"); + jettyServer.start(); + WebServiceConnection connection = null; + try { - StaticApplicationContext appContext = new StaticApplicationContext(); - appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class); - appContext.refresh(); + StaticApplicationContext appContext = new StaticApplicationContext(); + appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class); + appContext.refresh(); - CommonsHttpMessageSender messageSender = appContext - .getBean("messageSender", CommonsHttpMessageSender.class); - connection = messageSender.createConnection(new URI("http://localhost:" + port)); + CommonsHttpMessageSender messageSender = appContext + .getBean("messageSender", CommonsHttpMessageSender.class); + connection = messageSender.createConnection(new URI("http://localhost:" + port)); - appContext.close(); + appContext.close(); - connection.send(new SaajSoapMessage(messageFactory.createMessage())); - connection.receive(new SaajSoapMessageFactory(messageFactory)); - } - finally { - if (connection != null) { - try { - connection.close(); - } catch (IOException ex) { - // ignore - } - } - if (jettyServer.isRunning()) { - jettyServer.stop(); - } - } + connection.send(new SaajSoapMessage(messageFactory.createMessage())); + connection.receive(new SaajSoapMessageFactory(messageFactory)); + } + finally { + if (connection != null) { + try { + connection.close(); + } catch (IOException ex) { + // ignore + } + } + if (jettyServer.isRunning()) { + jettyServer.stop(); + } + } - } + } @SuppressWarnings("serial") - private class EchoServlet extends HttpServlet { + private class EchoServlet extends HttpServlet { - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/xml"); - FileCopyUtils.copy(request.getInputStream(), response.getOutputStream()); + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/xml"); + FileCopyUtils.copy(request.getInputStream(), response.getOutputStream()); - } - } + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpComponentsMessageSenderIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpComponentsMessageSenderIntegrationTest.java index b059b4cd..fac7acb9 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpComponentsMessageSenderIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpComponentsMessageSenderIntegrationTest.java @@ -42,72 +42,72 @@ import org.springframework.ws.transport.support.FreePortScanner; public class HttpComponentsMessageSenderIntegrationTest extends AbstractHttpWebServiceMessageSenderIntegrationTestCase { - @Override - protected AbstractHttpWebServiceMessageSender createMessageSender() { - return new HttpComponentsMessageSender(); - } + @Override + protected AbstractHttpWebServiceMessageSender createMessageSender() { + return new HttpComponentsMessageSender(); + } - @Test - public void testMaxConnections() throws URISyntaxException, URIException { - HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender(); - messageSender.setMaxTotalConnections(2); - Map maxConnectionsPerHost = new HashMap(); - maxConnectionsPerHost.put("https://www.example.com", "1"); - maxConnectionsPerHost.put("http://www.example.com:8080", "7"); - maxConnectionsPerHost.put("http://www.springframework.org", "10"); - messageSender.setMaxConnectionsPerHost(maxConnectionsPerHost); - } + @Test + public void testMaxConnections() throws URISyntaxException, URIException { + HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender(); + messageSender.setMaxTotalConnections(2); + Map maxConnectionsPerHost = new HashMap(); + maxConnectionsPerHost.put("https://www.example.com", "1"); + maxConnectionsPerHost.put("http://www.example.com:8080", "7"); + maxConnectionsPerHost.put("http://www.springframework.org", "10"); + messageSender.setMaxConnectionsPerHost(maxConnectionsPerHost); + } - @Test - public void testContextClose() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - int port = FreePortScanner.getFreePort(); - Server jettyServer = new Server(port); - Context jettyContext = new Context(jettyServer, "/"); - jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/"); - jettyServer.start(); - WebServiceConnection connection = null; - try { + @Test + public void testContextClose() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(); + int port = FreePortScanner.getFreePort(); + Server jettyServer = new Server(port); + Context jettyContext = new Context(jettyServer, "/"); + jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/"); + jettyServer.start(); + WebServiceConnection connection = null; + try { - StaticApplicationContext appContext = new StaticApplicationContext(); - appContext.registerSingleton("messageSender", HttpComponentsMessageSender.class); - appContext.refresh(); + StaticApplicationContext appContext = new StaticApplicationContext(); + appContext.registerSingleton("messageSender", HttpComponentsMessageSender.class); + appContext.refresh(); - HttpComponentsMessageSender messageSender = appContext - .getBean("messageSender", HttpComponentsMessageSender.class); - connection = messageSender.createConnection(new URI("http://localhost:" + port)); + HttpComponentsMessageSender messageSender = appContext + .getBean("messageSender", HttpComponentsMessageSender.class); + connection = messageSender.createConnection(new URI("http://localhost:" + port)); - connection.send(new SaajSoapMessage(messageFactory.createMessage())); - connection.receive(new SaajSoapMessageFactory(messageFactory)); + connection.send(new SaajSoapMessage(messageFactory.createMessage())); + connection.receive(new SaajSoapMessageFactory(messageFactory)); - appContext.close(); - } - finally { - if (connection != null) { - try { - connection.close(); - } catch (IOException ex) { - // ignore - } - } - if (jettyServer.isRunning()) { - jettyServer.stop(); - } - } + appContext.close(); + } + finally { + if (connection != null) { + try { + connection.close(); + } catch (IOException ex) { + // ignore + } + } + if (jettyServer.isRunning()) { + jettyServer.stop(); + } + } - } + } @SuppressWarnings("serial") - private class EchoServlet extends HttpServlet { + private class EchoServlet extends HttpServlet { - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/xml"); - FileCopyUtils.copy(request.getInputStream(), response.getOutputStream()); + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/xml"); + FileCopyUtils.copy(request.getInputStream(), response.getOutputStream()); - } - } + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpServletConnectionTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpServletConnectionTest.java index 5958af71..53dc9dd8 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpServletConnectionTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpServletConnectionTest.java @@ -40,71 +40,71 @@ import org.springframework.xml.transform.StringSource; public class HttpServletConnectionTest { - private HttpServletConnection connection; + private HttpServletConnection connection; - private MockHttpServletRequest httpServletRequest; + private MockHttpServletRequest httpServletRequest; - private MockHttpServletResponse httpServletResponse; + private MockHttpServletResponse httpServletResponse; - private static final String HEADER_NAME = "RequestHeader"; + private static final String HEADER_NAME = "RequestHeader"; - private static final String HEADER_VALUE = "RequestHeaderValue"; + private static final String HEADER_VALUE = "RequestHeaderValue"; - private static final String CONTENT = ""; + private static final String CONTENT = ""; - private static final String SOAP_CONTENT = - "" + - CONTENT + ""; + private static final String SOAP_CONTENT = + "" + + CONTENT + ""; - private SaajSoapMessageFactory messageFactory; + private SaajSoapMessageFactory messageFactory; - private TransformerFactory transformerFactory; + private TransformerFactory transformerFactory; - @Before - public void setUp() throws Exception { - httpServletRequest = new MockHttpServletRequest(); - httpServletResponse = new MockHttpServletResponse(); - connection = new HttpServletConnection(httpServletRequest, httpServletResponse); - MessageFactory saajMessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - messageFactory = new SaajSoapMessageFactory(saajMessageFactory); - transformerFactory = TransformerFactory.newInstance(); - } + @Before + public void setUp() throws Exception { + httpServletRequest = new MockHttpServletRequest(); + httpServletResponse = new MockHttpServletResponse(); + connection = new HttpServletConnection(httpServletRequest, httpServletResponse); + MessageFactory saajMessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + messageFactory = new SaajSoapMessageFactory(saajMessageFactory); + transformerFactory = TransformerFactory.newInstance(); + } - @Test - public void receive() throws Exception { - byte[] bytes = SOAP_CONTENT.getBytes("UTF-8"); - httpServletRequest.addHeader("Content-Type", "text/xml"); - httpServletRequest.addHeader("Content-Length", Integer.toString(bytes.length)); - httpServletRequest.addHeader(HEADER_NAME, HEADER_VALUE); - httpServletRequest.setContent(bytes); - SaajSoapMessage message = (SaajSoapMessage) connection.receive(messageFactory); - Assert.assertNotNull("No message received", message); - StringResult result = new StringResult(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.transform(message.getPayloadSource(), result); - assertXMLEqual("Invalid message", CONTENT, result.toString()); - SOAPMessage saajMessage = message.getSaajMessage(); - String[] headerValues = saajMessage.getMimeHeaders().getHeader(HEADER_NAME); - Assert.assertNotNull("Response has no header", headerValues); - assertEquals("Response has invalid header", 1, headerValues.length); - assertEquals("Response has invalid header values", HEADER_VALUE, headerValues[0]); - } + @Test + public void receive() throws Exception { + byte[] bytes = SOAP_CONTENT.getBytes("UTF-8"); + httpServletRequest.addHeader("Content-Type", "text/xml"); + httpServletRequest.addHeader("Content-Length", Integer.toString(bytes.length)); + httpServletRequest.addHeader(HEADER_NAME, HEADER_VALUE); + httpServletRequest.setContent(bytes); + SaajSoapMessage message = (SaajSoapMessage) connection.receive(messageFactory); + Assert.assertNotNull("No message received", message); + StringResult result = new StringResult(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(message.getPayloadSource(), result); + assertXMLEqual("Invalid message", CONTENT, result.toString()); + SOAPMessage saajMessage = message.getSaajMessage(); + String[] headerValues = saajMessage.getMimeHeaders().getHeader(HEADER_NAME); + Assert.assertNotNull("Response has no header", headerValues); + assertEquals("Response has invalid header", 1, headerValues.length); + assertEquals("Response has invalid header values", HEADER_VALUE, headerValues[0]); + } - @Test - public void send() throws Exception { - SaajSoapMessage message = messageFactory.createWebServiceMessage(); - SOAPMessage saajMessage = message.getSaajMessage(); - MimeHeaders mimeHeaders = saajMessage.getMimeHeaders(); - mimeHeaders.addHeader(HEADER_NAME, HEADER_VALUE); - Transformer transformer = transformerFactory.newTransformer(); - transformer.transform(new StringSource(CONTENT), message.getPayloadResult()); + @Test + public void send() throws Exception { + SaajSoapMessage message = messageFactory.createWebServiceMessage(); + SOAPMessage saajMessage = message.getSaajMessage(); + MimeHeaders mimeHeaders = saajMessage.getMimeHeaders(); + mimeHeaders.addHeader(HEADER_NAME, HEADER_VALUE); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(new StringSource(CONTENT), message.getPayloadResult()); - connection.send(message); + connection.send(message); - assertEquals("Invalid header", HEADER_VALUE, - httpServletResponse.getHeader(HEADER_NAME)); - assertXMLEqual("Invalid content", SOAP_CONTENT, httpServletResponse.getContentAsString()); - } + assertEquals("Invalid header", HEADER_VALUE, + httpServletResponse.getHeader(HEADER_NAME)); + assertXMLEqual("Invalid content", SOAP_CONTENT, httpServletResponse.getContentAsString()); + } @Test public void faultCodes() throws IOException { diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSenderIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSenderIntegrationTest.java index dcd5d791..19b3fd11 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSenderIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/HttpUrlConnectionMessageSenderIntegrationTest.java @@ -17,10 +17,10 @@ package org.springframework.ws.transport.http; public class HttpUrlConnectionMessageSenderIntegrationTest - extends AbstractHttpWebServiceMessageSenderIntegrationTestCase { + extends AbstractHttpWebServiceMessageSenderIntegrationTestCase { - @Override - protected AbstractHttpWebServiceMessageSender createMessageSender() { - return new HttpUrlConnectionMessageSender(); - } + @Override + protected AbstractHttpWebServiceMessageSender createMessageSender() { + return new HttpUrlConnectionMessageSender(); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/LastModifiedHelperTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/LastModifiedHelperTest.java index f5c1b7be..448bf1fc 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/LastModifiedHelperTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/LastModifiedHelperTest.java @@ -32,35 +32,35 @@ import org.w3c.dom.Document; public class LastModifiedHelperTest { - private Resource resource; + private Resource resource; - private long expected; + private long expected; - @Before - public void setUp() throws Exception { - resource = new ClassPathResource("single.xsd", getClass()); - expected = resource.lastModified(); - } + @Before + public void setUp() throws Exception { + resource = new ClassPathResource("single.xsd", getClass()); + expected = resource.lastModified(); + } - @Test - public void testSaxSource() throws Exception { - long result = LastModifiedHelper.getLastModified(new ResourceSource(resource)); - Assert.assertEquals("Invalid last modified", expected, result); - } + @Test + public void testSaxSource() throws Exception { + long result = LastModifiedHelper.getLastModified(new ResourceSource(resource)); + Assert.assertEquals("Invalid last modified", expected, result); + } - @Test - public void testDomSource() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.parse(resource.getFile()); - long result = LastModifiedHelper.getLastModified(new DOMSource(document)); - Assert.assertEquals("Invalid last modified", expected, result); - } + @Test + public void testDomSource() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.parse(resource.getFile()); + long result = LastModifiedHelper.getLastModified(new DOMSource(document)); + Assert.assertEquals("Invalid last modified", expected, result); + } - @Test - public void testStreamSource() throws Exception { - long result = LastModifiedHelper.getLastModified(new StreamSource(resource.getFile())); - Assert.assertEquals("Invalid last modified", expected, result); - } + @Test + public void testStreamSource() throws Exception { + long result = LastModifiedHelper.getLastModified(new StreamSource(resource.getFile())); + Assert.assertEquals("Invalid last modified", expected, result); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletIntegrationTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletIntegrationTest.java index 783d0785..ee3dc35e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletIntegrationTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletIntegrationTest.java @@ -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, @@ -43,54 +43,54 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; */ public class MessageDispatcherServletIntegrationTest { - private static Server jettyServer; + private static Server jettyServer; - private static String url; + private static String url; - private MessageFactory messageFactory; + private MessageFactory messageFactory; - private SOAPConnectionFactory connectionFactory; + private SOAPConnectionFactory connectionFactory; - @BeforeClass - public static void startJetty() throws Exception { - int port = FreePortScanner.getFreePort(); - url = "http://localhost:" + port; - jettyServer = new Server(port); - Context jettyContext = new Context(jettyServer, "/"); - String resourceBase = - new File(MessageDispatcherServletIntegrationTest.class.getResource("WEB-INF").toURI()).getParent(); - jettyContext.setResourceBase(resourceBase); - ServletHolder servletHolder = new ServletHolder(new MessageDispatcherServlet()); - servletHolder.setName("sws"); - jettyContext.addServlet(servletHolder, "/"); - jettyServer.start(); - } + @BeforeClass + public static void startJetty() throws Exception { + int port = FreePortScanner.getFreePort(); + url = "http://localhost:" + port; + jettyServer = new Server(port); + Context jettyContext = new Context(jettyServer, "/"); + String resourceBase = + new File(MessageDispatcherServletIntegrationTest.class.getResource("WEB-INF").toURI()).getParent(); + jettyContext.setResourceBase(resourceBase); + ServletHolder servletHolder = new ServletHolder(new MessageDispatcherServlet()); + servletHolder.setName("sws"); + jettyContext.addServlet(servletHolder, "/"); + jettyServer.start(); + } - @Before - public void setUpSaaj() throws SOAPException { - messageFactory = MessageFactory.newInstance(); - connectionFactory = SOAPConnectionFactory.newInstance(); - } + @Before + public void setUpSaaj() throws SOAPException { + messageFactory = MessageFactory.newInstance(); + connectionFactory = SOAPConnectionFactory.newInstance(); + } - @AfterClass - public static void stopJetty() throws Exception { - if (jettyServer.isRunning()) { - jettyServer.stop(); - } - } + @AfterClass + public static void stopJetty() throws Exception { + if (jettyServer.isRunning()) { + jettyServer.stop(); + } + } - @Test - public void echo() throws SOAPException { - SOAPMessage request = messageFactory.createMessage(); - SOAPElement element = request.getSOAPBody().addChildElement(new QName(EchoPayloadEndpoint.NAMESPACE, EchoPayloadEndpoint.LOCAL_PART)); - element.setTextContent("Hello World"); + @Test + public void echo() throws SOAPException { + SOAPMessage request = messageFactory.createMessage(); + SOAPElement element = request.getSOAPBody().addChildElement(new QName(EchoPayloadEndpoint.NAMESPACE, EchoPayloadEndpoint.LOCAL_PART)); + element.setTextContent("Hello World"); - SOAPConnection connection = connectionFactory.createConnection(); + SOAPConnection connection = connectionFactory.createConnection(); - SOAPMessage response = connection.call(request, url); + SOAPMessage response = connection.call(request, url); - assertXMLEqual(request.getSOAPPart(), response.getSOAPPart()); - } + assertXMLEqual(request.getSOAPPart(), response.getSOAPPart()); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletTest.java index aac909db..2ccf2bbc 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/MessageDispatcherServletTest.java @@ -47,77 +47,77 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class MessageDispatcherServletTest { - private ServletConfig config; + private ServletConfig config; - private MessageDispatcherServlet servlet; + private MessageDispatcherServlet servlet; - @Before - public void setUp() throws Exception { - config = new MockServletConfig(new MockServletContext(), "spring-ws"); - servlet = new MessageDispatcherServlet(); - } + @Before + public void setUp() throws Exception { + config = new MockServletConfig(new MockServletContext(), "spring-ws"); + servlet = new MessageDispatcherServlet(); + } - private void assertStrategies(Class expectedClass, List actual) { - Assert.assertEquals("Invalid amount of strategies", 1, actual.size()); - Object strategy = actual.get(0); - Assert.assertTrue("Invalid strategy", expectedClass.isAssignableFrom(strategy.getClass())); - } + private void assertStrategies(Class expectedClass, List actual) { + Assert.assertEquals("Invalid amount of strategies", 1, actual.size()); + Object strategy = actual.get(0); + Assert.assertTrue("Invalid strategy", expectedClass.isAssignableFrom(strategy.getClass())); + } - @Test - public void testDefaultStrategies() throws ServletException { - servlet.setContextClass(StaticWebApplicationContext.class); - servlet.init(config); - MessageDispatcher messageDispatcher = (MessageDispatcher) servlet.getMessageReceiver(); - Assert.assertNotNull("No messageDispatcher created", messageDispatcher); - } + @Test + public void testDefaultStrategies() throws ServletException { + servlet.setContextClass(StaticWebApplicationContext.class); + servlet.init(config); + MessageDispatcher messageDispatcher = (MessageDispatcher) servlet.getMessageReceiver(); + Assert.assertNotNull("No messageDispatcher created", messageDispatcher); + } - @Test - public void testDetectedStrategies() throws ServletException { - servlet.setContextClass(DetectWebApplicationContext.class); - servlet.init(config); - MessageDispatcher messageDispatcher = (MessageDispatcher) servlet.getMessageReceiver(); - Assert.assertNotNull("No messageDispatcher created", messageDispatcher); - assertStrategies(PayloadRootQNameEndpointMapping.class, messageDispatcher.getEndpointMappings()); - assertStrategies(PayloadEndpointAdapter.class, messageDispatcher.getEndpointAdapters()); - assertStrategies(SimpleSoapExceptionResolver.class, messageDispatcher.getEndpointExceptionResolvers()); - } + @Test + public void testDetectedStrategies() throws ServletException { + servlet.setContextClass(DetectWebApplicationContext.class); + servlet.init(config); + MessageDispatcher messageDispatcher = (MessageDispatcher) servlet.getMessageReceiver(); + Assert.assertNotNull("No messageDispatcher created", messageDispatcher); + assertStrategies(PayloadRootQNameEndpointMapping.class, messageDispatcher.getEndpointMappings()); + assertStrategies(PayloadEndpointAdapter.class, messageDispatcher.getEndpointAdapters()); + assertStrategies(SimpleSoapExceptionResolver.class, messageDispatcher.getEndpointExceptionResolvers()); + } - @Test - public void testDetectWsdlDefinitions() throws Exception { - servlet.setContextClass(WsdlDefinitionWebApplicationContext.class); - servlet.init(config); - MockHttpServletRequest request = - new MockHttpServletRequest(HttpTransportConstants.METHOD_GET, "/definition.wsdl"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document result = documentBuilder.parse(new ByteArrayInputStream(response.getContentAsByteArray())); - Document expected = documentBuilder.parse(getClass().getResourceAsStream("wsdl11-input.wsdl")); - XMLUnit.setIgnoreWhitespace(true); - assertXMLEqual("Invalid WSDL written", expected, result); - } + @Test + public void testDetectWsdlDefinitions() throws Exception { + servlet.setContextClass(WsdlDefinitionWebApplicationContext.class); + servlet.init(config); + MockHttpServletRequest request = + new MockHttpServletRequest(HttpTransportConstants.METHOD_GET, "/definition.wsdl"); + MockHttpServletResponse response = new MockHttpServletResponse(); + servlet.service(request, response); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document result = documentBuilder.parse(new ByteArrayInputStream(response.getContentAsByteArray())); + Document expected = documentBuilder.parse(getClass().getResourceAsStream("wsdl11-input.wsdl")); + XMLUnit.setIgnoreWhitespace(true); + assertXMLEqual("Invalid WSDL written", expected, result); + } - private static class DetectWebApplicationContext extends StaticWebApplicationContext { + private static class DetectWebApplicationContext extends StaticWebApplicationContext { - @Override - public void refresh() throws BeansException, IllegalStateException { - registerSingleton("payloadMapping", PayloadRootQNameEndpointMapping.class); - registerSingleton("payloadAdapter", PayloadEndpointAdapter.class); - registerSingleton("simpleExceptionResolver", SimpleSoapExceptionResolver.class); - super.refresh(); - } - } + @Override + public void refresh() throws BeansException, IllegalStateException { + registerSingleton("payloadMapping", PayloadRootQNameEndpointMapping.class); + registerSingleton("payloadAdapter", PayloadEndpointAdapter.class); + registerSingleton("simpleExceptionResolver", SimpleSoapExceptionResolver.class); + super.refresh(); + } + } - private static class WsdlDefinitionWebApplicationContext extends StaticWebApplicationContext { + private static class WsdlDefinitionWebApplicationContext extends StaticWebApplicationContext { - @Override - public void refresh() throws BeansException, IllegalStateException { - MutablePropertyValues mpv = new MutablePropertyValues(); - mpv.addPropertyValue("wsdl", new ClassPathResource("wsdl11-input.wsdl", getClass())); - registerSingleton("definition", SimpleWsdl11Definition.class, mpv); - super.refresh(); - } - } + @Override + public void refresh() throws BeansException, IllegalStateException { + MutablePropertyValues mpv = new MutablePropertyValues(); + mpv.addPropertyValue("wsdl", new ClassPathResource("wsdl11-input.wsdl", getClass())); + registerSingleton("definition", SimpleWsdl11Definition.class, mpv); + super.refresh(); + } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapterTest.java index 2a4c95d3..a19b1b50 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHandlerAdapterTest.java @@ -37,182 +37,182 @@ import org.springframework.ws.transport.WebServiceMessageReceiver; public class WebServiceMessageReceiverHandlerAdapterTest { - private static final String REQUEST = " \n" + " \n" + - " \n" + " DIS\n" + - " \n" + " \n" + ""; + private static final String REQUEST = " \n" + " \n" + + " \n" + " DIS\n" + + " \n" + " \n" + ""; - private WebServiceMessageReceiverHandlerAdapter adapter; + private WebServiceMessageReceiverHandlerAdapter adapter; - private MockHttpServletRequest httpRequest; + private MockHttpServletRequest httpRequest; - private MockHttpServletResponse httpResponse; + private MockHttpServletResponse httpResponse; - private WebServiceMessageFactory factoryMock; + private WebServiceMessageFactory factoryMock; - private FaultAwareWebServiceMessage responseMock; + private FaultAwareWebServiceMessage responseMock; - private FaultAwareWebServiceMessage requestMock; + private FaultAwareWebServiceMessage requestMock; - @Before - public void setUp() throws Exception { - adapter = new WebServiceMessageReceiverHandlerAdapter(); - httpRequest = new MockHttpServletRequest(); - httpResponse = new MockHttpServletResponse(); - factoryMock = createMock(WebServiceMessageFactory.class); - adapter.setMessageFactory(factoryMock); - requestMock = createMock("request", FaultAwareWebServiceMessage.class); - responseMock = createMock("response", FaultAwareWebServiceMessage.class); - } + @Before + public void setUp() throws Exception { + adapter = new WebServiceMessageReceiverHandlerAdapter(); + httpRequest = new MockHttpServletRequest(); + httpResponse = new MockHttpServletResponse(); + factoryMock = createMock(WebServiceMessageFactory.class); + adapter.setMessageFactory(factoryMock); + requestMock = createMock("request", FaultAwareWebServiceMessage.class); + responseMock = createMock("response", FaultAwareWebServiceMessage.class); + } - @Test - public void testHandleNonPost() throws Exception { - httpRequest.setMethod(HttpTransportConstants.METHOD_GET); - replayMockControls(); - WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { + @Test + public void testHandleNonPost() throws Exception { + httpRequest.setMethod(HttpTransportConstants.METHOD_GET); + replayMockControls(); + WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - } - }; - adapter.handle(httpRequest, httpResponse, endpoint); - Assert.assertEquals("METHOD_NOT_ALLOWED expected", HttpServletResponse.SC_METHOD_NOT_ALLOWED, - httpResponse.getStatus()); - verifyMockControls(); - } + @Override + public void receive(MessageContext messageContext) throws Exception { + } + }; + adapter.handle(httpRequest, httpResponse, endpoint); + Assert.assertEquals("METHOD_NOT_ALLOWED expected", HttpServletResponse.SC_METHOD_NOT_ALLOWED, + httpResponse.getStatus()); + verifyMockControls(); + } - @Test - public void testHandlePostNoResponse() throws Exception { - httpRequest.setMethod(HttpTransportConstants.METHOD_POST); - httpRequest.setContent(REQUEST.getBytes("UTF-8")); - httpRequest.setContentType("text/xml; charset=\"utf-8\""); - httpRequest.setCharacterEncoding("UTF-8"); - expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(responseMock); + @Test + public void testHandlePostNoResponse() throws Exception { + httpRequest.setMethod(HttpTransportConstants.METHOD_POST); + httpRequest.setContent(REQUEST.getBytes("UTF-8")); + httpRequest.setContentType("text/xml; charset=\"utf-8\""); + httpRequest.setCharacterEncoding("UTF-8"); + expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(responseMock); - replayMockControls(); - WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { + replayMockControls(); + WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + } + }; - adapter.handle(httpRequest, httpResponse, endpoint); + adapter.handle(httpRequest, httpResponse, endpoint); - Assert.assertEquals("Invalid status code on response", HttpServletResponse.SC_ACCEPTED, - httpResponse.getStatus()); - Assert.assertEquals("Response written", 0, httpResponse.getContentAsString().length()); - verifyMockControls(); - } + Assert.assertEquals("Invalid status code on response", HttpServletResponse.SC_ACCEPTED, + httpResponse.getStatus()); + Assert.assertEquals("Response written", 0, httpResponse.getContentAsString().length()); + verifyMockControls(); + } - @Test - public void testHandlePostResponse() throws Exception { - httpRequest.setMethod(HttpTransportConstants.METHOD_POST); - httpRequest.setContent(REQUEST.getBytes("UTF-8")); - httpRequest.setContentType("text/xml; charset=\"utf-8\""); - httpRequest.setCharacterEncoding("UTF-8"); - expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(requestMock); - expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); - expect(responseMock.getFaultCode()).andReturn(null); - responseMock.writeTo(isA(OutputStream.class)); + @Test + public void testHandlePostResponse() throws Exception { + httpRequest.setMethod(HttpTransportConstants.METHOD_POST); + httpRequest.setContent(REQUEST.getBytes("UTF-8")); + httpRequest.setContentType("text/xml; charset=\"utf-8\""); + httpRequest.setCharacterEncoding("UTF-8"); + expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(requestMock); + expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); + expect(responseMock.getFaultCode()).andReturn(null); + responseMock.writeTo(isA(OutputStream.class)); - replayMockControls(); - WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { + replayMockControls(); + WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - messageContext.getResponse(); - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + messageContext.getResponse(); + } + }; - adapter.handle(httpRequest, httpResponse, endpoint); + adapter.handle(httpRequest, httpResponse, endpoint); - Assert.assertEquals("Invalid status code on response", HttpServletResponse.SC_OK, httpResponse.getStatus()); - verifyMockControls(); - } + Assert.assertEquals("Invalid status code on response", HttpServletResponse.SC_OK, httpResponse.getStatus()); + verifyMockControls(); + } - @Test - public void testHandlePostFault() throws Exception { - httpRequest.setMethod(HttpTransportConstants.METHOD_POST); - httpRequest.setContent(REQUEST.getBytes("UTF-8")); - httpRequest.setContentType("text/xml; charset=\"utf-8\""); - httpRequest.setCharacterEncoding("UTF-8"); - expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(requestMock); - expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); - expect(responseMock.getFaultCode()).andReturn(SoapVersion.SOAP_11.getServerOrReceiverFaultName()); - responseMock.writeTo(isA(OutputStream.class)); + @Test + public void testHandlePostFault() throws Exception { + httpRequest.setMethod(HttpTransportConstants.METHOD_POST); + httpRequest.setContent(REQUEST.getBytes("UTF-8")); + httpRequest.setContentType("text/xml; charset=\"utf-8\""); + httpRequest.setCharacterEncoding("UTF-8"); + expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(requestMock); + expect(factoryMock.createWebServiceMessage()).andReturn(responseMock); + expect(responseMock.getFaultCode()).andReturn(SoapVersion.SOAP_11.getServerOrReceiverFaultName()); + responseMock.writeTo(isA(OutputStream.class)); - replayMockControls(); - WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { + replayMockControls(); + WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - messageContext.getResponse(); - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + messageContext.getResponse(); + } + }; - adapter.handle(httpRequest, httpResponse, endpoint); + adapter.handle(httpRequest, httpResponse, endpoint); - Assert.assertEquals("Invalid status code on response", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - httpResponse.getStatus()); - verifyMockControls(); - } + Assert.assertEquals("Invalid status code on response", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + httpResponse.getStatus()); + verifyMockControls(); + } - @Test - public void testHandleNotFound() throws Exception { - httpRequest.setMethod(HttpTransportConstants.METHOD_POST); - httpRequest.setContent(REQUEST.getBytes("UTF-8")); - httpRequest.setContentType("text/xml; charset=\"utf-8\""); - httpRequest.setCharacterEncoding("UTF-8"); - expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(requestMock); + @Test + public void testHandleNotFound() throws Exception { + httpRequest.setMethod(HttpTransportConstants.METHOD_POST); + httpRequest.setContent(REQUEST.getBytes("UTF-8")); + httpRequest.setContentType("text/xml; charset=\"utf-8\""); + httpRequest.setCharacterEncoding("UTF-8"); + expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andReturn(requestMock); - replayMockControls(); + replayMockControls(); - WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { + WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - throw new NoEndpointFoundException(messageContext.getRequest()); - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + throw new NoEndpointFoundException(messageContext.getRequest()); + } + }; - adapter.handle(httpRequest, httpResponse, endpoint); - Assert.assertEquals("No 404 returned", HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatus()); + adapter.handle(httpRequest, httpResponse, endpoint); + Assert.assertEquals("No 404 returned", HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatus()); - verifyMockControls(); + verifyMockControls(); - } + } - @Test - public void testHandleInvalidXml() throws Exception { - httpRequest.setMethod(HttpTransportConstants.METHOD_POST); - httpRequest.setContent(REQUEST.getBytes("UTF-8")); - httpRequest.setContentType("text/xml; charset=\"utf-8\""); - httpRequest.setCharacterEncoding("UTF-8"); - expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andThrow(new InvalidXmlException(null, null)); + @Test + public void testHandleInvalidXml() throws Exception { + httpRequest.setMethod(HttpTransportConstants.METHOD_POST); + httpRequest.setContent(REQUEST.getBytes("UTF-8")); + httpRequest.setContentType("text/xml; charset=\"utf-8\""); + httpRequest.setCharacterEncoding("UTF-8"); + expect(factoryMock.createWebServiceMessage(isA(InputStream.class))).andThrow(new InvalidXmlException(null, null)); - replayMockControls(); + replayMockControls(); - WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { + WebServiceMessageReceiver endpoint = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + } + }; - adapter.handle(httpRequest, httpResponse, endpoint); - Assert.assertEquals("No 400 returned", HttpServletResponse.SC_BAD_REQUEST, httpResponse.getStatus()); + adapter.handle(httpRequest, httpResponse, endpoint); + Assert.assertEquals("No 400 returned", HttpServletResponse.SC_BAD_REQUEST, httpResponse.getStatus()); - verifyMockControls(); - } + verifyMockControls(); + } - private void replayMockControls() { - replay(factoryMock, requestMock, responseMock); - } + private void replayMockControls() { + replay(factoryMock, requestMock, responseMock); + } - private void verifyMockControls() { - verify(factoryMock, requestMock, responseMock); - } + private void verifyMockControls() { + verify(factoryMock, requestMock, responseMock); + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapterTest.java index 93fbf192..0d7c1575 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/WsdlDefinitionHandlerAdapterTest.java @@ -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, @@ -40,189 +40,189 @@ import static org.easymock.EasyMock.*; public class WsdlDefinitionHandlerAdapterTest { - private WsdlDefinitionHandlerAdapter adapter; + private WsdlDefinitionHandlerAdapter adapter; - private WsdlDefinition definitionMock; + private WsdlDefinition definitionMock; - private MockHttpServletRequest request; + private MockHttpServletRequest request; - private MockHttpServletResponse response; + private MockHttpServletResponse response; - @Before - public void setUp() throws Exception { - adapter = new WsdlDefinitionHandlerAdapter(); - definitionMock = createMock(WsdlDefinition.class); - adapter.afterPropertiesSet(); - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - } + @Before + public void setUp() throws Exception { + adapter = new WsdlDefinitionHandlerAdapter(); + definitionMock = createMock(WsdlDefinition.class); + adapter.afterPropertiesSet(); + request = new MockHttpServletRequest(); + response = new MockHttpServletResponse(); + } - @Test - public void handleGet() throws Exception { - request.setMethod(HttpTransportConstants.METHOD_GET); - String definition = ""; - expect(definitionMock.getSource()).andReturn(new StringSource(definition)); + @Test + public void handleGet() throws Exception { + request.setMethod(HttpTransportConstants.METHOD_GET); + String definition = ""; + expect(definitionMock.getSource()).andReturn(new StringSource(definition)); - replay(definitionMock); + replay(definitionMock); - adapter.handle(request, response, definitionMock); - assertXMLEqual(definition, response.getContentAsString()); + adapter.handle(request, response, definitionMock); + assertXMLEqual(definition, response.getContentAsString()); - verify(definitionMock); - } + verify(definitionMock); + } - @Test - public void handleNonGet() throws Exception { - request.setMethod(HttpTransportConstants.METHOD_POST); + @Test + public void handleNonGet() throws Exception { + request.setMethod(HttpTransportConstants.METHOD_POST); - replay(definitionMock); + replay(definitionMock); - adapter.handle(request, response, definitionMock); - Assert.assertEquals("METHOD_NOT_ALLOWED expected", HttpServletResponse.SC_METHOD_NOT_ALLOWED, - response.getStatus()); + adapter.handle(request, response, definitionMock); + Assert.assertEquals("METHOD_NOT_ALLOWED expected", HttpServletResponse.SC_METHOD_NOT_ALLOWED, + response.getStatus()); - verify(definitionMock); - } + verify(definitionMock); + } - @Test - public void transformLocations() throws Exception { - adapter.setTransformLocations(true); - request.setMethod(HttpTransportConstants.METHOD_GET); - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(8080); - request.setContextPath("/context"); - request.setServletPath("/service.wsdl"); - request.setPathInfo(null); - request.setRequestURI("/context/service.wsdl"); + @Test + public void transformLocations() throws Exception { + adapter.setTransformLocations(true); + request.setMethod(HttpTransportConstants.METHOD_GET); + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(8080); + request.setContextPath("/context"); + request.setServletPath("/service.wsdl"); + request.setPathInfo(null); + request.setRequestURI("/context/service.wsdl"); - replay(definitionMock); + replay(definitionMock); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document result = documentBuilder.parse(getClass().getResourceAsStream("wsdl11-input.wsdl")); - adapter.transformLocations(result, request); - Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("wsdl11-expected.wsdl")); - assertXMLEqual("Invalid result", expectedDocument, result); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document result = documentBuilder.parse(getClass().getResourceAsStream("wsdl11-input.wsdl")); + adapter.transformLocations(result, request); + Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("wsdl11-expected.wsdl")); + assertXMLEqual("Invalid result", expectedDocument, result); - verify(definitionMock); - } + verify(definitionMock); + } - @Test - public void transformLocationFullUrl() throws Exception { - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(8080); - request.setContextPath("/context"); - request.setPathInfo("/service.wsdl"); - request.setRequestURI("/context/service.wsdl"); - String oldLocation = "http://localhost:8080/context/service"; + @Test + public void transformLocationFullUrl() throws Exception { + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(8080); + request.setContextPath("/context"); + request.setPathInfo("/service.wsdl"); + request.setRequestURI("/context/service.wsdl"); + String oldLocation = "http://localhost:8080/context/service"; - String result = adapter.transformLocation(oldLocation, request); - Assert.assertNotNull("No result", result); - Assert.assertEquals("Invalid result", new URI("http://example.com:8080/context/service"), new URI(result)); - } + String result = adapter.transformLocation(oldLocation, request); + Assert.assertNotNull("No result", result); + Assert.assertEquals("Invalid result", new URI("http://example.com:8080/context/service"), new URI(result)); + } - @Test - public void transformLocationEmptyContextFullUrl() throws Exception { - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(8080); - request.setContextPath(""); - request.setRequestURI("/service.wsdl"); - String oldLocation = "http://localhost:8080/service"; + @Test + public void transformLocationEmptyContextFullUrl() throws Exception { + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(8080); + request.setContextPath(""); + request.setRequestURI("/service.wsdl"); + String oldLocation = "http://localhost:8080/service"; - String result = adapter.transformLocation(oldLocation, request); - Assert.assertNotNull("No result", result); - Assert.assertEquals("Invalid result", new URI("http://example.com:8080/service"), new URI(result)); - } + String result = adapter.transformLocation(oldLocation, request); + Assert.assertNotNull("No result", result); + Assert.assertEquals("Invalid result", new URI("http://example.com:8080/service"), new URI(result)); + } - @Test - public void transformLocationRelativeUrl() throws Exception { - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(8080); - request.setContextPath("/context"); - request.setPathInfo("/service.wsdl"); - request.setRequestURI("/context/service.wsdl"); - String oldLocation = "/service"; + @Test + public void transformLocationRelativeUrl() throws Exception { + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(8080); + request.setContextPath("/context"); + request.setPathInfo("/service.wsdl"); + request.setRequestURI("/context/service.wsdl"); + String oldLocation = "/service"; - String result = adapter.transformLocation(oldLocation, request); - Assert.assertNotNull("No result", result); - Assert.assertEquals("Invalid result", new URI("http://example.com:8080/context/service"), new URI(result)); - } + String result = adapter.transformLocation(oldLocation, request); + Assert.assertNotNull("No result", result); + Assert.assertEquals("Invalid result", new URI("http://example.com:8080/context/service"), new URI(result)); + } - @Test - public void transformLocationEmptyContextRelativeUrl() throws Exception { - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(8080); - request.setContextPath(""); - request.setRequestURI("/service.wsdl"); - String oldLocation = "/service"; + @Test + public void transformLocationEmptyContextRelativeUrl() throws Exception { + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(8080); + request.setContextPath(""); + request.setRequestURI("/service.wsdl"); + String oldLocation = "/service"; - String result = adapter.transformLocation(oldLocation, request); - Assert.assertNotNull("No result", result); - Assert.assertEquals("Invalid result", new URI("http://example.com:8080/service"), new URI(result)); - } + String result = adapter.transformLocation(oldLocation, request); + Assert.assertNotNull("No result", result); + Assert.assertEquals("Invalid result", new URI("http://example.com:8080/service"), new URI(result)); + } - @Test - public void handleSimpleWsdl11DefinitionWithoutTransformLocations() throws Exception { - adapter.setTransformLocations(false); - request.setMethod(HttpTransportConstants.METHOD_GET); - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(8080); - request.setContextPath("/context"); - request.setServletPath("/service.wsdl"); - request.setPathInfo(null); - request.setRequestURI("/context/service.wsdl"); + @Test + public void handleSimpleWsdl11DefinitionWithoutTransformLocations() throws Exception { + adapter.setTransformLocations(false); + request.setMethod(HttpTransportConstants.METHOD_GET); + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(8080); + request.setContextPath("/context"); + request.setServletPath("/service.wsdl"); + request.setPathInfo(null); + request.setRequestURI("/context/service.wsdl"); - SimpleWsdl11Definition definition = - new SimpleWsdl11Definition(new ClassPathResource("echo-input.wsdl", getClass())); + SimpleWsdl11Definition definition = + new SimpleWsdl11Definition(new ClassPathResource("echo-input.wsdl", getClass())); - adapter.handle(request, response, definition); + adapter.handle(request, response, definition); - InputStream inputStream = new ByteArrayInputStream(response.getContentAsByteArray()); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document resultingDocument = documentBuilder.parse(inputStream); + InputStream inputStream = new ByteArrayInputStream(response.getContentAsByteArray()); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document resultingDocument = documentBuilder.parse(inputStream); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("echo-input.wsdl")); - assertXMLEqual("Invalid WSDL returned", expectedDocument, resultingDocument); - } + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("echo-input.wsdl")); + assertXMLEqual("Invalid WSDL returned", expectedDocument, resultingDocument); + } - @Test - public void handleSimpleWsdl11DefinitionWithTransformLocation() throws Exception { - adapter.setTransformLocations(true); - adapter.setTransformSchemaLocations(true); + @Test + public void handleSimpleWsdl11DefinitionWithTransformLocation() throws Exception { + adapter.setTransformLocations(true); + adapter.setTransformSchemaLocations(true); - request.setMethod(HttpTransportConstants.METHOD_GET); - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(80); - request.setContextPath("/context"); - request.setServletPath("/service.wsdl"); - request.setPathInfo(null); - request.setRequestURI("/context/service.wsdl"); + request.setMethod(HttpTransportConstants.METHOD_GET); + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(80); + request.setContextPath("/context"); + request.setServletPath("/service.wsdl"); + request.setPathInfo(null); + request.setRequestURI("/context/service.wsdl"); - SimpleWsdl11Definition definition = - new SimpleWsdl11Definition(new ClassPathResource("echo-input.wsdl", getClass())); + SimpleWsdl11Definition definition = + new SimpleWsdl11Definition(new ClassPathResource("echo-input.wsdl", getClass())); - adapter.handle(request, response, definition); + adapter.handle(request, response, definition); - InputStream inputStream = new ByteArrayInputStream(response.getContentAsByteArray()); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document resultingDocument = documentBuilder.parse(inputStream); + InputStream inputStream = new ByteArrayInputStream(response.getContentAsByteArray()); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document resultingDocument = documentBuilder.parse(inputStream); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("echo-expected.wsdl")); - assertXMLEqual("Invalid WSDL returned", expectedDocument, resultingDocument); - } + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("echo-expected.wsdl")); + assertXMLEqual("Invalid WSDL returned", expectedDocument, resultingDocument); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapterTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapterTest.java index 95cfb21a..0b0e7797 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapterTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/http/XsdSchemaHandlerAdapterTest.java @@ -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, @@ -38,75 +38,75 @@ import static org.junit.Assert.assertEquals; public class XsdSchemaHandlerAdapterTest { - private XsdSchemaHandlerAdapter adapter; + private XsdSchemaHandlerAdapter adapter; - private MockHttpServletRequest request; + private MockHttpServletRequest request; - private MockHttpServletResponse response; + private MockHttpServletResponse response; - @Before - public void setUp() throws Exception { - adapter = new XsdSchemaHandlerAdapter(); - adapter.afterPropertiesSet(); - request = new MockHttpServletRequest(); - response = new MockHttpServletResponse(); - } + @Before + public void setUp() throws Exception { + adapter = new XsdSchemaHandlerAdapter(); + adapter.afterPropertiesSet(); + request = new MockHttpServletRequest(); + response = new MockHttpServletResponse(); + } - @Test - public void getLastModified() throws Exception { - Resource single = new ClassPathResource("single.xsd", getClass()); - SimpleXsdSchema schema = new SimpleXsdSchema(single); - schema.afterPropertiesSet(); - long lastModified = single.getFile().lastModified(); - assertEquals("Invalid last modified", lastModified, adapter.getLastModified(null, schema)); - } + @Test + public void getLastModified() throws Exception { + Resource single = new ClassPathResource("single.xsd", getClass()); + SimpleXsdSchema schema = new SimpleXsdSchema(single); + schema.afterPropertiesSet(); + long lastModified = single.getFile().lastModified(); + assertEquals("Invalid last modified", lastModified, adapter.getLastModified(null, schema)); + } - @Test - public void handleGet() throws Exception { - request.setMethod(HttpTransportConstants.METHOD_GET); - Resource single = new ClassPathResource("single.xsd", getClass()); - SimpleXsdSchema schema = new SimpleXsdSchema(single); - schema.afterPropertiesSet(); - adapter.handle(request, response, schema); - String expected = new String(FileCopyUtils.copyToByteArray(single.getFile())); - assertXMLEqual(expected, response.getContentAsString()); - } + @Test + public void handleGet() throws Exception { + request.setMethod(HttpTransportConstants.METHOD_GET); + Resource single = new ClassPathResource("single.xsd", getClass()); + SimpleXsdSchema schema = new SimpleXsdSchema(single); + schema.afterPropertiesSet(); + adapter.handle(request, response, schema); + String expected = new String(FileCopyUtils.copyToByteArray(single.getFile())); + assertXMLEqual(expected, response.getContentAsString()); + } - @Test - public void handleNonGet() throws Exception { - request.setMethod(HttpTransportConstants.METHOD_POST); - adapter.handle(request, response, null); - assertEquals("METHOD_NOT_ALLOWED expected", HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus()); - } + @Test + public void handleNonGet() throws Exception { + request.setMethod(HttpTransportConstants.METHOD_POST); + adapter.handle(request, response, null); + assertEquals("METHOD_NOT_ALLOWED expected", HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus()); + } - @Test - public void handleGetWithTransformLocation() throws Exception { - adapter.setTransformSchemaLocations(true); + @Test + public void handleGetWithTransformLocation() throws Exception { + adapter.setTransformSchemaLocations(true); - request.setMethod(HttpTransportConstants.METHOD_GET); - request.setScheme("http"); - request.setServerName("example.com"); - request.setServerPort(80); - request.setContextPath("/context"); - request.setServletPath("/service.xsd"); - request.setPathInfo(null); - request.setRequestURI("/context/service.xsd"); + request.setMethod(HttpTransportConstants.METHOD_GET); + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(80); + request.setContextPath("/context"); + request.setServletPath("/service.xsd"); + request.setPathInfo(null); + request.setRequestURI("/context/service.xsd"); - Resource importing = new ClassPathResource("importing-input.xsd", getClass()); - SimpleXsdSchema schema = new SimpleXsdSchema(importing); - schema.afterPropertiesSet(); + Resource importing = new ClassPathResource("importing-input.xsd", getClass()); + SimpleXsdSchema schema = new SimpleXsdSchema(importing); + schema.afterPropertiesSet(); - adapter.handle(request, response, schema); + adapter.handle(request, response, schema); - InputStream inputStream = new ByteArrayInputStream(response.getContentAsByteArray()); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document resultingDocument = documentBuilder.parse(inputStream); + InputStream inputStream = new ByteArrayInputStream(response.getContentAsByteArray()); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document resultingDocument = documentBuilder.parse(inputStream); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("importing-expected.xsd")); - assertXMLEqual("Invalid WSDL returned", expectedDocument, resultingDocument); - } + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expectedDocument = documentBuilder.parse(getClass().getResourceAsStream("importing-expected.xsd")); + assertXMLEqual("Invalid WSDL returned", expectedDocument, resultingDocument); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java index 41972f73..bca64710 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java @@ -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.server.endpoint.annotation.ResponsePayload; @Endpoint public class EchoPayloadEndpoint { - public static final String NAMESPACE = "http://springframework.org"; + public static final String NAMESPACE = "http://springframework.org"; - public static final String LOCAL_PART = "root"; + public static final String LOCAL_PART = "root"; - @PayloadRoot(localPart = LOCAL_PART, namespace = NAMESPACE) - @ResponsePayload - public Source invoke(@RequestPayload Source request) throws Exception { - return request; - } + @PayloadRoot(localPart = LOCAL_PART, namespace = NAMESPACE) + @ResponsePayload + public Source invoke(@RequestPayload Source request) throws Exception { + return request; + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java index 6e2e45bb..23b34830 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java @@ -31,69 +31,69 @@ import org.springframework.util.Assert; */ public abstract class FreePortScanner { - private static final int MIN_SAFE_PORT = 1024; + private static final int MIN_SAFE_PORT = 1024; - private static final int MAX_PORT = 65535; + private static final int MAX_PORT = 65535; - private static final Random random = new Random(); + private static final Random random = new Random(); - /** - * Returns the number of a free port in the default range. - */ - public static int getFreePort() { - return getFreePort(MIN_SAFE_PORT, MAX_PORT); - } + /** + * Returns the number of a free port in the default range. + */ + public static int getFreePort() { + return getFreePort(MIN_SAFE_PORT, MAX_PORT); + } - /** - * Returns the number of a free port in the given range. - */ - public static int getFreePort(int minPort, int maxPort) { - Assert.isTrue(minPort > 0, "'minPort' must be larger than 0"); - Assert.isTrue(maxPort > minPort, "'maxPort' must be larger than minPort"); - int portRange = maxPort - minPort; - int candidatePort; - int searchCounter = 0; - do { - if (++searchCounter > portRange) { - throw new IllegalStateException( - String.format("There were no ports available in the range %d to %d", minPort, maxPort)); - } - candidatePort = getRandomPort(minPort, portRange); - } - while (!isPortAvailable(candidatePort)); + /** + * Returns the number of a free port in the given range. + */ + public static int getFreePort(int minPort, int maxPort) { + Assert.isTrue(minPort > 0, "'minPort' must be larger than 0"); + Assert.isTrue(maxPort > minPort, "'maxPort' must be larger than minPort"); + int portRange = maxPort - minPort; + int candidatePort; + int searchCounter = 0; + do { + if (++searchCounter > portRange) { + throw new IllegalStateException( + String.format("There were no ports available in the range %d to %d", minPort, maxPort)); + } + candidatePort = getRandomPort(minPort, portRange); + } + while (!isPortAvailable(candidatePort)); - return candidatePort; - } + return candidatePort; + } - private static int getRandomPort(int minPort, int portRange) { - return minPort + random.nextInt(portRange); - } + private static int getRandomPort(int minPort, int portRange) { + return minPort + random.nextInt(portRange); + } - private static boolean isPortAvailable(int port) { - ServerSocket serverSocket; - try { - serverSocket = new ServerSocket(); - } - catch (IOException ex) { - throw new IllegalStateException("Unable to create ServerSocket.", ex); - } + private static boolean isPortAvailable(int port) { + ServerSocket serverSocket; + try { + serverSocket = new ServerSocket(); + } + catch (IOException ex) { + throw new IllegalStateException("Unable to create ServerSocket.", ex); + } - try { - InetSocketAddress sa = new InetSocketAddress(port); - serverSocket.bind(sa); - return true; - } - catch (IOException ex) { - return false; - } - finally { - try { - serverSocket.close(); - } - catch (IOException ex) { - // ignore - } - } - } + try { + InetSocketAddress sa = new InetSocketAddress(port); + serverSocket.bind(sa); + return true; + } + catch (IOException ex) { + return false; + } + finally { + try { + serverSocket.close(); + } + catch (IOException ex) { + // ignore + } + } + } } diff --git a/spring-ws-core/src/test/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupportTest.java b/spring-ws-core/src/test/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupportTest.java index 03fe711e..76653376 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupportTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/transport/support/WebServiceMessageReceiverObjectSupportTest.java @@ -33,96 +33,96 @@ import org.springframework.ws.transport.FaultAwareWebServiceConnection; import org.springframework.ws.transport.WebServiceMessageReceiver; public class WebServiceMessageReceiverObjectSupportTest { - private WebServiceMessageReceiverObjectSupport receiverSupport; + private WebServiceMessageReceiverObjectSupport receiverSupport; - private FaultAwareWebServiceConnection connectionMock; + private FaultAwareWebServiceConnection connectionMock; - private MockWebServiceMessageFactory messageFactory; + private MockWebServiceMessageFactory messageFactory; - private MockWebServiceMessage request; + private MockWebServiceMessage request; - @Before - public void setUp() throws Exception { - receiverSupport = new MyReceiverSupport(); - messageFactory = new MockWebServiceMessageFactory(); - receiverSupport.setMessageFactory(messageFactory); - connectionMock = createStrictMock(FaultAwareWebServiceConnection.class); - request = new MockWebServiceMessage(); - } + @Before + public void setUp() throws Exception { + receiverSupport = new MyReceiverSupport(); + messageFactory = new MockWebServiceMessageFactory(); + receiverSupport.setMessageFactory(messageFactory); + connectionMock = createStrictMock(FaultAwareWebServiceConnection.class); + request = new MockWebServiceMessage(); + } - @Test - public void handleConnectionResponse() throws Exception { - expect(connectionMock.getUri()).andReturn(new URI("http://example.com")); - expect(connectionMock.receive(messageFactory)).andReturn(request); - connectionMock.setFaultCode(null); - connectionMock.send(isA(WebServiceMessage.class)); - connectionMock.close(); + @Test + public void handleConnectionResponse() throws Exception { + expect(connectionMock.getUri()).andReturn(new URI("http://example.com")); + expect(connectionMock.receive(messageFactory)).andReturn(request); + connectionMock.setFaultCode(null); + connectionMock.send(isA(WebServiceMessage.class)); + connectionMock.close(); - replay(connectionMock); + replay(connectionMock); - WebServiceMessageReceiver receiver = new WebServiceMessageReceiver() { + WebServiceMessageReceiver receiver = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - Assert.assertNotNull("No message context", messageContext); - messageContext.getResponse(); - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + Assert.assertNotNull("No message context", messageContext); + messageContext.getResponse(); + } + }; - receiverSupport.handleConnection(connectionMock, receiver); + receiverSupport.handleConnection(connectionMock, receiver); - verify(connectionMock); - } + verify(connectionMock); + } - @Test - public void handleConnectionFaultResponse() throws Exception { - final QName faultCode = SoapVersion.SOAP_11.getClientOrSenderFaultName(); + @Test + public void handleConnectionFaultResponse() throws Exception { + final QName faultCode = SoapVersion.SOAP_11.getClientOrSenderFaultName(); - expect(connectionMock.getUri()).andReturn(new URI("http://example.com")); - expect(connectionMock.receive(messageFactory)).andReturn(request); - connectionMock.setFaultCode(faultCode); - connectionMock.send(isA(WebServiceMessage.class)); - connectionMock.close(); + expect(connectionMock.getUri()).andReturn(new URI("http://example.com")); + expect(connectionMock.receive(messageFactory)).andReturn(request); + connectionMock.setFaultCode(faultCode); + connectionMock.send(isA(WebServiceMessage.class)); + connectionMock.close(); - replay(connectionMock); + replay(connectionMock); - WebServiceMessageReceiver receiver = new WebServiceMessageReceiver() { + WebServiceMessageReceiver receiver = new WebServiceMessageReceiver() { - @Override - public void receive(MessageContext messageContext) throws Exception { - Assert.assertNotNull("No message context", messageContext); - MockWebServiceMessage response = - (MockWebServiceMessage) messageContext.getResponse(); - response.setFaultCode(faultCode); - } - }; + @Override + public void receive(MessageContext messageContext) throws Exception { + Assert.assertNotNull("No message context", messageContext); + MockWebServiceMessage response = + (MockWebServiceMessage) messageContext.getResponse(); + response.setFaultCode(faultCode); + } + }; - receiverSupport.handleConnection(connectionMock, receiver); + receiverSupport.handleConnection(connectionMock, receiver); - verify(connectionMock); - } + verify(connectionMock); + } - @Test - public void handleConnectionNoResponse() throws Exception { - expect(connectionMock.getUri()).andReturn(new URI("http://example.com")); - expect(connectionMock.receive(messageFactory)).andReturn(request); - connectionMock.close(); + @Test + public void handleConnectionNoResponse() throws Exception { + expect(connectionMock.getUri()).andReturn(new URI("http://example.com")); + expect(connectionMock.receive(messageFactory)).andReturn(request); + connectionMock.close(); - replay(connectionMock); + replay(connectionMock); - WebServiceMessageReceiver receiver = new WebServiceMessageReceiver() { + WebServiceMessageReceiver receiver = new WebServiceMessageReceiver() { - public void receive(MessageContext messageContext) throws Exception { - Assert.assertNotNull("No message context", messageContext); - } - }; + public void receive(MessageContext messageContext) throws Exception { + Assert.assertNotNull("No message context", messageContext); + } + }; - receiverSupport.handleConnection(connectionMock, receiver); + receiverSupport.handleConnection(connectionMock, receiver); - verify(connectionMock); - } + verify(connectionMock); + } - private static class MyReceiverSupport extends WebServiceMessageReceiverObjectSupport { + private static class MyReceiverSupport extends WebServiceMessageReceiverObjectSupport { - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11DefinitionTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11DefinitionTest.java index e397178d..66c13006 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11DefinitionTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/DefaultWsdl11DefinitionTest.java @@ -36,112 +36,112 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class DefaultWsdl11DefinitionTest { - private DefaultWsdl11Definition definition; + private DefaultWsdl11Definition definition; - private Transformer transformer; + private Transformer transformer; - private DocumentBuilder documentBuilder; + private DocumentBuilder documentBuilder; - @Before - public void setUp() throws Exception { - definition = new DefaultWsdl11Definition(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public void setUp() throws Exception { + definition = new DefaultWsdl11Definition(); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + XMLUnit.setIgnoreWhitespace(true); + } - @Test - public void testSingle() throws Exception { - Resource resource = new ClassPathResource("single.xsd", getClass()); - SimpleXsdSchema schema = new SimpleXsdSchema(resource); - schema.afterPropertiesSet(); - definition.setSchema(schema); + @Test + public void testSingle() throws Exception { + Resource resource = new ClassPathResource("single.xsd", getClass()); + SimpleXsdSchema schema = new SimpleXsdSchema(resource); + schema.afterPropertiesSet(); + definition.setSchema(schema); - definition.setTargetNamespace("http://www.springframework.org/spring-ws/single/definitions"); - definition.setPortTypeName("Order"); - definition.setLocationUri("http://localhost:8080/"); + definition.setTargetNamespace("http://www.springframework.org/spring-ws/single/definitions"); + definition.setPortTypeName("Order"); + definition.setLocationUri("http://localhost:8080/"); - definition.afterPropertiesSet(); + definition.afterPropertiesSet(); - DOMResult domResult = new DOMResult(); - transformer.transform(definition.getSource(), domResult); + DOMResult domResult = new DOMResult(); + transformer.transform(definition.getSource(), domResult); - Document result = (Document) domResult.getNode(); - Document expected = documentBuilder.parse(getClass().getResourceAsStream("single-inline.wsdl")); + Document result = (Document) domResult.getNode(); + Document expected = documentBuilder.parse(getClass().getResourceAsStream("single-inline.wsdl")); - assertXMLEqual("Invalid WSDL built", expected, result); + assertXMLEqual("Invalid WSDL built", expected, result); - } + } - @Test - public void testInclude() throws Exception { - ClassPathResource resource = new ClassPathResource("including.xsd", getClass()); - CommonsXsdSchemaCollection schemaCollection = new CommonsXsdSchemaCollection(new Resource[]{resource}); - schemaCollection.setInline(true); - schemaCollection.afterPropertiesSet(); - definition.setSchemaCollection(schemaCollection); + @Test + public void testInclude() throws Exception { + ClassPathResource resource = new ClassPathResource("including.xsd", getClass()); + CommonsXsdSchemaCollection schemaCollection = new CommonsXsdSchemaCollection(new Resource[]{resource}); + schemaCollection.setInline(true); + schemaCollection.afterPropertiesSet(); + definition.setSchemaCollection(schemaCollection); - definition.setPortTypeName("Order"); - definition.setTargetNamespace("http://www.springframework.org/spring-ws/include/definitions"); - definition.setLocationUri("http://localhost:8080/"); - definition.afterPropertiesSet(); + definition.setPortTypeName("Order"); + definition.setTargetNamespace("http://www.springframework.org/spring-ws/include/definitions"); + definition.setLocationUri("http://localhost:8080/"); + definition.afterPropertiesSet(); - DOMResult domResult = new DOMResult(); - transformer.transform(definition.getSource(), domResult); + DOMResult domResult = new DOMResult(); + transformer.transform(definition.getSource(), domResult); - Document result = (Document) domResult.getNode(); - Document expected = documentBuilder.parse(getClass().getResourceAsStream("include-inline.wsdl")); - assertXMLEqual("Invalid WSDL built", expected, result); - } + Document result = (Document) domResult.getNode(); + Document expected = documentBuilder.parse(getClass().getResourceAsStream("include-inline.wsdl")); + assertXMLEqual("Invalid WSDL built", expected, result); + } - @Test - public void testImport() throws Exception { - ClassPathResource resource = new ClassPathResource("importing.xsd", getClass()); - CommonsXsdSchemaCollection schemaCollection = new CommonsXsdSchemaCollection(new Resource[]{resource}); - schemaCollection.setInline(true); - schemaCollection.afterPropertiesSet(); - definition.setSchemaCollection(schemaCollection); + @Test + public void testImport() throws Exception { + ClassPathResource resource = new ClassPathResource("importing.xsd", getClass()); + CommonsXsdSchemaCollection schemaCollection = new CommonsXsdSchemaCollection(new Resource[]{resource}); + schemaCollection.setInline(true); + schemaCollection.afterPropertiesSet(); + definition.setSchemaCollection(schemaCollection); - definition.setPortTypeName("Order"); - definition.setTargetNamespace("http://www.springframework.org/spring-ws/import/definitions"); - definition.setLocationUri("http://localhost:8080/"); - definition.afterPropertiesSet(); + definition.setPortTypeName("Order"); + definition.setTargetNamespace("http://www.springframework.org/spring-ws/import/definitions"); + definition.setLocationUri("http://localhost:8080/"); + definition.afterPropertiesSet(); - DOMResult domResult = new DOMResult(); - transformer.transform(definition.getSource(), domResult); + DOMResult domResult = new DOMResult(); + transformer.transform(definition.getSource(), domResult); - Document result = (Document) domResult.getNode(); - Document expected = documentBuilder.parse(getClass().getResourceAsStream("import-inline.wsdl")); - assertXMLEqual("Invalid WSDL built", expected, result); - } + Document result = (Document) domResult.getNode(); + Document expected = documentBuilder.parse(getClass().getResourceAsStream("import-inline.wsdl")); + assertXMLEqual("Invalid WSDL built", expected, result); + } - @Test - public void testSoap11And12() throws Exception { - Resource resource = new ClassPathResource("single.xsd", getClass()); - SimpleXsdSchema schema = new SimpleXsdSchema(resource); - schema.afterPropertiesSet(); - definition.setSchema(schema); + @Test + public void testSoap11And12() throws Exception { + Resource resource = new ClassPathResource("single.xsd", getClass()); + SimpleXsdSchema schema = new SimpleXsdSchema(resource); + schema.afterPropertiesSet(); + definition.setSchema(schema); - definition.setTargetNamespace("http://www.springframework.org/spring-ws/single/definitions"); - definition.setPortTypeName("Order"); - definition.setLocationUri("http://localhost:8080/"); - definition.setCreateSoap11Binding(true); - definition.setCreateSoap12Binding(true); + definition.setTargetNamespace("http://www.springframework.org/spring-ws/single/definitions"); + definition.setPortTypeName("Order"); + definition.setLocationUri("http://localhost:8080/"); + definition.setCreateSoap11Binding(true); + definition.setCreateSoap12Binding(true); - definition.afterPropertiesSet(); + definition.afterPropertiesSet(); - DOMResult domResult = new DOMResult(); - transformer.transform(definition.getSource(), domResult); + DOMResult domResult = new DOMResult(); + transformer.transform(definition.getSource(), domResult); - Document result = (Document) domResult.getNode(); - Document expected = documentBuilder.parse(getClass().getResourceAsStream("soap-11-12.wsdl")); + Document result = (Document) domResult.getNode(); + Document expected = documentBuilder.parse(getClass().getResourceAsStream("soap-11-12.wsdl")); - assertXMLEqual("Invalid WSDL built", expected, result); + assertXMLEqual("Invalid WSDL built", expected, result); - } + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11DefinitionTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11DefinitionTest.java index afabca2a..5658099e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11DefinitionTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/SimpleWsdl11DefinitionTest.java @@ -24,17 +24,17 @@ import org.junit.Test; public class SimpleWsdl11DefinitionTest { - private SimpleWsdl11Definition definition; + private SimpleWsdl11Definition definition; - @Before - public void setUp() throws Exception { - definition = new SimpleWsdl11Definition(); - definition.setWsdl(new ClassPathResource("complete.wsdl", getClass())); - definition.afterPropertiesSet(); - } + @Before + public void setUp() throws Exception { + definition = new SimpleWsdl11Definition(); + definition.setWsdl(new ClassPathResource("complete.wsdl", getClass())); + definition.afterPropertiesSet(); + } - @Test - public void testGetSource() throws Exception { - Assert.assertNotNull("No source returned", definition.getSource()); - } + @Test + public void testGetSource() throws Exception { + Assert.assertNotNull("No source returned", definition.getSource()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionTest.java index c9047f2e..de42e572 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/Wsdl4jDefinitionTest.java @@ -38,36 +38,36 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class Wsdl4jDefinitionTest { - private Wsdl4jDefinition definition; + private Wsdl4jDefinition definition; - private Transformer transformer; + private Transformer transformer; - @Before - public void setUp() throws Exception { - XMLUnit.setIgnoreWhitespace(true); - WSDLFactory factory = WSDLFactory.newInstance(); - WSDLReader reader = factory.newWSDLReader(); - InputStream is = getClass().getResourceAsStream("complete.wsdl"); - try { - Definition wsdl4jDefinition = reader.readWSDL(null, new InputSource(is)); - definition = new Wsdl4jDefinition(wsdl4jDefinition); - } - finally { - is.close(); - } - transformer = TransformerFactory.newInstance().newTransformer(); - } + @Before + public void setUp() throws Exception { + XMLUnit.setIgnoreWhitespace(true); + WSDLFactory factory = WSDLFactory.newInstance(); + WSDLReader reader = factory.newWSDLReader(); + InputStream is = getClass().getResourceAsStream("complete.wsdl"); + try { + Definition wsdl4jDefinition = reader.readWSDL(null, new InputSource(is)); + definition = new Wsdl4jDefinition(wsdl4jDefinition); + } + finally { + is.close(); + } + transformer = TransformerFactory.newInstance().newTransformer(); + } - @Test - public void testGetSource() throws Exception { - Source source = definition.getSource(); - Assert.assertNotNull("Source is null", source); - DOMResult result = new DOMResult(); - transformer.transform(source, result); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document expected = documentBuilder.parse(getClass().getResourceAsStream("complete.wsdl")); - assertXMLEqual(expected, (Document) result.getNode()); - } + @Test + public void testGetSource() throws Exception { + Source source = definition.getSource(); + Assert.assertNotNull("Source is null", source); + DOMResult result = new DOMResult(); + transformer.transform(source, result); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document expected = documentBuilder.parse(getClass().getResourceAsStream("complete.wsdl")); + assertXMLEqual(expected, (Document) result.getNode()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProviderTest.java index 29c14c70..7e351917 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/DefaultMessagesProviderTest.java @@ -37,62 +37,62 @@ import org.w3c.dom.Document; public class DefaultMessagesProviderTest { - private DefaultMessagesProvider provider; + private DefaultMessagesProvider provider; - private Definition definition; + private Definition definition; - private DocumentBuilder documentBuilder; + private DocumentBuilder documentBuilder; - @Before - public void setUp() throws Exception { - provider = new DefaultMessagesProvider(); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - } + @Before + public void setUp() throws Exception { + provider = new DefaultMessagesProvider(); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + } - @Test - public void testAddMessages() throws Exception { - String definitionNamespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", definitionNamespace); - definition.setTargetNamespace(definitionNamespace); - String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; - definition.addNamespace("schema", schemaNamespace); + @Test + public void testAddMessages() throws Exception { + String definitionNamespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", definitionNamespace); + definition.setTargetNamespace(definitionNamespace); + String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; + definition.addNamespace("schema", schemaNamespace); - Resource resource = new ClassPathResource("schema.xsd", getClass()); - Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(resource)); - Types types = definition.createTypes(); - definition.setTypes(types); - Schema schema = (Schema) definition.getExtensionRegistry() - .createExtension(Types.class, new QName("http://www.w3.org/2001/XMLSchema", "schema")); - types.addExtensibilityElement(schema); - schema.setElement(schemaDocument.getDocumentElement()); + Resource resource = new ClassPathResource("schema.xsd", getClass()); + Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(resource)); + Types types = definition.createTypes(); + definition.setTypes(types); + Schema schema = (Schema) definition.getExtensionRegistry() + .createExtension(Types.class, new QName("http://www.w3.org/2001/XMLSchema", "schema")); + types.addExtensibilityElement(schema); + schema.setElement(schemaDocument.getDocumentElement()); - provider.addMessages(definition); + provider.addMessages(definition); - Assert.assertEquals("Invalid amount of messages created", 3, definition.getMessages().size()); + Assert.assertEquals("Invalid amount of messages created", 3, definition.getMessages().size()); - Message message = definition.getMessage(new QName(definitionNamespace, "GetOrderRequest")); - Assert.assertNotNull("Message not created", message); - Part part = message.getPart("GetOrderRequest"); - Assert.assertNotNull("Part not created", part); - Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderRequest"), - part.getElementName()); + Message message = definition.getMessage(new QName(definitionNamespace, "GetOrderRequest")); + Assert.assertNotNull("Message not created", message); + Part part = message.getPart("GetOrderRequest"); + Assert.assertNotNull("Part not created", part); + Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderRequest"), + part.getElementName()); - message = definition.getMessage(new QName(definitionNamespace, "GetOrderResponse")); - Assert.assertNotNull("Message not created", message); - part = message.getPart("GetOrderResponse"); - Assert.assertNotNull("Part not created", part); - Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderResponse"), - part.getElementName()); + message = definition.getMessage(new QName(definitionNamespace, "GetOrderResponse")); + Assert.assertNotNull("Message not created", message); + part = message.getPart("GetOrderResponse"); + Assert.assertNotNull("Part not created", part); + Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderResponse"), + part.getElementName()); - message = definition.getMessage(new QName(definitionNamespace, "GetOrderFault")); - Assert.assertNotNull("Message not created", message); - part = message.getPart("GetOrderFault"); - Assert.assertNotNull("Part not created", part); - Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderFault"), - part.getElementName()); - } + message = definition.getMessage(new QName(definitionNamespace, "GetOrderFault")); + Assert.assertNotNull("Message not created", message); + part = message.getPart("GetOrderFault"); + Assert.assertNotNull("Part not created", part); + Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderFault"), + part.getElementName()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProviderTest.java index 3b7bb024..356910e3 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/InliningXsdSchemaTypesProviderTest.java @@ -32,66 +32,66 @@ import org.junit.Test; public class InliningXsdSchemaTypesProviderTest { - private InliningXsdSchemaTypesProvider provider; + private InliningXsdSchemaTypesProvider provider; - private Definition definition; + private Definition definition; - @Before - public void setUp() throws Exception { - provider = new InliningXsdSchemaTypesProvider(); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - } + @Before + public void setUp() throws Exception { + provider = new InliningXsdSchemaTypesProvider(); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + } - @Test - public void testSingle() throws Exception { - String definitionNamespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", definitionNamespace); - definition.setTargetNamespace(definitionNamespace); - String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; - definition.addNamespace("schema", schemaNamespace); + @Test + public void testSingle() throws Exception { + String definitionNamespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", definitionNamespace); + definition.setTargetNamespace(definitionNamespace); + String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; + definition.addNamespace("schema", schemaNamespace); - Resource resource = new ClassPathResource("schema.xsd", getClass()); - SimpleXsdSchema schema = new SimpleXsdSchema(resource); - schema.afterPropertiesSet(); + Resource resource = new ClassPathResource("schema.xsd", getClass()); + SimpleXsdSchema schema = new SimpleXsdSchema(resource); + schema.afterPropertiesSet(); - provider.setSchema(schema); + provider.setSchema(schema); - provider.addTypes(definition); + provider.addTypes(definition); - Types types = definition.getTypes(); - Assert.assertNotNull("No types created", types); - Assert.assertEquals("Invalid amount of schemas", 1, types.getExtensibilityElements().size()); + Types types = definition.getTypes(); + Assert.assertNotNull("No types created", types); + Assert.assertEquals("Invalid amount of schemas", 1, types.getExtensibilityElements().size()); - Schema wsdlSchema = (Schema) types.getExtensibilityElements().get(0); - Assert.assertNotNull("No element defined", wsdlSchema.getElement()); - } + Schema wsdlSchema = (Schema) types.getExtensibilityElements().get(0); + Assert.assertNotNull("No element defined", wsdlSchema.getElement()); + } - @Test - public void testComplex() throws Exception { - String definitionNamespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", definitionNamespace); - definition.setTargetNamespace(definitionNamespace); - String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; - definition.addNamespace("schema", schemaNamespace); + @Test + public void testComplex() throws Exception { + String definitionNamespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", definitionNamespace); + definition.setTargetNamespace(definitionNamespace); + String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; + definition.addNamespace("schema", schemaNamespace); - Resource resource = new ClassPathResource("A.xsd", getClass()); - CommonsXsdSchemaCollection collection = new CommonsXsdSchemaCollection(new Resource[]{resource}); - collection.setInline(true); - collection.afterPropertiesSet(); + Resource resource = new ClassPathResource("A.xsd", getClass()); + CommonsXsdSchemaCollection collection = new CommonsXsdSchemaCollection(new Resource[]{resource}); + collection.setInline(true); + collection.afterPropertiesSet(); - provider.setSchemaCollection(collection); + provider.setSchemaCollection(collection); - provider.addTypes(definition); + provider.addTypes(definition); - Types types = definition.getTypes(); - Assert.assertNotNull("No types created", types); - Assert.assertEquals("Invalid amount of schemas", 2, types.getExtensibilityElements().size()); + Types types = definition.getTypes(); + Assert.assertNotNull("No types created", types); + Assert.assertEquals("Invalid amount of schemas", 2, types.getExtensibilityElements().size()); - Schema wsdlSchema = (Schema) types.getExtensibilityElements().get(0); - Assert.assertNotNull("No element defined", wsdlSchema.getElement()); + Schema wsdlSchema = (Schema) types.getExtensibilityElements().get(0); + Assert.assertNotNull("No element defined", wsdlSchema.getElement()); - wsdlSchema = (Schema) types.getExtensibilityElements().get(1); - Assert.assertNotNull("No element defined", wsdlSchema.getElement()); - } + wsdlSchema = (Schema) types.getExtensibilityElements().get(1); + Assert.assertNotNull("No element defined", wsdlSchema.getElement()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11ProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11ProviderTest.java index 9486ca85..795230cc 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11ProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap11ProviderTest.java @@ -45,106 +45,106 @@ import org.junit.Test; public class Soap11ProviderTest { - private Soap11Provider provider; + private Soap11Provider provider; - private Definition definition; + private Definition definition; - @Before - public void setUp() throws Exception { - provider = new Soap11Provider(); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - } + @Before + public void setUp() throws Exception { + provider = new Soap11Provider(); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + } - @Test - public void testPopulateBinding() throws Exception { - String namespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", namespace); - definition.setTargetNamespace(namespace); + @Test + public void testPopulateBinding() throws Exception { + String namespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", namespace); + definition.setTargetNamespace(namespace); - PortType portType = definition.createPortType(); - portType.setQName(new QName(namespace, "PortType")); - portType.setUndefined(false); - definition.addPortType(portType); - Operation operation = definition.createOperation(); - operation.setName("Operation"); - operation.setUndefined(false); - operation.setStyle(OperationType.REQUEST_RESPONSE); - portType.addOperation(operation); - Input input = definition.createInput(); - input.setName("Input"); - operation.setInput(input); - Output output = definition.createOutput(); - output.setName("Output"); - operation.setOutput(output); - Fault fault = definition.createFault(); - fault.setName("Fault"); - operation.addFault(fault); + PortType portType = definition.createPortType(); + portType.setQName(new QName(namespace, "PortType")); + portType.setUndefined(false); + definition.addPortType(portType); + Operation operation = definition.createOperation(); + operation.setName("Operation"); + operation.setUndefined(false); + operation.setStyle(OperationType.REQUEST_RESPONSE); + portType.addOperation(operation); + Input input = definition.createInput(); + input.setName("Input"); + operation.setInput(input); + Output output = definition.createOutput(); + output.setName("Output"); + operation.setOutput(output); + Fault fault = definition.createFault(); + fault.setName("Fault"); + operation.addFault(fault); - Properties soapActions = new Properties(); - soapActions.setProperty("Operation", namespace + "/Action"); - provider.setSoapActions(soapActions); + Properties soapActions = new Properties(); + soapActions.setProperty("Operation", namespace + "/Action"); + provider.setSoapActions(soapActions); - provider.setServiceName("Service"); + provider.setServiceName("Service"); - String locationUri = "http://localhost:8080/services"; - provider.setLocationUri(locationUri); + String locationUri = "http://localhost:8080/services"; + provider.setLocationUri(locationUri); - provider.addBindings(definition); - provider.addServices(definition); + provider.addBindings(definition); + provider.addServices(definition); - Binding binding = definition.getBinding(new QName(namespace, "PortTypeSoap11")); - Assert.assertNotNull("No binding created", binding); - Assert.assertEquals("Invalid port type", portType, binding.getPortType()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, binding.getExtensibilityElements().size()); + Binding binding = definition.getBinding(new QName(namespace, "PortTypeSoap11")); + Assert.assertNotNull("No binding created", binding); + Assert.assertEquals("Invalid port type", portType, binding.getPortType()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, binding.getExtensibilityElements().size()); - SOAPBinding soapBinding = (SOAPBinding) binding.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid style", "document", soapBinding.getStyle()); - Assert.assertEquals("Invalid amount of binding operations", 1, binding.getBindingOperations().size()); + SOAPBinding soapBinding = (SOAPBinding) binding.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid style", "document", soapBinding.getStyle()); + Assert.assertEquals("Invalid amount of binding operations", 1, binding.getBindingOperations().size()); - BindingOperation bindingOperation = binding.getBindingOperation("Operation", "Input", "Output"); - Assert.assertNotNull("No binding operation created", bindingOperation); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingOperation.getExtensibilityElements().size()); + BindingOperation bindingOperation = binding.getBindingOperation("Operation", "Input", "Output"); + Assert.assertNotNull("No binding operation created", bindingOperation); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingOperation.getExtensibilityElements().size()); - SOAPOperation soapOperation = (SOAPOperation) bindingOperation.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid SOAPAction", namespace + "/Action", soapOperation.getSoapActionURI()); + SOAPOperation soapOperation = (SOAPOperation) bindingOperation.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid SOAPAction", namespace + "/Action", soapOperation.getSoapActionURI()); - BindingInput bindingInput = bindingOperation.getBindingInput(); - Assert.assertNotNull("No binding input", bindingInput); - Assert.assertEquals("Invalid name", "Input", bindingInput.getName()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingInput.getExtensibilityElements().size()); - SOAPBody soapBody = (SOAPBody) bindingInput.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); + BindingInput bindingInput = bindingOperation.getBindingInput(); + Assert.assertNotNull("No binding input", bindingInput); + Assert.assertEquals("Invalid name", "Input", bindingInput.getName()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingInput.getExtensibilityElements().size()); + SOAPBody soapBody = (SOAPBody) bindingInput.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); - BindingOutput bindingOutput = bindingOperation.getBindingOutput(); - Assert.assertNotNull("No binding output", bindingOutput); - Assert.assertEquals("Invalid name", "Output", bindingOutput.getName()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingOutput.getExtensibilityElements().size()); - soapBody = (SOAPBody) bindingOutput.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); + BindingOutput bindingOutput = bindingOperation.getBindingOutput(); + Assert.assertNotNull("No binding output", bindingOutput); + Assert.assertEquals("Invalid name", "Output", bindingOutput.getName()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingOutput.getExtensibilityElements().size()); + soapBody = (SOAPBody) bindingOutput.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); - BindingFault bindingFault = bindingOperation.getBindingFault("Fault"); - Assert.assertNotNull("No binding fault", bindingFault); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingFault.getExtensibilityElements().size()); - SOAPFault soapFault = (SOAPFault) bindingFault.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap fault use", "literal", soapFault.getUse()); + BindingFault bindingFault = bindingOperation.getBindingFault("Fault"); + Assert.assertNotNull("No binding fault", bindingFault); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingFault.getExtensibilityElements().size()); + SOAPFault soapFault = (SOAPFault) bindingFault.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap fault use", "literal", soapFault.getUse()); - Service service = definition.getService(new QName(namespace, "Service")); - Assert.assertNotNull("No Service created", service); - Assert.assertEquals("Invalid amount of ports", 1, service.getPorts().size()); + Service service = definition.getService(new QName(namespace, "Service")); + Assert.assertNotNull("No Service created", service); + Assert.assertEquals("Invalid amount of ports", 1, service.getPorts().size()); - Port port = service.getPort("PortTypeSoap11"); - Assert.assertNotNull("No port created", port); - Assert.assertEquals("Invalid binding", binding, port.getBinding()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, port.getExtensibilityElements().size()); + Port port = service.getPort("PortTypeSoap11"); + Assert.assertNotNull("No port created", port); + Assert.assertEquals("Invalid binding", binding, port.getBinding()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, port.getExtensibilityElements().size()); - SOAPAddress soapAddress = (SOAPAddress) port.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap address", locationUri, soapAddress.getLocationURI()); - } + SOAPAddress soapAddress = (SOAPAddress) port.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap address", locationUri, soapAddress.getLocationURI()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12ProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12ProviderTest.java index ef331b50..316f3e07 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12ProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/Soap12ProviderTest.java @@ -45,106 +45,106 @@ import org.junit.Test; public class Soap12ProviderTest { - private Soap12Provider provider; + private Soap12Provider provider; - private Definition definition; + private Definition definition; - @Before - public void setUp() throws Exception { - provider = new Soap12Provider(); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - } + @Before + public void setUp() throws Exception { + provider = new Soap12Provider(); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + } - @Test - public void testPopulateBinding() throws Exception { - String namespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", namespace); - definition.setTargetNamespace(namespace); + @Test + public void testPopulateBinding() throws Exception { + String namespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", namespace); + definition.setTargetNamespace(namespace); - PortType portType = definition.createPortType(); - portType.setQName(new QName(namespace, "PortType")); - portType.setUndefined(false); - definition.addPortType(portType); - Operation operation = definition.createOperation(); - operation.setName("Operation"); - operation.setUndefined(false); - operation.setStyle(OperationType.REQUEST_RESPONSE); - portType.addOperation(operation); - Input input = definition.createInput(); - input.setName("Input"); - operation.setInput(input); - Output output = definition.createOutput(); - output.setName("Output"); - operation.setOutput(output); - Fault fault = definition.createFault(); - fault.setName("Fault"); - operation.addFault(fault); + PortType portType = definition.createPortType(); + portType.setQName(new QName(namespace, "PortType")); + portType.setUndefined(false); + definition.addPortType(portType); + Operation operation = definition.createOperation(); + operation.setName("Operation"); + operation.setUndefined(false); + operation.setStyle(OperationType.REQUEST_RESPONSE); + portType.addOperation(operation); + Input input = definition.createInput(); + input.setName("Input"); + operation.setInput(input); + Output output = definition.createOutput(); + output.setName("Output"); + operation.setOutput(output); + Fault fault = definition.createFault(); + fault.setName("Fault"); + operation.addFault(fault); - Properties soapActions = new Properties(); - soapActions.setProperty("Operation", namespace + "/Action"); - provider.setSoapActions(soapActions); + Properties soapActions = new Properties(); + soapActions.setProperty("Operation", namespace + "/Action"); + provider.setSoapActions(soapActions); - provider.setServiceName("Service"); + provider.setServiceName("Service"); - String locationUri = "http://localhost:8080/services"; - provider.setLocationUri(locationUri); + String locationUri = "http://localhost:8080/services"; + provider.setLocationUri(locationUri); - provider.addBindings(definition); - provider.addServices(definition); + provider.addBindings(definition); + provider.addServices(definition); - Binding binding = definition.getBinding(new QName(namespace, "PortTypeSoap12")); - Assert.assertNotNull("No binding created", binding); - Assert.assertEquals("Invalid port type", portType, binding.getPortType()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, binding.getExtensibilityElements().size()); + Binding binding = definition.getBinding(new QName(namespace, "PortTypeSoap12")); + Assert.assertNotNull("No binding created", binding); + Assert.assertEquals("Invalid port type", portType, binding.getPortType()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, binding.getExtensibilityElements().size()); - SOAP12Binding soapBinding = (SOAP12Binding) binding.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid style", "document", soapBinding.getStyle()); - Assert.assertEquals("Invalid amount of binding operations", 1, binding.getBindingOperations().size()); + SOAP12Binding soapBinding = (SOAP12Binding) binding.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid style", "document", soapBinding.getStyle()); + Assert.assertEquals("Invalid amount of binding operations", 1, binding.getBindingOperations().size()); - BindingOperation bindingOperation = binding.getBindingOperation("Operation", "Input", "Output"); - Assert.assertNotNull("No binding operation created", bindingOperation); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingOperation.getExtensibilityElements().size()); + BindingOperation bindingOperation = binding.getBindingOperation("Operation", "Input", "Output"); + Assert.assertNotNull("No binding operation created", bindingOperation); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingOperation.getExtensibilityElements().size()); - SOAP12Operation soapOperation = (SOAP12Operation) bindingOperation.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid SOAPAction", namespace + "/Action", soapOperation.getSoapActionURI()); + SOAP12Operation soapOperation = (SOAP12Operation) bindingOperation.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid SOAPAction", namespace + "/Action", soapOperation.getSoapActionURI()); - BindingInput bindingInput = bindingOperation.getBindingInput(); - Assert.assertNotNull("No binding input", bindingInput); - Assert.assertEquals("Invalid name", "Input", bindingInput.getName()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingInput.getExtensibilityElements().size()); - SOAP12Body soapBody = (SOAP12Body) bindingInput.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); + BindingInput bindingInput = bindingOperation.getBindingInput(); + Assert.assertNotNull("No binding input", bindingInput); + Assert.assertEquals("Invalid name", "Input", bindingInput.getName()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingInput.getExtensibilityElements().size()); + SOAP12Body soapBody = (SOAP12Body) bindingInput.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); - BindingOutput bindingOutput = bindingOperation.getBindingOutput(); - Assert.assertNotNull("No binding output", bindingOutput); - Assert.assertEquals("Invalid name", "Output", bindingOutput.getName()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingOutput.getExtensibilityElements().size()); - soapBody = (SOAP12Body) bindingOutput.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); + BindingOutput bindingOutput = bindingOperation.getBindingOutput(); + Assert.assertNotNull("No binding output", bindingOutput); + Assert.assertEquals("Invalid name", "Output", bindingOutput.getName()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingOutput.getExtensibilityElements().size()); + soapBody = (SOAP12Body) bindingOutput.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap body use", "literal", soapBody.getUse()); - BindingFault bindingFault = bindingOperation.getBindingFault("Fault"); - Assert.assertNotNull("No binding fault", bindingFault); - Assert.assertEquals("Invalid amount of extensibility elements", 1, - bindingFault.getExtensibilityElements().size()); - SOAP12Fault soapFault = (SOAP12Fault) bindingFault.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap fault use", "literal", soapFault.getUse()); + BindingFault bindingFault = bindingOperation.getBindingFault("Fault"); + Assert.assertNotNull("No binding fault", bindingFault); + Assert.assertEquals("Invalid amount of extensibility elements", 1, + bindingFault.getExtensibilityElements().size()); + SOAP12Fault soapFault = (SOAP12Fault) bindingFault.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap fault use", "literal", soapFault.getUse()); - Service service = definition.getService(new QName(namespace, "Service")); - Assert.assertNotNull("No Service created", service); - Assert.assertEquals("Invalid amount of ports", 1, service.getPorts().size()); + Service service = definition.getService(new QName(namespace, "Service")); + Assert.assertNotNull("No Service created", service); + Assert.assertEquals("Invalid amount of ports", 1, service.getPorts().size()); - Port port = service.getPort("PortTypeSoap12"); - Assert.assertNotNull("No port created", port); - Assert.assertEquals("Invalid binding", binding, port.getBinding()); - Assert.assertEquals("Invalid amount of extensibility elements", 1, port.getExtensibilityElements().size()); + Port port = service.getPort("PortTypeSoap12"); + Assert.assertNotNull("No port created", port); + Assert.assertEquals("Invalid binding", binding, port.getBinding()); + Assert.assertEquals("Invalid amount of extensibility elements", 1, port.getExtensibilityElements().size()); - SOAP12Address soapAddress = (SOAP12Address) port.getExtensibilityElements().get(0); - Assert.assertEquals("Invalid soap address", locationUri, soapAddress.getLocationURI()); - } + SOAP12Address soapAddress = (SOAP12Address) port.getExtensibilityElements().get(0); + Assert.assertEquals("Invalid soap address", locationUri, soapAddress.getLocationURI()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProviderTest.java index da3b0027..a10f7fe2 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SoapProviderTest.java @@ -36,71 +36,71 @@ import org.junit.Test; public class SoapProviderTest { - private SoapProvider provider; + private SoapProvider provider; - private Definition definition; + private Definition definition; - @Before - public void setUp() throws Exception { - provider = new SoapProvider(); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - } + @Before + public void setUp() throws Exception { + provider = new SoapProvider(); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + } - @Test - public void testPopulateBinding() throws Exception { - String namespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", namespace); - definition.setTargetNamespace(namespace); + @Test + public void testPopulateBinding() throws Exception { + String namespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", namespace); + definition.setTargetNamespace(namespace); - PortType portType = definition.createPortType(); - portType.setQName(new QName(namespace, "PortType")); - portType.setUndefined(false); - definition.addPortType(portType); - Operation operation = definition.createOperation(); - operation.setName("Operation"); - operation.setUndefined(false); - operation.setStyle(OperationType.REQUEST_RESPONSE); - portType.addOperation(operation); - Input input = definition.createInput(); - input.setName("Input"); - operation.setInput(input); - Output output = definition.createOutput(); - output.setName("Output"); - operation.setOutput(output); - Fault fault = definition.createFault(); - fault.setName("Fault"); - operation.addFault(fault); + PortType portType = definition.createPortType(); + portType.setQName(new QName(namespace, "PortType")); + portType.setUndefined(false); + definition.addPortType(portType); + Operation operation = definition.createOperation(); + operation.setName("Operation"); + operation.setUndefined(false); + operation.setStyle(OperationType.REQUEST_RESPONSE); + portType.addOperation(operation); + Input input = definition.createInput(); + input.setName("Input"); + operation.setInput(input); + Output output = definition.createOutput(); + output.setName("Output"); + operation.setOutput(output); + Fault fault = definition.createFault(); + fault.setName("Fault"); + operation.addFault(fault); - Properties soapActions = new Properties(); - soapActions.setProperty("Operation", namespace + "/Action"); - provider.setSoapActions(soapActions); + Properties soapActions = new Properties(); + soapActions.setProperty("Operation", namespace + "/Action"); + provider.setSoapActions(soapActions); - provider.setServiceName("Service"); + provider.setServiceName("Service"); - String locationUri = "http://localhost:8080/services"; - provider.setLocationUri(locationUri); + String locationUri = "http://localhost:8080/services"; + provider.setLocationUri(locationUri); - provider.setCreateSoap11Binding(true); - provider.setCreateSoap12Binding(true); + provider.setCreateSoap11Binding(true); + provider.setCreateSoap12Binding(true); - provider.addBindings(definition); - provider.addServices(definition); + provider.addBindings(definition); + provider.addServices(definition); - Binding binding = definition.getBinding(new QName(namespace, "PortTypeSoap11")); - Assert.assertNotNull("No SOAP 1.1 binding created", binding); - binding = definition.getBinding(new QName(namespace, "PortTypeSoap12")); - Assert.assertNotNull("No SOAP 1.2 binding created", binding); + Binding binding = definition.getBinding(new QName(namespace, "PortTypeSoap11")); + Assert.assertNotNull("No SOAP 1.1 binding created", binding); + binding = definition.getBinding(new QName(namespace, "PortTypeSoap12")); + Assert.assertNotNull("No SOAP 1.2 binding created", binding); - Service service = definition.getService(new QName(namespace, "Service")); - Assert.assertNotNull("No Service created", service); - Assert.assertEquals("Invalid amount of ports", 2, service.getPorts().size()); + Service service = definition.getService(new QName(namespace, "Service")); + Assert.assertNotNull("No Service created", service); + Assert.assertEquals("Invalid amount of ports", 2, service.getPorts().size()); - Port port = service.getPort("PortTypeSoap11"); - Assert.assertNotNull("No SOAP 1.1 port created", port); - port = service.getPort("PortTypeSoap12"); - Assert.assertNotNull("No SOAP 1.2 port created", port); - } + Port port = service.getPort("PortTypeSoap11"); + Assert.assertNotNull("No SOAP 1.1 port created", port); + port = service.getPort("PortTypeSoap12"); + Assert.assertNotNull("No SOAP 1.2 port created", port); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProviderTest.java index fe83d0dc..914eeaf0 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedMessagesProviderTest.java @@ -37,56 +37,56 @@ import org.w3c.dom.Document; public class SuffixBasedMessagesProviderTest { - private SuffixBasedMessagesProvider provider; + private SuffixBasedMessagesProvider provider; - private Definition definition; + private Definition definition; - private DocumentBuilder documentBuilder; + private DocumentBuilder documentBuilder; - @Before - public void setUp() throws Exception { - provider = new SuffixBasedMessagesProvider(); - provider.setFaultSuffix("Foo"); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - } + @Before + public void setUp() throws Exception { + provider = new SuffixBasedMessagesProvider(); + provider.setFaultSuffix("Foo"); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + } - @Test - public void testAddMessages() throws Exception { - String definitionNamespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", definitionNamespace); - definition.setTargetNamespace(definitionNamespace); - String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; - definition.addNamespace("schema", schemaNamespace); + @Test + public void testAddMessages() throws Exception { + String definitionNamespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", definitionNamespace); + definition.setTargetNamespace(definitionNamespace); + String schemaNamespace = "http://www.springframework.org/spring-ws/schema"; + definition.addNamespace("schema", schemaNamespace); - Resource resource = new ClassPathResource("schema.xsd", getClass()); - Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(resource)); - Types types = definition.createTypes(); - definition.setTypes(types); - Schema schema = (Schema) definition.getExtensionRegistry() - .createExtension(Types.class, new QName("http://www.w3.org/2001/XMLSchema", "schema")); - types.addExtensibilityElement(schema); - schema.setElement(schemaDocument.getDocumentElement()); + Resource resource = new ClassPathResource("schema.xsd", getClass()); + Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(resource)); + Types types = definition.createTypes(); + definition.setTypes(types); + Schema schema = (Schema) definition.getExtensionRegistry() + .createExtension(Types.class, new QName("http://www.w3.org/2001/XMLSchema", "schema")); + types.addExtensibilityElement(schema); + schema.setElement(schemaDocument.getDocumentElement()); - provider.addMessages(definition); + provider.addMessages(definition); - Assert.assertEquals("Invalid amount of messages created", 2, definition.getMessages().size()); + Assert.assertEquals("Invalid amount of messages created", 2, definition.getMessages().size()); - Message message = definition.getMessage(new QName(definitionNamespace, "GetOrderRequest")); - Assert.assertNotNull("Message not created", message); - Part part = message.getPart("GetOrderRequest"); - Assert.assertNotNull("Part not created", part); - Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderRequest"), - part.getElementName()); + Message message = definition.getMessage(new QName(definitionNamespace, "GetOrderRequest")); + Assert.assertNotNull("Message not created", message); + Part part = message.getPart("GetOrderRequest"); + Assert.assertNotNull("Part not created", part); + Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderRequest"), + part.getElementName()); - message = definition.getMessage(new QName(definitionNamespace, "GetOrderResponse")); - Assert.assertNotNull("Message not created", message); - part = message.getPart("GetOrderResponse"); - Assert.assertNotNull("Part not created", part); - Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderResponse"), - part.getElementName()); - } + message = definition.getMessage(new QName(definitionNamespace, "GetOrderResponse")); + Assert.assertNotNull("Message not created", message); + part = message.getPart("GetOrderResponse"); + Assert.assertNotNull("Part not created", part); + Assert.assertEquals("Invalid element on part", new QName(schemaNamespace, "GetOrderResponse"), + part.getElementName()); + } } \ No newline at end of file diff --git a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProviderTest.java b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProviderTest.java index ea6366cc..a2e6e33e 100644 --- a/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProviderTest.java +++ b/spring-ws-core/src/test/java/org/springframework/ws/wsdl/wsdl11/provider/SuffixBasedPortTypesProviderTest.java @@ -29,45 +29,45 @@ import org.junit.Test; public class SuffixBasedPortTypesProviderTest { - private SuffixBasedPortTypesProvider provider; + private SuffixBasedPortTypesProvider provider; - private Definition definition; + private Definition definition; - @Before - public void setUp() throws Exception { - provider = new SuffixBasedPortTypesProvider(); - WSDLFactory factory = WSDLFactory.newInstance(); - definition = factory.newDefinition(); - } + @Before + public void setUp() throws Exception { + provider = new SuffixBasedPortTypesProvider(); + WSDLFactory factory = WSDLFactory.newInstance(); + definition = factory.newDefinition(); + } - @Test - public void testAddPortTypes() throws Exception { - String namespace = "http://springframework.org/spring-ws"; - definition.addNamespace("tns", namespace); - definition.setTargetNamespace(namespace); + @Test + public void testAddPortTypes() throws Exception { + String namespace = "http://springframework.org/spring-ws"; + definition.addNamespace("tns", namespace); + definition.setTargetNamespace(namespace); - Message message = definition.createMessage(); - message.setQName(new QName(namespace, "OperationRequest")); - definition.addMessage(message); + Message message = definition.createMessage(); + message.setQName(new QName(namespace, "OperationRequest")); + definition.addMessage(message); - message = definition.createMessage(); - message.setQName(new QName(namespace, "OperationResponse")); - definition.addMessage(message); + message = definition.createMessage(); + message.setQName(new QName(namespace, "OperationResponse")); + definition.addMessage(message); - message = definition.createMessage(); - message.setQName(new QName(namespace, "OperationFault")); - definition.addMessage(message); + message = definition.createMessage(); + message.setQName(new QName(namespace, "OperationFault")); + definition.addMessage(message); - provider.setPortTypeName("PortType"); - provider.addPortTypes(definition); + provider.setPortTypeName("PortType"); + provider.addPortTypes(definition); - PortType portType = definition.getPortType(new QName(namespace, "PortType")); - Assert.assertNotNull("No port type created", portType); + PortType portType = definition.getPortType(new QName(namespace, "PortType")); + Assert.assertNotNull("No port type created", portType); - Operation operation = portType.getOperation("Operation", "OperationRequest", "OperationResponse"); - Assert.assertNotNull("No operation created", operation); - Assert.assertNotNull("No input created", operation.getInput()); - Assert.assertNotNull("No output created", operation.getOutput()); - Assert.assertFalse("No fault created", operation.getFaults().isEmpty()); - } + Operation operation = portType.getOperation("Operation", "OperationRequest", "OperationResponse"); + Assert.assertNotNull("No operation created", operation); + Assert.assertNotNull("No input created", operation.getInput()); + Assert.assertNotNull("No output created", operation.getOutput()); + Assert.assertFalse("No fault created", operation.getFaults().isEmpty()); + } } \ No newline at end of file diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/AbstractWsSecurityInterceptor.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/AbstractWsSecurityInterceptor.java index 07940bed..cacd4ee7 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/AbstractWsSecurityInterceptor.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/AbstractWsSecurityInterceptor.java @@ -50,216 +50,216 @@ import org.springframework.ws.soap.soap11.Soap11Body; */ public abstract class AbstractWsSecurityInterceptor implements SoapEndpointInterceptor, ClientInterceptor { - /** Logger available to subclasses. */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); - protected static final QName WS_SECURITY_NAME = - new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security"); + protected static final QName WS_SECURITY_NAME = + new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security"); - private boolean secureResponse = true; + private boolean secureResponse = true; - private boolean validateRequest = true; + private boolean validateRequest = true; - private boolean secureRequest = true; + private boolean secureRequest = true; - private boolean validateResponse = true; - - private boolean skipValidationIfNoHeaderPresent = false; + private boolean validateResponse = true; + + private boolean skipValidationIfNoHeaderPresent = false; - private EndpointExceptionResolver exceptionResolver; + private EndpointExceptionResolver exceptionResolver; - /** Indicates whether server-side incoming request are to be validated. Defaults to {@code true}. */ - public void setValidateRequest(boolean validateRequest) { - this.validateRequest = validateRequest; - } + /** Indicates whether server-side incoming request are to be validated. Defaults to {@code true}. */ + public void setValidateRequest(boolean validateRequest) { + this.validateRequest = validateRequest; + } - /** Indicates whether server-side outgoing responses are to be secured. Defaults to {@code true}. */ - public void setSecureResponse(boolean secureResponse) { - this.secureResponse = secureResponse; - } + /** Indicates whether server-side outgoing responses are to be secured. Defaults to {@code true}. */ + public void setSecureResponse(boolean secureResponse) { + this.secureResponse = secureResponse; + } - /** Indicates whether client-side outgoing requests are to be secured. Defaults to {@code true}. */ - public void setSecureRequest(boolean secureRequest) { - this.secureRequest = secureRequest; - } + /** Indicates whether client-side outgoing requests are to be secured. Defaults to {@code true}. */ + public void setSecureRequest(boolean secureRequest) { + this.secureRequest = secureRequest; + } - /** Indicates whether client-side incoming responses are to be validated. Defaults to {@code true}. */ - public void setValidateResponse(boolean validateResponse) { - this.validateResponse = validateResponse; - } + /** Indicates whether client-side incoming responses are to be validated. Defaults to {@code true}. */ + public void setValidateResponse(boolean validateResponse) { + this.validateResponse = validateResponse; + } - /** Provide an {@link EndpointExceptionResolver} for resolving validation exceptions. */ - public void setExceptionResolver(EndpointExceptionResolver exceptionResolver) { - this.exceptionResolver = exceptionResolver; - } + /** Provide an {@link EndpointExceptionResolver} for resolving validation exceptions. */ + public void setExceptionResolver(EndpointExceptionResolver exceptionResolver) { + this.exceptionResolver = exceptionResolver; + } - /** Allows skipping validation if no security header is present. */ - public void setSkipValidationIfNoHeaderPresent( + /** Allows skipping validation if no security header is present. */ + public void setSkipValidationIfNoHeaderPresent( boolean skipValidationIfNoHeaderPresent) { this.skipValidationIfNoHeaderPresent = skipValidationIfNoHeaderPresent; } - /* - * Server-side - */ + /* + * Server-side + */ /** - * Validates a server-side incoming request. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} - * if the {@link #setValidateRequest(boolean) validateRequest} property is {@code true}. - * - * @param messageContext the message context, containing the request to be validated - * @param endpoint chosen endpoint to invoke - * @return {@code true} if the request was valid; {@code false} otherwise. - * @throws Exception in case of errors - * @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) - */ - @Override - public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { - if (validateRequest) { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){ - return true; - } - try { - validateMessage((SoapMessage) messageContext.getRequest(), messageContext); - return true; - } - catch (WsSecurityValidationException ex) { - return handleValidationException(ex, messageContext); - } - catch (WsSecurityFaultException ex) { - return handleFaultException(ex, messageContext); - } - } - else { - return true; - } - } + * Validates a server-side incoming request. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} + * if the {@link #setValidateRequest(boolean) validateRequest} property is {@code true}. + * + * @param messageContext the message context, containing the request to be validated + * @param endpoint chosen endpoint to invoke + * @return {@code true} if the request was valid; {@code false} otherwise. + * @throws Exception in case of errors + * @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) + */ + @Override + public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception { + if (validateRequest) { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){ + return true; + } + try { + validateMessage((SoapMessage) messageContext.getRequest(), messageContext); + return true; + } + catch (WsSecurityValidationException ex) { + return handleValidationException(ex, messageContext); + } + catch (WsSecurityFaultException ex) { + return handleFaultException(ex, messageContext); + } + } + else { + return true; + } + } /** - * Secures a server-side outgoing response. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} - * if the {@link #setSecureResponse(boolean) secureResponse} property is {@code true}. - * - * @param messageContext the message context, containing the response to be secured - * @param endpoint chosen endpoint to invoke - * @return {@code true} if the response was secured; {@code false} otherwise. - * @throws Exception in case of errors - * @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) - */ - @Override - public final boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { - boolean result = true; - try { - if (secureResponse) { - Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response"); - Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse()); - try { - secureMessage((SoapMessage) messageContext.getResponse(), messageContext); - } - catch (WsSecuritySecurementException ex) { - result = handleSecurementException(ex, messageContext); - } - catch (WsSecurityFaultException ex) { - result = handleFaultException(ex, messageContext); - } - } - } - finally { - if (!result) { - messageContext.clearResponse(); - } - } - return result; - } + * Secures a server-side outgoing response. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} + * if the {@link #setSecureResponse(boolean) secureResponse} property is {@code true}. + * + * @param messageContext the message context, containing the response to be secured + * @param endpoint chosen endpoint to invoke + * @return {@code true} if the response was secured; {@code false} otherwise. + * @throws Exception in case of errors + * @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) + */ + @Override + public final boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception { + boolean result = true; + try { + if (secureResponse) { + Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response"); + Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse()); + try { + secureMessage((SoapMessage) messageContext.getResponse(), messageContext); + } + catch (WsSecuritySecurementException ex) { + result = handleSecurementException(ex, messageContext); + } + catch (WsSecurityFaultException ex) { + result = handleFaultException(ex, messageContext); + } + } + } + finally { + if (!result) { + messageContext.clearResponse(); + } + } + return result; + } - /** Returns {@code true}, i.e. fault responses are not secured. */ - @Override - public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { - return true; - } + /** Returns {@code true}, i.e. fault responses are not secured. */ + @Override + public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception { + return true; + } - @Override - public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) { - cleanUp(); - } + @Override + public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) { + cleanUp(); + } - @Override - public boolean understands(SoapHeaderElement headerElement) { - return WS_SECURITY_NAME.equals(headerElement.getName()); - } + @Override + public boolean understands(SoapHeaderElement headerElement) { + return WS_SECURITY_NAME.equals(headerElement.getName()); + } - /* - * Client-side - */ + /* + * Client-side + */ - /** - * Secures a client-side outgoing request. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} - * if the {@link #setSecureRequest(boolean) secureRequest} property is {@code true}. - * - * @param messageContext the message context, containing the request to be secured - * @return {@code true} if the response was secured; {@code false} otherwise. - * @throws Exception in case of errors - * @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) - */ - @Override - public final boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { - if (secureRequest) { - Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); - try { - secureMessage((SoapMessage) messageContext.getRequest(), messageContext); - return true; - } - catch (WsSecuritySecurementException ex) { - return handleSecurementException(ex, messageContext); - } - catch (WsSecurityFaultException ex) { - return handleFaultException(ex, messageContext); - } - } - else { - return true; - } - } + /** + * Secures a client-side outgoing request. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} + * if the {@link #setSecureRequest(boolean) secureRequest} property is {@code true}. + * + * @param messageContext the message context, containing the request to be secured + * @return {@code true} if the response was secured; {@code false} otherwise. + * @throws Exception in case of errors + * @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) + */ + @Override + public final boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { + if (secureRequest) { + Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); + try { + secureMessage((SoapMessage) messageContext.getRequest(), messageContext); + return true; + } + catch (WsSecuritySecurementException ex) { + return handleSecurementException(ex, messageContext); + } + catch (WsSecurityFaultException ex) { + return handleFaultException(ex, messageContext); + } + } + else { + return true; + } + } - /** - * Validates a client-side incoming response. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} - * if the {@link #setValidateResponse(boolean) validateResponse} property is {@code true}. - * - * @param messageContext the message context, containing the response to be validated - * @return {@code true} if the request was valid; {@code false} otherwise. - * @throws Exception in case of errors - * @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) - */ - @Override - public final boolean handleResponse(MessageContext messageContext) throws WebServiceClientException { - if (validateResponse) { - Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response"); - Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse()); - if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){ - return true; - } - try { - validateMessage((SoapMessage) messageContext.getResponse(), messageContext); - return true; - } - catch (WsSecurityValidationException ex) { - return handleValidationException(ex, messageContext); - } - catch (WsSecurityFaultException ex) { - return handleFaultException(ex, messageContext); - } - } - else { - return true; - } - } + /** + * Validates a client-side incoming response. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)} + * if the {@link #setValidateResponse(boolean) validateResponse} property is {@code true}. + * + * @param messageContext the message context, containing the response to be validated + * @return {@code true} if the request was valid; {@code false} otherwise. + * @throws Exception in case of errors + * @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext) + */ + @Override + public final boolean handleResponse(MessageContext messageContext) throws WebServiceClientException { + if (validateResponse) { + Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response"); + Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse()); + if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){ + return true; + } + try { + validateMessage((SoapMessage) messageContext.getResponse(), messageContext); + return true; + } + catch (WsSecurityValidationException ex) { + return handleValidationException(ex, messageContext); + } + catch (WsSecurityFaultException ex) { + return handleFaultException(ex, messageContext); + } + } + else { + return true; + } + } - /** Returns {@code true}, i.e. fault responses are not validated. */ - @Override - public boolean handleFault(MessageContext messageContext) throws WebServiceClientException { - return true; - } + /** Returns {@code true}, i.e. fault responses are not validated. */ + @Override + public boolean handleFault(MessageContext messageContext) throws WebServiceClientException { + return true; + } @Override public void afterCompletion(MessageContext messageContext, Exception ex) @@ -268,107 +268,107 @@ public abstract class AbstractWsSecurityInterceptor implements SoapEndpointInter } /** - * Handles an securement exception. Default implementation logs the given exception, and returns - * {@code false}. - * - * @param ex the validation exception - * @param messageContext the message context - * @return {@code true} to continue processing the message, {@code false} (the default) otherwise - */ - protected boolean handleSecurementException(WsSecuritySecurementException ex, MessageContext messageContext) { - if (logger.isErrorEnabled()) { - logger.error("Could not secure response: " + ex.getMessage(), ex); - } - return false; - } + * Handles an securement exception. Default implementation logs the given exception, and returns + * {@code false}. + * + * @param ex the validation exception + * @param messageContext the message context + * @return {@code true} to continue processing the message, {@code false} (the default) otherwise + */ + protected boolean handleSecurementException(WsSecuritySecurementException ex, MessageContext messageContext) { + if (logger.isErrorEnabled()) { + logger.error("Could not secure response: " + ex.getMessage(), ex); + } + return false; + } - /** - * Handles an invalid SOAP message. Default implementation logs the given exception, delegates to the set {@link - * #setExceptionResolver(EndpointExceptionResolver) exceptionResolver} if any, or creates a SOAP 1.1 Client or SOAP - * 1.2 Sender Fault with the exception message as fault string, and returns {@code false}. - * - * @param ex the validation exception - * @param messageContext the message context - * @return {@code true} to continue processing the message, {@code false} (the default) otherwise - */ - protected boolean handleValidationException(WsSecurityValidationException ex, MessageContext messageContext) { - if (logger.isWarnEnabled()) { - logger.warn("Could not validate request: " + ex.getMessage()); - } - if (exceptionResolver != null) { - exceptionResolver.resolveException(messageContext, null, ex); - } - else { - if (logger.isDebugEnabled()) { - logger.debug("No exception resolver present, creating basic soap fault"); - } - SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody(); - response.addClientOrSenderFault(ex.getMessage(), Locale.ENGLISH); - } - return false; - } + /** + * Handles an invalid SOAP message. Default implementation logs the given exception, delegates to the set {@link + * #setExceptionResolver(EndpointExceptionResolver) exceptionResolver} if any, or creates a SOAP 1.1 Client or SOAP + * 1.2 Sender Fault with the exception message as fault string, and returns {@code false}. + * + * @param ex the validation exception + * @param messageContext the message context + * @return {@code true} to continue processing the message, {@code false} (the default) otherwise + */ + protected boolean handleValidationException(WsSecurityValidationException ex, MessageContext messageContext) { + if (logger.isWarnEnabled()) { + logger.warn("Could not validate request: " + ex.getMessage()); + } + if (exceptionResolver != null) { + exceptionResolver.resolveException(messageContext, null, ex); + } + else { + if (logger.isDebugEnabled()) { + logger.debug("No exception resolver present, creating basic soap fault"); + } + SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody(); + response.addClientOrSenderFault(ex.getMessage(), Locale.ENGLISH); + } + return false; + } - /** - * Handles a fault exception.Default implementation logs the given exception, and creates a SOAP Fault with the - * properties of the given exception, and returns {@code false}. - * - * @param ex the validation exception - * @param messageContext the message context - * @return {@code true} to continue processing the message, {@code false} (the default) otherwise - */ - protected boolean handleFaultException(WsSecurityFaultException ex, MessageContext messageContext) { - if (logger.isWarnEnabled()) { - logger.warn("Could not handle request: " + ex.getMessage()); - } - SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody(); - SoapFault fault; - if (response instanceof Soap11Body) { - fault = ((Soap11Body) response).addFault(ex.getFaultCode(), ex.getFaultString(), Locale.ENGLISH); - } - else { - fault = response.addClientOrSenderFault(ex.getFaultString(), Locale.ENGLISH); - } - fault.setFaultActorOrRole(ex.getFaultActor()); - return false; - } + /** + * Handles a fault exception.Default implementation logs the given exception, and creates a SOAP Fault with the + * properties of the given exception, and returns {@code false}. + * + * @param ex the validation exception + * @param messageContext the message context + * @return {@code true} to continue processing the message, {@code false} (the default) otherwise + */ + protected boolean handleFaultException(WsSecurityFaultException ex, MessageContext messageContext) { + if (logger.isWarnEnabled()) { + logger.warn("Could not handle request: " + ex.getMessage()); + } + SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody(); + SoapFault fault; + if (response instanceof Soap11Body) { + fault = ((Soap11Body) response).addFault(ex.getFaultCode(), ex.getFaultString(), Locale.ENGLISH); + } + else { + fault = response.addClientOrSenderFault(ex.getFaultString(), Locale.ENGLISH); + } + fault.setFaultActorOrRole(ex.getFaultActor()); + return false; + } - /** - * Abstract template method. Subclasses are required to validate the request contained in the given {@link - * SoapMessage}, and replace the original request with the validated version. - * - * @param soapMessage the soap message to validate - * @throws WsSecurityValidationException in case of validation errors - */ - protected abstract void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException; + /** + * Abstract template method. Subclasses are required to validate the request contained in the given {@link + * SoapMessage}, and replace the original request with the validated version. + * + * @param soapMessage the soap message to validate + * @throws WsSecurityValidationException in case of validation errors + */ + protected abstract void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException; - /** - * Abstract template method. Subclasses are required to secure the response contained in the given {@link - * SoapMessage}, and replace the original response with the secured version. - * - * @param soapMessage the soap message to secure - * @throws WsSecuritySecurementException in case of securement errors - */ - protected abstract void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecuritySecurementException; + /** + * Abstract template method. Subclasses are required to secure the response contained in the given {@link + * SoapMessage}, and replace the original response with the secured version. + * + * @param soapMessage the soap message to secure + * @throws WsSecuritySecurementException in case of securement errors + */ + protected abstract void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecuritySecurementException; - protected abstract void cleanUp(); + protected abstract void cleanUp(); - /** - * Iterates over header elements and returns true if WS-Security header is found. - */ - private boolean isSecurityHeaderPresent(SoapMessage message) { - SoapHeader soapHeader = message.getSoapHeader(); - if(soapHeader == null){ - return false; - } + /** + * Iterates over header elements and returns true if WS-Security header is found. + */ + private boolean isSecurityHeaderPresent(SoapMessage message) { + SoapHeader soapHeader = message.getSoapHeader(); + if(soapHeader == null){ + return false; + } Iterator elements = soapHeader.examineAllHeaderElements(); - while(elements.hasNext()){ - SoapHeaderElement e = elements.next(); - if(e.getName().equals(WS_SECURITY_NAME)){ - return true; - } - } - return false; + while(elements.hasNext()){ + SoapHeaderElement e = elements.next(); + if(e.getName().equals(WS_SECURITY_NAME)){ + return true; + } + } + return false; } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityException.java index e36e0959..0913241b 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityException.java @@ -28,11 +28,11 @@ import org.springframework.ws.WebServiceException; @SuppressWarnings("serial") public abstract class WsSecurityException extends WebServiceException { - public WsSecurityException(String msg) { - super(msg); - } + public WsSecurityException(String msg) { + super(msg); + } - public WsSecurityException(String msg, Throwable ex) { - super(msg, ex); - } + public WsSecurityException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityFaultException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityFaultException.java index 9815bdcf..1680cf48 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityFaultException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityFaultException.java @@ -27,32 +27,32 @@ import javax.xml.namespace.QName; @SuppressWarnings("serial") public abstract class WsSecurityFaultException extends WsSecurityException { - private QName faultCode; + private QName faultCode; - private String faultString; + private String faultString; - private String faultActor; + private String faultActor; - /** Construct a new {@code WsSecurityFaultException} with the given fault code, string, and actor. */ - public WsSecurityFaultException(QName faultCode, String faultString, String faultActor) { - super(faultString); - this.faultCode = faultCode; - this.faultString = faultString; - this.faultActor = faultActor; - } + /** Construct a new {@code WsSecurityFaultException} with the given fault code, string, and actor. */ + public WsSecurityFaultException(QName faultCode, String faultString, String faultActor) { + super(faultString); + this.faultCode = faultCode; + this.faultString = faultString; + this.faultActor = faultActor; + } - /** Returns the fault code for the exception. */ - public QName getFaultCode() { - return faultCode; - } + /** Returns the fault code for the exception. */ + public QName getFaultCode() { + return faultCode; + } - /** Returns the fault string for the exception. */ - public String getFaultString() { - return faultString; - } + /** Returns the fault string for the exception. */ + public String getFaultString() { + return faultString; + } - /** Returns the fault actor for the exception. */ - public String getFaultActor() { - return faultActor; - } + /** Returns the fault actor for the exception. */ + public String getFaultActor() { + return faultActor; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecuritySecurementException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecuritySecurementException.java index 900142b2..83f4fe1c 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecuritySecurementException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecuritySecurementException.java @@ -28,11 +28,11 @@ package org.springframework.ws.soap.security; @SuppressWarnings("serial") public abstract class WsSecuritySecurementException extends WsSecurityException { - public WsSecuritySecurementException(String msg) { - super(msg); - } + public WsSecuritySecurementException(String msg) { + super(msg); + } - public WsSecuritySecurementException(String msg, Throwable ex) { - super(msg, ex); - } + public WsSecuritySecurementException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityValidationException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityValidationException.java index 890fcd47..c3867aab 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityValidationException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/WsSecurityValidationException.java @@ -28,11 +28,11 @@ package org.springframework.ws.soap.security; @SuppressWarnings("serial") public abstract class WsSecurityValidationException extends WsSecurityException { - public WsSecurityValidationException(String msg) { - super(msg); - } + public WsSecurityValidationException(String msg) { + super(msg); + } - public WsSecurityValidationException(String msg, Throwable ex) { - super(msg, ex); - } + public WsSecurityValidationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/AbstractCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/AbstractCallbackHandler.java index 7ace1cff..5ed0b229 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/AbstractCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/AbstractCallbackHandler.java @@ -32,25 +32,25 @@ import org.apache.commons.logging.LogFactory; */ public abstract class AbstractCallbackHandler implements CallbackHandler { - /** Logger available to subclasses. */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); - protected AbstractCallbackHandler() { - } + protected AbstractCallbackHandler() { + } - /** - * Iterates over the given callbacks, and calls {@code handleInternal} for each of them. - * - * @param callbacks the callbacks - * @see #handleInternal(javax.security.auth.callback.Callback) - */ - @Override - public final void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (Callback callback : callbacks) { - handleInternal(callback); - } - } + /** + * Iterates over the given callbacks, and calls {@code handleInternal} for each of them. + * + * @param callbacks the callbacks + * @see #handleInternal(javax.security.auth.callback.Callback) + */ + @Override + public final void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + for (Callback callback : callbacks) { + handleInternal(callback); + } + } - /** Template method that should be implemented by subclasses. */ - protected abstract void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException; + /** Template method that should be implemented by subclasses. */ + protected abstract void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException; } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CallbackHandlerChain.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CallbackHandlerChain.java index 7ed9c38b..a6a0cf73 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CallbackHandlerChain.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CallbackHandlerChain.java @@ -30,30 +30,30 @@ import javax.security.auth.callback.UnsupportedCallbackException; */ public class CallbackHandlerChain extends AbstractCallbackHandler { - private final CallbackHandler[] callbackHandlers; + private final CallbackHandler[] callbackHandlers; - public CallbackHandlerChain(CallbackHandler[] callbackHandlers) { - this.callbackHandlers = callbackHandlers; - } + public CallbackHandlerChain(CallbackHandler[] callbackHandlers) { + this.callbackHandlers = callbackHandlers; + } - public CallbackHandler[] getCallbackHandlers() { - return callbackHandlers; - } + public CallbackHandler[] getCallbackHandlers() { + return callbackHandlers; + } - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - boolean allUnsupported = true; - for (CallbackHandler callbackHandler : callbackHandlers) { - try { - callbackHandler.handle(new Callback[]{callback}); - allUnsupported = false; - } - catch (UnsupportedCallbackException ex) { - // if an UnsupportedCallbackException occurs, go to the next handler - } - } - if (allUnsupported) { - throw new UnsupportedCallbackException(callback); - } - } + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + boolean allUnsupported = true; + for (CallbackHandler callbackHandler : callbackHandlers) { + try { + callbackHandler.handle(new Callback[]{callback}); + allUnsupported = false; + } + catch (UnsupportedCallbackException ex) { + // if an UnsupportedCallbackException occurs, go to the next handler + } + } + if (allUnsupported) { + throw new UnsupportedCallbackException(callback); + } + } } \ No newline at end of file diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CleanupCallback.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CleanupCallback.java index 32a84a27..f6bedb65 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CleanupCallback.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/callback/CleanupCallback.java @@ -28,6 +28,6 @@ import javax.security.auth.callback.Callback; */ public class CleanupCallback implements Callback, Serializable { - private static final long serialVersionUID = 4744181820980888237L; + private static final long serialVersionUID = 4744181820980888237L; } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBean.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBean.java index 4e3ac9f3..596e2358 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBean.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBean.java @@ -39,75 +39,75 @@ public class KeyManagersFactoryBean implements FactoryBean, Initia private KeyManager[] keyManagers; - private KeyStore keyStore; + private KeyStore keyStore; - private String algorithm; + private String algorithm; - private String provider; + private String provider; - private char[] password; + private char[] password; - /** - * Sets the password to use for integrity checking. If this property is not set, then integrity checking is not - * performed. - */ - public void setPassword(String password) { - if (password != null) { - this.password = password.toCharArray(); - } - } + /** + * Sets the password to use for integrity checking. If this property is not set, then integrity checking is not + * performed. + */ + public void setPassword(String password) { + if (password != null) { + this.password = password.toCharArray(); + } + } - /** - * Sets the provider of the key manager to use. If this is not set, the default is used. - */ - public void setProvider(String provider) { - this.provider = provider; - } + /** + * Sets the provider of the key manager to use. If this is not set, the default is used. + */ + public void setProvider(String provider) { + this.provider = provider; + } - /** - * Sets the algorithm of the {@code KeyManager} to use. If this is not set, the default is used. - * - * @see KeyManagerFactory#getDefaultAlgorithm() - */ - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } + /** + * Sets the algorithm of the {@code KeyManager} to use. If this is not set, the default is used. + * + * @see KeyManagerFactory#getDefaultAlgorithm() + */ + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } - /** - * Sets the source of key material. - * - * @see KeyManagerFactory#init(KeyStore, char[]) - */ - public void setKeyStore(KeyStore keyStore) { - this.keyStore = keyStore; - } + /** + * Sets the source of key material. + * + * @see KeyManagerFactory#init(KeyStore, char[]) + */ + public void setKeyStore(KeyStore keyStore) { + this.keyStore = keyStore; + } - @Override - public KeyManager[] getObject() throws Exception { - return keyManagers; - } + @Override + public KeyManager[] getObject() throws Exception { + return keyManagers; + } - @Override - public Class getObjectType() { - return KeyManager[].class; - } + @Override + public Class getObjectType() { + return KeyManager[].class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } - @Override - public void afterPropertiesSet() throws Exception { - String algorithm = - StringUtils.hasLength(this.algorithm) ? this.algorithm : KeyManagerFactory.getDefaultAlgorithm(); + @Override + public void afterPropertiesSet() throws Exception { + String algorithm = + StringUtils.hasLength(this.algorithm) ? this.algorithm : KeyManagerFactory.getDefaultAlgorithm(); - KeyManagerFactory keyManagerFactory = - StringUtils.hasLength(this.provider) ? KeyManagerFactory.getInstance(algorithm, this.provider) : - KeyManagerFactory.getInstance(algorithm); + KeyManagerFactory keyManagerFactory = + StringUtils.hasLength(this.provider) ? KeyManagerFactory.getInstance(algorithm, this.provider) : + KeyManagerFactory.getInstance(algorithm); - keyManagerFactory.init(keyStore, password); + keyManagerFactory.init(keyStore, password); - this.keyManagers = keyManagerFactory.getKeyManagers(); - } + this.keyManagers = keyManagerFactory.getKeyManagers(); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreFactoryBean.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreFactoryBean.java index 479ed5ea..6ad0fd23 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreFactoryBean.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreFactoryBean.java @@ -42,94 +42,94 @@ import org.springframework.util.StringUtils; */ public class KeyStoreFactoryBean implements FactoryBean, InitializingBean { - private static final Log logger = LogFactory.getLog(KeyStoreFactoryBean.class); + private static final Log logger = LogFactory.getLog(KeyStoreFactoryBean.class); - private KeyStore keyStore; + private KeyStore keyStore; - private String type; + private String type; - private String provider; + private String provider; - private Resource location; + private Resource location; - private char[] password; + private char[] password; - /** - * Sets the location of the key store to use. If this is not set, a new, empty key store will be used. - * - * @see KeyStore#load(java.io.InputStream,char[]) - */ - public void setLocation(Resource location) { - this.location = location; - } + /** + * Sets the location of the key store to use. If this is not set, a new, empty key store will be used. + * + * @see KeyStore#load(java.io.InputStream,char[]) + */ + public void setLocation(Resource location) { + this.location = location; + } - /** - * Sets the password to use for integrity checking. If this property is not set, then integrity checking is not - * performed. - */ - public void setPassword(String password) { - if (password != null) { - this.password = password.toCharArray(); - } - } + /** + * Sets the password to use for integrity checking. If this property is not set, then integrity checking is not + * performed. + */ + public void setPassword(String password) { + if (password != null) { + this.password = password.toCharArray(); + } + } - /** Sets the provider of the key store to use. If this is not set, the default is used. */ - public void setProvider(String provider) { - this.provider = provider; - } + /** Sets the provider of the key store to use. If this is not set, the default is used. */ + public void setProvider(String provider) { + this.provider = provider; + } - /** - * Sets the type of the {@code KeyStore} to use. If this is not set, the default is used. - * - * @see KeyStore#getDefaultType() - */ - public void setType(String type) { - this.type = type; - } + /** + * Sets the type of the {@code KeyStore} to use. If this is not set, the default is used. + * + * @see KeyStore#getDefaultType() + */ + public void setType(String type) { + this.type = type; + } - @Override - public KeyStore getObject() { - return keyStore; - } + @Override + public KeyStore getObject() { + return keyStore; + } - @Override - public Class getObjectType() { - return KeyStore.class; - } + @Override + public Class getObjectType() { + return KeyStore.class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } - @Override - public final void afterPropertiesSet() throws GeneralSecurityException, IOException { - if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) { - keyStore = KeyStore.getInstance(type, provider); - } - else if (StringUtils.hasLength(type)) { - keyStore = KeyStore.getInstance(type); - } - else { - keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - } - InputStream is = null; - try { - if (location != null && location.exists()) { - is = location.getInputStream(); - if (logger.isInfoEnabled()) { - logger.info("Loading key store from " + location); - } - } - else if (logger.isWarnEnabled()) { - logger.warn("Creating empty key store"); - } - keyStore.load(is, password); - } - finally { - if (is != null) { - is.close(); - } - } - } + @Override + public final void afterPropertiesSet() throws GeneralSecurityException, IOException { + if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) { + keyStore = KeyStore.getInstance(type, provider); + } + else if (StringUtils.hasLength(type)) { + keyStore = KeyStore.getInstance(type); + } + else { + keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + } + InputStream is = null; + try { + if (location != null && location.exists()) { + is = location.getInputStream(); + if (logger.isInfoEnabled()) { + logger.info("Loading key store from " + location); + } + } + else if (logger.isWarnEnabled()) { + logger.warn("Creating empty key store"); + } + keyStore.load(is, password); + } + finally { + if (is != null) { + is.close(); + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreUtils.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreUtils.java index b33a749a..e2800c6d 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreUtils.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/KeyStoreUtils.java @@ -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, @@ -33,91 +33,91 @@ import org.springframework.util.StringUtils; */ public abstract class KeyStoreUtils { - /** - * Loads the key store indicated by system properties. This method tries to load a key store by consulting the - * following system properties:{@code javax.net.ssl.keyStore}, {@code javax.net.ssl.keyStorePassword}, and - * {@code javax.net.ssl.keyStoreType}. - * - *

If these properties specify a file with an appropriate password, the factory uses this file for the key store. If - * that file does not exist, then a default, empty keystore is created. - * - *

This behavior corresponds to the standard J2SDK behavior for SSL key stores. - * - * @see The - * standard J2SDK SSL key store mechanism - */ - public static KeyStore loadDefaultKeyStore() throws GeneralSecurityException, IOException { - Resource location = null; - String type = null; - String password = null; - String locationProperty = System.getProperty("javax.net.ssl.keyStore"); - if (StringUtils.hasLength(locationProperty)) { - File f = new File(locationProperty); - if (f.exists() && f.isFile() && f.canRead()) { - location = new FileSystemResource(f); - } - String passwordProperty = System.getProperty("javax.net.ssl.keyStorePassword"); - if (StringUtils.hasLength(passwordProperty)) { - password = passwordProperty; - } - type = System.getProperty("javax.net.ssl.keyStoreType"); - } - // use the factory bean here, easier to setup - KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean(); - factoryBean.setLocation(location); - factoryBean.setPassword(password); - factoryBean.setType(type); - factoryBean.afterPropertiesSet(); - return factoryBean.getObject(); - } + /** + * Loads the key store indicated by system properties. This method tries to load a key store by consulting the + * following system properties:{@code javax.net.ssl.keyStore}, {@code javax.net.ssl.keyStorePassword}, and + * {@code javax.net.ssl.keyStoreType}. + * + *

If these properties specify a file with an appropriate password, the factory uses this file for the key store. If + * that file does not exist, then a default, empty keystore is created. + * + *

This behavior corresponds to the standard J2SDK behavior for SSL key stores. + * + * @see The + * standard J2SDK SSL key store mechanism + */ + public static KeyStore loadDefaultKeyStore() throws GeneralSecurityException, IOException { + Resource location = null; + String type = null; + String password = null; + String locationProperty = System.getProperty("javax.net.ssl.keyStore"); + if (StringUtils.hasLength(locationProperty)) { + File f = new File(locationProperty); + if (f.exists() && f.isFile() && f.canRead()) { + location = new FileSystemResource(f); + } + String passwordProperty = System.getProperty("javax.net.ssl.keyStorePassword"); + if (StringUtils.hasLength(passwordProperty)) { + password = passwordProperty; + } + type = System.getProperty("javax.net.ssl.keyStoreType"); + } + // use the factory bean here, easier to setup + KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean(); + factoryBean.setLocation(location); + factoryBean.setPassword(password); + factoryBean.setType(type); + factoryBean.afterPropertiesSet(); + return factoryBean.getObject(); + } - /** - * Loads a default trust store. This method uses the following algorithm:

  1. If the system property - * {@code javax.net.ssl.trustStore} is defined, its value is loaded. If the - * {@code javax.net.ssl.trustStorePassword} system property is also defined, its value is used as a password. - * If the {@code javax.net.ssl.trustStoreType} system property is defined, its value is used as a key store - * type. - * - *

    If {@code javax.net.ssl.trustStore} is defined but the specified file does not exist, then a default, empty - * trust store is created.

  2. If the {@code javax.net.ssl.trustStore} system property was not - * specified, but if the file {@code $JAVA_HOME/lib/security/jssecacerts} exists, that file is used.
  3. - * Otherwise,
  4. If the file {@code $JAVA_HOME/lib/security/cacerts} exists, that file is used.
- * - *

This behavior corresponds to the standard J2SDK behavior for SSL trust stores. - * - * @see The - * standard J2SDK SSL trust store mechanism - */ - public static KeyStore loadDefaultTrustStore() throws GeneralSecurityException, IOException { - Resource location = null; - String type = null; - String password = null; - String locationProperty = System.getProperty("javax.net.ssl.trustStore"); - if (StringUtils.hasLength(locationProperty)) { - File f = new File(locationProperty); - if (f.exists() && f.isFile() && f.canRead()) { - location = new FileSystemResource(f); - } - String passwordProperty = System.getProperty("javax.net.ssl.trustStorePassword"); - if (StringUtils.hasLength(passwordProperty)) { - password = passwordProperty; - } - type = System.getProperty("javax.net.ssl.trustStoreType"); - } - else { - String javaHome = System.getProperty("java.home"); - location = new FileSystemResource(javaHome + "/lib/security/jssecacerts"); - if (!location.exists()) { - location = new FileSystemResource(javaHome + "/lib/security/cacerts"); - } - } - // use the factory bean here, easier to setup - KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean(); - factoryBean.setLocation(location); - factoryBean.setPassword(password); - factoryBean.setType(type); - factoryBean.afterPropertiesSet(); - return factoryBean.getObject(); - } + /** + * Loads a default trust store. This method uses the following algorithm:

  1. If the system property + * {@code javax.net.ssl.trustStore} is defined, its value is loaded. If the + * {@code javax.net.ssl.trustStorePassword} system property is also defined, its value is used as a password. + * If the {@code javax.net.ssl.trustStoreType} system property is defined, its value is used as a key store + * type. + * + *

    If {@code javax.net.ssl.trustStore} is defined but the specified file does not exist, then a default, empty + * trust store is created.

  2. If the {@code javax.net.ssl.trustStore} system property was not + * specified, but if the file {@code $JAVA_HOME/lib/security/jssecacerts} exists, that file is used.
  3. + * Otherwise,
  4. If the file {@code $JAVA_HOME/lib/security/cacerts} exists, that file is used.
+ * + *

This behavior corresponds to the standard J2SDK behavior for SSL trust stores. + * + * @see The + * standard J2SDK SSL trust store mechanism + */ + public static KeyStore loadDefaultTrustStore() throws GeneralSecurityException, IOException { + Resource location = null; + String type = null; + String password = null; + String locationProperty = System.getProperty("javax.net.ssl.trustStore"); + if (StringUtils.hasLength(locationProperty)) { + File f = new File(locationProperty); + if (f.exists() && f.isFile() && f.canRead()) { + location = new FileSystemResource(f); + } + String passwordProperty = System.getProperty("javax.net.ssl.trustStorePassword"); + if (StringUtils.hasLength(passwordProperty)) { + password = passwordProperty; + } + type = System.getProperty("javax.net.ssl.trustStoreType"); + } + else { + String javaHome = System.getProperty("java.home"); + location = new FileSystemResource(javaHome + "/lib/security/jssecacerts"); + if (!location.exists()) { + location = new FileSystemResource(javaHome + "/lib/security/cacerts"); + } + } + // use the factory bean here, easier to setup + KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean(); + factoryBean.setLocation(location); + factoryBean.setPassword(password); + factoryBean.setType(type); + factoryBean.afterPropertiesSet(); + return factoryBean.getObject(); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/SpringSecurityUtils.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/SpringSecurityUtils.java index f3f33ede..effae3ad 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/SpringSecurityUtils.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/SpringSecurityUtils.java @@ -30,31 +30,31 @@ import org.springframework.security.core.userdetails.UserDetails; */ public abstract class SpringSecurityUtils { - /** - * Checks the validity of a user's account and credentials. - * @param user the user to check - * @throws AccountExpiredException if the account has expired - * @throws CredentialsExpiredException if the credentials have expired - * @throws DisabledException if the account is disabled - * @throws LockedException if the account is locked - */ - @SuppressWarnings("deprecation") - public static void checkUserValidity(UserDetails user) - throws AccountExpiredException, CredentialsExpiredException, DisabledException, LockedException { - if (!user.isAccountNonLocked()) { - throw new LockedException("User account is locked", user); - } + /** + * Checks the validity of a user's account and credentials. + * @param user the user to check + * @throws AccountExpiredException if the account has expired + * @throws CredentialsExpiredException if the credentials have expired + * @throws DisabledException if the account is disabled + * @throws LockedException if the account is locked + */ + @SuppressWarnings("deprecation") + public static void checkUserValidity(UserDetails user) + throws AccountExpiredException, CredentialsExpiredException, DisabledException, LockedException { + if (!user.isAccountNonLocked()) { + throw new LockedException("User account is locked", user); + } - if (!user.isEnabled()) { - throw new DisabledException("User is disabled", user); - } + if (!user.isEnabled()) { + throw new DisabledException("User is disabled", user); + } - if (!user.isAccountNonExpired()) { - throw new AccountExpiredException("User account has expired", user); - } + if (!user.isAccountNonExpired()) { + throw new AccountExpiredException("User account has expired", user); + } - if (!user.isCredentialsNonExpired()) { - throw new CredentialsExpiredException("User credentials have expired", user); - } - } + if (!user.isCredentialsNonExpired()) { + throw new CredentialsExpiredException("User credentials have expired", user); + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBean.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBean.java index 6085d695..ecccef15 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBean.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBean.java @@ -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, diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jHandler.java index 32c9e1be..9f5d9a14 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jHandler.java @@ -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, @@ -36,87 +36,87 @@ import org.w3c.dom.Document; */ class Wss4jHandler extends WSHandler { - /** Keys are constants from {@link WSHandlerConstants}; values are strings. */ - private Properties options = new Properties(); + /** Keys are constants from {@link WSHandlerConstants}; values are strings. */ + private Properties options = new Properties(); - private String securementPassword; + private String securementPassword; - private Crypto securementEncryptionCrypto; + private Crypto securementEncryptionCrypto; - private Crypto securementSignatureCrypto; + private Crypto securementSignatureCrypto; - Wss4jHandler() { - // set up default handler properties - options.setProperty(WSHandlerConstants.MUST_UNDERSTAND, Boolean.toString(true)); - options.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, Boolean.toString(true)); - } + Wss4jHandler() { + // set up default handler properties + options.setProperty(WSHandlerConstants.MUST_UNDERSTAND, Boolean.toString(true)); + options.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, Boolean.toString(true)); + } - @Override - protected boolean checkReceiverResultsAnyOrder(List wsResult, List actions) { - return super.checkReceiverResultsAnyOrder(wsResult, actions); - } + @Override + protected boolean checkReceiverResultsAnyOrder(List wsResult, List actions) { + return super.checkReceiverResultsAnyOrder(wsResult, actions); + } - void setOption(String key, String value) { - options.setProperty(key, value); - } + void setOption(String key, String value) { + options.setProperty(key, value); + } - void setOption(String key, boolean value) { - options.setProperty(key, Boolean.toString(value)); - } + void setOption(String key, boolean value) { + options.setProperty(key, Boolean.toString(value)); + } - @Override - public Object getOption(String key) { - return options.getProperty(key); - } + @Override + public Object getOption(String key) { + return options.getProperty(key); + } - void setSecurementPassword(String securementPassword) { - this.securementPassword = securementPassword; - } + void setSecurementPassword(String securementPassword) { + this.securementPassword = securementPassword; + } - void setSecurementEncryptionCrypto(Crypto securementEncryptionCrypto) { - this.securementEncryptionCrypto = securementEncryptionCrypto; - } + void setSecurementEncryptionCrypto(Crypto securementEncryptionCrypto) { + this.securementEncryptionCrypto = securementEncryptionCrypto; + } - void setSecurementSignatureCrypto(Crypto securementSignatureCrypto) { - this.securementSignatureCrypto = securementSignatureCrypto; - } + void setSecurementSignatureCrypto(Crypto securementSignatureCrypto) { + this.securementSignatureCrypto = securementSignatureCrypto; + } - @Override - public String getPassword(Object msgContext) { - return securementPassword; - } + @Override + public String getPassword(Object msgContext) { + return securementPassword; + } - @Override - public Object getProperty(Object msgContext, String key) { - return ((MessageContext) msgContext).getProperty(key); - } + @Override + public Object getProperty(Object msgContext, String key) { + return ((MessageContext) msgContext).getProperty(key); + } - @Override - protected Crypto loadEncryptionCrypto(RequestData reqData) throws WSSecurityException { - return securementEncryptionCrypto; - } + @Override + protected Crypto loadEncryptionCrypto(RequestData reqData) throws WSSecurityException { + return securementEncryptionCrypto; + } - @Override - public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException { - return securementSignatureCrypto; - } + @Override + public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException { + return securementSignatureCrypto; + } - @Override - public void setPassword(Object msgContext, String password) { - securementPassword = password; - } + @Override + public void setPassword(Object msgContext, String password) { + securementPassword = password; + } - @Override - public void setProperty(Object msgContext, String key, Object value) { - ((MessageContext) msgContext).setProperty(key, value); - } + @Override + public void setProperty(Object msgContext, String key, Object value) { + ((MessageContext) msgContext).setProperty(key, value); + } - @Override - protected void doSenderAction(int doAction, - Document doc, - RequestData reqData, - List actions, - boolean isRequest) throws WSSecurityException { - super.doSenderAction(doAction, doc, reqData, actions, isRequest); - } + @Override + protected void doSenderAction(int doAction, + Document doc, + RequestData reqData, + List actions, + boolean isRequest) throws WSSecurityException { + super.doSenderAction(doAction, doc, reqData, actions, isRequest); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityFaultException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityFaultException.java old mode 100755 new mode 100644 index f82f6bf7..e2941679 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityFaultException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityFaultException.java @@ -30,7 +30,7 @@ import org.springframework.ws.soap.security.WsSecurityFaultException; @SuppressWarnings("serial") public class Wss4jSecurityFaultException extends WsSecurityFaultException { - public Wss4jSecurityFaultException(QName faultCode, String faultString, String faultActor) { - super(faultCode, faultString, faultActor); - } + public Wss4jSecurityFaultException(QName faultCode, String faultString, String faultActor) { + super(faultCode, faultString, faultActor); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityInterceptor.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityInterceptor.java old mode 100755 new mode 100644 index 440e79e1..fbfaa67a --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityInterceptor.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityInterceptor.java @@ -88,404 +88,404 @@ import org.springframework.ws.soap.security.wss4j.callback.UsernameTokenPrincipa */ public class Wss4jSecurityInterceptor extends AbstractWsSecurityInterceptor implements InitializingBean { - public static final String SECUREMENT_USER_PROPERTY_NAME = "Wss4jSecurityInterceptor.securementUser"; + public static final String SECUREMENT_USER_PROPERTY_NAME = "Wss4jSecurityInterceptor.securementUser"; - private static final String SAML_ISSUER_PROPERTY_NAME = "Wss4jSecurityInterceptor.samlIssuer"; + private static final String SAML_ISSUER_PROPERTY_NAME = "Wss4jSecurityInterceptor.samlIssuer"; - private int securementAction; + private int securementAction; - private String securementActions; + private String securementActions; - private List securementActionsVector; + private List securementActionsVector; - private String securementUsername; + private String securementUsername; - private CallbackHandler validationCallbackHandler; + private CallbackHandler validationCallbackHandler; - private int validationAction; + private int validationAction; - private String validationActions; + private String validationActions; - private List validationActionsVector; + private List validationActionsVector; - private String validationActor; + private String validationActor; - private Crypto validationDecryptionCrypto; + private Crypto validationDecryptionCrypto; - private Crypto validationSignatureCrypto; + private Crypto validationSignatureCrypto; - private boolean timestampStrict = true; + private boolean timestampStrict = true; - private boolean enableSignatureConfirmation; + private boolean enableSignatureConfirmation; - private int validationTimeToLive = 300; + private int validationTimeToLive = 300; - private int securementTimeToLive = 300; + private int securementTimeToLive = 300; private int futureTimeToLive = 60; private SAMLIssuer samlIssuer; - - private WSSConfig wssConfig; + + private WSSConfig wssConfig; - private final Wss4jHandler handler = new Wss4jHandler(); + private final Wss4jHandler handler = new Wss4jHandler(); - private final WSSecurityEngine securityEngine = new WSSecurityEngine(); + private final WSSecurityEngine securityEngine = new WSSecurityEngine(); - private boolean enableRevocation; + private boolean enableRevocation; - private boolean bspCompliant; + private boolean bspCompliant; - private boolean securementUseDerivedKey; + private boolean securementUseDerivedKey; - // To maintain same behavior as default, this flag is set to true - private boolean removeSecurityHeader = true; + // To maintain same behavior as default, this flag is set to true + private boolean removeSecurityHeader = true; - public void setSecurementActions(String securementActions) { - this.securementActions = securementActions; - securementActionsVector = new ArrayList(); - try { - securementAction = WSSecurityUtil.decodeAction(securementActions, securementActionsVector); - } - catch (WSSecurityException ex) { - throw new IllegalArgumentException(ex); - } - } + public void setSecurementActions(String securementActions) { + this.securementActions = securementActions; + securementActionsVector = new ArrayList(); + try { + securementAction = WSSecurityUtil.decodeAction(securementActions, securementActionsVector); + } + catch (WSSecurityException ex) { + throw new IllegalArgumentException(ex); + } + } - /** - * The actor name of the {@code wsse:Security} header. - * - *

If this parameter is omitted, the actor name is not set. - * - *

The value of the actor or role has to match the receiver's setting or may contain standard values. - */ - public void setSecurementActor(String securementActor) { - handler.setOption(WSHandlerConstants.ACTOR, securementActor); - } + /** + * The actor name of the {@code wsse:Security} header. + * + *

If this parameter is omitted, the actor name is not set. + * + *

The value of the actor or role has to match the receiver's setting or may contain standard values. + */ + public void setSecurementActor(String securementActor) { + handler.setOption(WSHandlerConstants.ACTOR, securementActor); + } - public void setSecurementEncryptionCrypto(Crypto securementEncryptionCrypto) { - handler.setSecurementEncryptionCrypto(securementEncryptionCrypto); - } + public void setSecurementEncryptionCrypto(Crypto securementEncryptionCrypto) { + handler.setSecurementEncryptionCrypto(securementEncryptionCrypto); + } - /** Sets the key name that needs to be sent for encryption. */ - public void setSecurementEncryptionEmbeddedKeyName(String securementEncryptionEmbeddedKeyName) { - handler.setOption(WSHandlerConstants.ENC_KEY_NAME, securementEncryptionEmbeddedKeyName); - } + /** Sets the key name that needs to be sent for encryption. */ + public void setSecurementEncryptionEmbeddedKeyName(String securementEncryptionEmbeddedKeyName) { + handler.setOption(WSHandlerConstants.ENC_KEY_NAME, securementEncryptionEmbeddedKeyName); + } - /** - * Defines which key identifier type to use. The WS-Security specifications recommends to use the identifier type - * {@code IssuerSerial}. For possible encryption key identifier types refer to {@link - * org.apache.ws.security.handler.WSHandlerConstants#keyIdentifier}. For encryption {@code IssuerSerial}, - * {@code X509KeyIdentifier}, {@code DirectReference}, {@code Thumbprint}, - * {@code SKIKeyIdentifier}, and {@code EmbeddedKeyName} are valid only. - */ - public void setSecurementEncryptionKeyIdentifier(String securementEncryptionKeyIdentifier) { - handler.setOption(WSHandlerConstants.ENC_KEY_ID, securementEncryptionKeyIdentifier); - } + /** + * Defines which key identifier type to use. The WS-Security specifications recommends to use the identifier type + * {@code IssuerSerial}. For possible encryption key identifier types refer to {@link + * org.apache.ws.security.handler.WSHandlerConstants#keyIdentifier}. For encryption {@code IssuerSerial}, + * {@code X509KeyIdentifier}, {@code DirectReference}, {@code Thumbprint}, + * {@code SKIKeyIdentifier}, and {@code EmbeddedKeyName} are valid only. + */ + public void setSecurementEncryptionKeyIdentifier(String securementEncryptionKeyIdentifier) { + handler.setOption(WSHandlerConstants.ENC_KEY_ID, securementEncryptionKeyIdentifier); + } - /** - * Defines which algorithm to use to encrypt the generated symmetric key. Currently WSS4J supports {@link - * WSConstants#KEYTRANSPORT_RSA15} and {@link WSConstants#KEYTRANSPORT_RSAOEP}. - */ - public void setSecurementEncryptionKeyTransportAlgorithm(String securementEncryptionKeyTransportAlgorithm) { - handler.setOption(WSHandlerConstants.ENC_KEY_TRANSPORT, securementEncryptionKeyTransportAlgorithm); - } + /** + * Defines which algorithm to use to encrypt the generated symmetric key. Currently WSS4J supports {@link + * WSConstants#KEYTRANSPORT_RSA15} and {@link WSConstants#KEYTRANSPORT_RSAOEP}. + */ + public void setSecurementEncryptionKeyTransportAlgorithm(String securementEncryptionKeyTransportAlgorithm) { + handler.setOption(WSHandlerConstants.ENC_KEY_TRANSPORT, securementEncryptionKeyTransportAlgorithm); + } - /** - * Property to define which parts of the request shall be encrypted. - * - *

The value of this property is a list of semi-colon separated element names that identify the elements to encrypt. - * An encryption mode specifier and a namespace identification, each inside a pair of curly brackets, may precede - * each element name. - * - *

The encryption mode specifier is either {@code{Content}} or {@code{Element}}. Please refer to the W3C - * XML Encryption specification about the differences between Element and Content encryption. The encryption mode - * defaults to {@code Content} if it is omitted. Example of a list: - *

-     * <property name="securementEncryptionParts"
-     *   value="{Content}{http://example.org/paymentv2}CreditCard;
-     *             {Element}{}UserName" />
-     * 
- * The the first entry of the list identifies the element {@code CreditCard} in the namespace - * {@code http://example.org/paymentv2}, and will encrypt its content. Be aware that the element name, the - * namespace identifier, and the encryption modifier are case sensitive. - * - *

The encryption modifier and the namespace identifier can be omitted. In this case the encryption mode defaults to - * {@code Content} and the namespace is set to the SOAP namespace. - * - *

An empty encryption mode defaults to {@code Content}, an empty namespace identifier defaults to the SOAP - * namespace. The second line of the example defines {@code Element} as encryption mode for an - * {@code UserName} element in the SOAP namespace. - * - *

To specify an element without a namespace use the string {@code Null} as the namespace name (this is a case - * sensitive string) - * - *

If no list is specified, the handler encrypts the SOAP Body in {@code Content} mode by default. - */ - public void setSecurementEncryptionParts(String securementEncryptionParts) { - handler.setOption(WSHandlerConstants.ENCRYPTION_PARTS, securementEncryptionParts); - } + /** + * Property to define which parts of the request shall be encrypted. + * + *

The value of this property is a list of semi-colon separated element names that identify the elements to encrypt. + * An encryption mode specifier and a namespace identification, each inside a pair of curly brackets, may precede + * each element name. + * + *

The encryption mode specifier is either {@code{Content}} or {@code{Element}}. Please refer to the W3C + * XML Encryption specification about the differences between Element and Content encryption. The encryption mode + * defaults to {@code Content} if it is omitted. Example of a list: + *

+	 * <property name="securementEncryptionParts"
+	 *	 value="{Content}{http://example.org/paymentv2}CreditCard;
+	 *			   {Element}{}UserName" />
+	 * 
+ * The the first entry of the list identifies the element {@code CreditCard} in the namespace + * {@code http://example.org/paymentv2}, and will encrypt its content. Be aware that the element name, the + * namespace identifier, and the encryption modifier are case sensitive. + * + *

The encryption modifier and the namespace identifier can be omitted. In this case the encryption mode defaults to + * {@code Content} and the namespace is set to the SOAP namespace. + * + *

An empty encryption mode defaults to {@code Content}, an empty namespace identifier defaults to the SOAP + * namespace. The second line of the example defines {@code Element} as encryption mode for an + * {@code UserName} element in the SOAP namespace. + * + *

To specify an element without a namespace use the string {@code Null} as the namespace name (this is a case + * sensitive string) + * + *

If no list is specified, the handler encrypts the SOAP Body in {@code Content} mode by default. + */ + public void setSecurementEncryptionParts(String securementEncryptionParts) { + handler.setOption(WSHandlerConstants.ENCRYPTION_PARTS, securementEncryptionParts); + } - /** - * Defines which symmetric encryption algorithm to use. WSS4J supports the following alorithms: {@link - * WSConstants#TRIPLE_DES}, {@link WSConstants#AES_128}, {@link WSConstants#AES_256}, and {@link - * WSConstants#AES_192}. Except for AES 192 all of these algorithms are required by the XML Encryption - * specification. - */ - public void setSecurementEncryptionSymAlgorithm(String securementEncryptionSymAlgorithm) { - this.handler.setOption(WSHandlerConstants.ENC_SYM_ALGO, securementEncryptionSymAlgorithm); - } + /** + * Defines which symmetric encryption algorithm to use. WSS4J supports the following alorithms: {@link + * WSConstants#TRIPLE_DES}, {@link WSConstants#AES_128}, {@link WSConstants#AES_256}, and {@link + * WSConstants#AES_192}. Except for AES 192 all of these algorithms are required by the XML Encryption + * specification. + */ + public void setSecurementEncryptionSymAlgorithm(String securementEncryptionSymAlgorithm) { + this.handler.setOption(WSHandlerConstants.ENC_SYM_ALGO, securementEncryptionSymAlgorithm); + } - /** - * The user's name for encryption. - * - *

The encryption functions uses the public key of this user's certificate to encrypt the generated symmetric key. - * - *

If this parameter is not set, then the encryption function falls back to the {@link - * org.apache.ws.security.handler.WSHandlerConstants#USER} parameter to get the certificate. - * - *

If only encryption of the SOAP body data is requested, it is recommended to use this parameter to define - * the username. The application can then use the standard user and password functions (see example at {@link - * org.apache.ws.security.handler.WSHandlerConstants#USER} to enable HTTP authentication functions. - * - *

Encryption only does not authenticate a user / sender, therefore it does not need a password. - * - *

Placing the username of the encryption certificate in the configuration file is not a security risk, because the - * public key of that certificate is used only. - */ - public void setSecurementEncryptionUser(String securementEncryptionUser) { - handler.setOption(WSHandlerConstants.ENCRYPTION_USER, securementEncryptionUser); - } + /** + * The user's name for encryption. + * + *

The encryption functions uses the public key of this user's certificate to encrypt the generated symmetric key. + * + *

If this parameter is not set, then the encryption function falls back to the {@link + * org.apache.ws.security.handler.WSHandlerConstants#USER} parameter to get the certificate. + * + *

If only encryption of the SOAP body data is requested, it is recommended to use this parameter to define + * the username. The application can then use the standard user and password functions (see example at {@link + * org.apache.ws.security.handler.WSHandlerConstants#USER} to enable HTTP authentication functions. + * + *

Encryption only does not authenticate a user / sender, therefore it does not need a password. + * + *

Placing the username of the encryption certificate in the configuration file is not a security risk, because the + * public key of that certificate is used only. + */ + public void setSecurementEncryptionUser(String securementEncryptionUser) { + handler.setOption(WSHandlerConstants.ENCRYPTION_USER, securementEncryptionUser); + } - public void setSecurementPassword(String securementPassword) { - this.handler.setSecurementPassword(securementPassword); - } + public void setSecurementPassword(String securementPassword) { + this.handler.setSecurementPassword(securementPassword); + } - /** - * Specific parameter for UsernameToken action to define the encoding of the passowrd. - * - *

The parameter can be set to either {@link WSConstants#PW_DIGEST} or to {@link WSConstants#PW_TEXT}. - * - *

The default setting is PW_DIGEST. - */ - public void setSecurementPasswordType(String securementUsernameTokenPasswordType) { - handler.setOption(WSHandlerConstants.PASSWORD_TYPE, securementUsernameTokenPasswordType); - } + /** + * Specific parameter for UsernameToken action to define the encoding of the passowrd. + * + *

The parameter can be set to either {@link WSConstants#PW_DIGEST} or to {@link WSConstants#PW_TEXT}. + * + *

The default setting is PW_DIGEST. + */ + public void setSecurementPasswordType(String securementUsernameTokenPasswordType) { + handler.setOption(WSHandlerConstants.PASSWORD_TYPE, securementUsernameTokenPasswordType); + } - /** - * Defines which signature algorithm to use. - * @see WSConstants#RSA - * @see WSConstants#DSA - */ - public void setSecurementSignatureAlgorithm(String securementSignatureAlgorithm) { - handler.setOption(WSHandlerConstants.SIG_ALGO, securementSignatureAlgorithm); - } + /** + * Defines which signature algorithm to use. + * @see WSConstants#RSA + * @see WSConstants#DSA + */ + public void setSecurementSignatureAlgorithm(String securementSignatureAlgorithm) { + handler.setOption(WSHandlerConstants.SIG_ALGO, securementSignatureAlgorithm); + } - /** - * Defines which signature digest algorithm to use. - */ - public void setSecurementSignatureDigestAlgorithm(String digestAlgorithm) { - handler.setOption(WSHandlerConstants.SIG_DIGEST_ALGO, digestAlgorithm); - } + /** + * Defines which signature digest algorithm to use. + */ + public void setSecurementSignatureDigestAlgorithm(String digestAlgorithm) { + handler.setOption(WSHandlerConstants.SIG_DIGEST_ALGO, digestAlgorithm); + } - public void setSecurementSignatureCrypto(Crypto securementSignatureCrypto) { - handler.setSecurementSignatureCrypto(securementSignatureCrypto); - } + public void setSecurementSignatureCrypto(Crypto securementSignatureCrypto) { + handler.setSecurementSignatureCrypto(securementSignatureCrypto); + } - /** - * Defines which key identifier type to use. The WS-Security specifications recommends to use the identifier type - * {@code IssuerSerial}. For possible signature key identifier types refer to {@link - * org.apache.ws.security.handler.WSHandlerConstants#keyIdentifier}. For signature {@code IssuerSerial} and - * {@code DirectReference} are valid only. - */ - public void setSecurementSignatureKeyIdentifier(String securementSignatureKeyIdentifier) { - handler.setOption(WSHandlerConstants.SIG_KEY_ID, securementSignatureKeyIdentifier); - } + /** + * Defines which key identifier type to use. The WS-Security specifications recommends to use the identifier type + * {@code IssuerSerial}. For possible signature key identifier types refer to {@link + * org.apache.ws.security.handler.WSHandlerConstants#keyIdentifier}. For signature {@code IssuerSerial} and + * {@code DirectReference} are valid only. + */ + public void setSecurementSignatureKeyIdentifier(String securementSignatureKeyIdentifier) { + handler.setOption(WSHandlerConstants.SIG_KEY_ID, securementSignatureKeyIdentifier); + } - /** - * Property to define which parts of the request shall be signed. - * - *

Refer to {@link #setSecurementEncryptionParts(String)} for a detailed description of the format of the value - * string. - * - *

If this property is not specified the handler signs the SOAP Body by default. - * - *

The WS Security specifications define several formats to transfer the signature tokens (certificates) or - * references to these tokens. Thus, the plain element name {@code Token} signs the token and takes care of the - * different formats. - * - *

To sign the SOAP body and the signature token the value of this parameter must contain: - *

-     * <property name="securementSignatureParts"
-     *   value="{}{http://schemas.xmlsoap.org/soap/envelope/}Body; Token" />
-     * 
- * To specify an element without a namespace use the string {@code Null} as the namespace name (this is a case - * sensitive string) - * - *

If there is no other element in the request with a local name of {@code Body} then the SOAP namespace - * identifier can be empty ({@code{}}). - */ - public void setSecurementSignatureParts(String securementSignatureParts) { - handler.setOption(WSHandlerConstants.SIGNATURE_PARTS, securementSignatureParts); - } + /** + * Property to define which parts of the request shall be signed. + * + *

Refer to {@link #setSecurementEncryptionParts(String)} for a detailed description of the format of the value + * string. + * + *

If this property is not specified the handler signs the SOAP Body by default. + * + *

The WS Security specifications define several formats to transfer the signature tokens (certificates) or + * references to these tokens. Thus, the plain element name {@code Token} signs the token and takes care of the + * different formats. + * + *

To sign the SOAP body and the signature token the value of this parameter must contain: + *

+	 * <property name="securementSignatureParts"
+	 *	 value="{}{http://schemas.xmlsoap.org/soap/envelope/}Body; Token" />
+	 * 
+ * To specify an element without a namespace use the string {@code Null} as the namespace name (this is a case + * sensitive string) + * + *

If there is no other element in the request with a local name of {@code Body} then the SOAP namespace + * identifier can be empty ({@code{}}). + */ + public void setSecurementSignatureParts(String securementSignatureParts) { + handler.setOption(WSHandlerConstants.SIGNATURE_PARTS, securementSignatureParts); + } - /** - * The user's name for signature. - * - *

This name is used as the alias name in the keystore to get user's - * certificate and private key to perform signing. - * - *

If this parameter is not set, then the signature - * function falls back to the alias specified by {@link #setSecurementUsername(String)}. - * - */ - public void setSecurementSignatureUser(String securementSignatureUser) { - handler.setOption(WSHandlerConstants.SIGNATURE_USER, securementSignatureUser); - } + /** + * The user's name for signature. + * + *

This name is used as the alias name in the keystore to get user's + * certificate and private key to perform signing. + * + *

If this parameter is not set, then the signature + * function falls back to the alias specified by {@link #setSecurementUsername(String)}. + * + */ + public void setSecurementSignatureUser(String securementSignatureUser) { + handler.setOption(WSHandlerConstants.SIGNATURE_USER, securementSignatureUser); + } - /** Sets the username for securement username token or/and the alias of the private key for securement signature */ - public void setSecurementUsername(String securementUsername) { - this.securementUsername = securementUsername; - } + /** Sets the username for securement username token or/and the alias of the private key for securement signature */ + public void setSecurementUsername(String securementUsername) { + this.securementUsername = securementUsername; + } - /** Sets the time to live on the outgoing message */ - public void setSecurementTimeToLive(int securementTimeToLive) { - if (securementTimeToLive <= 0) { - throw new IllegalArgumentException("timeToLive must be positive"); - } - this.securementTimeToLive = securementTimeToLive; - } + /** Sets the time to live on the outgoing message */ + public void setSecurementTimeToLive(int securementTimeToLive) { + if (securementTimeToLive <= 0) { + throw new IllegalArgumentException("timeToLive must be positive"); + } + this.securementTimeToLive = securementTimeToLive; + } - /** - * Enables the derivation of keys as per the UsernameTokenProfile 1.1 spec. Default is {@code true}. - */ - public void setSecurementUseDerivedKey(boolean securementUseDerivedKey) { - this.securementUseDerivedKey = securementUseDerivedKey; - } + /** + * Enables the derivation of keys as per the UsernameTokenProfile 1.1 spec. Default is {@code true}. + */ + public void setSecurementUseDerivedKey(boolean securementUseDerivedKey) { + this.securementUseDerivedKey = securementUseDerivedKey; + } - /** Sets the server-side time to live */ - public void setValidationTimeToLive(int validationTimeToLive) { - if (validationTimeToLive <= 0) { - throw new IllegalArgumentException("timeToLive must be positive"); - } - this.validationTimeToLive = validationTimeToLive; - } + /** Sets the server-side time to live */ + public void setValidationTimeToLive(int validationTimeToLive) { + if (validationTimeToLive <= 0) { + throw new IllegalArgumentException("timeToLive must be positive"); + } + this.validationTimeToLive = validationTimeToLive; + } - /** Sets the validation actions to be executed by the interceptor. */ - public void setValidationActions(String actions) { - this.validationActions = actions; - try { - validationActionsVector = new ArrayList(); - validationAction = WSSecurityUtil.decodeAction(actions, validationActionsVector); - } - catch (WSSecurityException ex) { - throw new IllegalArgumentException(ex); - } - } + /** Sets the validation actions to be executed by the interceptor. */ + public void setValidationActions(String actions) { + this.validationActions = actions; + try { + validationActionsVector = new ArrayList(); + validationAction = WSSecurityUtil.decodeAction(actions, validationActionsVector); + } + catch (WSSecurityException ex) { + throw new IllegalArgumentException(ex); + } + } - public void setValidationActor(String validationActor) { - this.validationActor = validationActor; - } + public void setValidationActor(String validationActor) { + this.validationActor = validationActor; + } - /** - * Sets the {@link org.apache.ws.security.WSPasswordCallback} handler to use when validating messages. - * - * @see #setValidationCallbackHandlers(CallbackHandler[]) - */ - public void setValidationCallbackHandler(CallbackHandler callbackHandler) { - this.validationCallbackHandler = callbackHandler; - } + /** + * Sets the {@link org.apache.ws.security.WSPasswordCallback} handler to use when validating messages. + * + * @see #setValidationCallbackHandlers(CallbackHandler[]) + */ + public void setValidationCallbackHandler(CallbackHandler callbackHandler) { + this.validationCallbackHandler = callbackHandler; + } - /** - * Sets the {@link org.apache.ws.security.WSPasswordCallback} handlers to use when validating messages. - * - * @see #setValidationCallbackHandler(CallbackHandler) - */ - public void setValidationCallbackHandlers(CallbackHandler[] callbackHandler) { - this.validationCallbackHandler = new CallbackHandlerChain(callbackHandler); - } + /** + * Sets the {@link org.apache.ws.security.WSPasswordCallback} handlers to use when validating messages. + * + * @see #setValidationCallbackHandler(CallbackHandler) + */ + public void setValidationCallbackHandlers(CallbackHandler[] callbackHandler) { + this.validationCallbackHandler = new CallbackHandlerChain(callbackHandler); + } - /** Sets the Crypto to use to decrypt incoming messages */ - public void setValidationDecryptionCrypto(Crypto decryptionCrypto) { - this.validationDecryptionCrypto = decryptionCrypto; - } + /** Sets the Crypto to use to decrypt incoming messages */ + public void setValidationDecryptionCrypto(Crypto decryptionCrypto) { + this.validationDecryptionCrypto = decryptionCrypto; + } - /** Sets the Crypto to use to verify the signature of incoming messages */ - public void setValidationSignatureCrypto(Crypto signatureCrypto) { - this.validationSignatureCrypto = signatureCrypto; - } + /** Sets the Crypto to use to verify the signature of incoming messages */ + public void setValidationSignatureCrypto(Crypto signatureCrypto) { + this.validationSignatureCrypto = signatureCrypto; + } - /** Whether to enable signatureConfirmation or not. By default signatureConfirmation is enabled */ - public void setEnableSignatureConfirmation(boolean enableSignatureConfirmation) { - handler.setOption(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, enableSignatureConfirmation); - this.enableSignatureConfirmation = enableSignatureConfirmation; - } + /** Whether to enable signatureConfirmation or not. By default signatureConfirmation is enabled */ + public void setEnableSignatureConfirmation(boolean enableSignatureConfirmation) { + handler.setOption(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, enableSignatureConfirmation); + this.enableSignatureConfirmation = enableSignatureConfirmation; + } - /** Sets if the generated timestamp header's precision is in milliseconds. */ - public void setTimestampPrecisionInMilliseconds(boolean timestampPrecisionInMilliseconds) { - handler.setOption(WSHandlerConstants.TIMESTAMP_PRECISION, timestampPrecisionInMilliseconds); - } + /** Sets if the generated timestamp header's precision is in milliseconds. */ + public void setTimestampPrecisionInMilliseconds(boolean timestampPrecisionInMilliseconds) { + handler.setOption(WSHandlerConstants.TIMESTAMP_PRECISION, timestampPrecisionInMilliseconds); + } - /** Sets whether or not timestamp verification is done with the server-side time to live */ - public void setTimestampStrict(boolean timestampStrict) { - this.timestampStrict = timestampStrict; - } + /** Sets whether or not timestamp verification is done with the server-side time to live */ + public void setTimestampStrict(boolean timestampStrict) { + this.timestampStrict = timestampStrict; + } - /** - * Enables the {@code mustUnderstand} attribute on WS-Security headers on outgoing messages. Default is - * {@code true}. - */ - public void setSecurementMustUnderstand(boolean securementMustUnderstand) { - handler.setOption(WSHandlerConstants.MUST_UNDERSTAND, securementMustUnderstand); - } + /** + * Enables the {@code mustUnderstand} attribute on WS-Security headers on outgoing messages. Default is + * {@code true}. + */ + public void setSecurementMustUnderstand(boolean securementMustUnderstand) { + handler.setOption(WSHandlerConstants.MUST_UNDERSTAND, securementMustUnderstand); + } - /** - * Sets the additional elements in {@code UsernameToken}s. - * - *

The value of this parameter is a list of element names that are added to the UsernameToken. The names of the list - * a separated by spaces. - * - *

The list may contain the names {@code Nonce} and {@code Created} only (case sensitive). Use this option - * if the password type is {@code passwordText} and the handler shall add the {@code Nonce} and/or - * {@code Created} elements. - */ - public void setSecurementUsernameTokenElements(String securementUsernameTokenElements) { - handler.setOption(WSHandlerConstants.ADD_UT_ELEMENTS, securementUsernameTokenElements); - } - - /** - * Sets the web service specification settings. - *

- * The default settings follow the latest OASIS and changing anything might violate the OASIS specs. - * - * @param config web service security configuration or {@code null} to use default settings - */ - public void setWssConfig(WSSConfig config) { - securityEngine.setWssConfig(config); - wssConfig = config; - } + /** + * Sets the additional elements in {@code UsernameToken}s. + * + *

The value of this parameter is a list of element names that are added to the UsernameToken. The names of the list + * a separated by spaces. + * + *

The list may contain the names {@code Nonce} and {@code Created} only (case sensitive). Use this option + * if the password type is {@code passwordText} and the handler shall add the {@code Nonce} and/or + * {@code Created} elements. + */ + public void setSecurementUsernameTokenElements(String securementUsernameTokenElements) { + handler.setOption(WSHandlerConstants.ADD_UT_ELEMENTS, securementUsernameTokenElements); + } + + /** + * Sets the web service specification settings. + *

+ * The default settings follow the latest OASIS and changing anything might violate the OASIS specs. + * + * @param config web service security configuration or {@code null} to use default settings + */ + public void setWssConfig(WSSConfig config) { + securityEngine.setWssConfig(config); + wssConfig = config; + } - /** - * Set whether to enable CRL checking or not when verifying trust in a certificate. - */ - public void setEnableRevocation(boolean enableRevocation) { - this.enableRevocation = enableRevocation; - } + /** + * Set whether to enable CRL checking or not when verifying trust in a certificate. + */ + public void setEnableRevocation(boolean enableRevocation) { + this.enableRevocation = enableRevocation; + } - /** - * Set the WS-I Basic Security Profile compliance mode. Default is {@code true}. - */ - public void setBspCompliant(boolean bspCompliant) { - this.handler.setOption(WSHandlerConstants.IS_BSP_COMPLIANT, bspCompliant); - this.bspCompliant = bspCompliant; - } + /** + * Set the WS-I Basic Security Profile compliance mode. Default is {@code true}. + */ + public void setBspCompliant(boolean bspCompliant) { + this.handler.setOption(WSHandlerConstants.IS_BSP_COMPLIANT, bspCompliant); + this.bspCompliant = bspCompliant; + } - /** - * Sets the location of the SAML properties file. The file should be available on the classpath. - */ - public void setSamlProperties(String location) { - handler.setOption(WSHandlerConstants.SAML_PROP_FILE, location); - } + /** + * Sets the location of the SAML properties file. The file should be available on the classpath. + */ + public void setSamlProperties(String location) { + handler.setOption(WSHandlerConstants.SAML_PROP_FILE, location); + } /** * Sets the time in seconds in the future within which the Created time of an @@ -506,253 +506,253 @@ public class Wss4jSecurityInterceptor extends AbstractWsSecurityInterceptor impl this.samlIssuer = samlIssuer; } - public boolean getRemoveSecurityHeader() { - return removeSecurityHeader; - } + public boolean getRemoveSecurityHeader() { + return removeSecurityHeader; + } - public void setRemoveSecurityHeader(boolean removeSecurityHeader) { - this.removeSecurityHeader = removeSecurityHeader; - } + public void setRemoveSecurityHeader(boolean removeSecurityHeader) { + this.removeSecurityHeader = removeSecurityHeader; + } - @Override + @Override public void afterPropertiesSet() throws Exception { - Assert.isTrue(validationActions != null || securementActions != null, - "validationActions or securementActions are required"); - if (validationActions != null) { - if ((validationAction & WSConstants.UT) != 0) { - Assert.notNull(validationCallbackHandler, "validationCallbackHandler is required"); - } + Assert.isTrue(validationActions != null || securementActions != null, + "validationActions or securementActions are required"); + if (validationActions != null) { + if ((validationAction & WSConstants.UT) != 0) { + Assert.notNull(validationCallbackHandler, "validationCallbackHandler is required"); + } - if ((validationAction & WSConstants.SIGN) != 0) { - Assert.notNull(validationSignatureCrypto, "validationSignatureCrypto is required"); - } - } - // securement actions are not to be validated at start up as they could - // be configured dynamically via the message context + if ((validationAction & WSConstants.SIGN) != 0) { + Assert.notNull(validationSignatureCrypto, "validationSignatureCrypto is required"); + } + } + // securement actions are not to be validated at start up as they could + // be configured dynamically via the message context - // allow for qualified password types for .Net interoperability - securityEngine.getWssConfig().setAllowNamespaceQualifiedPasswordTypes(true); - securityEngine.getWssConfig().setWsiBSPCompliant(bspCompliant); - } + // allow for qualified password types for .Net interoperability + securityEngine.getWssConfig().setAllowNamespaceQualifiedPasswordTypes(true); + securityEngine.getWssConfig().setWsiBSPCompliant(bspCompliant); + } - @Override - protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecuritySecurementException { - if (securementAction == WSConstants.NO_SECURITY && !enableSignatureConfirmation) { - return; - } - if (logger.isDebugEnabled()) { - logger.debug("Securing message [" + soapMessage + "] with actions [" + securementActions + "]"); - } - RequestData requestData = initializeRequestData(messageContext); + @Override + protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecuritySecurementException { + if (securementAction == WSConstants.NO_SECURITY && !enableSignatureConfirmation) { + return; + } + if (logger.isDebugEnabled()) { + logger.debug("Securing message [" + soapMessage + "] with actions [" + securementActions + "]"); + } + RequestData requestData = initializeRequestData(messageContext); - Document envelopeAsDocument = soapMessage.getDocument(); - try { - // In case on signature confirmation with no other securement - // action, we need to pass an empty securementActionsVector to avoid - // NPE - if (securementAction == WSConstants.NO_SECURITY) { - securementActionsVector = new ArrayList(0); - } + Document envelopeAsDocument = soapMessage.getDocument(); + try { + // In case on signature confirmation with no other securement + // action, we need to pass an empty securementActionsVector to avoid + // NPE + if (securementAction == WSConstants.NO_SECURITY) { + securementActionsVector = new ArrayList(0); + } - handler.doSenderAction(securementAction, envelopeAsDocument, requestData, securementActionsVector, false); - } - catch (WSSecurityException ex) { - throw new Wss4jSecuritySecurementException(ex.getMessage(), ex); - } + handler.doSenderAction(securementAction, envelopeAsDocument, requestData, securementActionsVector, false); + } + catch (WSSecurityException ex) { + throw new Wss4jSecuritySecurementException(ex.getMessage(), ex); + } - soapMessage.setDocument(envelopeAsDocument); - } + soapMessage.setDocument(envelopeAsDocument); + } - /** - * Creates and initializes a request data for the given message context. - * - * @param messageContext the message context - * @return the request data - */ - protected RequestData initializeRequestData(MessageContext messageContext) { - RequestData requestData = new RequestData(); - requestData.setMsgContext(messageContext); + /** + * Creates and initializes a request data for the given message context. + * + * @param messageContext the message context + * @return the request data + */ + protected RequestData initializeRequestData(MessageContext messageContext) { + RequestData requestData = new RequestData(); + requestData.setMsgContext(messageContext); - // reads securementUsername first from the context then from the property - String contextUsername = (String) messageContext.getProperty(SECUREMENT_USER_PROPERTY_NAME); - if (StringUtils.hasLength(contextUsername)) { - requestData.setUsername(contextUsername); - } - else { - requestData.setUsername(securementUsername); - } + // reads securementUsername first from the context then from the property + String contextUsername = (String) messageContext.getProperty(SECUREMENT_USER_PROPERTY_NAME); + if (StringUtils.hasLength(contextUsername)) { + requestData.setUsername(contextUsername); + } + else { + requestData.setUsername(securementUsername); + } - requestData.setTimeToLive(securementTimeToLive); + requestData.setTimeToLive(securementTimeToLive); - requestData.setUseDerivedKey(securementUseDerivedKey); - - requestData.setWssConfig(wssConfig); + requestData.setUseDerivedKey(securementUseDerivedKey); + + requestData.setWssConfig(wssConfig); - messageContext.setProperty(WSHandlerConstants.TTL_TIMESTAMP, Integer.toString(securementTimeToLive)); + messageContext.setProperty(WSHandlerConstants.TTL_TIMESTAMP, Integer.toString(securementTimeToLive)); - messageContext.setProperty(SAML_ISSUER_PROPERTY_NAME, samlIssuer); + messageContext.setProperty(SAML_ISSUER_PROPERTY_NAME, samlIssuer); - return requestData; - } + return requestData; + } - @Override - @SuppressWarnings("unchecked") - protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException { - if (logger.isDebugEnabled()) { - logger.debug("Validating message [" + soapMessage + "] with actions [" + validationActions + "]"); - } + @Override + @SuppressWarnings("unchecked") + protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException { + if (logger.isDebugEnabled()) { + logger.debug("Validating message [" + soapMessage + "] with actions [" + validationActions + "]"); + } - if (validationAction == WSConstants.NO_SECURITY) { - return; - } + if (validationAction == WSConstants.NO_SECURITY) { + return; + } - Document envelopeAsDocument = soapMessage.getDocument(); + Document envelopeAsDocument = soapMessage.getDocument(); - // Header processing + // Header processing - try { - List results = securityEngine - .processSecurityHeader(envelopeAsDocument, validationActor, validationCallbackHandler, - validationSignatureCrypto, validationDecryptionCrypto); + try { + List results = securityEngine + .processSecurityHeader(envelopeAsDocument, validationActor, validationCallbackHandler, + validationSignatureCrypto, validationDecryptionCrypto); - // Results verification - if (CollectionUtils.isEmpty(results)) { - throw new Wss4jSecurityValidationException("No WS-Security header found"); - } + // Results verification + if (CollectionUtils.isEmpty(results)) { + throw new Wss4jSecurityValidationException("No WS-Security header found"); + } - checkResults(results, validationActionsVector); + checkResults(results, validationActionsVector); - // puts the results in the context - // useful for Signature Confirmation - updateContextWithResults(messageContext, results); + // puts the results in the context + // useful for Signature Confirmation + updateContextWithResults(messageContext, results); - verifyCertificateTrust(results); + verifyCertificateTrust(results); - verifyTimestamp(results); + verifyTimestamp(results); - processPrincipal(results); - } - catch (WSSecurityException ex) { - throw new Wss4jSecurityValidationException(ex.getMessage(), ex); - } + processPrincipal(results); + } + catch (WSSecurityException ex) { + throw new Wss4jSecurityValidationException(ex.getMessage(), ex); + } - soapMessage.setDocument(envelopeAsDocument); + soapMessage.setDocument(envelopeAsDocument); - if (this.getRemoveSecurityHeader()) { - soapMessage.getEnvelope().getHeader().removeHeaderElement(WS_SECURITY_NAME); - } - } + if (this.getRemoveSecurityHeader()) { + soapMessage.getEnvelope().getHeader().removeHeaderElement(WS_SECURITY_NAME); + } + } - /** - * Checks whether the received headers match the configured validation actions. Subclasses could override this method - * for custom verification behavior. - * - * - * @param results the results of the validation function - * @param validationActions the decoded validation actions - * @throws Wss4jSecurityValidationException if the results are deemed invalid - */ - protected void checkResults(List results, List validationActions) - throws Wss4jSecurityValidationException { - if (!handler.checkReceiverResultsAnyOrder(results, validationActions)) { - throw new Wss4jSecurityValidationException("Security processing failed (actions mismatch)"); - } - } + /** + * Checks whether the received headers match the configured validation actions. Subclasses could override this method + * for custom verification behavior. + * + * + * @param results the results of the validation function + * @param validationActions the decoded validation actions + * @throws Wss4jSecurityValidationException if the results are deemed invalid + */ + protected void checkResults(List results, List validationActions) + throws Wss4jSecurityValidationException { + if (!handler.checkReceiverResultsAnyOrder(results, validationActions)) { + throw new Wss4jSecurityValidationException("Security processing failed (actions mismatch)"); + } + } - /** - * Puts the results of WS-Security headers processing in the message context. Some actions like Signature - * Confirmation require this. - */ - @SuppressWarnings("unchecked") - private void updateContextWithResults(MessageContext messageContext, List results) { - List handlerResults; - if ((handlerResults = (List) messageContext.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) { - handlerResults = new ArrayList(); - messageContext.setProperty(WSHandlerConstants.RECV_RESULTS, handlerResults); - } - WSHandlerResult rResult = new WSHandlerResult(validationActor, results); - handlerResults.add(0, rResult); - messageContext.setProperty(WSHandlerConstants.RECV_RESULTS, handlerResults); - } + /** + * Puts the results of WS-Security headers processing in the message context. Some actions like Signature + * Confirmation require this. + */ + @SuppressWarnings("unchecked") + private void updateContextWithResults(MessageContext messageContext, List results) { + List handlerResults; + if ((handlerResults = (List) messageContext.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) { + handlerResults = new ArrayList(); + messageContext.setProperty(WSHandlerConstants.RECV_RESULTS, handlerResults); + } + WSHandlerResult rResult = new WSHandlerResult(validationActor, results); + handlerResults.add(0, rResult); + messageContext.setProperty(WSHandlerConstants.RECV_RESULTS, handlerResults); + } - /** Verifies the trust of a certificate. */ - protected void verifyCertificateTrust(List results) throws WSSecurityException { - WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN); + /** Verifies the trust of a certificate. */ + protected void verifyCertificateTrust(List results) throws WSSecurityException { + WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN); - if (actionResult != null) { - X509Certificate returnCert = - (X509Certificate) actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); - Credential credential = new Credential(); - credential.setCertificates(new X509Certificate[] { returnCert}); + if (actionResult != null) { + X509Certificate returnCert = + (X509Certificate) actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); + Credential credential = new Credential(); + credential.setCertificates(new X509Certificate[] { returnCert}); - RequestData requestData = new RequestData(); - requestData.setSigCrypto(validationSignatureCrypto); - requestData.setEnableRevocation(enableRevocation); + RequestData requestData = new RequestData(); + requestData.setSigCrypto(validationSignatureCrypto); + requestData.setEnableRevocation(enableRevocation); - SignatureTrustValidator validator = new SignatureTrustValidator(); - validator.validate(credential, requestData); - } - } + SignatureTrustValidator validator = new SignatureTrustValidator(); + validator.validate(credential, requestData); + } + } - /** Verifies the timestamp. */ - protected void verifyTimestamp(List results) throws WSSecurityException { - WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS); + /** Verifies the timestamp. */ + protected void verifyTimestamp(List results) throws WSSecurityException { + WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS); - if (actionResult != null) { - Timestamp timestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP); - if (timestamp != null && timestampStrict) { - Credential credential = new Credential(); - credential.setTimestamp(timestamp); + if (actionResult != null) { + Timestamp timestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP); + if (timestamp != null && timestampStrict) { + Credential credential = new Credential(); + credential.setTimestamp(timestamp); - RequestData requestData = new RequestData(); - WSSConfig config = new WSSConfig(); - config.setTimeStampTTL(validationTimeToLive); - config.setTimeStampStrict(timestampStrict); - config.setTimeStampFutureTTL(futureTimeToLive); - requestData.setWssConfig(config); + RequestData requestData = new RequestData(); + WSSConfig config = new WSSConfig(); + config.setTimeStampTTL(validationTimeToLive); + config.setTimeStampStrict(timestampStrict); + config.setTimeStampFutureTTL(futureTimeToLive); + requestData.setWssConfig(config); - TimestampValidator validator = new TimestampValidator(); - validator.validate(credential, requestData); - } - } - } + TimestampValidator validator = new TimestampValidator(); + validator.validate(credential, requestData); + } + } + } - private void processPrincipal(List results) { - WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.UT); + private void processPrincipal(List results) { + WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.UT); - if (actionResult != null) { - Principal principal = (Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); - if (principal != null && principal instanceof WSUsernameTokenPrincipal) { - WSUsernameTokenPrincipal usernameTokenPrincipal = (WSUsernameTokenPrincipal) principal; - UsernameTokenPrincipalCallback callback = new UsernameTokenPrincipalCallback(usernameTokenPrincipal); - try { - validationCallbackHandler.handle(new Callback[]{callback}); - } - catch (IOException ex) { - logger.warn("Principal callback resulted in IOException", ex); - } - catch (UnsupportedCallbackException ex) { - // ignore - } - } - } - } + if (actionResult != null) { + Principal principal = (Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); + if (principal != null && principal instanceof WSUsernameTokenPrincipal) { + WSUsernameTokenPrincipal usernameTokenPrincipal = (WSUsernameTokenPrincipal) principal; + UsernameTokenPrincipalCallback callback = new UsernameTokenPrincipalCallback(usernameTokenPrincipal); + try { + validationCallbackHandler.handle(new Callback[]{callback}); + } + catch (IOException ex) { + logger.warn("Principal callback resulted in IOException", ex); + } + catch (UnsupportedCallbackException ex) { + // ignore + } + } + } + } - @Override - protected void cleanUp() { - if (validationCallbackHandler != null) { - try { - CleanupCallback cleanupCallback = new CleanupCallback(); - validationCallbackHandler.handle(new Callback[]{cleanupCallback}); - } - catch (IOException ex) { - logger.warn("Cleanup callback resulted in IOException", ex); - } - catch (UnsupportedCallbackException ex) { - // ignore - } - } - } + @Override + protected void cleanUp() { + if (validationCallbackHandler != null) { + try { + CleanupCallback cleanupCallback = new CleanupCallback(); + validationCallbackHandler.handle(new Callback[]{cleanupCallback}); + } + catch (IOException ex) { + logger.warn("Cleanup callback resulted in IOException", ex); + } + catch (UnsupportedCallbackException ex) { + // ignore + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecuritySecurementException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecuritySecurementException.java old mode 100755 new mode 100644 index 2e5feeab..18a8bdc0 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecuritySecurementException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecuritySecurementException.java @@ -28,12 +28,12 @@ import org.springframework.ws.soap.security.WsSecuritySecurementException; @SuppressWarnings("serial") public class Wss4jSecuritySecurementException extends WsSecuritySecurementException { - public Wss4jSecuritySecurementException(String msg) { - super(msg); - } + public Wss4jSecuritySecurementException(String msg) { + super(msg); + } - public Wss4jSecuritySecurementException(String msg, Throwable ex) { - super(msg, ex); - } + public Wss4jSecuritySecurementException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityValidationException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityValidationException.java old mode 100755 new mode 100644 index 74af8d75..45c00d3c --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityValidationException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/Wss4jSecurityValidationException.java @@ -28,12 +28,12 @@ import org.springframework.ws.soap.security.WsSecurityValidationException; @SuppressWarnings("serial") public class Wss4jSecurityValidationException extends WsSecurityValidationException { - public Wss4jSecurityValidationException(String msg) { - super(msg); - } + public Wss4jSecurityValidationException(String msg) { + super(msg); + } - public Wss4jSecurityValidationException(String msg, Throwable ex) { - super(msg, ex); - } + public Wss4jSecurityValidationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/AbstractWsPasswordCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/AbstractWsPasswordCallbackHandler.java index c593cc98..2f782ce0 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/AbstractWsPasswordCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/AbstractWsPasswordCallbackHandler.java @@ -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,137 +34,137 @@ import org.apache.ws.security.WSPasswordCallback; */ public abstract class AbstractWsPasswordCallbackHandler extends AbstractCallbackHandler { - /** - * Handles {@link WSPasswordCallback} callbacks. Inspects the callback {@link WSPasswordCallback#getUsage() usage} - * code, and calls the various {@code handle*} template methods. - * - * @param callback the callback - * @throws IOException in case of I/O errors - * @throws UnsupportedCallbackException when the callback is not supported - */ - @Override - protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof WSPasswordCallback) { - WSPasswordCallback passwordCallback = (WSPasswordCallback) callback; - switch (passwordCallback.getUsage()) { - case WSPasswordCallback.DECRYPT: - handleDecrypt(passwordCallback); - break; - case WSPasswordCallback.USERNAME_TOKEN: - handleUsernameToken(passwordCallback); - break; - case WSPasswordCallback.SIGNATURE: - handleSignature(passwordCallback); - break; - case WSPasswordCallback.SECURITY_CONTEXT_TOKEN: - handleSecurityContextToken(passwordCallback); - break; - case WSPasswordCallback.CUSTOM_TOKEN: - handleCustomToken(passwordCallback); - break; - case WSPasswordCallback.SECRET_KEY: - handleSecretKey(passwordCallback); - break; - default: - throw new UnsupportedCallbackException(callback, - "Unknown usage [" + passwordCallback.getUsage() + "]"); - } - } - else if (callback instanceof CleanupCallback) { - handleCleanup((CleanupCallback) callback); - } - else if (callback instanceof UsernameTokenPrincipalCallback) { - handleUsernameTokenPrincipal((UsernameTokenPrincipalCallback) callback); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Handles {@link WSPasswordCallback} callbacks. Inspects the callback {@link WSPasswordCallback#getUsage() usage} + * code, and calls the various {@code handle*} template methods. + * + * @param callback the callback + * @throws IOException in case of I/O errors + * @throws UnsupportedCallbackException when the callback is not supported + */ + @Override + protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof WSPasswordCallback) { + WSPasswordCallback passwordCallback = (WSPasswordCallback) callback; + switch (passwordCallback.getUsage()) { + case WSPasswordCallback.DECRYPT: + handleDecrypt(passwordCallback); + break; + case WSPasswordCallback.USERNAME_TOKEN: + handleUsernameToken(passwordCallback); + break; + case WSPasswordCallback.SIGNATURE: + handleSignature(passwordCallback); + break; + case WSPasswordCallback.SECURITY_CONTEXT_TOKEN: + handleSecurityContextToken(passwordCallback); + break; + case WSPasswordCallback.CUSTOM_TOKEN: + handleCustomToken(passwordCallback); + break; + case WSPasswordCallback.SECRET_KEY: + handleSecretKey(passwordCallback); + break; + default: + throw new UnsupportedCallbackException(callback, + "Unknown usage [" + passwordCallback.getUsage() + "]"); + } + } + else if (callback instanceof CleanupCallback) { + handleCleanup((CleanupCallback) callback); + } + else if (callback instanceof UsernameTokenPrincipalCallback) { + handleUsernameTokenPrincipal((UsernameTokenPrincipalCallback) callback); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Invoked when the callback has a {@link WSPasswordCallback#DECRYPT} usage. - * - *

This method is invoked when WSS4J needs a password to get the private key of the {@link - * WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to - * decrypt the session (symmetric) key. Because the encryption method uses the public key to encrypt the session key - * it needs no password (a public key is usually not protected by a password). - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when the callback has a {@link WSPasswordCallback#DECRYPT} usage. + * + *

This method is invoked when WSS4J needs a password to get the private key of the {@link + * WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to + * decrypt the session (symmetric) key. Because the encryption method uses the public key to encrypt the session key + * it needs no password (a public key is usually not protected by a password). + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when the callback has a {@link WSPasswordCallback#USERNAME_TOKEN} usage. - * - *

This method is invoked when WSS4J needs the password to fill in or to verify a UsernameToken. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when the callback has a {@link WSPasswordCallback#USERNAME_TOKEN} usage. + * + *

This method is invoked when WSS4J needs the password to fill in or to verify a UsernameToken. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when the callback has a {@link WSPasswordCallback#SIGNATURE} usage. - * - *

This method is invoked when WSS4J needs the password to get the private key of the {@link - * WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to - * produce a signature. The signature verfication uses the public key to verfiy the signature. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleSignature(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when the callback has a {@link WSPasswordCallback#SIGNATURE} usage. + * + *

This method is invoked when WSS4J needs the password to get the private key of the {@link + * WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to + * produce a signature. The signature verfication uses the public key to verfiy the signature. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleSignature(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when the callback has a {@link WSPasswordCallback#SECURITY_CONTEXT_TOKEN} usage. - * - *

This method is invoked when WSS4J needs the key to to be associated with a SecurityContextToken. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleSecurityContextToken(WSPasswordCallback callback) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when the callback has a {@link WSPasswordCallback#SECURITY_CONTEXT_TOKEN} usage. + * + *

This method is invoked when WSS4J needs the key to to be associated with a SecurityContextToken. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleSecurityContextToken(WSPasswordCallback callback) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when the callback has a {@link WSPasswordCallback#CUSTOM_TOKEN} usage. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleCustomToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when the callback has a {@link WSPasswordCallback#CUSTOM_TOKEN} usage. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleCustomToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when the callback has a {@link WSPasswordCallback#SECRET_KEY} usage. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when the callback has a {@link WSPasswordCallback#SECRET_KEY} usage. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when a {@link CleanupCallback} is passed to {@link #handle(Callback[])}. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when a {@link CleanupCallback} is passed to {@link #handle(Callback[])}. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Invoked when a {@link UsernameTokenPrincipalCallback} is passed to {@link #handle(Callback[])}. - * - *

Default implementation throws an {@link UnsupportedCallbackException}. - */ - protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Invoked when a {@link UsernameTokenPrincipalCallback} is passed to {@link #handle(Callback[])}. + * + *

Default implementation throws an {@link UnsupportedCallbackException}. + */ + protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandler.java index cef0c73d..ce53c0f6 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandler.java @@ -39,83 +39,83 @@ import org.springframework.ws.soap.security.support.KeyStoreUtils; */ public class KeyStoreCallbackHandler extends AbstractWsPasswordCallbackHandler implements InitializingBean { - private String privateKeyPassword; + private String privateKeyPassword; - private char[] symmetricKeyPassword; + private char[] symmetricKeyPassword; - private KeyStore keyStore; + private KeyStore keyStore; - /** Sets the key store to use if a symmetric key name is embedded. */ - public void setKeyStore(KeyStore keyStore) { - this.keyStore = keyStore; - } + /** Sets the key store to use if a symmetric key name is embedded. */ + public void setKeyStore(KeyStore keyStore) { + this.keyStore = keyStore; + } - /** - * Sets the password used to retrieve private keys from the keystore. This property is required for decryption based - * on private keys, and signing. - */ - public void setPrivateKeyPassword(String privateKeyPassword) { - if (privateKeyPassword != null) { - this.privateKeyPassword = privateKeyPassword; - } - } + /** + * Sets the password used to retrieve private keys from the keystore. This property is required for decryption based + * on private keys, and signing. + */ + public void setPrivateKeyPassword(String privateKeyPassword) { + if (privateKeyPassword != null) { + this.privateKeyPassword = privateKeyPassword; + } + } - /** - * Sets the password used to retrieve keys from the symmetric keystore. If this property is not set, it defaults to - * the private key password. - * - * @see #setPrivateKeyPassword(String) - */ - public void setSymmetricKeyPassword(String symmetricKeyPassword) { - if (symmetricKeyPassword != null) { - this.symmetricKeyPassword = symmetricKeyPassword.toCharArray(); - } - } + /** + * Sets the password used to retrieve keys from the symmetric keystore. If this property is not set, it defaults to + * the private key password. + * + * @see #setPrivateKeyPassword(String) + */ + public void setSymmetricKeyPassword(String symmetricKeyPassword) { + if (symmetricKeyPassword != null) { + this.symmetricKeyPassword = symmetricKeyPassword.toCharArray(); + } + } - @Override - public void afterPropertiesSet() throws Exception { - if (keyStore == null) { - loadDefaultKeyStore(); - } - if (symmetricKeyPassword == null) { - symmetricKeyPassword = privateKeyPassword.toCharArray(); - } - } + @Override + public void afterPropertiesSet() throws Exception { + if (keyStore == null) { + loadDefaultKeyStore(); + } + if (symmetricKeyPassword == null) { + symmetricKeyPassword = privateKeyPassword.toCharArray(); + } + } - @Override - protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - callback.setPassword(privateKeyPassword); - } + @Override + protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + callback.setPassword(privateKeyPassword); + } - @Override - protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - try { - String identifier = callback.getIdentifier(); - Key key = keyStore.getKey(identifier, symmetricKeyPassword); - if (key instanceof SecretKey) { - callback.setKey(key.getEncoded()); - } - else { - logger.error("Key [" + key + "] is not a javax.crypto.SecretKey"); - } - } - catch (GeneralSecurityException ex) { - logger.error("Could not obtain symmetric key", ex); - } - } + @Override + protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + try { + String identifier = callback.getIdentifier(); + Key key = keyStore.getKey(identifier, symmetricKeyPassword); + if (key instanceof SecretKey) { + callback.setKey(key.getEncoded()); + } + else { + logger.error("Key [" + key + "] is not a javax.crypto.SecretKey"); + } + } + catch (GeneralSecurityException ex) { + logger.error("Could not obtain symmetric key", ex); + } + } - /** Loads the key store indicated by system properties. Delegates to {@link KeyStoreUtils#loadDefaultKeyStore()}. */ - protected void loadDefaultKeyStore() { - try { - keyStore = KeyStoreUtils.loadDefaultKeyStore(); - if (logger.isDebugEnabled()) { - logger.debug("Loaded default key store"); - } - } - catch (Exception ex) { - logger.warn("Could not open default key store", ex); - } - } + /** Loads the key store indicated by system properties. Delegates to {@link KeyStoreUtils#loadDefaultKeyStore()}. */ + protected void loadDefaultKeyStore() { + try { + keyStore = KeyStoreUtils.loadDefaultKeyStore(); + if (logger.isDebugEnabled()) { + logger.debug("Loaded default key store"); + } + } + catch (Exception ex) { + logger.warn("Could not open default key store", ex); + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SimplePasswordValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SimplePasswordValidationCallbackHandler.java index 967496b7..ec706502 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SimplePasswordValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SimplePasswordValidationCallbackHandler.java @@ -37,32 +37,32 @@ import org.springframework.util.Assert; * @since 1.5.0 */ public class SimplePasswordValidationCallbackHandler extends AbstractWsPasswordCallbackHandler - implements InitializingBean { + implements InitializingBean { - private Map users = new HashMap(); + private Map users = new HashMap(); - /** Sets the users to validate against. Property names are usernames, property values are passwords. */ - public void setUsers(Properties users) { - for (Map.Entry entry : users.entrySet()) { - if (entry.getKey() instanceof String && entry.getValue() instanceof String) { - this.users.put((String) entry.getKey(), (String) entry.getValue()); - } - } - } + /** Sets the users to validate against. Property names are usernames, property values are passwords. */ + public void setUsers(Properties users) { + for (Map.Entry entry : users.entrySet()) { + if (entry.getKey() instanceof String && entry.getValue() instanceof String) { + this.users.put((String) entry.getKey(), (String) entry.getValue()); + } + } + } - public void setUsersMap(Map users) { - this.users = users; - } + public void setUsersMap(Map users) { + this.users = users; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(users, "users is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(users, "users is required"); + } - @Override - protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - String identifier = callback.getIdentifier(); - callback.setPassword(users.get(identifier)); - } + @Override + protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + String identifier = callback.getIdentifier(); + callback.setPassword(users.get(identifier)); + } } \ No newline at end of file diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandler.java index ea41f044..301cd499 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandler.java @@ -45,70 +45,70 @@ import org.springframework.ws.soap.security.support.SpringSecurityUtils; * @since 2.1 */ public class SpringSecurityPasswordValidationCallbackHandler extends AbstractWsPasswordCallbackHandler - implements InitializingBean { + implements InitializingBean { - private UserCache userCache = new NullUserCache(); + private UserCache userCache = new NullUserCache(); - private UserDetailsService userDetailsService; + private UserDetailsService userDetailsService; - /** Sets the users cache. Not required, but can benefit performance. */ - public void setUserCache(UserCache userCache) { - this.userCache = userCache; - } + /** Sets the users cache. Not required, but can benefit performance. */ + public void setUserCache(UserCache userCache) { + this.userCache = userCache; + } - /** Sets the Spring Security user details service. Required. */ - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } + /** Sets the Spring Security user details service. Required. */ + public void setUserDetailsService(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(userDetailsService, "userDetailsService is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(userDetailsService, "userDetailsService is required"); + } - @Override - protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { - String identifier = callback.getIdentifier(); - UserDetails user = loadUserDetails(identifier); - if (user != null) { - SpringSecurityUtils.checkUserValidity(user); - callback.setPassword(user.getPassword()); - } - } + @Override + protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException { + String identifier = callback.getIdentifier(); + UserDetails user = loadUserDetails(identifier); + if (user != null) { + SpringSecurityUtils.checkUserValidity(user); + callback.setPassword(user.getPassword()); + } + } - @Override - protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback) - throws IOException, UnsupportedCallbackException { - UserDetails user = loadUserDetails(callback.getPrincipal().getName()); - WSUsernameTokenPrincipal principal = callback.getPrincipal(); - UsernamePasswordAuthenticationToken authRequest = - new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), user.getAuthorities()); - if (logger.isDebugEnabled()) { - logger.debug("Authentication success: " + authRequest.toString()); - } - SecurityContextHolder.getContext().setAuthentication(authRequest); - } + @Override + protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback) + throws IOException, UnsupportedCallbackException { + UserDetails user = loadUserDetails(callback.getPrincipal().getName()); + WSUsernameTokenPrincipal principal = callback.getPrincipal(); + UsernamePasswordAuthenticationToken authRequest = + new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), user.getAuthorities()); + if (logger.isDebugEnabled()) { + logger.debug("Authentication success: " + authRequest.toString()); + } + SecurityContextHolder.getContext().setAuthentication(authRequest); + } - @Override - protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException { - SecurityContextHolder.clearContext(); - } + @Override + protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException { + SecurityContextHolder.clearContext(); + } - private UserDetails loadUserDetails(String username) throws DataAccessException { - UserDetails user = userCache.getUserFromCache(username); + private UserDetails loadUserDetails(String username) throws DataAccessException { + UserDetails user = userCache.getUserFromCache(username); - if (user == null) { - try { - user = userDetailsService.loadUserByUsername(username); - } - catch (UsernameNotFoundException notFound) { - if (logger.isDebugEnabled()) { - logger.debug("Username '" + username + "' not found"); - } - return null; - } - userCache.putUserInCache(user); - } - return user; - } + if (user == null) { + try { + user = userDetailsService.loadUserByUsername(username); + } + catch (UsernameNotFoundException notFound) { + if (logger.isDebugEnabled()) { + logger.debug("Username '" + username + "' not found"); + } + return null; + } + userCache.putUserInCache(user); + } + return user; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/UsernameTokenPrincipalCallback.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/UsernameTokenPrincipalCallback.java index 564ae602..85242845 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/UsernameTokenPrincipalCallback.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/callback/UsernameTokenPrincipalCallback.java @@ -32,17 +32,17 @@ import org.apache.ws.security.WSUsernameTokenPrincipal; */ public class UsernameTokenPrincipalCallback implements Callback, Serializable { - private static final long serialVersionUID = -3022202225157082715L; + private static final long serialVersionUID = -3022202225157082715L; - private final WSUsernameTokenPrincipal principal; + private final WSUsernameTokenPrincipal principal; - /** Construct a {@code UsernameTokenPrincipalCallback}. */ - public UsernameTokenPrincipalCallback(WSUsernameTokenPrincipal principal) { - this.principal = principal; - } + /** Construct a {@code UsernameTokenPrincipalCallback}. */ + public UsernameTokenPrincipalCallback(WSUsernameTokenPrincipal principal) { + this.principal = principal; + } - /** Get the retrieved {@code Principal}. */ - public WSUsernameTokenPrincipal getPrincipal() { - return principal; - } + /** Get the retrieved {@code Principal}. */ + public WSUsernameTokenPrincipal getPrincipal() { + return principal; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBean.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBean.java old mode 100755 new mode 100644 index 24c554d5..afa49993 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBean.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBean.java @@ -44,151 +44,151 @@ import org.springframework.util.Assert; */ public class CryptoFactoryBean implements FactoryBean, BeanClassLoaderAware, InitializingBean { - private Properties configuration = new Properties(); + private Properties configuration = new Properties(); - private ClassLoader classLoader; + private ClassLoader classLoader; - private Crypto crypto; + private Crypto crypto; - private static final String CRYPTO_PROVIDER_PROPERTY = "org.apache.ws.security.crypto.provider"; + private static final String CRYPTO_PROVIDER_PROPERTY = "org.apache.ws.security.crypto.provider"; - /** - * Sets the configuration of the Crypto. Setting this property overrides all previously set configuration, through - * the type-safe properties - * - * @see org.apache.ws.security.components.crypto.CryptoFactory#getInstance(java.util.Properties) - */ - public void setConfiguration(Properties properties) { - Assert.notNull(properties, "'properties' must not be null"); - this.configuration.putAll(properties); - } + /** + * Sets the configuration of the Crypto. Setting this property overrides all previously set configuration, through + * the type-safe properties + * + * @see org.apache.ws.security.components.crypto.CryptoFactory#getInstance(java.util.Properties) + */ + public void setConfiguration(Properties properties) { + Assert.notNull(properties, "'properties' must not be null"); + this.configuration.putAll(properties); + } - /** - * Sets the {@link org.apache.ws.security.components.crypto.Crypto} provider name. Defaults to {@link - * org.apache.ws.security.components.crypto.Merlin}. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.provider} property. - * - * @param cryptoProviderClass the crypto provider class - */ - public void setCryptoProvider(Class cryptoProviderClass) { - this.configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, cryptoProviderClass.getName()); - } + /** + * Sets the {@link org.apache.ws.security.components.crypto.Crypto} provider name. Defaults to {@link + * org.apache.ws.security.components.crypto.Merlin}. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.provider} property. + * + * @param cryptoProviderClass the crypto provider class + */ + public void setCryptoProvider(Class cryptoProviderClass) { + this.configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, cryptoProviderClass.getName()); + } - /** - * Sets the location of the key store to be loaded in the {@link org.apache.ws.security.components.crypto.Crypto} - * instance. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.file} property. - * - * @param location the key store location - * @throws java.io.IOException when the resource cannot be opened - */ - public void setKeyStoreLocation(Resource location) throws IOException { - String resourcePath = getResourcePath(location); - this.configuration.setProperty("org.apache.ws.security.crypto.merlin.file", resourcePath); - } + /** + * Sets the location of the key store to be loaded in the {@link org.apache.ws.security.components.crypto.Crypto} + * instance. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.file} property. + * + * @param location the key store location + * @throws java.io.IOException when the resource cannot be opened + */ + public void setKeyStoreLocation(Resource location) throws IOException { + String resourcePath = getResourcePath(location); + this.configuration.setProperty("org.apache.ws.security.crypto.merlin.file", resourcePath); + } - private String getResourcePath(Resource resource) throws IOException { - try { - return resource.getFile().getAbsolutePath(); - } - catch (IOException ex) { - if (resource instanceof ClassPathResource) { - ClassPathResource classPathResource = (ClassPathResource) resource; - return classPathResource.getPath(); - } - else { - throw ex; - } - } - } + private String getResourcePath(Resource resource) throws IOException { + try { + return resource.getFile().getAbsolutePath(); + } + catch (IOException ex) { + if (resource instanceof ClassPathResource) { + ClassPathResource classPathResource = (ClassPathResource) resource; + return classPathResource.getPath(); + } + else { + throw ex; + } + } + } - /** - * Sets the key store provider. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.provider} property. - * - * @param provider the key store provider - */ - public void setKeyStoreProvider(String provider) { - this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.provider", provider); - } + /** + * Sets the key store provider. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.provider} property. + * + * @param provider the key store provider + */ + public void setKeyStoreProvider(String provider) { + this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.provider", provider); + } - /** - * Sets the key store password. Defaults to {@code security}. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.password} property. - * - * @param password the key store password - */ - public void setKeyStorePassword(String password) { - this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", password); - } + /** + * Sets the key store password. Defaults to {@code security}. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.password} property. + * + * @param password the key store password + */ + public void setKeyStorePassword(String password) { + this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", password); + } - /** - * Sets the key store type. Defaults to {@link java.security.KeyStore#getDefaultType()}. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.type} property. - * - * @param type the key store type - */ - public void setKeyStoreType(String type) { - this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", type); - } + /** + * Sets the key store type. Defaults to {@link java.security.KeyStore#getDefaultType()}. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.type} property. + * + * @param type the key store type + */ + public void setKeyStoreType(String type) { + this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", type); + } - /** - * Sets the trust store password. Defaults to {@code changeit}. - * - *

WSS4J crypto uses the standard J2SE trust store, i.e. {@code $JAVA_HOME/lib/security/cacerts}. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.cacerts.password} property. - * - * @param password the trust store password - */ - public void setTrustStorePassword(String password) { - this.configuration.setProperty("org.apache.ws.security.crypto.merlin.cacerts.password", password); - } + /** + * Sets the trust store password. Defaults to {@code changeit}. + * + *

WSS4J crypto uses the standard J2SE trust store, i.e. {@code $JAVA_HOME/lib/security/cacerts}. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.cacerts.password} property. + * + * @param password the trust store password + */ + public void setTrustStorePassword(String password) { + this.configuration.setProperty("org.apache.ws.security.crypto.merlin.cacerts.password", password); + } - /** - * Sets the alias name of the default certificate which has been specified as a property. This should be the - * certificate that is used for signature and encryption. This alias corresponds to the certificate that should be - * used whenever KeyInfo is not present in a signed or an encrypted message. - * - *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.alias} property. - * - * @param defaultX509Alias alias name of the default X509 certificate - */ - public void setDefaultX509Alias(String defaultX509Alias) { - this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", defaultX509Alias); - } + /** + * Sets the alias name of the default certificate which has been specified as a property. This should be the + * certificate that is used for signature and encryption. This alias corresponds to the certificate that should be + * used whenever KeyInfo is not present in a signed or an encrypted message. + * + *

This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.alias} property. + * + * @param defaultX509Alias alias name of the default X509 certificate + */ + public void setDefaultX509Alias(String defaultX509Alias) { + this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", defaultX509Alias); + } - @Override - public void setBeanClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } + @Override + public void setBeanClassLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } - @Override - public void afterPropertiesSet() throws Exception { - if (!configuration.containsKey(CRYPTO_PROVIDER_PROPERTY)) { - configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, Merlin.class.getName()); - } - this.crypto = CryptoFactory.getInstance(configuration, classLoader); - } + @Override + public void afterPropertiesSet() throws Exception { + if (!configuration.containsKey(CRYPTO_PROVIDER_PROPERTY)) { + configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, Merlin.class.getName()); + } + this.crypto = CryptoFactory.getInstance(configuration, classLoader); + } - @Override - public Class getObjectType() { - return Crypto.class; - } + @Override + public Class getObjectType() { + return Crypto.class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } - @Override - public Crypto getObject() throws Exception { - return crypto; - } + @Override + public Crypto getObject() throws Exception { + return crypto; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationProvider.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationProvider.java index 716bbbf6..afffedfa 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationProvider.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationProvider.java @@ -44,89 +44,89 @@ import org.springframework.ws.soap.security.x509.cache.X509UserCache; * @version $Id: X509AuthenticationProvider.java 3256 2008-08-18 18:20:48Z luke_t $ */ public class X509AuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware { - //~ Static fields/initializers ===================================================================================== + //~ Static fields/initializers ===================================================================================== - private static final Log logger = LogFactory.getLog(X509AuthenticationProvider.class); + private static final Log logger = LogFactory.getLog(X509AuthenticationProvider.class); - //~ Instance fields ================================================================================================ + //~ Instance fields ================================================================================================ - protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - private X509AuthoritiesPopulator x509AuthoritiesPopulator; - private X509UserCache userCache = new NullX509UserCache(); + protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); + private X509AuthoritiesPopulator x509AuthoritiesPopulator; + private X509UserCache userCache = new NullX509UserCache(); - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(userCache, "An x509UserCache must be set"); - Assert.notNull(x509AuthoritiesPopulator, "An X509AuthoritiesPopulator must be set"); - Assert.notNull(this.messages, "A message source must be set"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(userCache, "An x509UserCache must be set"); + Assert.notNull(x509AuthoritiesPopulator, "An X509AuthoritiesPopulator must be set"); + Assert.notNull(this.messages, "A message source must be set"); + } - /** - * If the supplied authentication token contains a certificate then this will be passed to the configured - * {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the - * certificate.

If no certificate is present (for example, if the filter is applied to an HttpRequest for - * which client authentication hasn't been configured in the container) then a BadCredentialsException will be - * raised.

- * - * @param authentication the authentication request. - * - * @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate. - * - * @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate. - * @throws BadCredentialsException if no certificate was presented in the authentication request. - */ - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - if (!supports(authentication.getClass())) { - return null; - } + /** + * If the supplied authentication token contains a certificate then this will be passed to the configured + * {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the + * certificate.

If no certificate is present (for example, if the filter is applied to an HttpRequest for + * which client authentication hasn't been configured in the container) then a BadCredentialsException will be + * raised.

+ * + * @param authentication the authentication request. + * + * @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate. + * + * @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate. + * @throws BadCredentialsException if no certificate was presented in the authentication request. + */ + @Override + public Authentication authenticate(Authentication authentication) + throws AuthenticationException { + if (!supports(authentication.getClass())) { + return null; + } - if (logger.isDebugEnabled()) { - logger.debug("X509 authentication request: " + authentication); - } + if (logger.isDebugEnabled()) { + logger.debug("X509 authentication request: " + authentication); + } - X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials(); + X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials(); - if (clientCertificate == null) { - throw new BadCredentialsException(messages.getMessage("X509AuthenticationProvider.certificateNull", - "Certificate is null")); - } + if (clientCertificate == null) { + throw new BadCredentialsException(messages.getMessage("X509AuthenticationProvider.certificateNull", + "Certificate is null")); + } - UserDetails user = userCache.getUserFromCache(clientCertificate); + UserDetails user = userCache.getUserFromCache(clientCertificate); - if (user == null) { - if (logger.isDebugEnabled()) { - logger.debug("Authenticating with certificate " + clientCertificate); - } - user = x509AuthoritiesPopulator.getUserDetails(clientCertificate); - userCache.putUserInCache(clientCertificate, user); - } + if (user == null) { + if (logger.isDebugEnabled()) { + logger.debug("Authenticating with certificate " + clientCertificate); + } + user = x509AuthoritiesPopulator.getUserDetails(clientCertificate); + userCache.putUserInCache(clientCertificate, user); + } - X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate, user.getAuthorities()); + X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate, user.getAuthorities()); - result.setDetails(authentication.getDetails()); + result.setDetails(authentication.getDetails()); - return result; - } + return result; + } - @Override - public void setMessageSource(MessageSource messageSource) { - this.messages = new MessageSourceAccessor(messageSource); - } + @Override + public void setMessageSource(MessageSource messageSource) { + this.messages = new MessageSourceAccessor(messageSource); + } - public void setX509AuthoritiesPopulator(X509AuthoritiesPopulator x509AuthoritiesPopulator) { - this.x509AuthoritiesPopulator = x509AuthoritiesPopulator; - } + public void setX509AuthoritiesPopulator(X509AuthoritiesPopulator x509AuthoritiesPopulator) { + this.x509AuthoritiesPopulator = x509AuthoritiesPopulator; + } - public void setX509UserCache(X509UserCache cache) { - this.userCache = cache; - } + public void setX509UserCache(X509UserCache cache) { + this.userCache = cache; + } - @Override - public boolean supports(Class authentication) { - return X509AuthenticationToken.class.isAssignableFrom(authentication); - } + @Override + public boolean supports(Class authentication) { + return X509AuthenticationToken.class.isAssignableFrom(authentication); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationToken.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationToken.java index b5421d9d..eced71d4 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationToken.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthenticationToken.java @@ -30,50 +30,50 @@ import org.springframework.security.core.GrantedAuthority; * @author Luke Taylor */ public class X509AuthenticationToken extends AbstractAuthenticationToken { - //~ Instance fields ================================================================================================ + //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; - private Object principal; - private X509Certificate credentials; + private static final long serialVersionUID = 1L; + private Object principal; + private X509Certificate credentials; - //~ Constructors =================================================================================================== + //~ Constructors =================================================================================================== - /** - * Used for an authentication request. The {@link org.springframework.security.core.Authentication#isAuthenticated()} will return - * {@code false}. - * - * @param credentials the certificate - */ - public X509AuthenticationToken(X509Certificate credentials) { - super(null); - this.credentials = credentials; - } + /** + * Used for an authentication request. The {@link org.springframework.security.core.Authentication#isAuthenticated()} will return + * {@code false}. + * + * @param credentials the certificate + */ + public X509AuthenticationToken(X509Certificate credentials) { + super(null); + this.credentials = credentials; + } - /** - * Used for an authentication response object. The {@link org.springframework.security.core.Authentication#isAuthenticated()} - * will return {@code true}. - * - * @param principal the principal, which is generally a - * {@code UserDetails} - * @param credentials the certificate - * @param authorities the authorities - */ - public X509AuthenticationToken(Object principal, X509Certificate credentials, Collection authorities) { - super(authorities); - this.principal = principal; - this.credentials = credentials; - setAuthenticated(true); - } + /** + * Used for an authentication response object. The {@link org.springframework.security.core.Authentication#isAuthenticated()} + * will return {@code true}. + * + * @param principal the principal, which is generally a + * {@code UserDetails} + * @param credentials the certificate + * @param authorities the authorities + */ + public X509AuthenticationToken(Object principal, X509Certificate credentials, Collection authorities) { + super(authorities); + this.principal = principal; + this.credentials = credentials; + setAuthenticated(true); + } - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - @Override - public Object getCredentials() { - return credentials; - } + @Override + public Object getCredentials() { + return credentials; + } - @Override - public Object getPrincipal() { - return principal; - } + @Override + public Object getPrincipal() { + return principal; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthoritiesPopulator.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthoritiesPopulator.java index c646efd5..f4f1869e 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthoritiesPopulator.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/X509AuthoritiesPopulator.java @@ -36,19 +36,19 @@ import org.springframework.security.core.userdetails.UserDetails; * @author Luke Taylor */ public interface X509AuthoritiesPopulator { - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - /** - * Obtains the granted authorities for the specified user.

May throw any - * {@code AuthenticationException} or return {@code null} if the authorities are unavailable.

- * - * @param userCertificate the X.509 certificate supplied - * - * @return the details of the indicated user (at minimum the granted authorities and the username) - * - * @throws AuthenticationException if the user details are not available or the certificate isn't valid for the - * application's purpose. - */ - UserDetails getUserDetails(X509Certificate userCertificate) - throws AuthenticationException; + /** + * Obtains the granted authorities for the specified user.

May throw any + * {@code AuthenticationException} or return {@code null} if the authorities are unavailable.

+ * + * @param userCertificate the X.509 certificate supplied + * + * @return the details of the indicated user (at minimum the granted authorities and the username) + * + * @throws AuthenticationException if the user details are not available or the certificate isn't valid for the + * application's purpose. + */ + UserDetails getUserDetails(X509Certificate userCertificate) + throws AuthenticationException; } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/EhCacheBasedX509UserCache.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/EhCacheBasedX509UserCache.java index 63b76056..067b4ea2 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/EhCacheBasedX509UserCache.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/EhCacheBasedX509UserCache.java @@ -39,69 +39,69 @@ import org.springframework.util.Assert; * @author Ben Alex */ public class EhCacheBasedX509UserCache implements X509UserCache, InitializingBean { - //~ Static fields/initializers ===================================================================================== + //~ Static fields/initializers ===================================================================================== - private static final Log logger = LogFactory.getLog(EhCacheBasedX509UserCache.class); + private static final Log logger = LogFactory.getLog(EhCacheBasedX509UserCache.class); - //~ Instance fields ================================================================================================ + //~ Instance fields ================================================================================================ - private Ehcache cache; + private Ehcache cache; - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(cache, "cache is mandatory"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(cache, "cache is mandatory"); + } - @Override - public UserDetails getUserFromCache(X509Certificate userCert) { - Element element = null; + @Override + public UserDetails getUserFromCache(X509Certificate userCert) { + Element element = null; - try { - element = cache.get(userCert); - } catch (CacheException cacheException) { - throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage()); - } + try { + element = cache.get(userCert); + } catch (CacheException cacheException) { + throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage()); + } - if (logger.isDebugEnabled()) { - String subjectDN = "unknown"; + if (logger.isDebugEnabled()) { + String subjectDN = "unknown"; - if ((userCert != null) && (userCert.getSubjectDN() != null)) { - subjectDN = userCert.getSubjectDN().toString(); - } + if ((userCert != null) && (userCert.getSubjectDN() != null)) { + subjectDN = userCert.getSubjectDN().toString(); + } - logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN); - } + logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN); + } - if (element == null) { - return null; - } else { - return (UserDetails) element.getObjectValue(); - } - } + if (element == null) { + return null; + } else { + return (UserDetails) element.getObjectValue(); + } + } - @Override - public void putUserInCache(X509Certificate userCert, UserDetails user) { - Element element = new Element(userCert, user); + @Override + public void putUserInCache(X509Certificate userCert, UserDetails user) { + Element element = new Element(userCert, user); - if (logger.isDebugEnabled()) { - logger.debug("Cache put: " + userCert.getSubjectDN()); - } + if (logger.isDebugEnabled()) { + logger.debug("Cache put: " + userCert.getSubjectDN()); + } - cache.put(element); - } + cache.put(element); + } - @Override - public void removeUserFromCache(X509Certificate userCert) { - if (logger.isDebugEnabled()) { - logger.debug("Cache remove: " + userCert.getSubjectDN()); - } + @Override + public void removeUserFromCache(X509Certificate userCert) { + if (logger.isDebugEnabled()) { + logger.debug("Cache remove: " + userCert.getSubjectDN()); + } - cache.remove(userCert); - } + cache.remove(userCert); + } - public void setCache(Ehcache cache) { - this.cache = cache; - } + public void setCache(Ehcache cache) { + this.cache = cache; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/NullX509UserCache.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/NullX509UserCache.java index 25ffe885..fa87a946 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/NullX509UserCache.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/NullX509UserCache.java @@ -28,16 +28,16 @@ import org.springframework.security.core.userdetails.UserDetails; * @author Luke Taylor */ public class NullX509UserCache implements X509UserCache { - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - @Override - public UserDetails getUserFromCache(X509Certificate certificate) { - return null; - } + @Override + public UserDetails getUserFromCache(X509Certificate certificate) { + return null; + } - @Override - public void putUserInCache(X509Certificate certificate, UserDetails user) {} + @Override + public void putUserInCache(X509Certificate certificate, UserDetails user) {} - @Override - public void removeUserFromCache(X509Certificate certificate) {} + @Override + public void removeUserFromCache(X509Certificate certificate) {} } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/X509UserCache.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/X509UserCache.java index 33fe0515..c51ddb4a 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/X509UserCache.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/cache/X509UserCache.java @@ -34,11 +34,11 @@ import org.springframework.security.core.userdetails.UserDetails; * @author Luke Taylor */ public interface X509UserCache { - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - UserDetails getUserFromCache(X509Certificate userCertificate); + UserDetails getUserFromCache(X509Certificate userCertificate); - void putUserInCache(X509Certificate key, UserDetails user); + void putUserInCache(X509Certificate key, UserDetails user); - void removeUserFromCache(X509Certificate key); + void removeUserFromCache(X509Certificate key); } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/populator/DaoX509AuthoritiesPopulator.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/populator/DaoX509AuthoritiesPopulator.java index 3ae04770..556de527 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/populator/DaoX509AuthoritiesPopulator.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/x509/populator/DaoX509AuthoritiesPopulator.java @@ -44,74 +44,74 @@ import org.springframework.ws.soap.security.x509.X509AuthoritiesPopulator; * @version $Id: DaoX509AuthoritiesPopulator.java 2544 2008-01-29 11:50:33Z luke_t $ */ public class DaoX509AuthoritiesPopulator implements X509AuthoritiesPopulator, InitializingBean, MessageSourceAware { - //~ Static fields/initializers ===================================================================================== + //~ Static fields/initializers ===================================================================================== - private static final Log logger = LogFactory.getLog(DaoX509AuthoritiesPopulator.class); + private static final Log logger = LogFactory.getLog(DaoX509AuthoritiesPopulator.class); - //~ Instance fields ================================================================================================ + //~ Instance fields ================================================================================================ - protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - private Pattern subjectDNPattern; - private String subjectDNRegex = "CN=(.*?),"; - private UserDetailsService userDetailsService; + protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); + private Pattern subjectDNPattern; + private String subjectDNRegex = "CN=(.*?),"; + private UserDetailsService userDetailsService; - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(userDetailsService, "An authenticationDao must be set"); - Assert.notNull(this.messages, "A message source must be set"); + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(userDetailsService, "An authenticationDao must be set"); + Assert.notNull(this.messages, "A message source must be set"); - subjectDNPattern = Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE); - } + subjectDNPattern = Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE); + } - @Override - public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException { - String subjectDN = clientCert.getSubjectDN().getName(); + @Override + public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException { + String subjectDN = clientCert.getSubjectDN().getName(); - Matcher matcher = subjectDNPattern.matcher(subjectDN); + Matcher matcher = subjectDNPattern.matcher(subjectDN); - if (!matcher.find()) { - throw new BadCredentialsException(messages.getMessage("DaoX509AuthoritiesPopulator.noMatching", - new Object[] {subjectDN}, "No matching pattern was found in subjectDN: {0}")); - } + if (!matcher.find()) { + throw new BadCredentialsException(messages.getMessage("DaoX509AuthoritiesPopulator.noMatching", + new Object[] {subjectDN}, "No matching pattern was found in subjectDN: {0}")); + } - if (matcher.groupCount() != 1) { - throw new IllegalArgumentException("Regular expression must contain a single group "); - } + if (matcher.groupCount() != 1) { + throw new IllegalArgumentException("Regular expression must contain a single group "); + } - String userName = matcher.group(1); + String userName = matcher.group(1); - UserDetails user = this.userDetailsService.loadUserByUsername(userName); + UserDetails user = this.userDetailsService.loadUserByUsername(userName); - if (user == null) { - throw new AuthenticationServiceException( - "UserDetailsService returned null, which is an interface contract violation"); - } + if (user == null) { + throw new AuthenticationServiceException( + "UserDetailsService returned null, which is an interface contract violation"); + } - return user; - } + return user; + } - @Override - public void setMessageSource(MessageSource messageSource) { - this.messages = new MessageSourceAccessor(messageSource); - } + @Override + public void setMessageSource(MessageSource messageSource) { + this.messages = new MessageSourceAccessor(messageSource); + } - /** - * Sets the regular expression which will by used to extract the user name from the certificate's Subject - * DN. - *

It should contain a single group; for example the default expression "CN=(.?)," matches the common - * name field. So "CN=Jimi Hendrix, OU=..." will give a user name of "Jimi Hendrix".

- *

The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org, - * CN=..." giving a user name "jimi@hendrix.org"

- * - * @param subjectDNRegex the regular expression to find in the subject - */ - public void setSubjectDNRegex(String subjectDNRegex) { - this.subjectDNRegex = subjectDNRegex; - } + /** + * Sets the regular expression which will by used to extract the user name from the certificate's Subject + * DN. + *

It should contain a single group; for example the default expression "CN=(.?)," matches the common + * name field. So "CN=Jimi Hendrix, OU=..." will give a user name of "Jimi Hendrix".

+ *

The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org, + * CN=..." giving a user name "jimi@hendrix.org"

+ * + * @param subjectDNRegex the regular expression to find in the subject + */ + public void setSubjectDNRegex(String subjectDNRegex) { + this.subjectDNRegex = subjectDNRegex; + } - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } + public void setUserDetailsService(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityFaultException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityFaultException.java index d4acdcf8..b353683e 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityFaultException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityFaultException.java @@ -29,7 +29,7 @@ import org.springframework.ws.soap.security.WsSecurityFaultException; @SuppressWarnings("serial") public class XwsSecurityFaultException extends WsSecurityFaultException { - public XwsSecurityFaultException(QName faultCode, String faultString, String faultActor) { - super(faultCode, faultString, faultActor); - } + public XwsSecurityFaultException(QName faultCode, String faultString, String faultActor) { + super(faultCode, faultString, faultActor); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptor.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptor.java index 8ec8ed96..f6df7192 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptor.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptor.java @@ -42,7 +42,7 @@ import org.springframework.ws.soap.security.callback.CleanupCallback; import org.springframework.ws.soap.security.xwss.callback.XwssCallbackHandlerChain; /** - * WS-Security endpoint interceptor that is based on Sun's XML and Web Services Security package (XWSS). This + * WS-Security endpoint interceptor that is based on Sun's XML and Web Services Security package (XWSS). This * WS-Security implementation is part of the Java Web Services Developer Pack (Java WSDP). * *

This interceptor needs a {@code CallbackHandler} to operate. This handler is used to retrieve certificates, @@ -66,111 +66,111 @@ import org.springframework.ws.soap.security.xwss.callback.XwssCallbackHandlerCha */ public class XwsSecurityInterceptor extends AbstractWsSecurityInterceptor implements InitializingBean { - private XWSSProcessor processor; + private XWSSProcessor processor; - private CallbackHandler callbackHandler; + private CallbackHandler callbackHandler; - private Resource policyConfiguration; + private Resource policyConfiguration; - /** - * Sets the handler to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is - * required. - * - * @see com.sun.xml.wss.impl.callback.XWSSCallback - * @see #setCallbackHandlers(javax.security.auth.callback.CallbackHandler[]) - */ - public void setCallbackHandler(CallbackHandler callbackHandler) { - this.callbackHandler = callbackHandler; - } + /** + * Sets the handler to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is + * required. + * + * @see com.sun.xml.wss.impl.callback.XWSSCallback + * @see #setCallbackHandlers(javax.security.auth.callback.CallbackHandler[]) + */ + public void setCallbackHandler(CallbackHandler callbackHandler) { + this.callbackHandler = callbackHandler; + } - /** - * Sets the handlers to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is - * required. - * - * @see com.sun.xml.wss.impl.callback.XWSSCallback - * @see #setCallbackHandler(javax.security.auth.callback.CallbackHandler) - */ - public void setCallbackHandlers(CallbackHandler[] callbackHandler) { - this.callbackHandler = new XwssCallbackHandlerChain(callbackHandler); - } + /** + * Sets the handlers to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is + * required. + * + * @see com.sun.xml.wss.impl.callback.XWSSCallback + * @see #setCallbackHandler(javax.security.auth.callback.CallbackHandler) + */ + public void setCallbackHandlers(CallbackHandler[] callbackHandler) { + this.callbackHandler = new XwssCallbackHandlerChain(callbackHandler); + } - /** Sets the policy configuration to use for XWSS. Required. */ - public void setPolicyConfiguration(Resource policyConfiguration) { - this.policyConfiguration = policyConfiguration; - } + /** Sets the policy configuration to use for XWSS. Required. */ + public void setPolicyConfiguration(Resource policyConfiguration) { + this.policyConfiguration = policyConfiguration; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(policyConfiguration, "policyConfiguration is required"); - Assert.isTrue(policyConfiguration.exists(), "policyConfiguration [" + policyConfiguration + "] does not exist"); - Assert.notNull(callbackHandler, "callbackHandler is required"); - XWSSProcessorFactory processorFactory = XWSSProcessorFactory.newInstance(); - InputStream is = null; - try { - if (logger.isInfoEnabled()) { - logger.info("Loading policy configuration from from '" + policyConfiguration + "'"); - } - is = policyConfiguration.getInputStream(); - processor = processorFactory.createProcessorForSecurityConfiguration(is, callbackHandler); - } - finally { - if (is != null) { - is.close(); - } - } - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(policyConfiguration, "policyConfiguration is required"); + Assert.isTrue(policyConfiguration.exists(), "policyConfiguration [" + policyConfiguration + "] does not exist"); + Assert.notNull(callbackHandler, "callbackHandler is required"); + XWSSProcessorFactory processorFactory = XWSSProcessorFactory.newInstance(); + InputStream is = null; + try { + if (logger.isInfoEnabled()) { + logger.info("Loading policy configuration from from '" + policyConfiguration + "'"); + } + is = policyConfiguration.getInputStream(); + processor = processorFactory.createProcessorForSecurityConfiguration(is, callbackHandler); + } + finally { + if (is != null) { + is.close(); + } + } + } - /** - * Secures the given SoapMessage message in accordance with the defined security policy. - * - * @param soapMessage the message to be secured - * @throws XwsSecuritySecurementException in case of errors - * @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage} - */ - @Override - protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws XwsSecuritySecurementException { - Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " + - "Use a SaajSoapMessageFactory to create the SOAP messages."); - SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; - try { - ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage()); - SOAPMessage result = processor.secureOutboundMessage(context); - saajSoapMessage.setSaajMessage(result); - } - catch (XWSSecurityException ex) { - throw new XwsSecuritySecurementException(ex.getMessage(), ex); - } - catch (WssSoapFaultException ex) { - throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor()); - } - } + /** + * Secures the given SoapMessage message in accordance with the defined security policy. + * + * @param soapMessage the message to be secured + * @throws XwsSecuritySecurementException in case of errors + * @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage} + */ + @Override + protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws XwsSecuritySecurementException { + Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " + + "Use a SaajSoapMessageFactory to create the SOAP messages."); + SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; + try { + ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage()); + SOAPMessage result = processor.secureOutboundMessage(context); + saajSoapMessage.setSaajMessage(result); + } + catch (XWSSecurityException ex) { + throw new XwsSecuritySecurementException(ex.getMessage(), ex); + } + catch (WssSoapFaultException ex) { + throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor()); + } + } - /** - * Validates the given SoapMessage message in accordance with the defined security policy. - * - * @param soapMessage the message to be validated - * @throws XwsSecurityValidationException in case of errors - * @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage} - */ - @Override - protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException { - Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " + - "Use a SaajSoapMessageFactory to create the SOAP messages."); - SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; - try { - ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage()); - SOAPMessage result = processor.verifyInboundMessage(context); - saajSoapMessage.setSaajMessage(result); - } - catch (XWSSecurityException ex) { - throw new XwsSecurityValidationException(ex.getMessage(), ex); - } - catch (WssSoapFaultException ex) { - throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor()); - } - } + /** + * Validates the given SoapMessage message in accordance with the defined security policy. + * + * @param soapMessage the message to be validated + * @throws XwsSecurityValidationException in case of errors + * @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage} + */ + @Override + protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException { + Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " + + "Use a SaajSoapMessageFactory to create the SOAP messages."); + SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; + try { + ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage()); + SOAPMessage result = processor.verifyInboundMessage(context); + saajSoapMessage.setSaajMessage(result); + } + catch (XWSSecurityException ex) { + throw new XwsSecurityValidationException(ex.getMessage(), ex); + } + catch (WssSoapFaultException ex) { + throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor()); + } + } private SOAPMessage verifyInboundMessage(ProcessingContext context) throws XWSSecurityException { @@ -191,18 +191,18 @@ public class XwsSecurityInterceptor extends AbstractWsSecurityInterceptor implem } @Override - protected void cleanUp() { - if (callbackHandler != null) { - try { - CleanupCallback cleanupCallback = new CleanupCallback(); - callbackHandler.handle(new Callback[]{cleanupCallback}); - } - catch (IOException ex) { - logger.warn("Cleanup callback resulted in IOException", ex); - } - catch (UnsupportedCallbackException ex) { - // ignore - } - } - } + protected void cleanUp() { + if (callbackHandler != null) { + try { + CleanupCallback cleanupCallback = new CleanupCallback(); + callbackHandler.handle(new Callback[]{cleanupCallback}); + } + catch (IOException ex) { + logger.warn("Cleanup callback resulted in IOException", ex); + } + catch (UnsupportedCallbackException ex) { + // ignore + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecuritySecurementException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecuritySecurementException.java index 6c7f3397..17cff75c 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecuritySecurementException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecuritySecurementException.java @@ -27,11 +27,11 @@ import org.springframework.ws.soap.security.WsSecuritySecurementException; @SuppressWarnings("serial") public class XwsSecuritySecurementException extends WsSecuritySecurementException { - public XwsSecuritySecurementException(String msg) { - super(msg); - } + public XwsSecuritySecurementException(String msg) { + super(msg); + } - public XwsSecuritySecurementException(String msg, Throwable ex) { - super(msg, ex); - } + public XwsSecuritySecurementException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityValidationException.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityValidationException.java index ed2ec3fd..14de61f0 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityValidationException.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/XwsSecurityValidationException.java @@ -27,11 +27,11 @@ import org.springframework.ws.soap.security.WsSecurityValidationException; @SuppressWarnings("serial") public class XwsSecurityValidationException extends WsSecurityValidationException { - public XwsSecurityValidationException(String msg) { - super(msg); - } + public XwsSecurityValidationException(String msg) { + super(msg); + } - public XwsSecurityValidationException(String msg, Throwable ex) { - super(msg, ex); - } + public XwsSecurityValidationException(String msg, Throwable ex) { + super(msg, ex); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/CryptographyCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/CryptographyCallbackHandler.java index ecc246d9..f68c8322 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/CryptographyCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/CryptographyCallbackHandler.java @@ -38,458 +38,458 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; */ public class CryptographyCallbackHandler extends AbstractCallbackHandler { - @Override - protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof CertificateValidationCallback) { - handleCertificateValidationCallback((CertificateValidationCallback) callback); - } - else if (callback instanceof DecryptionKeyCallback) { - handleDecryptionKeyCallback((DecryptionKeyCallback) callback); - } - else if (callback instanceof EncryptionKeyCallback) { - handleEncryptionKeyCallback((EncryptionKeyCallback) callback); - } - else if (callback instanceof SignatureKeyCallback) { - handleSignatureKeyCallback((SignatureKeyCallback) callback); - } - else if (callback instanceof SignatureVerificationKeyCallback) { - handleSignatureVerificationKeyCallback((SignatureVerificationKeyCallback) callback); - } - else { - throw new UnsupportedCallbackException(callback); - } + @Override + protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof CertificateValidationCallback) { + handleCertificateValidationCallback((CertificateValidationCallback) callback); + } + else if (callback instanceof DecryptionKeyCallback) { + handleDecryptionKeyCallback((DecryptionKeyCallback) callback); + } + else if (callback instanceof EncryptionKeyCallback) { + handleEncryptionKeyCallback((EncryptionKeyCallback) callback); + } + else if (callback instanceof SignatureKeyCallback) { + handleSignatureKeyCallback((SignatureKeyCallback) callback); + } + else if (callback instanceof SignatureVerificationKeyCallback) { + handleSignatureVerificationKeyCallback((SignatureVerificationKeyCallback) callback); + } + else { + throw new UnsupportedCallbackException(callback); + } - } + } - // - // Certificate validation - // + // + // Certificate validation + // - /** - * Template method that handles {@code CertificateValidationCallback}s. Called from - * {@code handleInternal()}. Default implementation throws an {@code UnsupportedCallbackException}. - */ - protected void handleCertificateValidationCallback(CertificateValidationCallback callback) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code CertificateValidationCallback}s. Called from + * {@code handleInternal()}. Default implementation throws an {@code UnsupportedCallbackException}. + */ + protected void handleCertificateValidationCallback(CertificateValidationCallback callback) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - // - // Decryption - // + // + // Decryption + // - /** - * Method that handles {@code DecryptionKeyCallback}s. Called from {@code handleInternal()}. Default - * implementation delegates to specific handling methods. - * - * @see #handlePrivateKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, - * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.PrivateKeyRequest) - * @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, - * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.SymmetricKeyRequest) - */ - protected final void handleDecryptionKeyCallback(DecryptionKeyCallback callback) - throws IOException, UnsupportedCallbackException { - if (callback.getRequest() instanceof DecryptionKeyCallback.PrivateKeyRequest) { - handlePrivateKeyRequest(callback, (DecryptionKeyCallback.PrivateKeyRequest) callback.getRequest()); - } - else if (callback.getRequest() instanceof DecryptionKeyCallback.SymmetricKeyRequest) { - handleSymmetricKeyRequest(callback, (DecryptionKeyCallback.SymmetricKeyRequest) callback.getRequest()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code DecryptionKeyCallback}s. Called from {@code handleInternal()}. Default + * implementation delegates to specific handling methods. + * + * @see #handlePrivateKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, + * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.PrivateKeyRequest) + * @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, + * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.SymmetricKeyRequest) + */ + protected final void handleDecryptionKeyCallback(DecryptionKeyCallback callback) + throws IOException, UnsupportedCallbackException { + if (callback.getRequest() instanceof DecryptionKeyCallback.PrivateKeyRequest) { + handlePrivateKeyRequest(callback, (DecryptionKeyCallback.PrivateKeyRequest) callback.getRequest()); + } + else if (callback.getRequest() instanceof DecryptionKeyCallback.SymmetricKeyRequest) { + handleSymmetricKeyRequest(callback, (DecryptionKeyCallback.SymmetricKeyRequest) callback.getRequest()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Method that handles {@code DecryptionKeyCallback}s with {@code PrivateKeyRequest} . Called from - * {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods. - * - * @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) - * @see #handleX509CertificateBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, - * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509CertificateBasedRequest) - * @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, - * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509IssuerSerialBasedRequest) - * @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, - * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) - */ - protected final void handlePrivateKeyRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.PrivateKeyRequest request) - throws IOException, UnsupportedCallbackException { - if (request instanceof DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) { - handlePublicKeyBasedPrivKeyRequest(callback, (DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) request); - } - else if (request instanceof DecryptionKeyCallback.X509CertificateBasedRequest) { - handleX509CertificateBasedRequest(callback, (DecryptionKeyCallback.X509CertificateBasedRequest) request); - } - else if (request instanceof DecryptionKeyCallback.X509IssuerSerialBasedRequest) { - handleX509IssuerSerialBasedRequest(callback, (DecryptionKeyCallback.X509IssuerSerialBasedRequest) request); - } - else if (request instanceof DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) { - handleX509SubjectKeyIdentifierBasedRequest(callback, - (DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) request); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code DecryptionKeyCallback}s with {@code PrivateKeyRequest} . Called from + * {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods. + * + * @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) + * @see #handleX509CertificateBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, + * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509CertificateBasedRequest) + * @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, + * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509IssuerSerialBasedRequest) + * @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, + * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) + */ + protected final void handlePrivateKeyRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.PrivateKeyRequest request) + throws IOException, UnsupportedCallbackException { + if (request instanceof DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) { + handlePublicKeyBasedPrivKeyRequest(callback, (DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) request); + } + else if (request instanceof DecryptionKeyCallback.X509CertificateBasedRequest) { + handleX509CertificateBasedRequest(callback, (DecryptionKeyCallback.X509CertificateBasedRequest) request); + } + else if (request instanceof DecryptionKeyCallback.X509IssuerSerialBasedRequest) { + handleX509IssuerSerialBasedRequest(callback, (DecryptionKeyCallback.X509IssuerSerialBasedRequest) request); + } + else if (request instanceof DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) { + handleX509SubjectKeyIdentifierBasedRequest(callback, + (DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) request); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Template method that handles {@code DecryptionKeyCallback}s with {@code PublicKeyBasedPrivKeyRequest}s. - * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handlePublicKeyBasedPrivKeyRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code DecryptionKeyCallback}s with {@code PublicKeyBasedPrivKeyRequest}s. + * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handlePublicKeyBasedPrivKeyRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code DecryptionKeyCallback}s with {@code X509CertificateBasedRequest}s. - * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleX509CertificateBasedRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.X509CertificateBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code DecryptionKeyCallback}s with {@code X509CertificateBasedRequest}s. + * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleX509CertificateBasedRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.X509CertificateBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code DecryptionKeyCallback}s with {@code X509IssuerSerialBasedRequest}s. - * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleX509IssuerSerialBasedRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.X509IssuerSerialBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code DecryptionKeyCallback}s with {@code X509IssuerSerialBasedRequest}s. + * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleX509IssuerSerialBasedRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.X509IssuerSerialBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code DecryptionKeyCallback}s with {@code X509SubjectKeyIdentifierBasedRequest}s. - * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleX509SubjectKeyIdentifierBasedRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code DecryptionKeyCallback}s with {@code X509SubjectKeyIdentifierBasedRequest}s. + * Called from {@code handlePrivateKeyRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleX509SubjectKeyIdentifierBasedRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Method that handles {@code DecryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from - * {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods. - * - * @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, - * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.AliasSymmetricKeyRequest) - */ - protected final void handleSymmetricKeyRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.SymmetricKeyRequest request) - throws IOException, UnsupportedCallbackException { - if (request instanceof DecryptionKeyCallback.AliasSymmetricKeyRequest) { - DecryptionKeyCallback.AliasSymmetricKeyRequest aliasSymmetricKeyRequest = - (DecryptionKeyCallback.AliasSymmetricKeyRequest) request; - handleAliasSymmetricKeyRequest(callback, aliasSymmetricKeyRequest); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code DecryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from + * {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods. + * + * @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback, + * com.sun.xml.wss.impl.callback.DecryptionKeyCallback.AliasSymmetricKeyRequest) + */ + protected final void handleSymmetricKeyRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.SymmetricKeyRequest request) + throws IOException, UnsupportedCallbackException { + if (request instanceof DecryptionKeyCallback.AliasSymmetricKeyRequest) { + DecryptionKeyCallback.AliasSymmetricKeyRequest aliasSymmetricKeyRequest = + (DecryptionKeyCallback.AliasSymmetricKeyRequest) request; + handleAliasSymmetricKeyRequest(callback, aliasSymmetricKeyRequest); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Template method that handles {@code DecryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s. - * Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleAliasSymmetricKeyRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.AliasSymmetricKeyRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code DecryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s. + * Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleAliasSymmetricKeyRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.AliasSymmetricKeyRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - // - // Encryption - // + // + // Encryption + // - /** - * Method that handles {@code EncryptionKeyCallback}s. Called from {@code handleInternal()}. Default - * implementation delegates to specific handling methods. - * - * @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, - * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.SymmetricKeyRequest) - * @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, - * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.X509CertificateRequest) - */ - protected final void handleEncryptionKeyCallback(EncryptionKeyCallback callback) - throws IOException, UnsupportedCallbackException { - if (callback.getRequest() instanceof EncryptionKeyCallback.SymmetricKeyRequest) { - handleSymmetricKeyRequest(callback, (EncryptionKeyCallback.SymmetricKeyRequest) callback.getRequest()); - } - else if (callback.getRequest() instanceof EncryptionKeyCallback.X509CertificateRequest) { - handleX509CertificateRequest(callback, - (EncryptionKeyCallback.X509CertificateRequest) callback.getRequest()); - } - else { - throw new UnsupportedCallbackException(callback); + /** + * Method that handles {@code EncryptionKeyCallback}s. Called from {@code handleInternal()}. Default + * implementation delegates to specific handling methods. + * + * @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, + * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.SymmetricKeyRequest) + * @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, + * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.X509CertificateRequest) + */ + protected final void handleEncryptionKeyCallback(EncryptionKeyCallback callback) + throws IOException, UnsupportedCallbackException { + if (callback.getRequest() instanceof EncryptionKeyCallback.SymmetricKeyRequest) { + handleSymmetricKeyRequest(callback, (EncryptionKeyCallback.SymmetricKeyRequest) callback.getRequest()); + } + else if (callback.getRequest() instanceof EncryptionKeyCallback.X509CertificateRequest) { + handleX509CertificateRequest(callback, + (EncryptionKeyCallback.X509CertificateRequest) callback.getRequest()); + } + else { + throw new UnsupportedCallbackException(callback); - } - } + } + } - /** - * Method that handles {@code EncryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from - * {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods. - * - * @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, - * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasSymmetricKeyRequest) - */ - protected final void handleSymmetricKeyRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.SymmetricKeyRequest request) - throws IOException, UnsupportedCallbackException { - if (request instanceof EncryptionKeyCallback.AliasSymmetricKeyRequest) { - handleAliasSymmetricKeyRequest(callback, (EncryptionKeyCallback.AliasSymmetricKeyRequest) request); - } - } + /** + * Method that handles {@code EncryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from + * {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods. + * + * @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, + * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasSymmetricKeyRequest) + */ + protected final void handleSymmetricKeyRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.SymmetricKeyRequest request) + throws IOException, UnsupportedCallbackException { + if (request instanceof EncryptionKeyCallback.AliasSymmetricKeyRequest) { + handleAliasSymmetricKeyRequest(callback, (EncryptionKeyCallback.AliasSymmetricKeyRequest) request); + } + } - /** - * Template method that handles {@code EncryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s. - * Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleAliasSymmetricKeyRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.AliasSymmetricKeyRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code EncryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s. + * Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleAliasSymmetricKeyRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.AliasSymmetricKeyRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Method that handles {@code EncryptionKeyCallback}s with {@code X509CertificateRequest} . Called from - * {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods. - * - * @see #handleAliasX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, - * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasX509CertificateRequest) - * @see #handleDefaultX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, - * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.DefaultX509CertificateRequest) - * @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, - * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.PublicKeyBasedRequest) - */ - protected final void handleX509CertificateRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.X509CertificateRequest request) - throws IOException, UnsupportedCallbackException { - if (request instanceof EncryptionKeyCallback.AliasX509CertificateRequest) { - handleAliasX509CertificateRequest(callback, (EncryptionKeyCallback.AliasX509CertificateRequest) request); - } - else if (request instanceof EncryptionKeyCallback.DefaultX509CertificateRequest) { - handleDefaultX509CertificateRequest(callback, - (EncryptionKeyCallback.DefaultX509CertificateRequest) request); - } - else if (request instanceof EncryptionKeyCallback.PublicKeyBasedRequest) { - handlePublicKeyBasedRequest(callback, (EncryptionKeyCallback.PublicKeyBasedRequest) request); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code EncryptionKeyCallback}s with {@code X509CertificateRequest} . Called from + * {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods. + * + * @see #handleAliasX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, + * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasX509CertificateRequest) + * @see #handleDefaultX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, + * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.DefaultX509CertificateRequest) + * @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback, + * com.sun.xml.wss.impl.callback.EncryptionKeyCallback.PublicKeyBasedRequest) + */ + protected final void handleX509CertificateRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.X509CertificateRequest request) + throws IOException, UnsupportedCallbackException { + if (request instanceof EncryptionKeyCallback.AliasX509CertificateRequest) { + handleAliasX509CertificateRequest(callback, (EncryptionKeyCallback.AliasX509CertificateRequest) request); + } + else if (request instanceof EncryptionKeyCallback.DefaultX509CertificateRequest) { + handleDefaultX509CertificateRequest(callback, + (EncryptionKeyCallback.DefaultX509CertificateRequest) request); + } + else if (request instanceof EncryptionKeyCallback.PublicKeyBasedRequest) { + handlePublicKeyBasedRequest(callback, (EncryptionKeyCallback.PublicKeyBasedRequest) request); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Template method that handles {@code EncryptionKeyCallback}s with {@code AliasX509CertificateRequest}s. - * Called from {@code handleX509CertificateRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleAliasX509CertificateRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.AliasX509CertificateRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code EncryptionKeyCallback}s with {@code AliasX509CertificateRequest}s. + * Called from {@code handleX509CertificateRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleAliasX509CertificateRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.AliasX509CertificateRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code EncryptionKeyCallback}s with {@code DefaultX509CertificateRequest}s. - * Called from {@code handleX509CertificateRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleDefaultX509CertificateRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.DefaultX509CertificateRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code EncryptionKeyCallback}s with {@code DefaultX509CertificateRequest}s. + * Called from {@code handleX509CertificateRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleDefaultX509CertificateRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.DefaultX509CertificateRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code EncryptionKeyCallback}s with {@code PublicKeyBasedRequest}s. Called - * from {@code handleX509CertificateRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handlePublicKeyBasedRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.PublicKeyBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code EncryptionKeyCallback}s with {@code PublicKeyBasedRequest}s. Called + * from {@code handleX509CertificateRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handlePublicKeyBasedRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.PublicKeyBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - // - // Signing - // + // + // Signing + // - /** - * Method that handles {@code SignatureKeyCallback}s. Called from {@code handleInternal()}. Default - * implementation delegates to specific handling methods. - * - * @see #handlePrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureKeyCallback.PrivKeyCertRequest) - */ - protected final void handleSignatureKeyCallback(SignatureKeyCallback callback) - throws IOException, UnsupportedCallbackException { - if (callback.getRequest() instanceof SignatureKeyCallback.PrivKeyCertRequest) { - handlePrivKeyCertRequest(callback, (SignatureKeyCallback.PrivKeyCertRequest) callback.getRequest()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code SignatureKeyCallback}s. Called from {@code handleInternal()}. Default + * implementation delegates to specific handling methods. + * + * @see #handlePrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureKeyCallback.PrivKeyCertRequest) + */ + protected final void handleSignatureKeyCallback(SignatureKeyCallback callback) + throws IOException, UnsupportedCallbackException { + if (callback.getRequest() instanceof SignatureKeyCallback.PrivKeyCertRequest) { + handlePrivKeyCertRequest(callback, (SignatureKeyCallback.PrivKeyCertRequest) callback.getRequest()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Method that handles {@code SignatureKeyCallback}s with {@code PrivKeyCertRequest}s. Called from - * {@code handleSignatureKeyCallback()}. Default implementation delegates to specific handling methods. - * - * @see #handleDefaultPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureKeyCallback.DefaultPrivKeyCertRequest) - * @see #handleAliasPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureKeyCallback.AliasPrivKeyCertRequest) - * @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) - */ - protected final void handlePrivKeyCertRequest(SignatureKeyCallback cb, - SignatureKeyCallback.PrivKeyCertRequest request) - throws IOException, UnsupportedCallbackException { - if (request instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) { - handleDefaultPrivKeyCertRequest(cb, (SignatureKeyCallback.DefaultPrivKeyCertRequest) request); - } - else if (cb.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) { - handleAliasPrivKeyCertRequest(cb, (SignatureKeyCallback.AliasPrivKeyCertRequest) request); - } - else if (cb.getRequest() instanceof SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) { - handlePublicKeyBasedPrivKeyCertRequest(cb, (SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) request); - } - else { - throw new UnsupportedCallbackException(cb); - } - } + /** + * Method that handles {@code SignatureKeyCallback}s with {@code PrivKeyCertRequest}s. Called from + * {@code handleSignatureKeyCallback()}. Default implementation delegates to specific handling methods. + * + * @see #handleDefaultPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureKeyCallback.DefaultPrivKeyCertRequest) + * @see #handleAliasPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureKeyCallback.AliasPrivKeyCertRequest) + * @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) + */ + protected final void handlePrivKeyCertRequest(SignatureKeyCallback cb, + SignatureKeyCallback.PrivKeyCertRequest request) + throws IOException, UnsupportedCallbackException { + if (request instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) { + handleDefaultPrivKeyCertRequest(cb, (SignatureKeyCallback.DefaultPrivKeyCertRequest) request); + } + else if (cb.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) { + handleAliasPrivKeyCertRequest(cb, (SignatureKeyCallback.AliasPrivKeyCertRequest) request); + } + else if (cb.getRequest() instanceof SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) { + handlePublicKeyBasedPrivKeyCertRequest(cb, (SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) request); + } + else { + throw new UnsupportedCallbackException(cb); + } + } - /** - * Template method that handles {@code SignatureKeyCallback}s with {@code DefaultPrivKeyCertRequest}s. - * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleDefaultPrivKeyCertRequest(SignatureKeyCallback callback, - SignatureKeyCallback.DefaultPrivKeyCertRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code SignatureKeyCallback}s with {@code DefaultPrivKeyCertRequest}s. + * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleDefaultPrivKeyCertRequest(SignatureKeyCallback callback, + SignatureKeyCallback.DefaultPrivKeyCertRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code SignatureKeyCallback}s with {@code AliasPrivKeyCertRequest}s. - * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleAliasPrivKeyCertRequest(SignatureKeyCallback callback, - SignatureKeyCallback.AliasPrivKeyCertRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code SignatureKeyCallback}s with {@code AliasPrivKeyCertRequest}s. + * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleAliasPrivKeyCertRequest(SignatureKeyCallback callback, + SignatureKeyCallback.AliasPrivKeyCertRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s. - * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handlePublicKeyBasedPrivKeyCertRequest(SignatureKeyCallback callback, - SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s. + * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handlePublicKeyBasedPrivKeyCertRequest(SignatureKeyCallback callback, + SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - // - // Signature verification - // + // + // Signature verification + // - /** - * Method that handles {@code SignatureVerificationKeyCallback}s. Called from {@code handleInternal()}. - * Default implementation delegates to specific handling methods. - * - * @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509CertificateRequest) - */ - protected final void handleSignatureVerificationKeyCallback(SignatureVerificationKeyCallback callback) - throws UnsupportedCallbackException, IOException { - if (callback.getRequest() instanceof SignatureVerificationKeyCallback.X509CertificateRequest) { - handleX509CertificateRequest(callback, - (SignatureVerificationKeyCallback.X509CertificateRequest) callback.getRequest()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code SignatureVerificationKeyCallback}s. Called from {@code handleInternal()}. + * Default implementation delegates to specific handling methods. + * + * @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509CertificateRequest) + */ + protected final void handleSignatureVerificationKeyCallback(SignatureVerificationKeyCallback callback) + throws UnsupportedCallbackException, IOException { + if (callback.getRequest() instanceof SignatureVerificationKeyCallback.X509CertificateRequest) { + handleX509CertificateRequest(callback, + (SignatureVerificationKeyCallback.X509CertificateRequest) callback.getRequest()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Method that handles {@code SignatureVerificationKeyCallback}s with {@code X509CertificateRequest}s. - * Called from {@code handleSignatureVerificationKeyCallback()}. Default implementation delegates to specific - * handling methods. - * - * @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.PublicKeyBasedRequest) - * @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) - * @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, - * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) - */ - protected final void handleX509CertificateRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.X509CertificateRequest request) - throws UnsupportedCallbackException, IOException { - if (request instanceof SignatureVerificationKeyCallback.PublicKeyBasedRequest) { - handlePublicKeyBasedRequest(callback, (SignatureVerificationKeyCallback.PublicKeyBasedRequest) request); - } - else if (request instanceof SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) { - handleX509IssuerSerialBasedRequest(callback, - (SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) request); - } - else if (request instanceof SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) { - handleX509SubjectKeyIdentifierBasedRequest(callback, - (SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) request); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Method that handles {@code SignatureVerificationKeyCallback}s with {@code X509CertificateRequest}s. + * Called from {@code handleSignatureVerificationKeyCallback()}. Default implementation delegates to specific + * handling methods. + * + * @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.PublicKeyBasedRequest) + * @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) + * @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback, + * com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) + */ + protected final void handleX509CertificateRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.X509CertificateRequest request) + throws UnsupportedCallbackException, IOException { + if (request instanceof SignatureVerificationKeyCallback.PublicKeyBasedRequest) { + handlePublicKeyBasedRequest(callback, (SignatureVerificationKeyCallback.PublicKeyBasedRequest) request); + } + else if (request instanceof SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) { + handleX509IssuerSerialBasedRequest(callback, + (SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) request); + } + else if (request instanceof SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) { + handleX509SubjectKeyIdentifierBasedRequest(callback, + (SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) request); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - /** - * Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s. - * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleX509SubjectKeyIdentifierBasedRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s. + * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleX509SubjectKeyIdentifierBasedRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code SignatureKeyCallback}s with {@code X509IssuerSerialBasedRequest}s. - * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handleX509IssuerSerialBasedRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code SignatureKeyCallback}s with {@code X509IssuerSerialBasedRequest}s. + * Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handleX509IssuerSerialBasedRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } - /** - * Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedRequest}s. Called - * from {@code handlePrivKeyCertRequest()}. Default implementation throws an - * {@code UnsupportedCallbackException}. - */ - protected void handlePublicKeyBasedRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.PublicKeyBasedRequest request) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedCallbackException(callback); - } + /** + * Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedRequest}s. Called + * from {@code handlePrivKeyCertRequest()}. Default implementation throws an + * {@code UnsupportedCallbackException}. + */ + protected void handlePublicKeyBasedRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.PublicKeyBasedRequest request) + throws IOException, UnsupportedCallbackException { + throw new UnsupportedCallbackException(callback); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidator.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidator.java index 4ae641a7..16f7ac1e 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidator.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidator.java @@ -33,101 +33,101 @@ import com.sun.xml.wss.impl.callback.TimestampValidationCallback; */ public class DefaultTimestampValidator implements TimestampValidationCallback.TimestampValidator { - @Override - public void validate(TimestampValidationCallback.Request request) - throws TimestampValidationCallback.TimestampValidationException { - if (request instanceof TimestampValidationCallback.UTCTimestampRequest) { - TimestampValidationCallback.UTCTimestampRequest utcRequest = - (TimestampValidationCallback.UTCTimestampRequest) request; - Date created = parseDate(utcRequest.getCreated()); + @Override + public void validate(TimestampValidationCallback.Request request) + throws TimestampValidationCallback.TimestampValidationException { + if (request instanceof TimestampValidationCallback.UTCTimestampRequest) { + TimestampValidationCallback.UTCTimestampRequest utcRequest = + (TimestampValidationCallback.UTCTimestampRequest) request; + Date created = parseDate(utcRequest.getCreated()); - validateCreationTime(created, utcRequest.getMaxClockSkew(), utcRequest.getTimestampFreshnessLimit()); + validateCreationTime(created, utcRequest.getMaxClockSkew(), utcRequest.getTimestampFreshnessLimit()); - if (utcRequest.getExpired() != null) { - Date expired = parseDate(utcRequest.getExpired()); - validateExpirationTime(expired, utcRequest.getMaxClockSkew()); - } - } - else { - throw new TimestampValidationCallback.TimestampValidationException("Unsupport request: [" + request + "]"); - } - } + if (utcRequest.getExpired() != null) { + Date expired = parseDate(utcRequest.getExpired()); + validateExpirationTime(expired, utcRequest.getMaxClockSkew()); + } + } + else { + throw new TimestampValidationCallback.TimestampValidationException("Unsupport request: [" + request + "]"); + } + } - private Date getFreshnessAndSkewAdjustedDate(long maxClockSkew, long timestampFreshnessLimit) { - Calendar c = new GregorianCalendar(); - long offset = c.get(Calendar.ZONE_OFFSET); - if (c.getTimeZone().inDaylightTime(c.getTime())) { - offset += c.getTimeZone().getDSTSavings(); - } - long beforeTime = c.getTimeInMillis(); - long currentTime = beforeTime - offset; + private Date getFreshnessAndSkewAdjustedDate(long maxClockSkew, long timestampFreshnessLimit) { + Calendar c = new GregorianCalendar(); + long offset = c.get(Calendar.ZONE_OFFSET); + if (c.getTimeZone().inDaylightTime(c.getTime())) { + offset += c.getTimeZone().getDSTSavings(); + } + long beforeTime = c.getTimeInMillis(); + long currentTime = beforeTime - offset; - long adjustedTime = currentTime - maxClockSkew - timestampFreshnessLimit; - c.setTimeInMillis(adjustedTime); + long adjustedTime = currentTime - maxClockSkew - timestampFreshnessLimit; + c.setTimeInMillis(adjustedTime); - return c.getTime(); - } + return c.getTime(); + } - private Date getGMTDateWithSkewAdjusted(Calendar calendar, long maxClockSkew, boolean addSkew) { - long offset = calendar.get(Calendar.ZONE_OFFSET); - if (calendar.getTimeZone().inDaylightTime(calendar.getTime())) { - offset += calendar.getTimeZone().getDSTSavings(); - } - long beforeTime = calendar.getTimeInMillis(); - long currentTime = beforeTime - offset; + private Date getGMTDateWithSkewAdjusted(Calendar calendar, long maxClockSkew, boolean addSkew) { + long offset = calendar.get(Calendar.ZONE_OFFSET); + if (calendar.getTimeZone().inDaylightTime(calendar.getTime())) { + offset += calendar.getTimeZone().getDSTSavings(); + } + long beforeTime = calendar.getTimeInMillis(); + long currentTime = beforeTime - offset; - if (addSkew) { - currentTime = currentTime + maxClockSkew; - } - else { - currentTime = currentTime - maxClockSkew; - } + if (addSkew) { + currentTime = currentTime + maxClockSkew; + } + else { + currentTime = currentTime - maxClockSkew; + } - calendar.setTimeInMillis(currentTime); - return calendar.getTime(); - } + calendar.setTimeInMillis(currentTime); + return calendar.getTime(); + } - private Date parseDate(String date) throws TimestampValidationCallback.TimestampValidationException { - SimpleDateFormat calendarFormatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - SimpleDateFormat calendarFormatter2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'"); + private Date parseDate(String date) throws TimestampValidationCallback.TimestampValidationException { + SimpleDateFormat calendarFormatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + SimpleDateFormat calendarFormatter2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'"); - try { - try { - return calendarFormatter1.parse(date); - } - catch (ParseException ignored) { - return calendarFormatter2.parse(date); - } - } - catch (ParseException ex) { - throw new TimestampValidationCallback.TimestampValidationException("Could not parse request date: " + date, - ex); - } - } + try { + try { + return calendarFormatter1.parse(date); + } + catch (ParseException ignored) { + return calendarFormatter2.parse(date); + } + } + catch (ParseException ex) { + throw new TimestampValidationCallback.TimestampValidationException("Could not parse request date: " + date, + ex); + } + } - private void validateCreationTime(Date created, long maxClockSkew, long timestampFreshnessLimit) - throws TimestampValidationCallback.TimestampValidationException { - Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew, timestampFreshnessLimit); + private void validateCreationTime(Date created, long maxClockSkew, long timestampFreshnessLimit) + throws TimestampValidationCallback.TimestampValidationException { + Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew, timestampFreshnessLimit); - if (created.before(current)) { - throw new TimestampValidationCallback.TimestampValidationException( - "The creation time is older than currenttime - timestamp-freshness-limit - max-clock-skew"); - } + if (created.before(current)) { + throw new TimestampValidationCallback.TimestampValidationException( + "The creation time is older than currenttime - timestamp-freshness-limit - max-clock-skew"); + } - Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, true); - if (currentTime.before(created)) { - throw new TimestampValidationCallback.TimestampValidationException( - "The creation time is ahead of the current time."); - } - } + Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, true); + if (currentTime.before(created)) { + throw new TimestampValidationCallback.TimestampValidationException( + "The creation time is ahead of the current time."); + } + } - private void validateExpirationTime(Date expires, long maxClockSkew) - throws TimestampValidationCallback.TimestampValidationException { - Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, false); - if (expires.before(currentTime)) { - throw new TimestampValidationCallback.TimestampValidationException( - "The current time is ahead of the expiration time in Timestamp"); - } - } + private void validateExpirationTime(Date expires, long maxClockSkew) + throws TimestampValidationCallback.TimestampValidationException { + Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, false); + if (expires.before(currentTime)) { + throw new TimestampValidationCallback.TimestampValidationException( + "The current time is ahead of the expiration time in Timestamp"); + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandler.java index 9386a2ee..ef0db0cc 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandler.java @@ -68,25 +68,25 @@ import org.springframework.ws.soap.security.support.KeyStoreUtils; * certificates or signatures, you would use a trust store, like so: *

  * <bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
- *     <property name="trustStore" ref="trustStore"/>
+ *	   <property name="trustStore" ref="trustStore"/>
  * </bean>
  *
  * <bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
- *     <property name="location" value="classpath:truststore.jks"/>
- *     <property name="password" value="changeit"/>
+ *	   <property name="location" value="classpath:truststore.jks"/>
+ *	   <property name="password" value="changeit"/>
  * </bean>
  * 
* If you want to use it to decrypt incoming certificates or sign outgoing messages, you would use a key store, like * so: *
  * <bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
- *     <property name="keyStore" ref="keyStore"/>
- *     <property name="privateKeyPassword" value="changeit"/>
+ *	   <property name="keyStore" ref="keyStore"/>
+ *	   <property name="privateKeyPassword" value="changeit"/>
  * </bean>
  *
  * <bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
- *     <property name="location" value="classpath:keystore.jks"/>
- *     <property name="password" value="changeit"/>
+ *	   <property name="location" value="classpath:keystore.jks"/>
+ *	   <property name="password" value="changeit"/>
  * </bean>
  * 
* @@ -103,118 +103,118 @@ import org.springframework.ws.soap.security.support.KeyStoreUtils; * @see SignatureKeyCallback * @see SignatureVerificationKeyCallback * @see The - * standard Java trust store mechanism + * standard Java trust store mechanism * @since 1.0.0 */ public class KeyStoreCallbackHandler extends CryptographyCallbackHandler implements InitializingBean { - private static final String X_509_CERTIFICATE_TYPE = "X.509"; + private static final String X_509_CERTIFICATE_TYPE = "X.509"; - private static final String SUBJECT_KEY_IDENTIFIER_OID = "2.5.29.14"; + private static final String SUBJECT_KEY_IDENTIFIER_OID = "2.5.29.14"; - private KeyStore keyStore; + private KeyStore keyStore; - private KeyStore symmetricStore; + private KeyStore symmetricStore; - private KeyStore trustStore; + private KeyStore trustStore; - private String defaultAlias; + private String defaultAlias; - private char[] privateKeyPassword; + private char[] privateKeyPassword; - private char[] symmetricKeyPassword; + private char[] symmetricKeyPassword; private boolean revocationEnabled = false; - private static X509Certificate getCertificate(String alias, KeyStore store) throws IOException { - try { - return (X509Certificate) store.getCertificate(alias); - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - } + private static X509Certificate getCertificate(String alias, KeyStore store) throws IOException { + try { + return (X509Certificate) store.getCertificate(alias); + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + } - private static X509Certificate getCertificate(PublicKey pk, KeyStore store) throws IOException { - try { - Enumeration aliases = store.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - Certificate cert = store.getCertificate(alias); - if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) { - continue; - } - X509Certificate x509Cert = (X509Certificate) cert; - if (x509Cert.getPublicKey().equals(pk)) { - return x509Cert; - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + private static X509Certificate getCertificate(PublicKey pk, KeyStore store) throws IOException { + try { + Enumeration aliases = store.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + Certificate cert = store.getCertificate(alias); + if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) { + continue; + } + X509Certificate x509Cert = (X509Certificate) cert; + if (x509Cert.getPublicKey().equals(pk)) { + return x509Cert; + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - /** Sets the key store alias for the default certificate and private key. */ - public void setDefaultAlias(String defaultAlias) { - this.defaultAlias = defaultAlias; - } + /** Sets the key store alias for the default certificate and private key. */ + public void setDefaultAlias(String defaultAlias) { + this.defaultAlias = defaultAlias; + } - /** - * Sets the default key store. This property is required for decription based on private keys, and signing. If this - * property is not set, a default key store is loaded. - * - * @see org.springframework.ws.soap.security.support.KeyStoreFactoryBean - * @see #loadDefaultTrustStore() - */ - public void setKeyStore(KeyStore keyStore) { - this.keyStore = keyStore; - } + /** + * Sets the default key store. This property is required for decription based on private keys, and signing. If this + * property is not set, a default key store is loaded. + * + * @see org.springframework.ws.soap.security.support.KeyStoreFactoryBean + * @see #loadDefaultTrustStore() + */ + public void setKeyStore(KeyStore keyStore) { + this.keyStore = keyStore; + } - /** - * Sets the password used to retrieve private keys from the keystore. This property is required for decription based - * on private keys, and signing. - */ - public void setPrivateKeyPassword(String privateKeyPassword) { - if (privateKeyPassword != null) { - this.privateKeyPassword = privateKeyPassword.toCharArray(); - } - } + /** + * Sets the password used to retrieve private keys from the keystore. This property is required for decription based + * on private keys, and signing. + */ + public void setPrivateKeyPassword(String privateKeyPassword) { + if (privateKeyPassword != null) { + this.privateKeyPassword = privateKeyPassword.toCharArray(); + } + } - /** - * Sets the password used to retrieve keys from the symmetric keystore. If this property is not set, it default to - * the private key password. - * - * @see #setPrivateKeyPassword(String) - */ - public void setSymmetricKeyPassword(String symmetricKeyPassword) { - if (symmetricKeyPassword != null) { - this.symmetricKeyPassword = symmetricKeyPassword.toCharArray(); - } - } + /** + * Sets the password used to retrieve keys from the symmetric keystore. If this property is not set, it default to + * the private key password. + * + * @see #setPrivateKeyPassword(String) + */ + public void setSymmetricKeyPassword(String symmetricKeyPassword) { + if (symmetricKeyPassword != null) { + this.symmetricKeyPassword = symmetricKeyPassword.toCharArray(); + } + } - /** - * Sets the key store used for encryption and decryption using symmetric keys. If this property is not set, it - * defaults to the {@code keyStore} property. - * - * @see org.springframework.ws.soap.security.support.KeyStoreFactoryBean - * @see #setKeyStore(java.security.KeyStore) - */ - public void setSymmetricStore(KeyStore symmetricStore) { - this.symmetricStore = symmetricStore; - } + /** + * Sets the key store used for encryption and decryption using symmetric keys. If this property is not set, it + * defaults to the {@code keyStore} property. + * + * @see org.springframework.ws.soap.security.support.KeyStoreFactoryBean + * @see #setKeyStore(java.security.KeyStore) + */ + public void setSymmetricStore(KeyStore symmetricStore) { + this.symmetricStore = symmetricStore; + } - /** - * Sets the key store used for signature verifications and encryptions. If this property is not set, a default key - * store will be loaded. - * - * @see org.springframework.ws.soap.security.support.KeyStoreFactoryBean - * @see #loadDefaultTrustStore() - */ - public void setTrustStore(KeyStore trustStore) { - this.trustStore = trustStore; - } + /** + * Sets the key store used for signature verifications and encryptions. If this property is not set, a default key + * store will be loaded. + * + * @see org.springframework.ws.soap.security.support.KeyStoreFactoryBean + * @see #loadDefaultTrustStore() + */ + public void setTrustStore(KeyStore trustStore) { + this.trustStore = trustStore; + } /** * Determines if certificate revocation checking is enabled or not. Default is @@ -226,391 +226,391 @@ public class KeyStoreCallbackHandler extends CryptographyCallbackHandler impleme @Override public void afterPropertiesSet() throws Exception { - if (keyStore == null) { - loadDefaultKeyStore(); - } - if (trustStore == null) { - loadDefaultTrustStore(); - } - if (symmetricStore == null) { - symmetricStore = keyStore; - } - if (symmetricKeyPassword == null) { - symmetricKeyPassword = privateKeyPassword; - } - } + if (keyStore == null) { + loadDefaultKeyStore(); + } + if (trustStore == null) { + loadDefaultTrustStore(); + } + if (symmetricStore == null) { + symmetricStore = keyStore; + } + if (symmetricKeyPassword == null) { + symmetricKeyPassword = privateKeyPassword; + } + } - @Override - protected final void handleAliasPrivKeyCertRequest(SignatureKeyCallback callback, - SignatureKeyCallback.AliasPrivKeyCertRequest request) - throws IOException { - PrivateKey privateKey = getPrivateKey(request.getAlias()); - X509Certificate certificate = getCertificate(request.getAlias()); - request.setPrivateKey(privateKey); - request.setX509Certificate(certificate); - } + @Override + protected final void handleAliasPrivKeyCertRequest(SignatureKeyCallback callback, + SignatureKeyCallback.AliasPrivKeyCertRequest request) + throws IOException { + PrivateKey privateKey = getPrivateKey(request.getAlias()); + X509Certificate certificate = getCertificate(request.getAlias()); + request.setPrivateKey(privateKey); + request.setX509Certificate(certificate); + } - @Override - protected final void handleAliasSymmetricKeyRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.AliasSymmetricKeyRequest request) - throws IOException { - SecretKey secretKey = getSymmetricKey(request.getAlias()); - request.setSymmetricKey(secretKey); - } + @Override + protected final void handleAliasSymmetricKeyRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.AliasSymmetricKeyRequest request) + throws IOException { + SecretKey secretKey = getSymmetricKey(request.getAlias()); + request.setSymmetricKey(secretKey); + } - // - // Encryption - // + // + // Encryption + // - @Override - protected final void handleAliasSymmetricKeyRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.AliasSymmetricKeyRequest request) - throws IOException { - SecretKey secretKey = getSymmetricKey(request.getAlias()); - request.setSymmetricKey(secretKey); - } + @Override + protected final void handleAliasSymmetricKeyRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.AliasSymmetricKeyRequest request) + throws IOException { + SecretKey secretKey = getSymmetricKey(request.getAlias()); + request.setSymmetricKey(secretKey); + } - @Override - protected final void handleAliasX509CertificateRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.AliasX509CertificateRequest request) - throws IOException { - X509Certificate certificate = getCertificateFromTrustStore(request.getAlias()); - request.setX509Certificate(certificate); - } + @Override + protected final void handleAliasX509CertificateRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.AliasX509CertificateRequest request) + throws IOException { + X509Certificate certificate = getCertificateFromTrustStore(request.getAlias()); + request.setX509Certificate(certificate); + } - // - // Certificate validation - // + // + // Certificate validation + // - @Override - protected final void handleCertificateValidationCallback(CertificateValidationCallback callback) { - callback.setValidator(new KeyStoreCertificateValidator()); - } + @Override + protected final void handleCertificateValidationCallback(CertificateValidationCallback callback) { + callback.setValidator(new KeyStoreCertificateValidator()); + } - // - // Signing - // + // + // Signing + // - @Override - protected final void handleDefaultPrivKeyCertRequest(SignatureKeyCallback callback, - SignatureKeyCallback.DefaultPrivKeyCertRequest request) - throws IOException { - PrivateKey privateKey = getPrivateKey(defaultAlias); - X509Certificate certificate = getCertificate(defaultAlias); - request.setPrivateKey(privateKey); - request.setX509Certificate(certificate); - } + @Override + protected final void handleDefaultPrivKeyCertRequest(SignatureKeyCallback callback, + SignatureKeyCallback.DefaultPrivKeyCertRequest request) + throws IOException { + PrivateKey privateKey = getPrivateKey(defaultAlias); + X509Certificate certificate = getCertificate(defaultAlias); + request.setPrivateKey(privateKey); + request.setX509Certificate(certificate); + } - @Override - protected final void handleDefaultX509CertificateRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.DefaultX509CertificateRequest request) - throws IOException { - X509Certificate certificate = getCertificateFromTrustStore(defaultAlias); - request.setX509Certificate(certificate); - } + @Override + protected final void handleDefaultX509CertificateRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.DefaultX509CertificateRequest request) + throws IOException { + X509Certificate certificate = getCertificateFromTrustStore(defaultAlias); + request.setX509Certificate(certificate); + } - @Override - protected final void handlePublicKeyBasedPrivKeyCertRequest(SignatureKeyCallback callback, - SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest request) - throws IOException { - PrivateKey privateKey = getPrivateKey(request.getPublicKey()); - X509Certificate certificate = getCertificate(request.getPublicKey()); - request.setPrivateKey(privateKey); - request.setX509Certificate(certificate); - } + @Override + protected final void handlePublicKeyBasedPrivKeyCertRequest(SignatureKeyCallback callback, + SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest request) + throws IOException { + PrivateKey privateKey = getPrivateKey(request.getPublicKey()); + X509Certificate certificate = getCertificate(request.getPublicKey()); + request.setPrivateKey(privateKey); + request.setX509Certificate(certificate); + } - // - // Decryption - // - @Override - protected final void handlePublicKeyBasedPrivKeyRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request) - throws IOException { - PrivateKey key = getPrivateKey(request.getPublicKey()); - request.setPrivateKey(key); - } + // + // Decryption + // + @Override + protected final void handlePublicKeyBasedPrivKeyRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request) + throws IOException { + PrivateKey key = getPrivateKey(request.getPublicKey()); + request.setPrivateKey(key); + } - @Override - protected final void handlePublicKeyBasedRequest(EncryptionKeyCallback callback, - EncryptionKeyCallback.PublicKeyBasedRequest request) - throws IOException { - X509Certificate certificate = getCertificateFromTrustStore(request.getPublicKey()); - request.setX509Certificate(certificate); - } + @Override + protected final void handlePublicKeyBasedRequest(EncryptionKeyCallback callback, + EncryptionKeyCallback.PublicKeyBasedRequest request) + throws IOException { + X509Certificate certificate = getCertificateFromTrustStore(request.getPublicKey()); + request.setX509Certificate(certificate); + } - @Override - protected final void handlePublicKeyBasedRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.PublicKeyBasedRequest request) - throws IOException { - X509Certificate certificate = getCertificateFromTrustStore(request.getPublicKey()); - request.setX509Certificate(certificate); - } + @Override + protected final void handlePublicKeyBasedRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.PublicKeyBasedRequest request) + throws IOException { + X509Certificate certificate = getCertificateFromTrustStore(request.getPublicKey()); + request.setX509Certificate(certificate); + } - @Override - protected final void handleX509CertificateBasedRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.X509CertificateBasedRequest request) - throws IOException { - PrivateKey privKey = getPrivateKey(request.getX509Certificate()); - request.setPrivateKey(privKey); - } + @Override + protected final void handleX509CertificateBasedRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.X509CertificateBasedRequest request) + throws IOException { + PrivateKey privKey = getPrivateKey(request.getX509Certificate()); + request.setPrivateKey(privKey); + } - @Override - protected final void handleX509IssuerSerialBasedRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.X509IssuerSerialBasedRequest request) - throws IOException { - PrivateKey key = getPrivateKey(request.getIssuerName(), request.getSerialNumber()); - request.setPrivateKey(key); - } + @Override + protected final void handleX509IssuerSerialBasedRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.X509IssuerSerialBasedRequest request) + throws IOException { + PrivateKey key = getPrivateKey(request.getIssuerName(), request.getSerialNumber()); + request.setPrivateKey(key); + } - @Override - protected final void handleX509IssuerSerialBasedRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request) - throws IOException { - X509Certificate certificate = getCertificateFromTrustStore(request.getIssuerName(), request.getSerialNumber()); - request.setX509Certificate(certificate); - } + @Override + protected final void handleX509IssuerSerialBasedRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request) + throws IOException { + X509Certificate certificate = getCertificateFromTrustStore(request.getIssuerName(), request.getSerialNumber()); + request.setX509Certificate(certificate); + } - @Override - protected final void handleX509SubjectKeyIdentifierBasedRequest(DecryptionKeyCallback callback, - DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request) - throws IOException { - PrivateKey key = getPrivateKey(request.getSubjectKeyIdentifier()); - request.setPrivateKey(key); - } + @Override + protected final void handleX509SubjectKeyIdentifierBasedRequest(DecryptionKeyCallback callback, + DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request) + throws IOException { + PrivateKey key = getPrivateKey(request.getSubjectKeyIdentifier()); + request.setPrivateKey(key); + } - // - // Signature verification - // + // + // Signature verification + // - @Override - protected final void handleX509SubjectKeyIdentifierBasedRequest(SignatureVerificationKeyCallback callback, - SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request) - throws IOException { - X509Certificate certificate = getCertificateFromTrustStore(request.getSubjectKeyIdentifier()); - request.setX509Certificate(certificate); - } + @Override + protected final void handleX509SubjectKeyIdentifierBasedRequest(SignatureVerificationKeyCallback callback, + SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request) + throws IOException { + X509Certificate certificate = getCertificateFromTrustStore(request.getSubjectKeyIdentifier()); + request.setX509Certificate(certificate); + } - // Certificate methods + // Certificate methods - protected X509Certificate getCertificate(String alias) throws IOException { - return getCertificate(alias, keyStore); - } + protected X509Certificate getCertificate(String alias) throws IOException { + return getCertificate(alias, keyStore); + } - protected X509Certificate getCertificate(PublicKey pk) throws IOException { - return getCertificate(pk, keyStore); - } + protected X509Certificate getCertificate(PublicKey pk) throws IOException { + return getCertificate(pk, keyStore); + } - protected X509Certificate getCertificateFromTrustStore(String alias) throws IOException { - return getCertificate(alias, trustStore); - } + protected X509Certificate getCertificateFromTrustStore(String alias) throws IOException { + return getCertificate(alias, trustStore); + } - protected X509Certificate getCertificateFromTrustStore(byte[] subjectKeyIdentifier) throws IOException { - try { - Enumeration aliases = trustStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - Certificate cert = trustStore.getCertificate(alias); - if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) { - continue; - } - X509Certificate x509Cert = (X509Certificate) cert; - byte[] keyId = getSubjectKeyIdentifier(x509Cert); - if (keyId == null) { - // Cert does not contain a key identifier - continue; - } - if (Arrays.equals(subjectKeyIdentifier, keyId)) { - return x509Cert; - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + protected X509Certificate getCertificateFromTrustStore(byte[] subjectKeyIdentifier) throws IOException { + try { + Enumeration aliases = trustStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + Certificate cert = trustStore.getCertificate(alias); + if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) { + continue; + } + X509Certificate x509Cert = (X509Certificate) cert; + byte[] keyId = getSubjectKeyIdentifier(x509Cert); + if (keyId == null) { + // Cert does not contain a key identifier + continue; + } + if (Arrays.equals(subjectKeyIdentifier, keyId)) { + return x509Cert; + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - protected X509Certificate getCertificateFromTrustStore(PublicKey pk) throws IOException { - return getCertificate(pk, trustStore); - } + protected X509Certificate getCertificateFromTrustStore(PublicKey pk) throws IOException { + return getCertificate(pk, trustStore); + } - protected X509Certificate getCertificateFromTrustStore(String issuerName, BigInteger serialNumber) - throws IOException { - try { - Enumeration aliases = trustStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - Certificate cert = trustStore.getCertificate(alias); - if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) { - continue; - } - X509Certificate x509Cert = (X509Certificate) cert; - String thisIssuerName = RFC2253Parser.normalize(x509Cert.getIssuerDN().getName()); - BigInteger thisSerialNumber = x509Cert.getSerialNumber(); - if (thisIssuerName.equals(issuerName) && thisSerialNumber.equals(serialNumber)) { - return x509Cert; - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + protected X509Certificate getCertificateFromTrustStore(String issuerName, BigInteger serialNumber) + throws IOException { + try { + Enumeration aliases = trustStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + Certificate cert = trustStore.getCertificate(alias); + if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) { + continue; + } + X509Certificate x509Cert = (X509Certificate) cert; + String thisIssuerName = RFC2253Parser.normalize(x509Cert.getIssuerDN().getName()); + BigInteger thisSerialNumber = x509Cert.getSerialNumber(); + if (thisIssuerName.equals(issuerName) && thisSerialNumber.equals(serialNumber)) { + return x509Cert; + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - // Private Key methods + // Private Key methods - protected PrivateKey getPrivateKey(String alias) throws IOException { - try { - return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - } + protected PrivateKey getPrivateKey(String alias) throws IOException { + try { + return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + } - protected PrivateKey getPrivateKey(PublicKey publicKey) throws IOException { - try { - Enumeration aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - if (keyStore.isKeyEntry(alias)) { - // Just returning the first one here - return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + protected PrivateKey getPrivateKey(PublicKey publicKey) throws IOException { + try { + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + // Just returning the first one here + return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - protected PrivateKey getPrivateKey(X509Certificate certificate) throws IOException { - try { - Enumeration aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - if (!keyStore.isKeyEntry(alias)) { - continue; - } - Certificate cert = keyStore.getCertificate(alias); - if (cert != null && cert.equals(certificate)) { - return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + protected PrivateKey getPrivateKey(X509Certificate certificate) throws IOException { + try { + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!keyStore.isKeyEntry(alias)) { + continue; + } + Certificate cert = keyStore.getCertificate(alias); + if (cert != null && cert.equals(certificate)) { + return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - protected PrivateKey getPrivateKey(byte[] keyIdentifier) throws IOException { - try { - Enumeration aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - if (!keyStore.isKeyEntry(alias)) { - continue; - } - Certificate cert = keyStore.getCertificate(alias); - if (cert == null || !"X.509".equals(cert.getType())) { - continue; - } - X509Certificate x509Cert = (X509Certificate) cert; - byte[] keyId = getSubjectKeyIdentifier(x509Cert); - if (keyId == null) { - // Cert does not contain a key identifier - continue; - } - if (Arrays.equals(keyIdentifier, keyId)) { - return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + protected PrivateKey getPrivateKey(byte[] keyIdentifier) throws IOException { + try { + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!keyStore.isKeyEntry(alias)) { + continue; + } + Certificate cert = keyStore.getCertificate(alias); + if (cert == null || !"X.509".equals(cert.getType())) { + continue; + } + X509Certificate x509Cert = (X509Certificate) cert; + byte[] keyId = getSubjectKeyIdentifier(x509Cert); + if (keyId == null) { + // Cert does not contain a key identifier + continue; + } + if (Arrays.equals(keyIdentifier, keyId)) { + return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - protected PrivateKey getPrivateKey(String issuerName, BigInteger serialNumber) throws IOException { - try { - Enumeration aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - if (!keyStore.isKeyEntry(alias)) { - continue; - } - Certificate cert = keyStore.getCertificate(alias); - if (cert == null || !"X.509".equals(cert.getType())) { - continue; - } - X509Certificate x509Cert = (X509Certificate) cert; - String thisIssuerName = RFC2253Parser.normalize(x509Cert.getIssuerDN().getName()); - BigInteger thisSerialNumber = x509Cert.getSerialNumber(); - if (thisIssuerName.equals(issuerName) && thisSerialNumber.equals(serialNumber)) { - return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); - } - } - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - return null; - } + protected PrivateKey getPrivateKey(String issuerName, BigInteger serialNumber) throws IOException { + try { + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!keyStore.isKeyEntry(alias)) { + continue; + } + Certificate cert = keyStore.getCertificate(alias); + if (cert == null || !"X.509".equals(cert.getType())) { + continue; + } + X509Certificate x509Cert = (X509Certificate) cert; + String thisIssuerName = RFC2253Parser.normalize(x509Cert.getIssuerDN().getName()); + BigInteger thisSerialNumber = x509Cert.getSerialNumber(); + if (thisIssuerName.equals(issuerName) && thisSerialNumber.equals(serialNumber)) { + return (PrivateKey) keyStore.getKey(alias, privateKeyPassword); + } + } + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + return null; + } - // Utility methods + // Utility methods - protected final byte[] getSubjectKeyIdentifier(X509Certificate cert) { - byte[] subjectKeyIdentifier = cert.getExtensionValue(SUBJECT_KEY_IDENTIFIER_OID); - if (subjectKeyIdentifier == null) { - return null; - } - byte[] dest = new byte[subjectKeyIdentifier.length - 4]; - System.arraycopy(subjectKeyIdentifier, 4, dest, 0, subjectKeyIdentifier.length - 4); - return dest; - } + protected final byte[] getSubjectKeyIdentifier(X509Certificate cert) { + byte[] subjectKeyIdentifier = cert.getExtensionValue(SUBJECT_KEY_IDENTIFIER_OID); + if (subjectKeyIdentifier == null) { + return null; + } + byte[] dest = new byte[subjectKeyIdentifier.length - 4]; + System.arraycopy(subjectKeyIdentifier, 4, dest, 0, subjectKeyIdentifier.length - 4); + return dest; + } - // - // Symmetric key methods - // + // + // Symmetric key methods + // - protected SecretKey getSymmetricKey(String alias) throws IOException { - try { - return (SecretKey) symmetricStore.getKey(alias, symmetricKeyPassword); - } - catch (GeneralSecurityException e) { - throw new IOException(e.getMessage()); - } - } + protected SecretKey getSymmetricKey(String alias) throws IOException { + try { + return (SecretKey) symmetricStore.getKey(alias, symmetricKeyPassword); + } + catch (GeneralSecurityException e) { + throw new IOException(e.getMessage()); + } + } - /** Loads the key store indicated by system properties. Delegates to {@link KeyStoreUtils#loadDefaultKeyStore()}. */ - protected void loadDefaultKeyStore() { - try { - keyStore = KeyStoreUtils.loadDefaultKeyStore(); - if (logger.isDebugEnabled()) { - logger.debug("Loaded default key store"); - } - } - catch (Exception ex) { - logger.warn("Could not open default key store", ex); - } - } + /** Loads the key store indicated by system properties. Delegates to {@link KeyStoreUtils#loadDefaultKeyStore()}. */ + protected void loadDefaultKeyStore() { + try { + keyStore = KeyStoreUtils.loadDefaultKeyStore(); + if (logger.isDebugEnabled()) { + logger.debug("Loaded default key store"); + } + } + catch (Exception ex) { + logger.warn("Could not open default key store", ex); + } + } - /** Loads a default trust store. Delegates to {@link KeyStoreUtils#loadDefaultTrustStore()}. */ - protected void loadDefaultTrustStore() { - try { - trustStore = KeyStoreUtils.loadDefaultTrustStore(); - if (logger.isDebugEnabled()) { - logger.debug("Loaded default trust store"); - } - } - catch (Exception ex) { - logger.warn("Could not open default trust store", ex); - } - } + /** Loads a default trust store. Delegates to {@link KeyStoreUtils#loadDefaultTrustStore()}. */ + protected void loadDefaultTrustStore() { + try { + trustStore = KeyStoreUtils.loadDefaultTrustStore(); + if (logger.isDebugEnabled()) { + logger.debug("Loaded default trust store"); + } + } + catch (Exception ex) { + logger.warn("Could not open default trust store", ex); + } + } /** * Creates a {@code PKIXBuilderParameters} instance with the given parameters. @@ -629,107 +629,107 @@ public class KeyStoreCallbackHandler extends CryptographyCallbackHandler impleme } - // - // Inner classes - // + // + // Inner classes + // - private class KeyStoreCertificateValidator implements CertificateValidationCallback.CertificateValidator { + private class KeyStoreCertificateValidator implements CertificateValidationCallback.CertificateValidator { - @Override - public boolean validate(X509Certificate certificate) - throws CertificateValidationCallback.CertificateValidationException { - if (isOwnedCert(certificate)) { - if (logger.isDebugEnabled()) { - logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + - "] is in private keystore"); - } - return true; - } - else if (trustStore == null) { - return false; - } + @Override + public boolean validate(X509Certificate certificate) + throws CertificateValidationCallback.CertificateValidationException { + if (isOwnedCert(certificate)) { + if (logger.isDebugEnabled()) { + logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + + "] is in private keystore"); + } + return true; + } + else if (trustStore == null) { + return false; + } - try { - certificate.checkValidity(); - } - catch (CertificateExpiredException e) { - if (logger.isDebugEnabled()) { - logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + - "] has expired"); - } - return false; - } - catch (CertificateNotYetValidException e) { - if (logger.isDebugEnabled()) { - logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + - "] is not yet valid"); - } - return false; - } + try { + certificate.checkValidity(); + } + catch (CertificateExpiredException e) { + if (logger.isDebugEnabled()) { + logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + + "] has expired"); + } + return false; + } + catch (CertificateNotYetValidException e) { + if (logger.isDebugEnabled()) { + logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + + "] is not yet valid"); + } + return false; + } - X509CertSelector certSelector = new X509CertSelector(); - certSelector.setCertificate(certificate); + X509CertSelector certSelector = new X509CertSelector(); + certSelector.setCertificate(certificate); - PKIXBuilderParameters parameters; - CertPathBuilder builder; - try { - parameters = createBuilderParameters(trustStore, certSelector); - parameters.setRevocationEnabled(revocationEnabled); - builder = CertPathBuilder.getInstance("PKIX"); - } - catch (GeneralSecurityException ex) { - throw new CertificateValidationCallback.CertificateValidationException( - "Could not create PKIX CertPathBuilder", ex); - } + PKIXBuilderParameters parameters; + CertPathBuilder builder; + try { + parameters = createBuilderParameters(trustStore, certSelector); + parameters.setRevocationEnabled(revocationEnabled); + builder = CertPathBuilder.getInstance("PKIX"); + } + catch (GeneralSecurityException ex) { + throw new CertificateValidationCallback.CertificateValidationException( + "Could not create PKIX CertPathBuilder", ex); + } - try { - builder.build(parameters); - } - catch (CertPathBuilderException e) { - if (logger.isDebugEnabled()) { - logger.debug("Certification path of certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] could not be validated"); - } - return false; - } - catch (InvalidAlgorithmParameterException e) { - if (logger.isDebugEnabled()) { - logger.debug("Algorithm of certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] could not be validated"); - } - return false; - } - if (logger.isDebugEnabled()) { - logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + "] validated"); - } - return true; - } + try { + builder.build(parameters); + } + catch (CertPathBuilderException e) { + if (logger.isDebugEnabled()) { + logger.debug("Certification path of certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] could not be validated"); + } + return false; + } + catch (InvalidAlgorithmParameterException e) { + if (logger.isDebugEnabled()) { + logger.debug("Algorithm of certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] could not be validated"); + } + return false; + } + if (logger.isDebugEnabled()) { + logger.debug("Certificate with DN [" + certificate.getSubjectX500Principal().getName() + "] validated"); + } + return true; + } - private boolean isOwnedCert(X509Certificate cert) - throws CertificateValidationCallback.CertificateValidationException { - if (keyStore == null) { - return false; - } - try { - Enumeration aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - String alias = aliases.nextElement(); - if (keyStore.isKeyEntry(alias)) { - X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias); - if (x509Cert != null) { - if (x509Cert.equals(cert)) { - return true; - } - } - } - } - return false; - } - catch (GeneralSecurityException e) { - throw new CertificateValidationCallback.CertificateValidationException( - "Could not determine whether certificate is contained in main key store", e); - } - } - } + private boolean isOwnedCert(X509Certificate cert) + throws CertificateValidationCallback.CertificateValidationException { + if (keyStore == null) { + return false; + } + try { + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias); + if (x509Cert != null) { + if (x509Cert.equals(cert)) { + return true; + } + } + } + } + return false; + } + catch (GeneralSecurityException e) { + throw new CertificateValidationCallback.CertificateValidationException( + "Could not determine whether certificate is contained in main key store", e); + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/MockValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/MockValidationCallbackHandler.java index 0de880ec..c037bec0 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/MockValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/MockValidationCallbackHandler.java @@ -40,49 +40,49 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; */ public class MockValidationCallbackHandler extends AbstractCallbackHandler { - private boolean isValid = true; + private boolean isValid = true; - public MockValidationCallbackHandler() { - } + public MockValidationCallbackHandler() { + } - public MockValidationCallbackHandler(boolean valid) { - isValid = valid; - } + public MockValidationCallbackHandler(boolean valid) { + isValid = valid; + } - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof CertificateValidationCallback) { - CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback; - validationCallback.setValidator(new MockCertificateValidator()); - } - else if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; - validationCallback.setValidator(new MockPasswordValidator()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof CertificateValidationCallback) { + CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback; + validationCallback.setValidator(new MockCertificateValidator()); + } + else if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; + validationCallback.setValidator(new MockPasswordValidator()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - public void setValid(boolean valid) { - isValid = valid; - } + public void setValid(boolean valid) { + isValid = valid; + } - private class MockCertificateValidator implements CertificateValidationCallback.CertificateValidator { + private class MockCertificateValidator implements CertificateValidationCallback.CertificateValidator { - @Override - public boolean validate(X509Certificate certificate) - throws CertificateValidationCallback.CertificateValidationException { - return isValid; - } - } + @Override + public boolean validate(X509Certificate certificate) + throws CertificateValidationCallback.CertificateValidationException { + return isValid; + } + } - private class MockPasswordValidator implements PasswordValidationCallback.PasswordValidator { + private class MockPasswordValidator implements PasswordValidationCallback.PasswordValidator { - @Override - public boolean validate(PasswordValidationCallback.Request request) - throws PasswordValidationCallback.PasswordValidationException { - return isValid; - } - } + @Override + public boolean validate(PasswordValidationCallback.Request request) + throws PasswordValidationCallback.PasswordValidationException { + return isValid; + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandler.java index 0ae25338..c9c3c37b 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandler.java @@ -43,59 +43,59 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; */ public class SimplePasswordValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean { - private Map users = new HashMap(); + private Map users = new HashMap(); - /** Sets the users to validate against. Property names are usernames, property values are passwords. */ - public void setUsers(Properties users) { - for (Map.Entry entry : users.entrySet()) { - if (entry.getKey() instanceof String && entry.getValue() instanceof String) { - this.users.put((String) entry.getKey(), (String) entry.getValue()); - } - } - } + /** Sets the users to validate against. Property names are usernames, property values are passwords. */ + public void setUsers(Properties users) { + for (Map.Entry entry : users.entrySet()) { + if (entry.getKey() instanceof String && entry.getValue() instanceof String) { + this.users.put((String) entry.getKey(), (String) entry.getValue()); + } + } + } - public void setUsersMap(Map users) { - this.users = users; - } + public void setUsersMap(Map users) { + this.users = users; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(users, "users is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(users, "users is required"); + } - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback; - if (passwordCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) { - passwordCallback.setValidator(new SimplePlainTextPasswordValidator()); - } - else if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) { - PasswordValidationCallback.DigestPasswordRequest digestPasswordRequest = - (PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest(); - String password = users.get(digestPasswordRequest.getUsername()); - digestPasswordRequest.setPassword(password); - passwordCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator()); - } - } - else if (callback instanceof TimestampValidationCallback) { - TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback; - timestampCallback.setValidator(new DefaultTimestampValidator()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback; + if (passwordCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) { + passwordCallback.setValidator(new SimplePlainTextPasswordValidator()); + } + else if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) { + PasswordValidationCallback.DigestPasswordRequest digestPasswordRequest = + (PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest(); + String password = users.get(digestPasswordRequest.getUsername()); + digestPasswordRequest.setPassword(password); + passwordCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator()); + } + } + else if (callback instanceof TimestampValidationCallback) { + TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback; + timestampCallback.setValidator(new DefaultTimestampValidator()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - private class SimplePlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { + private class SimplePlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { - @Override - public boolean validate(PasswordValidationCallback.Request request) - throws PasswordValidationCallback.PasswordValidationException { - PasswordValidationCallback.PlainTextPasswordRequest plainTextPasswordRequest = - (PasswordValidationCallback.PlainTextPasswordRequest) request; - String password = users.get(plainTextPasswordRequest.getUsername()); - return password != null && password.equals(plainTextPasswordRequest.getPassword()); - } - } + @Override + public boolean validate(PasswordValidationCallback.Request request) + throws PasswordValidationCallback.PasswordValidationException { + PasswordValidationCallback.PlainTextPasswordRequest plainTextPasswordRequest = + (PasswordValidationCallback.PlainTextPasswordRequest) request; + String password = users.get(plainTextPasswordRequest.getUsername()); + return password != null && password.equals(plainTextPasswordRequest.getPassword()); + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandler.java index fb0ac073..19759c74 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandler.java @@ -40,51 +40,51 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; */ public class SimpleUsernamePasswordCallbackHandler extends AbstractCallbackHandler implements InitializingBean { - private String username; + private String username; - private String password; + private String password; - /** - * Constructs an empty instance of the {@code SimpleUsernamePasswordCallbackHandler}. - */ - public SimpleUsernamePasswordCallbackHandler() { - } + /** + * Constructs an empty instance of the {@code SimpleUsernamePasswordCallbackHandler}. + */ + public SimpleUsernamePasswordCallbackHandler() { + } - /** - * Constructs an instance of the {@code SimpleUsernamePasswordCallbackHandler} with the given name and password. - */ - public SimpleUsernamePasswordCallbackHandler(String username, String password) { - this.username = username; - this.password = password; - } + /** + * Constructs an instance of the {@code SimpleUsernamePasswordCallbackHandler} with the given name and password. + */ + public SimpleUsernamePasswordCallbackHandler(String username, String password) { + this.username = username; + this.password = password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.hasLength(username, "username must be set"); - Assert.hasLength(password, "password must be set"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.hasLength(username, "username must be set"); + Assert.hasLength(password, "password must be set"); + } - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof UsernameCallback) { - UsernameCallback usernameCallback = (UsernameCallback) callback; - usernameCallback.setUsername(username); - } - else if (callback instanceof PasswordCallback) { - PasswordCallback passwordCallback = (PasswordCallback) callback; - passwordCallback.setPassword(password); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof UsernameCallback) { + UsernameCallback usernameCallback = (UsernameCallback) callback; + usernameCallback.setUsername(username); + } + else if (callback instanceof PasswordCallback) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword(password); + } + else { + throw new UnsupportedCallbackException(callback); + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandler.java index a6490454..039555fb 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandler.java @@ -53,69 +53,69 @@ import org.springframework.ws.soap.security.x509.X509AuthenticationToken; */ public class SpringCertificateValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean { - private AuthenticationManager authenticationManager; + private AuthenticationManager authenticationManager; - private boolean ignoreFailure = false; + private boolean ignoreFailure = false; - /** Sets the Spring Security authentication manager. Required. */ - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } + /** Sets the Spring Security authentication manager. Required. */ + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } - public void setIgnoreFailure(boolean ignoreFailure) { - this.ignoreFailure = ignoreFailure; - } + public void setIgnoreFailure(boolean ignoreFailure) { + this.ignoreFailure = ignoreFailure; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(authenticationManager, "authenticationManager is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(authenticationManager, "authenticationManager is required"); + } - /** - * Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for - * others - * - * @throws javax.security.auth.callback.UnsupportedCallbackException - * when the callback is not supported - */ - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof CertificateValidationCallback) { - ((CertificateValidationCallback) callback).setValidator(new SpringSecurityCertificateValidator()); - } - else if (callback instanceof CleanupCallback) { - SecurityContextHolder.clearContext(); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for + * others + * + * @throws javax.security.auth.callback.UnsupportedCallbackException + * when the callback is not supported + */ + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof CertificateValidationCallback) { + ((CertificateValidationCallback) callback).setValidator(new SpringSecurityCertificateValidator()); + } + else if (callback instanceof CleanupCallback) { + SecurityContextHolder.clearContext(); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - private class SpringSecurityCertificateValidator implements CertificateValidationCallback.CertificateValidator { + private class SpringSecurityCertificateValidator implements CertificateValidationCallback.CertificateValidator { - @Override - public boolean validate(X509Certificate certificate) - throws CertificateValidationCallback.CertificateValidationException { - boolean result; - try { - Authentication authResult = - authenticationManager.authenticate(new X509AuthenticationToken(certificate)); - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] successful"); - } - SecurityContextHolder.getContext().setAuthentication(authResult); - return true; - } - catch (AuthenticationException failed) { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] failed: " + failed.toString()); - } - SecurityContextHolder.clearContext(); - result = ignoreFailure; - } - return result; - } - } + @Override + public boolean validate(X509Certificate certificate) + throws CertificateValidationCallback.CertificateValidationException { + boolean result; + try { + Authentication authResult = + authenticationManager.authenticate(new X509AuthenticationToken(certificate)); + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] successful"); + } + SecurityContextHolder.getContext().setAuthentication(authResult); + return true; + } + catch (AuthenticationException failed) { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] failed: " + failed.toString()); + } + SecurityContextHolder.clearContext(); + result = ignoreFailure; + } + return result; + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandler.java index 9c028444..c4179ceb 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandler.java @@ -55,105 +55,105 @@ import org.springframework.ws.soap.security.support.SpringSecurityUtils; */ public class SpringDigestPasswordValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean { - private UserCache userCache = new NullUserCache(); + private UserCache userCache = new NullUserCache(); - private UserDetailsService userDetailsService; + private UserDetailsService userDetailsService; - /** Sets the users cache. Not required, but can benefit performance. */ - public void setUserCache(UserCache userCache) { - this.userCache = userCache; - } + /** Sets the users cache. Not required, but can benefit performance. */ + public void setUserCache(UserCache userCache) { + this.userCache = userCache; + } - /** Sets the Spring Security user details service. Required. */ - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } + /** Sets the Spring Security user details service. Required. */ + public void setUserDetailsService(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(userDetailsService, "userDetailsService is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(userDetailsService, "userDetailsService is required"); + } - /** - * Handles {@code PasswordValidationCallback}s that contain a {@code DigestPasswordRequest}, and throws an - * {@code UnsupportedCallbackException} for others - * - * @throws javax.security.auth.callback.UnsupportedCallbackException - * when the callback is not supported - */ - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback; - if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) { - PasswordValidationCallback.DigestPasswordRequest request = - (PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest(); - String username = request.getUsername(); - UserDetails user = loadUserDetails(username); - if (user != null) { - SpringSecurityUtils.checkUserValidity(user); - request.setPassword(user.getPassword()); - } - SpringSecurityDigestPasswordValidator validator = new SpringSecurityDigestPasswordValidator(user); - passwordCallback.setValidator(validator); - return; - } - } - else if (callback instanceof TimestampValidationCallback) { - TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback; - timestampCallback.setValidator(new DefaultTimestampValidator()); + /** + * Handles {@code PasswordValidationCallback}s that contain a {@code DigestPasswordRequest}, and throws an + * {@code UnsupportedCallbackException} for others + * + * @throws javax.security.auth.callback.UnsupportedCallbackException + * when the callback is not supported + */ + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback; + if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) { + PasswordValidationCallback.DigestPasswordRequest request = + (PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest(); + String username = request.getUsername(); + UserDetails user = loadUserDetails(username); + if (user != null) { + SpringSecurityUtils.checkUserValidity(user); + request.setPassword(user.getPassword()); + } + SpringSecurityDigestPasswordValidator validator = new SpringSecurityDigestPasswordValidator(user); + passwordCallback.setValidator(validator); + return; + } + } + else if (callback instanceof TimestampValidationCallback) { + TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback; + timestampCallback.setValidator(new DefaultTimestampValidator()); - } - else if (callback instanceof CleanupCallback) { - SecurityContextHolder.clearContext(); - return; - } - throw new UnsupportedCallbackException(callback); - } + } + else if (callback instanceof CleanupCallback) { + SecurityContextHolder.clearContext(); + return; + } + throw new UnsupportedCallbackException(callback); + } - private UserDetails loadUserDetails(String username) throws DataAccessException { - UserDetails user = userCache.getUserFromCache(username); + private UserDetails loadUserDetails(String username) throws DataAccessException { + UserDetails user = userCache.getUserFromCache(username); - if (user == null) { - try { - user = userDetailsService.loadUserByUsername(username); - } - catch (UsernameNotFoundException notFound) { - if (logger.isDebugEnabled()) { - logger.debug("Username '" + username + "' not found"); - } - return null; - } - userCache.putUserInCache(user); - } - return user; - } + if (user == null) { + try { + user = userDetailsService.loadUserByUsername(username); + } + catch (UsernameNotFoundException notFound) { + if (logger.isDebugEnabled()) { + logger.debug("Username '" + username + "' not found"); + } + return null; + } + userCache.putUserInCache(user); + } + return user; + } - private class SpringSecurityDigestPasswordValidator extends PasswordValidationCallback.DigestPasswordValidator { + private class SpringSecurityDigestPasswordValidator extends PasswordValidationCallback.DigestPasswordValidator { - private UserDetails user; + private UserDetails user; - private SpringSecurityDigestPasswordValidator(UserDetails user) { - this.user = user; - } + private SpringSecurityDigestPasswordValidator(UserDetails user) { + this.user = user; + } - @Override - public boolean validate(PasswordValidationCallback.Request request) - throws PasswordValidationCallback.PasswordValidationException { - if (super.validate(request)) { - UsernamePasswordAuthenticationToken authRequest = - new UsernamePasswordAuthenticationToken(user, user.getPassword()); - if (logger.isDebugEnabled()) { - logger.debug("Authentication success: " + authRequest.toString()); - } + @Override + public boolean validate(PasswordValidationCallback.Request request) + throws PasswordValidationCallback.PasswordValidationException { + if (super.validate(request)) { + UsernamePasswordAuthenticationToken authRequest = + new UsernamePasswordAuthenticationToken(user, user.getPassword()); + if (logger.isDebugEnabled()) { + logger.debug("Authentication success: " + authRequest.toString()); + } - SecurityContextHolder.getContext().setAuthentication(authRequest); - return true; - } - else { - return false; - } - } - } + SecurityContextHolder.getContext().setAuthentication(authRequest); + return true; + } + else { + return false; + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandler.java index 0bca6a82..a782ca33 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandler.java @@ -50,74 +50,74 @@ import org.springframework.ws.soap.security.callback.CleanupCallback; * @since 1.5.0 */ public class SpringPlainTextPasswordValidationCallbackHandler extends AbstractCallbackHandler - implements InitializingBean { + implements InitializingBean { - private AuthenticationManager authenticationManager; + private AuthenticationManager authenticationManager; - private boolean ignoreFailure = false; + private boolean ignoreFailure = false; - /** Sets the Spring Security authentication manager. Required. */ - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } + /** Sets the Spring Security authentication manager. Required. */ + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } - public void setIgnoreFailure(boolean ignoreFailure) { - this.ignoreFailure = ignoreFailure; - } + public void setIgnoreFailure(boolean ignoreFailure) { + this.ignoreFailure = ignoreFailure; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(authenticationManager, "authenticationManager is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(authenticationManager, "authenticationManager is required"); + } - /** - * Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws - * an {@code UnsupportedCallbackException} for others. - * - * @throws javax.security.auth.callback.UnsupportedCallbackException - * when the callback is not supported - */ - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; - if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) { - validationCallback.setValidator(new SpringSecurityPlainTextPasswordValidator()); - return; - } - } - else if (callback instanceof CleanupCallback) { - SecurityContextHolder.clearContext(); - return; - } - throw new UnsupportedCallbackException(callback); - } + /** + * Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws + * an {@code UnsupportedCallbackException} for others. + * + * @throws javax.security.auth.callback.UnsupportedCallbackException + * when the callback is not supported + */ + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; + if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) { + validationCallback.setValidator(new SpringSecurityPlainTextPasswordValidator()); + return; + } + } + else if (callback instanceof CleanupCallback) { + SecurityContextHolder.clearContext(); + return; + } + throw new UnsupportedCallbackException(callback); + } - private class SpringSecurityPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { + private class SpringSecurityPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { - @Override - public boolean validate(PasswordValidationCallback.Request request) - throws PasswordValidationCallback.PasswordValidationException { - PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest = - (PasswordValidationCallback.PlainTextPasswordRequest) request; - try { - Authentication authResult = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( - plainTextRequest.getUsername(), plainTextRequest.getPassword())); - if (logger.isDebugEnabled()) { - logger.debug("Authentication success: " + authResult.toString()); - } - SecurityContextHolder.getContext().setAuthentication(authResult); - return true; - } - catch (AuthenticationException failed) { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for user '" + plainTextRequest.getUsername() + "' failed: " + - failed.toString()); - } - SecurityContextHolder.clearContext(); - return ignoreFailure; - } - } - } + @Override + public boolean validate(PasswordValidationCallback.Request request) + throws PasswordValidationCallback.PasswordValidationException { + PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest = + (PasswordValidationCallback.PlainTextPasswordRequest) request; + try { + Authentication authResult = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( + plainTextRequest.getUsername(), plainTextRequest.getPassword())); + if (logger.isDebugEnabled()) { + logger.debug("Authentication success: " + authResult.toString()); + } + SecurityContextHolder.getContext().setAuthentication(authResult); + return true; + } + catch (AuthenticationException failed) { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for user '" + plainTextRequest.getUsername() + "' failed: " + + failed.toString()); + } + SecurityContextHolder.clearContext(); + return ignoreFailure; + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandler.java index f821d05e..7ceba09d 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandler.java @@ -39,32 +39,32 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; */ public class SpringUsernamePasswordCallbackHandler extends AbstractCallbackHandler { - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof UsernameCallback) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.getName() != null) { - UsernameCallback usernameCallback = (UsernameCallback) callback; - usernameCallback.setUsername(authentication.getName()); - return; - } - else { - logger.warn( - "Cannot handle UsernameCallback: Spring Security SecurityContext contains no Authentication"); - } - } - else if (callback instanceof PasswordCallback) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.getName() != null) { - PasswordCallback passwordCallback = (PasswordCallback) callback; - passwordCallback.setPassword(authentication.getCredentials().toString()); - return; - } - else { - logger.warn( - "Canot handle PasswordCallback: Spring Security SecurityContext contains no Authentication"); - } - } - throw new UnsupportedCallbackException(callback); - } + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof UsernameCallback) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getName() != null) { + UsernameCallback usernameCallback = (UsernameCallback) callback; + usernameCallback.setUsername(authentication.getName()); + return; + } + else { + logger.warn( + "Cannot handle UsernameCallback: Spring Security SecurityContext contains no Authentication"); + } + } + else if (callback instanceof PasswordCallback) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getName() != null) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword(authentication.getCredentials().toString()); + return; + } + else { + logger.warn( + "Canot handle PasswordCallback: Spring Security SecurityContext contains no Authentication"); + } + } + throw new UnsupportedCallbackException(callback); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/XwssCallbackHandlerChain.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/XwssCallbackHandlerChain.java index 4938bda3..88427d15 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/XwssCallbackHandlerChain.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/XwssCallbackHandlerChain.java @@ -37,126 +37,126 @@ import org.springframework.ws.soap.security.callback.CallbackHandlerChain; */ public class XwssCallbackHandlerChain extends CallbackHandlerChain { - public XwssCallbackHandlerChain(CallbackHandler[] callbackHandlers) { - super(callbackHandlers); - } + public XwssCallbackHandlerChain(CallbackHandler[] callbackHandlers) { + super(callbackHandlers); + } - @Override - protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { - if (callback instanceof CertificateValidationCallback) { - handleCertificateValidationCallback((CertificateValidationCallback) callback); - } - else if (callback instanceof PasswordValidationCallback) { - handlePasswordValidationCallback((PasswordValidationCallback) callback); - } - else if (callback instanceof TimestampValidationCallback) { - handleTimestampValidationCallback((TimestampValidationCallback) callback); - } - else { - super.handleInternal(callback); - } - } + @Override + protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException { + if (callback instanceof CertificateValidationCallback) { + handleCertificateValidationCallback((CertificateValidationCallback) callback); + } + else if (callback instanceof PasswordValidationCallback) { + handlePasswordValidationCallback((PasswordValidationCallback) callback); + } + else if (callback instanceof TimestampValidationCallback) { + handleTimestampValidationCallback((TimestampValidationCallback) callback); + } + else { + super.handleInternal(callback); + } + } - private void handleCertificateValidationCallback(CertificateValidationCallback callback) { - callback.setValidator(new CertificateValidatorChain(callback)); - } + private void handleCertificateValidationCallback(CertificateValidationCallback callback) { + callback.setValidator(new CertificateValidatorChain(callback)); + } - private void handlePasswordValidationCallback(PasswordValidationCallback callback) { - callback.setValidator(new PasswordValidatorChain(callback)); - } + private void handlePasswordValidationCallback(PasswordValidationCallback callback) { + callback.setValidator(new PasswordValidatorChain(callback)); + } - private void handleTimestampValidationCallback(TimestampValidationCallback callback) { - callback.setValidator(new TimestampValidatorChain(callback)); - } + private void handleTimestampValidationCallback(TimestampValidationCallback callback) { + callback.setValidator(new TimestampValidatorChain(callback)); + } - private class TimestampValidatorChain implements TimestampValidationCallback.TimestampValidator { + private class TimestampValidatorChain implements TimestampValidationCallback.TimestampValidator { - private TimestampValidationCallback callback; + private TimestampValidationCallback callback; - private TimestampValidatorChain(TimestampValidationCallback callback) { - this.callback = callback; - } + private TimestampValidatorChain(TimestampValidationCallback callback) { + this.callback = callback; + } - @Override - public void validate(TimestampValidationCallback.Request request) - throws TimestampValidationCallback.TimestampValidationException { - for (int i = 0; i < getCallbackHandlers().length; i++) { - CallbackHandler callbackHandler = getCallbackHandlers()[i]; - try { - callbackHandler.handle(new Callback[]{callback}); - callback.getResult(); - } - catch (IOException e) { - throw new TimestampValidationCallback.TimestampValidationException(e); - } - catch (UnsupportedCallbackException e) { - // ignore - } - } - } - } + @Override + public void validate(TimestampValidationCallback.Request request) + throws TimestampValidationCallback.TimestampValidationException { + for (int i = 0; i < getCallbackHandlers().length; i++) { + CallbackHandler callbackHandler = getCallbackHandlers()[i]; + try { + callbackHandler.handle(new Callback[]{callback}); + callback.getResult(); + } + catch (IOException e) { + throw new TimestampValidationCallback.TimestampValidationException(e); + } + catch (UnsupportedCallbackException e) { + // ignore + } + } + } + } - private class PasswordValidatorChain implements PasswordValidationCallback.PasswordValidator { + private class PasswordValidatorChain implements PasswordValidationCallback.PasswordValidator { - private PasswordValidationCallback callback; + private PasswordValidationCallback callback; - private PasswordValidatorChain(PasswordValidationCallback callback) { - this.callback = callback; - } + private PasswordValidatorChain(PasswordValidationCallback callback) { + this.callback = callback; + } - @Override - public boolean validate(PasswordValidationCallback.Request request) - throws PasswordValidationCallback.PasswordValidationException { - boolean allUnsupported = true; - for (int i = 0; i < getCallbackHandlers().length; i++) { - CallbackHandler callbackHandler = getCallbackHandlers()[i]; - try { - callbackHandler.handle(new Callback[]{callback}); - allUnsupported = false; - if (!callback.getResult()) { - return false; - } - } - catch (IOException e) { - throw new PasswordValidationCallback.PasswordValidationException(e); - } - catch (UnsupportedCallbackException e) { - // ignore - } - } - return !allUnsupported; - } - } + @Override + public boolean validate(PasswordValidationCallback.Request request) + throws PasswordValidationCallback.PasswordValidationException { + boolean allUnsupported = true; + for (int i = 0; i < getCallbackHandlers().length; i++) { + CallbackHandler callbackHandler = getCallbackHandlers()[i]; + try { + callbackHandler.handle(new Callback[]{callback}); + allUnsupported = false; + if (!callback.getResult()) { + return false; + } + } + catch (IOException e) { + throw new PasswordValidationCallback.PasswordValidationException(e); + } + catch (UnsupportedCallbackException e) { + // ignore + } + } + return !allUnsupported; + } + } - private class CertificateValidatorChain implements CertificateValidationCallback.CertificateValidator { + private class CertificateValidatorChain implements CertificateValidationCallback.CertificateValidator { - private CertificateValidationCallback callback; + private CertificateValidationCallback callback; - private CertificateValidatorChain(CertificateValidationCallback callback) { - this.callback = callback; - } + private CertificateValidatorChain(CertificateValidationCallback callback) { + this.callback = callback; + } - @Override - public boolean validate(X509Certificate certificate) - throws CertificateValidationCallback.CertificateValidationException { - boolean allUnsupported = true; - for (int i = 0; i < getCallbackHandlers().length; i++) { - CallbackHandler callbackHandler = getCallbackHandlers()[i]; - try { - callbackHandler.handle(new Callback[]{callback}); - allUnsupported = false; - if (!callback.getResult()) { - return false; - } - } - catch (IOException e) { - throw new CertificateValidationCallback.CertificateValidationException(e); - } - catch (UnsupportedCallbackException e) { - // ignore - } - } - return !allUnsupported; - } - } + @Override + public boolean validate(X509Certificate certificate) + throws CertificateValidationCallback.CertificateValidationException { + boolean allUnsupported = true; + for (int i = 0; i < getCallbackHandlers().length; i++) { + CallbackHandler callbackHandler = getCallbackHandlers()[i]; + try { + callbackHandler.handle(new Callback[]{callback}); + allUnsupported = false; + if (!callback.getResult()) { + return false; + } + } + catch (IOException e) { + throw new CertificateValidationCallback.CertificateValidationException(e); + } + catch (UnsupportedCallbackException e) { + // ignore + } + } + return !allUnsupported; + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/AbstractJaasValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/AbstractJaasValidationCallbackHandler.java index 38d19821..68ed46e2 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/AbstractJaasValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/AbstractJaasValidationCallbackHandler.java @@ -27,25 +27,25 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; * @since 1.0.0 */ public abstract class AbstractJaasValidationCallbackHandler extends AbstractCallbackHandler - implements InitializingBean { + implements InitializingBean { - private String loginContextName; + private String loginContextName; - protected AbstractJaasValidationCallbackHandler() { - } + protected AbstractJaasValidationCallbackHandler() { + } - /** Returns the login context name. */ - public String getLoginContextName() { - return loginContextName; - } + /** Returns the login context name. */ + public String getLoginContextName() { + return loginContextName; + } - /** Sets the login context name. */ - public void setLoginContextName(String loginContextName) { - this.loginContextName = loginContextName; - } + /** Sets the login context name. */ + public void setLoginContextName(String loginContextName) { + this.loginContextName = loginContextName; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(loginContextName, "loginContextName is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(loginContextName, "loginContextName is required"); + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandler.java index 4cc2d617..1773e135 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandler.java @@ -39,65 +39,65 @@ import com.sun.xml.wss.impl.callback.CertificateValidationCallback; */ public class JaasCertificateValidationCallbackHandler extends AbstractJaasValidationCallbackHandler { - /** - * Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for - * others - * - * @throws UnsupportedCallbackException when the callback is not supported - */ - @Override - protected final void handleInternal(Callback callback) throws UnsupportedCallbackException { - if (callback instanceof CertificateValidationCallback) { - ((CertificateValidationCallback) callback).setValidator(new JaasCertificateValidator()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } + /** + * Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for + * others + * + * @throws UnsupportedCallbackException when the callback is not supported + */ + @Override + protected final void handleInternal(Callback callback) throws UnsupportedCallbackException { + if (callback instanceof CertificateValidationCallback) { + ((CertificateValidationCallback) callback).setValidator(new JaasCertificateValidator()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } - private class JaasCertificateValidator implements CertificateValidationCallback.CertificateValidator { + private class JaasCertificateValidator implements CertificateValidationCallback.CertificateValidator { - @Override - public boolean validate(X509Certificate certificate) - throws CertificateValidationCallback.CertificateValidationException { - Subject subject = new Subject(); - subject.getPrincipals().add(certificate.getSubjectX500Principal()); - LoginContext loginContext; - try { - loginContext = new LoginContext(getLoginContextName(), subject); - } - catch (LoginException ex) { - throw new CertificateValidationCallback.CertificateValidationException(ex); - } - catch (SecurityException ex) { - throw new CertificateValidationCallback.CertificateValidationException(ex); - } + @Override + public boolean validate(X509Certificate certificate) + throws CertificateValidationCallback.CertificateValidationException { + Subject subject = new Subject(); + subject.getPrincipals().add(certificate.getSubjectX500Principal()); + LoginContext loginContext; + try { + loginContext = new LoginContext(getLoginContextName(), subject); + } + catch (LoginException ex) { + throw new CertificateValidationCallback.CertificateValidationException(ex); + } + catch (SecurityException ex) { + throw new CertificateValidationCallback.CertificateValidationException(ex); + } - try { - loginContext.login(); - Subject subj = loginContext.getSubject(); - if (!subj.getPrincipals().isEmpty()) { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] successful"); - } - return true; - } - else { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] failed"); - } - return false; - } - } - catch (LoginException ex) { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for certificate with DN [" + - certificate.getSubjectX500Principal().getName() + "] failed"); - } - return false; - } - } - } + try { + loginContext.login(); + Subject subj = loginContext.getSubject(); + if (!subj.getPrincipals().isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] successful"); + } + return true; + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] failed"); + } + return false; + } + } + catch (LoginException ex) { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for certificate with DN [" + + certificate.getSubjectX500Principal().getName() + "] failed"); + } + return false; + } + } + } } diff --git a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandler.java b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandler.java index 23e4e5ae..08dedd9f 100644 --- a/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandler.java +++ b/spring-ws-security/src/main/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandler.java @@ -40,85 +40,85 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler; */ public class JaasPlainTextPasswordValidationCallbackHandler extends AbstractJaasValidationCallbackHandler { - /** - * Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws - * an {@code UnsupportedCallbackException} for others. - * - * @throws UnsupportedCallbackException when the callback is not supported - */ - @Override - protected final void handleInternal(Callback callback) throws UnsupportedCallbackException { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; - if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) { - validationCallback.setValidator(new JaasPlainTextPasswordValidator()); - return; - } - } - throw new UnsupportedCallbackException(callback); - } + /** + * Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws + * an {@code UnsupportedCallbackException} for others. + * + * @throws UnsupportedCallbackException when the callback is not supported + */ + @Override + protected final void handleInternal(Callback callback) throws UnsupportedCallbackException { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; + if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) { + validationCallback.setValidator(new JaasPlainTextPasswordValidator()); + return; + } + } + throw new UnsupportedCallbackException(callback); + } - private class JaasPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { + private class JaasPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator { - @Override - public boolean validate(PasswordValidationCallback.Request request) - throws PasswordValidationCallback.PasswordValidationException { - PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest = - (PasswordValidationCallback.PlainTextPasswordRequest) request; + @Override + public boolean validate(PasswordValidationCallback.Request request) + throws PasswordValidationCallback.PasswordValidationException { + PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest = + (PasswordValidationCallback.PlainTextPasswordRequest) request; - final String username = plainTextRequest.getUsername(); - final String password = plainTextRequest.getPassword(); + final String username = plainTextRequest.getUsername(); + final String password = plainTextRequest.getPassword(); - LoginContext loginContext; - try { - loginContext = new LoginContext(getLoginContextName(), new AbstractCallbackHandler() { + LoginContext loginContext; + try { + loginContext = new LoginContext(getLoginContextName(), new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) throws UnsupportedCallbackException { - if (callback instanceof NameCallback) { - ((NameCallback) callback).setName(username); - } - else if (callback instanceof PasswordCallback) { - ((PasswordCallback) callback).setPassword(password.toCharArray()); - } - else { - throw new UnsupportedCallbackException(callback); - } - } - }); - } - catch (LoginException ex) { - throw new PasswordValidationCallback.PasswordValidationException(ex); - } - catch (SecurityException ex) { - throw new PasswordValidationCallback.PasswordValidationException(ex); - } + @Override + protected void handleInternal(Callback callback) throws UnsupportedCallbackException { + if (callback instanceof NameCallback) { + ((NameCallback) callback).setName(username); + } + else if (callback instanceof PasswordCallback) { + ((PasswordCallback) callback).setPassword(password.toCharArray()); + } + else { + throw new UnsupportedCallbackException(callback); + } + } + }); + } + catch (LoginException ex) { + throw new PasswordValidationCallback.PasswordValidationException(ex); + } + catch (SecurityException ex) { + throw new PasswordValidationCallback.PasswordValidationException(ex); + } - try { - loginContext.login(); - Subject subject = loginContext.getSubject(); - if (!subject.getPrincipals().isEmpty()) { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for user '" + username + "' successful"); - } - return true; - } - else { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for user '" + username + "' failed"); - } - return false; - } - } - catch (LoginException ex) { - if (logger.isDebugEnabled()) { - logger.debug("Authentication request for user '" + username + "' failed"); - } - return false; - } - } + try { + loginContext.login(); + Subject subject = loginContext.getSubject(); + if (!subject.getPrincipals().isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for user '" + username + "' successful"); + } + return true; + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for user '" + username + "' failed"); + } + return false; + } + } + catch (LoginException ex) { + if (logger.isDebugEnabled()) { + logger.debug("Authentication request for user '" + username + "' failed"); + } + return false; + } + } - } + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/callback/CallbackHandlerChainTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/callback/CallbackHandlerChainTest.java index 3e073bc2..22055cfb 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/callback/CallbackHandlerChainTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/callback/CallbackHandlerChainTest.java @@ -24,35 +24,35 @@ import org.junit.Test; public class CallbackHandlerChainTest { - private CallbackHandler supported = new CallbackHandler() { - public void handle(Callback[] callbacks) { - } - }; + private CallbackHandler supported = new CallbackHandler() { + public void handle(Callback[] callbacks) { + } + }; - private CallbackHandler unsupported = new CallbackHandler() { - public void handle(Callback[] callbacks) throws UnsupportedCallbackException { - throw new UnsupportedCallbackException(callbacks[0]); - } - }; + private CallbackHandler unsupported = new CallbackHandler() { + public void handle(Callback[] callbacks) throws UnsupportedCallbackException { + throw new UnsupportedCallbackException(callbacks[0]); + } + }; - private Callback callback = new Callback() { - }; + private Callback callback = new Callback() { + }; - @Test - public void testSupported() throws Exception { - CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{supported}); - chain.handle(new Callback[]{callback}); - } + @Test + public void testSupported() throws Exception { + CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{supported}); + chain.handle(new Callback[]{callback}); + } - @Test - public void testUnsupportedSupported() throws Exception { - CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported, supported}); - chain.handle(new Callback[]{callback}); - } + @Test + public void testUnsupportedSupported() throws Exception { + CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported, supported}); + chain.handle(new Callback[]{callback}); + } - @Test(expected = UnsupportedCallbackException.class) - public void testUnsupported() throws Exception { - CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported}); - chain.handle(new Callback[]{callback}); - } + @Test(expected = UnsupportedCallbackException.class) + public void testUnsupported() throws Exception { + CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported}); + chain.handle(new Callback[]{callback}); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBeanTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBeanTest.java index 8bf0d9c2..b48edcc8 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBeanTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/KeyManagersFactoryBeanTest.java @@ -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, diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBeanTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBeanTest.java index e2570a0a..e5e32a05 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBeanTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/support/TrustManagersFactoryBeanTest.java @@ -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, diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jInterceptorTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jInterceptorTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorEncryptionTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorEncryptionTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorHeaderTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorHeaderTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorSignTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorSignTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java old mode 100755 new mode 100644 index 148ceb28..5be3bb45 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java @@ -17,6 +17,6 @@ package org.springframework.ws.soap.security.wss4j; public class AxiomWss4jMessageInterceptorSpringSecurityCallbackHandlerTest - extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase { + extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase { } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorTimestampTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorTimestampTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorUsernameTokenSignatureTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorUsernameTokenSignatureTest.java old mode 100755 new mode 100644 index 4353708b..f8e09df1 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorUsernameTokenSignatureTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorUsernameTokenSignatureTest.java @@ -17,6 +17,6 @@ package org.springframework.ws.soap.security.wss4j; public class AxiomWss4jMessageInterceptorUsernameTokenSignatureTest - extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase { + extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase { } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorUsernameTokenTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/AxiomWss4jMessageInterceptorUsernameTokenTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jInterceptorTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jInterceptorTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorEncryptionTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorEncryptionTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorHeaderTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorHeaderTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSignTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSignTest.java old mode 100755 new mode 100644 index c79b3e41..4cbc1651 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSignTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSignTest.java @@ -41,43 +41,43 @@ import static org.junit.Assert.assertTrue; public class SaajWss4jMessageInterceptorSignTest extends Wss4jMessageInterceptorSignTestCase { - private static final String PAYLOAD = - "QQQ"; + private static final String PAYLOAD = + "QQQ"; - @Test - public void testSignAndValidate() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - interceptor.setSecurementActions("Signature"); - interceptor.setEnableSignatureConfirmation(false); - interceptor.setSecurementPassword("123456"); - interceptor.setSecurementUsername("rsaKey"); - SOAPMessage saajMessage = saajSoap11MessageFactory.createMessage(); - transformer.transform(new StringSource(PAYLOAD), new DOMResult(saajMessage.getSOAPBody())); - SoapMessage message = new SaajSoapMessage(saajMessage, saajSoap11MessageFactory); - MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory)); + @Test + public void testSignAndValidate() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + interceptor.setSecurementActions("Signature"); + interceptor.setEnableSignatureConfirmation(false); + interceptor.setSecurementPassword("123456"); + interceptor.setSecurementUsername("rsaKey"); + SOAPMessage saajMessage = saajSoap11MessageFactory.createMessage(); + transformer.transform(new StringSource(PAYLOAD), new DOMResult(saajMessage.getSOAPBody())); + SoapMessage message = new SaajSoapMessage(saajMessage, saajSoap11MessageFactory); + MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory)); - interceptor.secureMessage(message, messageContext); + interceptor.secureMessage(message, messageContext); - SOAPHeader header = ((SaajSoapMessage) message).getSaajMessage().getSOAPHeader(); - Iterator iterator = header.getChildElements(new QName( - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security")); - assertTrue("No security header", iterator.hasNext()); - SOAPHeaderElement securityHeader = (SOAPHeaderElement) iterator.next(); - iterator = securityHeader.getChildElements(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")); - assertTrue("No signature header", iterator.hasNext()); + SOAPHeader header = ((SaajSoapMessage) message).getSaajMessage().getSOAPHeader(); + Iterator iterator = header.getChildElements(new QName( + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security")); + assertTrue("No security header", iterator.hasNext()); + SOAPHeaderElement securityHeader = (SOAPHeaderElement) iterator.next(); + iterator = securityHeader.getChildElements(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")); + assertTrue("No signature header", iterator.hasNext()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - message.writeTo(bos); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + message.writeTo(bos); - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader("Content-Type", "text/xml"); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader("Content-Type", "text/xml"); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - SOAPMessage signed = saajSoap11MessageFactory.createMessage(mimeHeaders, bis); - message = new SaajSoapMessage(signed, saajSoap11MessageFactory); - messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory)); + SOAPMessage signed = saajSoap11MessageFactory.createMessage(mimeHeaders, bis); + message = new SaajSoapMessage(signed, saajSoap11MessageFactory); + messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory)); - interceptor.validateMessage(message, messageContext); - } + interceptor.validateMessage(message, messageContext); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java old mode 100755 new mode 100644 index 7d6d1019..ed7faa1c --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorSpringSecurityCallbackHandlerTest.java @@ -17,6 +17,6 @@ package org.springframework.ws.soap.security.wss4j; public class SaajWss4jMessageInterceptorSpringSecurityCallbackHandlerTest - extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase { + extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase { } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorTimestampTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorTimestampTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorUsernameTokenSignatureTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorUsernameTokenSignatureTest.java old mode 100755 new mode 100644 index 43b05f38..6c31316c --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorUsernameTokenSignatureTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorUsernameTokenSignatureTest.java @@ -17,6 +17,6 @@ package org.springframework.ws.soap.security.wss4j; public class SaajWss4jMessageInterceptorUsernameTokenSignatureTest - extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase { + extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase { } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorUsernameTokenTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/SaajWss4jMessageInterceptorUsernameTokenTest.java old mode 100755 new mode 100644 diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jInterceptorTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jInterceptorTestCase.java old mode 100755 new mode 100644 index 3a5a2e41..f602bc35 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jInterceptorTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jInterceptorTestCase.java @@ -29,56 +29,56 @@ import static org.junit.Assert.fail; public abstract class Wss4jInterceptorTestCase extends Wss4jTestCase { - @Test - public void testHandleRequest() throws Exception { - SoapMessage request = loadSoap11Message("empty-soap.xml"); - final Object requestMessage = getMessage(request); - SoapMessage validatedRequest = loadSoap11Message("empty-soap.xml"); - final Object validatedRequestMessage = getMessage(validatedRequest); - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() { - @Override - protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecuritySecurementException { - fail("secure not expected"); - } + @Test + public void testHandleRequest() throws Exception { + SoapMessage request = loadSoap11Message("empty-soap.xml"); + final Object requestMessage = getMessage(request); + SoapMessage validatedRequest = loadSoap11Message("empty-soap.xml"); + final Object validatedRequestMessage = getMessage(validatedRequest); + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() { + @Override + protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecuritySecurementException { + fail("secure not expected"); + } - @Override - protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException { - assertEquals("Invalid message", requestMessage, getMessage(soapMessage)); - setMessage(soapMessage, validatedRequestMessage); - } - }; - MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory()); - interceptor.handleRequest(context, null); - assertEquals("Invalid request", validatedRequestMessage, getMessage((SoapMessage) context.getRequest())); - } + @Override + protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException { + assertEquals("Invalid message", requestMessage, getMessage(soapMessage)); + setMessage(soapMessage, validatedRequestMessage); + } + }; + MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory()); + interceptor.handleRequest(context, null); + assertEquals("Invalid request", validatedRequestMessage, getMessage((SoapMessage) context.getRequest())); + } - @Test - public void testHandleResponse() throws Exception { - SoapMessage securedResponse = loadSoap11Message("empty-soap.xml"); - final Object securedResponseMessage = getMessage(securedResponse); + @Test + public void testHandleResponse() throws Exception { + SoapMessage securedResponse = loadSoap11Message("empty-soap.xml"); + final Object securedResponseMessage = getMessage(securedResponse); - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() { - @Override - protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecuritySecurementException { - setMessage(soapMessage, securedResponseMessage); - } + @Override + protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecuritySecurementException { + setMessage(soapMessage, securedResponseMessage); + } - @Override - protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException { - fail("validate not expected"); - } + @Override + protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException { + fail("validate not expected"); + } - }; - SoapMessage request = loadSoap11Message("empty-soap.xml"); - MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory()); - context.getResponse(); - interceptor.handleResponse(context, null); - assertEquals("Invalid response", securedResponseMessage, getMessage((SoapMessage) context.getResponse())); - } + }; + SoapMessage request = loadSoap11Message("empty-soap.xml"); + MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory()); + context.getResponse(); + interceptor.handleResponse(context, null); + assertEquals("Invalid response", securedResponseMessage, getMessage((SoapMessage) context.getResponse())); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorEncryptionTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorEncryptionTestCase.java old mode 100755 new mode 100644 index 7543f0c0..60a9a969 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorEncryptionTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorEncryptionTestCase.java @@ -29,58 +29,58 @@ import org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean; public abstract class Wss4jMessageInterceptorEncryptionTestCase extends Wss4jTestCase { - protected Wss4jSecurityInterceptor interceptor; + protected Wss4jSecurityInterceptor interceptor; - @Override - protected void onSetup() throws Exception { - interceptor = new Wss4jSecurityInterceptor(); - interceptor.setValidationActions("Encrypt"); - interceptor.setSecurementActions("Encrypt"); + @Override + protected void onSetup() throws Exception { + interceptor = new Wss4jSecurityInterceptor(); + interceptor.setValidationActions("Encrypt"); + interceptor.setSecurementActions("Encrypt"); - KeyStoreCallbackHandler callbackHandler = new KeyStoreCallbackHandler(); - callbackHandler.setPrivateKeyPassword("123456"); - interceptor.setValidationCallbackHandler(callbackHandler); + KeyStoreCallbackHandler callbackHandler = new KeyStoreCallbackHandler(); + callbackHandler.setPrivateKeyPassword("123456"); + interceptor.setValidationCallbackHandler(callbackHandler); - CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean(); + CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean(); - Properties cryptoFactoryBeanConfig = new Properties(); - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider", - "org.apache.ws.security.components.crypto.Merlin"); - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks"); - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456"); + Properties cryptoFactoryBeanConfig = new Properties(); + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider", + "org.apache.ws.security.components.crypto.Merlin"); + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks"); + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456"); - // from the class path - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks"); - cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig); - cryptoFactoryBean.afterPropertiesSet(); - interceptor.setValidationDecryptionCrypto(cryptoFactoryBean - .getObject()); - interceptor.setSecurementEncryptionCrypto(cryptoFactoryBean - .getObject()); + // from the class path + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks"); + cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig); + cryptoFactoryBean.afterPropertiesSet(); + interceptor.setValidationDecryptionCrypto(cryptoFactoryBean + .getObject()); + interceptor.setSecurementEncryptionCrypto(cryptoFactoryBean + .getObject()); - interceptor.afterPropertiesSet(); - } + interceptor.afterPropertiesSet(); + } - @Test - public void testDecryptRequest() throws Exception { - SoapMessage message = loadSoap11Message("encrypted-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); - Document document = getDocument((SoapMessage) messageContext.getRequest()); - assertXpathEvaluatesTo("Decryption error", "Hello", "/SOAP-ENV:Envelope/SOAP-ENV:Body/echo:echoRequest/text()", - document); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", - getDocument(message)); - } + @Test + public void testDecryptRequest() throws Exception { + SoapMessage message = loadSoap11Message("encrypted-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); + Document document = getDocument((SoapMessage) messageContext.getRequest()); + assertXpathEvaluatesTo("Decryption error", "Hello", "/SOAP-ENV:Envelope/SOAP-ENV:Body/echo:echoRequest/text()", + document); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", + getDocument(message)); + } - @Test - public void testEncryptResponse() throws Exception { - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); - interceptor.setSecurementEncryptionUser("rsakey"); - interceptor.secureMessage(message, messageContext); - Document document = getDocument(message); - assertXpathExists("Encryption error", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", - document); - } + @Test + public void testEncryptResponse() throws Exception { + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext messageContext = getSoap11MessageContext(message); + interceptor.setSecurementEncryptionUser("rsakey"); + interceptor.secureMessage(message, messageContext); + Document document = getDocument(message); + assertXpathExists("Encryption error", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", + document); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorHeaderTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorHeaderTestCase.java old mode 100755 new mode 100644 index a3c3ecd0..528dc3f0 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorHeaderTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorHeaderTestCase.java @@ -39,122 +39,122 @@ import org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidat */ public abstract class Wss4jMessageInterceptorHeaderTestCase extends Wss4jTestCase { - private Wss4jSecurityInterceptor interceptor; - private Wss4jSecurityInterceptor interceptorThatKeepsSecurityHeader; + private Wss4jSecurityInterceptor interceptor; + private Wss4jSecurityInterceptor interceptorThatKeepsSecurityHeader; - @Override - protected void onSetup() throws Exception { - Properties users = new Properties(); - users.setProperty("Bert", "Ernie"); - interceptor = new Wss4jSecurityInterceptor(); - interceptor.setValidateRequest(true); - interceptor.setSecureResponse(true); - interceptor.setValidationActions("UsernameToken"); - SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler(); - callbackHandler.setUsers(users); - interceptor.setValidationCallbackHandler(callbackHandler); - interceptor.afterPropertiesSet(); + @Override + protected void onSetup() throws Exception { + Properties users = new Properties(); + users.setProperty("Bert", "Ernie"); + interceptor = new Wss4jSecurityInterceptor(); + interceptor.setValidateRequest(true); + interceptor.setSecureResponse(true); + interceptor.setValidationActions("UsernameToken"); + SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler(); + callbackHandler.setUsers(users); + interceptor.setValidationCallbackHandler(callbackHandler); + interceptor.afterPropertiesSet(); - interceptorThatKeepsSecurityHeader = new Wss4jSecurityInterceptor(); - interceptorThatKeepsSecurityHeader.setValidateRequest(true); - interceptorThatKeepsSecurityHeader.setSecureResponse(true); - interceptorThatKeepsSecurityHeader.setValidationActions("UsernameToken"); - interceptorThatKeepsSecurityHeader.setValidationCallbackHandler(callbackHandler); - interceptorThatKeepsSecurityHeader.setRemoveSecurityHeader(false); - interceptorThatKeepsSecurityHeader.afterPropertiesSet(); - } - - @Test - public void testValidateUsernameTokenPlainText() throws Exception { - SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); - Object result = getMessage(message); - assertNotNull("No result returned", result); + interceptorThatKeepsSecurityHeader = new Wss4jSecurityInterceptor(); + interceptorThatKeepsSecurityHeader.setValidateRequest(true); + interceptorThatKeepsSecurityHeader.setSecureResponse(true); + interceptorThatKeepsSecurityHeader.setValidationActions("UsernameToken"); + interceptorThatKeepsSecurityHeader.setValidationCallbackHandler(callbackHandler); + interceptorThatKeepsSecurityHeader.setRemoveSecurityHeader(false); + interceptorThatKeepsSecurityHeader.afterPropertiesSet(); + } + + @Test + public void testValidateUsernameTokenPlainText() throws Exception { + SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); + Object result = getMessage(message); + assertNotNull("No result returned", result); - for (Iterator i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) { - SoapHeaderElement element = i.next(); - QName name = element.getName(); - if (name.getNamespaceURI() - .equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) { - fail("Security Header not removed"); - } + for (Iterator i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) { + SoapHeaderElement element = i.next(); + QName name = element.getName(); + if (name.getNamespaceURI() + .equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) { + fail("Security Header not removed"); + } - } + } - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", - getDocument(message)); - assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message)); - assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message)); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", + getDocument(message)); + assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message)); + assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message)); - } + } - @Test - public void testValidateUsernameTokenPlainTextButKeepSecurityHeader() throws Exception { - SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptorThatKeepsSecurityHeader.validateMessage(message, messageContext); - Object result = getMessage(message); - assertNotNull("No result returned", result); + @Test + public void testValidateUsernameTokenPlainTextButKeepSecurityHeader() throws Exception { + SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptorThatKeepsSecurityHeader.validateMessage(message, messageContext); + Object result = getMessage(message); + assertNotNull("No result returned", result); - boolean foundSecurityHeader = false; - for (Iterator i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) { - SoapHeaderElement element = i.next(); - QName name = element.getName(); - if (name.getNamespaceURI() - .equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) { - foundSecurityHeader = true; - } + boolean foundSecurityHeader = false; + for (Iterator i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) { + SoapHeaderElement element = i.next(); + QName name = element.getName(); + if (name.getNamespaceURI() + .equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) { + foundSecurityHeader = true; + } - } - assertTrue(foundSecurityHeader); + } + assertTrue(foundSecurityHeader); - assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message)); - assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message)); + assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message)); + assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message)); - } + } - @Test(expected=WsSecurityValidationException.class) - public void testEmptySecurityHeader() throws Exception { - SoapMessage message = loadSoap11Message("emptySecurityHeader-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); - } - - @Test - public void testPreserveCustomHeaders() throws Exception { - interceptor.setSecurementActions("UsernameToken"); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); + @Test(expected=WsSecurityValidationException.class) + public void testEmptySecurityHeader() throws Exception { + SoapMessage message = loadSoap11Message("emptySecurityHeader-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); + } + + @Test + public void testPreserveCustomHeaders() throws Exception { + interceptor.setSecurementActions("UsernameToken"); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - SoapMessage message = loadSoap11Message("customHeader-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - message.writeTo(os); - String document = os.toString("UTF-8"); - assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1", - document); - assertXpathNotExists("Header 2 exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", document); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SoapMessage message = loadSoap11Message("customHeader-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + message.writeTo(os); + String document = os.toString("UTF-8"); + assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1", + document); + assertXpathNotExists("Header 2 exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", document); - interceptor.secureMessage(message, messageContext); + interceptor.secureMessage(message, messageContext); - SoapHeaderElement element = message.getSoapHeader().addHeaderElement(new QName("http://test", "header2")); - element.setText("test2"); + SoapHeaderElement element = message.getSoapHeader().addHeaderElement(new QName("http://test", "header2")); + element.setText("test2"); - os = new ByteArrayOutputStream(); - message.writeTo(os); - document = os.toString("UTF-8"); - assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1", - document); - assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", - document); + os = new ByteArrayOutputStream(); + message.writeTo(os); + document = os.toString("UTF-8"); + assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1", + document); + assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", + document); - os = new ByteArrayOutputStream(); - message.writeTo(os); - document = os.toString("UTF-8"); - assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1", - document); - assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", - document); - } + os = new ByteArrayOutputStream(); + message.writeTo(os); + document = os.toString("UTF-8"); + assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1", + document); + assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", + document); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSignTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSignTestCase.java old mode 100755 new mode 100644 index adb9192c..03a3e87d --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSignTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSignTestCase.java @@ -31,93 +31,93 @@ import static org.junit.Assert.assertNotNull; public abstract class Wss4jMessageInterceptorSignTestCase extends Wss4jTestCase { - protected Wss4jSecurityInterceptor interceptor; + protected Wss4jSecurityInterceptor interceptor; - @Override - protected void onSetup() throws Exception { - interceptor = new Wss4jSecurityInterceptor(); - interceptor.setValidationActions("Signature"); + @Override + protected void onSetup() throws Exception { + interceptor = new Wss4jSecurityInterceptor(); + interceptor.setValidationActions("Signature"); - CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean(); - Properties cryptoFactoryBeanConfig = new Properties(); - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider", - "org.apache.ws.security.components.crypto.Merlin"); - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks"); - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456"); + CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean(); + Properties cryptoFactoryBeanConfig = new Properties(); + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider", + "org.apache.ws.security.components.crypto.Merlin"); + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks"); + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456"); - // from the class path - cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks"); - cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig); - cryptoFactoryBean.afterPropertiesSet(); - interceptor.setValidationSignatureCrypto(cryptoFactoryBean - .getObject()); - interceptor.setSecurementSignatureCrypto(cryptoFactoryBean - .getObject()); - interceptor.afterPropertiesSet(); + // from the class path + cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks"); + cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig); + cryptoFactoryBean.afterPropertiesSet(); + interceptor.setValidationSignatureCrypto(cryptoFactoryBean + .getObject()); + interceptor.setSecurementSignatureCrypto(cryptoFactoryBean + .getObject()); + interceptor.afterPropertiesSet(); - } + } - @Test - public void testValidateCertificate() throws Exception { - SoapMessage message = loadSoap11Message("signed-soap.xml"); + @Test + public void testValidateCertificate() throws Exception { + SoapMessage message = loadSoap11Message("signed-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); - Object result = getMessage(message); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", - getDocument(message)); - } + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); + Object result = getMessage(message); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", + getDocument(message)); + } - @Test - public void testValidateCertificateWithSignatureConfirmation() throws Exception { - SoapMessage message = loadSoap11Message("signed-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); - interceptor.setEnableSignatureConfirmation(true); - interceptor.validateMessage(message, messageContext); - WebServiceMessage response = messageContext.getResponse(); - interceptor.secureMessage(message, messageContext); - assertNotNull("No result returned", response); - Document document = getDocument((SoapMessage) response); - assertXpathExists("Absent SignatureConfirmation element", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse11:SignatureConfirmation", document); - } + @Test + public void testValidateCertificateWithSignatureConfirmation() throws Exception { + SoapMessage message = loadSoap11Message("signed-soap.xml"); + MessageContext messageContext = getSoap11MessageContext(message); + interceptor.setEnableSignatureConfirmation(true); + interceptor.validateMessage(message, messageContext); + WebServiceMessage response = messageContext.getResponse(); + interceptor.secureMessage(message, messageContext); + assertNotNull("No result returned", response); + Document document = getDocument((SoapMessage) response); + assertXpathExists("Absent SignatureConfirmation element", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse11:SignatureConfirmation", document); + } - @Test - public void testSignResponse() throws Exception { - interceptor.setSecurementActions("Signature"); - interceptor.setEnableSignatureConfirmation(false); - interceptor.setSecurementPassword("123456"); - interceptor.setSecurementUsername("rsaKey"); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); + @Test + public void testSignResponse() throws Exception { + interceptor.setSecurementActions("Signature"); + interceptor.setEnableSignatureConfirmation(false); + interceptor.setSecurementPassword("123456"); + interceptor.setSecurementUsername("rsaKey"); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext messageContext = getSoap11MessageContext(message); - // interceptor.setSecurementSignatureKeyIdentifier("IssuerSerial"); + // interceptor.setSecurementSignatureKeyIdentifier("IssuerSerial"); - interceptor.secureMessage(message, messageContext); + interceptor.secureMessage(message, messageContext); - Document document = getDocument(message); - assertXpathExists("Absent SignatureConfirmation element", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document); + Document document = getDocument(message); + assertXpathExists("Absent SignatureConfirmation element", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document); - } + } - @Test - public void testSignResponseWithSignatureUser() throws Exception { - interceptor.setSecurementActions("Signature"); - interceptor.setEnableSignatureConfirmation(false); - interceptor.setSecurementPassword("123456"); - interceptor.setSecurementSignatureUser("rsaKey"); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); + @Test + public void testSignResponseWithSignatureUser() throws Exception { + interceptor.setSecurementActions("Signature"); + interceptor.setEnableSignatureConfirmation(false); + interceptor.setSecurementPassword("123456"); + interceptor.setSecurementSignatureUser("rsaKey"); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext messageContext = getSoap11MessageContext(message); - interceptor.secureMessage(message, messageContext); + interceptor.secureMessage(message, messageContext); - Document document = getDocument(message); - assertXpathExists("Absent SignatureConfirmation element", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document); + Document document = getDocument(message); + assertXpathExists("Absent SignatureConfirmation element", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document); - } + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSoapActionTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSoapActionTestCase.java index 6ce9200b..836f2424 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSoapActionTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSoapActionTestCase.java @@ -32,77 +32,77 @@ import static org.junit.Assert.assertNotNull; public abstract class Wss4jMessageInterceptorSoapActionTestCase extends Wss4jTestCase { - private static final String SOAP_ACTION = "\"http://test\""; + private static final String SOAP_ACTION = "\"http://test\""; - private Properties users; + private Properties users; - private Wss4jSecurityInterceptor interceptor; + private Wss4jSecurityInterceptor interceptor; - @Override - protected void onSetup() throws Exception { - users = new Properties(); - users.setProperty("Bert", "Ernie"); - interceptor = new Wss4jSecurityInterceptor(); - interceptor.setValidationActions("UsernameToken"); - interceptor.setSecurementActions("UsernameToken"); - interceptor.setSecurementPasswordType(WSConstants.PW_TEXT); - SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler(); - callbackHandler.setUsers(users); - interceptor.setValidationCallbackHandler(callbackHandler); + @Override + protected void onSetup() throws Exception { + users = new Properties(); + users.setProperty("Bert", "Ernie"); + interceptor = new Wss4jSecurityInterceptor(); + interceptor.setValidationActions("UsernameToken"); + interceptor.setSecurementActions("UsernameToken"); + interceptor.setSecurementPasswordType(WSConstants.PW_TEXT); + SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler(); + callbackHandler.setUsers(users); + interceptor.setValidationCallbackHandler(callbackHandler); - interceptor.afterPropertiesSet(); - } + interceptor.afterPropertiesSet(); + } - @Test - public void testPreserveSoapActionOnValidation() throws Exception { - SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml"); - message.setSoapAction(SOAP_ACTION); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); + @Test + public void testPreserveSoapActionOnValidation() throws Exception { + SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml"); + message.setSoapAction(SOAP_ACTION); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); - assertNotNull("Soap Action must not be null", message.getSoapAction()); - assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); - } + assertNotNull("Soap Action must not be null", message.getSoapAction()); + assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); + } - @Test - public void testPreserveSoap12ActionOnValidation() throws Exception { - SoapMessage message = loadSoap12Message("usernameTokenPlainText-soap12.xml"); - message.setSoapAction(SOAP_ACTION); - WebServiceMessageFactory messageFactory = getSoap12MessageFactory(); - MessageContext messageContext = new DefaultMessageContext(message, messageFactory); - interceptor.validateMessage(message, messageContext); + @Test + public void testPreserveSoap12ActionOnValidation() throws Exception { + SoapMessage message = loadSoap12Message("usernameTokenPlainText-soap12.xml"); + message.setSoapAction(SOAP_ACTION); + WebServiceMessageFactory messageFactory = getSoap12MessageFactory(); + MessageContext messageContext = new DefaultMessageContext(message, messageFactory); + interceptor.validateMessage(message, messageContext); - assertNotNull("Soap Action must not be null", message.getSoapAction()); - assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); - } + assertNotNull("Soap Action must not be null", message.getSoapAction()); + assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); + } - @Test - public void testPreserveSoapActionOnSecurement() throws Exception { - SoapMessage message = loadSoap11Message("empty-soap.xml"); - message.setSoapAction(SOAP_ACTION); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - MessageContext messageContext = getSoap11MessageContext(message); - interceptor.secureMessage(message, messageContext); + @Test + public void testPreserveSoapActionOnSecurement() throws Exception { + SoapMessage message = loadSoap11Message("empty-soap.xml"); + message.setSoapAction(SOAP_ACTION); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + MessageContext messageContext = getSoap11MessageContext(message); + interceptor.secureMessage(message, messageContext); - assertNotNull("Soap Action must not be null", message.getSoapAction()); - assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); + assertNotNull("Soap Action must not be null", message.getSoapAction()); + assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); - } + } - @Test - public void testPreserveSoap12ActionOnSecurement() throws Exception { - SoapMessage message = loadSoap12Message("empty-soap12.xml"); - message.setSoapAction(SOAP_ACTION); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - MessageContext messageContext = getSoap12MessageContext(message); - interceptor.secureMessage(message, messageContext); + @Test + public void testPreserveSoap12ActionOnSecurement() throws Exception { + SoapMessage message = loadSoap12Message("empty-soap12.xml"); + message.setSoapAction(SOAP_ACTION); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + MessageContext messageContext = getSoap12MessageContext(message); + interceptor.secureMessage(message, messageContext); - assertNotNull("Soap Action must not be null", message.getSoapAction()); - assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); + assertNotNull("Soap Action must not be null", message.getSoapAction()); + assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction()); - } + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase.java old mode 100755 new mode 100644 index 4bb0b913..29efefa4 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase.java @@ -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, @@ -37,91 +37,91 @@ import static org.junit.Assert.assertNull; public abstract class Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase extends Wss4jTestCase { - private Properties users = new Properties(); + private Properties users = new Properties(); - private AuthenticationManager authenticationManager; + private AuthenticationManager authenticationManager; - @Override - protected void onSetup() throws Exception { - authenticationManager = createMock(AuthenticationManager.class); - users.setProperty("Bert", "Ernie,ROLE_TEST"); - } + @Override + protected void onSetup() throws Exception { + authenticationManager = createMock(AuthenticationManager.class); + users.setProperty("Bert", "Ernie,ROLE_TEST"); + } - @After - public void tearDown() throws Exception { - verify(authenticationManager); - SecurityContextHolder.clearContext(); - } + @After + public void tearDown() throws Exception { + verify(authenticationManager); + SecurityContextHolder.clearContext(); + } - @Test - public void testValidateUsernameTokenPlainText() throws Exception { - EndpointInterceptor interceptor = prepareInterceptor("UsernameToken", true, false); - SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.handleRequest(messageContext, null); - assertValidateUsernameToken(message); + @Test + public void testValidateUsernameTokenPlainText() throws Exception { + EndpointInterceptor interceptor = prepareInterceptor("UsernameToken", true, false); + SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.handleRequest(messageContext, null); + assertValidateUsernameToken(message); - // test clean up - messageContext.getResponse(); - interceptor.handleResponse(messageContext, null); - interceptor.afterCompletion(messageContext, null, null); - assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - } + // test clean up + messageContext.getResponse(); + interceptor.handleResponse(messageContext, null); + interceptor.afterCompletion(messageContext, null, null); + assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + } - @Test - public void testValidateUsernameTokenDigest() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("UsernameToken"); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); + @Test + public void testValidateUsernameTokenDigest() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("UsernameToken"); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.handleRequest(messageContext); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.handleRequest(messageContext); - interceptor = prepareInterceptor("UsernameToken", true, true); - interceptor.handleRequest(messageContext, null); - assertValidateUsernameToken(message); + interceptor = prepareInterceptor("UsernameToken", true, true); + interceptor.handleRequest(messageContext, null); + assertValidateUsernameToken(message); - // test clean up - messageContext.getResponse(); - interceptor.handleResponse(messageContext, null); - interceptor.afterCompletion(messageContext, null, null); - assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - } + // test clean up + messageContext.getResponse(); + interceptor.handleResponse(messageContext, null); + interceptor.afterCompletion(messageContext, null, null); + assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + } - protected void assertValidateUsernameToken(SoapMessage message) throws Exception { - Object result = getMessage(message); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", - getDocument(message)); - assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); - } + protected void assertValidateUsernameToken(SoapMessage message) throws Exception { + Object result = getMessage(message); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", + getDocument(message)); + assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); + } - protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest) - throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - if (validating) { - interceptor.setValidationActions(actions); - } - else { - interceptor.setSecurementActions(actions); - } - SpringSecurityPasswordValidationCallbackHandler callbackHandler = - new SpringSecurityPasswordValidationCallbackHandler(); - InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(users); - callbackHandler.setUserDetailsService(userDetailsManager); - if (digest) { - interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); - } - else { - interceptor.setSecurementPasswordType(WSConstants.PW_TEXT); - } - interceptor.setValidationCallbackHandler(callbackHandler); - interceptor.afterPropertiesSet(); - replay(authenticationManager); - return interceptor; - } + protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest) + throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + if (validating) { + interceptor.setValidationActions(actions); + } + else { + interceptor.setSecurementActions(actions); + } + SpringSecurityPasswordValidationCallbackHandler callbackHandler = + new SpringSecurityPasswordValidationCallbackHandler(); + InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(users); + callbackHandler.setUserDetailsService(userDetailsManager); + if (digest) { + interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); + } + else { + interceptor.setSecurementPasswordType(WSConstants.PW_TEXT); + } + interceptor.setValidationCallbackHandler(callbackHandler); + interceptor.afterPropertiesSet(); + replay(authenticationManager); + return interceptor; + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorTimestampTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorTimestampTestCase.java old mode 100755 new mode 100644 index 04ac9d92..6f53b499 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorTimestampTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorTimestampTestCase.java @@ -31,73 +31,73 @@ import static org.junit.Assert.assertEquals; public abstract class Wss4jMessageInterceptorTimestampTestCase extends Wss4jTestCase { - @Test - public void testAddTimestamp() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("Timestamp"); - interceptor.afterPropertiesSet(); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext context = getSoap11MessageContext(message); - interceptor.secureMessage(message, context); - Document document = getDocument(message); - assertXpathExists("timestamp header not found", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp", document); - } + @Test + public void testAddTimestamp() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("Timestamp"); + interceptor.afterPropertiesSet(); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext context = getSoap11MessageContext(message); + interceptor.secureMessage(message, context); + Document document = getDocument(message); + assertXpathExists("timestamp header not found", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp", document); + } - @Test - public void testValidateTimestamp() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setValidationActions("Timestamp"); - interceptor.afterPropertiesSet(); - SoapMessage message = getMessageWithTimestamp(); + @Test + public void testValidateTimestamp() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setValidationActions("Timestamp"); + interceptor.afterPropertiesSet(); + SoapMessage message = getMessageWithTimestamp(); - MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, context); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", - getDocument(message)); - } + MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, context); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", + getDocument(message)); + } - @Test(expected = WsSecurityValidationException.class) - public void testValidateTimestampWithExpiredTtl() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setValidationActions("Timestamp"); - interceptor.afterPropertiesSet(); - SoapMessage message = loadSoap11Message("expiredTimestamp-soap.xml"); - MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, context); - } + @Test(expected = WsSecurityValidationException.class) + public void testValidateTimestampWithExpiredTtl() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setValidationActions("Timestamp"); + interceptor.afterPropertiesSet(); + SoapMessage message = loadSoap11Message("expiredTimestamp-soap.xml"); + MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, context); + } - @Test - public void testSecureTimestampWithCustomTtl() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("Timestamp"); - interceptor.setTimestampStrict(true); - int ttlInSeconds = 1; - interceptor.setSecurementTimeToLive(ttlInSeconds); - interceptor.afterPropertiesSet(); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.secureMessage(message, context); - - String created = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Created/text()", - message.getEnvelope().getSource()); - String expires = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Expires/text()", - message.getEnvelope().getSource()); + @Test + public void testSecureTimestampWithCustomTtl() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("Timestamp"); + interceptor.setTimestampStrict(true); + int ttlInSeconds = 1; + interceptor.setSecurementTimeToLive(ttlInSeconds); + interceptor.afterPropertiesSet(); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.secureMessage(message, context); + + String created = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Created/text()", + message.getEnvelope().getSource()); + String expires = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Expires/text()", + message.getEnvelope().getSource()); - DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); - long actualTtl = format.parse(expires).getTime() - format.parse(created).getTime(); - assertEquals("invalid ttl", 1000 * ttlInSeconds, actualTtl); - } + long actualTtl = format.parse(expires).getTime() - format.parse(created).getTime(); + assertEquals("invalid ttl", 1000 * ttlInSeconds, actualTtl); + } - private SoapMessage getMessageWithTimestamp() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("Timestamp"); - interceptor.afterPropertiesSet(); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext context = getSoap11MessageContext(message); - interceptor.secureMessage(message, context); - return message; - } + private SoapMessage getMessageWithTimestamp() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("Timestamp"); + interceptor.afterPropertiesSet(); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext context = getSoap11MessageContext(message); + interceptor.secureMessage(message, context); + return message; + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenSignatureTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenSignatureTestCase.java old mode 100755 new mode 100644 index a34b0d9a..bb28b21e --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenSignatureTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenSignatureTestCase.java @@ -24,22 +24,22 @@ import org.w3c.dom.Document; public abstract class Wss4jMessageInterceptorUsernameTokenSignatureTestCase extends Wss4jTestCase { - @Test - public void testAddUsernameTokenSignature() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("UsernameTokenSignature"); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - interceptor.afterPropertiesSet(); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext context = getSoap11MessageContext(message); - interceptor.secureMessage(message, context); + @Test + public void testAddUsernameTokenSignature() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("UsernameTokenSignature"); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + interceptor.afterPropertiesSet(); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext context = getSoap11MessageContext(message); + interceptor.secureMessage(message, context); - Document doc = getDocument(message); - assertXpathEvaluatesTo("Invalid Username", "Bert", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc); - assertXpathExists("Invalid Password", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']/text()", - doc); - } + Document doc = getDocument(message); + assertXpathEvaluatesTo("Invalid Username", "Bert", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc); + assertXpathExists("Invalid Password", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']/text()", + doc); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenTestCase.java old mode 100755 new mode 100644 index a69ab90e..b6e7111f --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorUsernameTokenTestCase.java @@ -31,122 +31,122 @@ import static org.junit.Assert.assertNotNull; public abstract class Wss4jMessageInterceptorUsernameTokenTestCase extends Wss4jTestCase { - private Properties users = new Properties(); + private Properties users = new Properties(); - @Override - protected void onSetup() throws Exception { - users.setProperty("Bert", "Ernie"); - } + @Override + protected void onSetup() throws Exception { + users.setProperty("Bert", "Ernie"); + } - @Test - public void testValidateUsernameTokenPlainText() throws Exception { - Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false); - SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); - assertValidateUsernameToken(message); - } + @Test + public void testValidateUsernameTokenPlainText() throws Exception { + Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false); + SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); + assertValidateUsernameToken(message); + } - @Test - public void testValidateUsernameTokenDigest() throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("UsernameToken"); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); + @Test + public void testValidateUsernameTokenDigest() throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("UsernameToken"); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.handleRequest(messageContext); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.handleRequest(messageContext); - interceptor = prepareInterceptor("UsernameToken", true, true); - interceptor.validateMessage(message, messageContext); - assertValidateUsernameToken(message); - } + interceptor = prepareInterceptor("UsernameToken", true, true); + interceptor.validateMessage(message, messageContext); + assertValidateUsernameToken(message); + } - @Test - public void testValidateUsernameTokenWithQualifiedType() throws Exception { - Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false); - SoapMessage message = loadSoap11Message("usernameTokenPlainTextQualifiedType-soap.xml"); - MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); - interceptor.validateMessage(message, messageContext); - assertValidateUsernameToken(message); - } + @Test + public void testValidateUsernameTokenWithQualifiedType() throws Exception { + Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false); + SoapMessage message = loadSoap11Message("usernameTokenPlainTextQualifiedType-soap.xml"); + MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory()); + interceptor.validateMessage(message, messageContext); + assertValidateUsernameToken(message); + } - @Test - public void testAddUsernameTokenPlainText() throws Exception { - Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, false); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - SoapMessage message = loadSoap11Message("empty-soap.xml"); + @Test + public void testAddUsernameTokenPlainText() throws Exception { + Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, false); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); + MessageContext messageContext = getSoap11MessageContext(message); - interceptor.secureMessage(message, messageContext); - assertAddUsernameTokenPlainText(message); - } + interceptor.secureMessage(message, messageContext); + assertAddUsernameTokenPlainText(message); + } - @Test - public void testAddUsernameTokenDigest() throws Exception { - Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, true); - interceptor.setSecurementUsername("Bert"); - interceptor.setSecurementPassword("Ernie"); - SoapMessage message = loadSoap11Message("empty-soap.xml"); + @Test + public void testAddUsernameTokenDigest() throws Exception { + Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, true); + interceptor.setSecurementUsername("Bert"); + interceptor.setSecurementPassword("Ernie"); + SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); - interceptor.secureMessage(message, messageContext); - assertAddUsernameTokenDigest(message); - } + MessageContext messageContext = getSoap11MessageContext(message); + interceptor.secureMessage(message, messageContext); + assertAddUsernameTokenDigest(message); + } - protected void assertValidateUsernameToken(SoapMessage message) throws Exception { - Object result = getMessage(message); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", - getDocument(message)); - } + protected void assertValidateUsernameToken(SoapMessage message) throws Exception { + Object result = getMessage(message); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", + getDocument(message)); + } - protected void assertAddUsernameTokenPlainText(SoapMessage message) throws Exception { - Object result = getMessage(message); - assertNotNull("No result returned", result); - Document doc = getDocument(message); - assertXpathEvaluatesTo("Invalid Username", "Bert", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc); - assertXpathEvaluatesTo("Invalid Password", "Ernie", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()", - doc); - } + protected void assertAddUsernameTokenPlainText(SoapMessage message) throws Exception { + Object result = getMessage(message); + assertNotNull("No result returned", result); + Document doc = getDocument(message); + assertXpathEvaluatesTo("Invalid Username", "Bert", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc); + assertXpathEvaluatesTo("Invalid Password", "Ernie", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()", + doc); + } - protected void assertAddUsernameTokenDigest(SoapMessage message) throws Exception { - Object result = getMessage(message); - Document doc = getDocument(message); - assertNotNull("No result returned", result); - assertXpathEvaluatesTo("Invalid Username", "Bert", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc); - assertXpathExists("Password does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']", - doc); + protected void assertAddUsernameTokenDigest(SoapMessage message) throws Exception { + Object result = getMessage(message); + Document doc = getDocument(message); + assertNotNull("No result returned", result); + assertXpathEvaluatesTo("Invalid Username", "Bert", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc); + assertXpathExists("Password does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']", + doc); - } + } - protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest) - throws Exception { - Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); - if (validating) { - interceptor.setValidationActions(actions); - } - else { - interceptor.setSecurementActions(actions); - } - SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler(); - callbackHandler.setUsers(users); - if (digest) { - interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); - } - else { - interceptor.setSecurementPasswordType(WSConstants.PW_TEXT); - } - interceptor.setValidationCallbackHandler(callbackHandler); - interceptor.afterPropertiesSet(); - return interceptor; - } + protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest) + throws Exception { + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + if (validating) { + interceptor.setValidationActions(actions); + } + else { + interceptor.setSecurementActions(actions); + } + SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler(); + callbackHandler.setUsers(users); + if (digest) { + interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST); + } + else { + interceptor.setSecurementPasswordType(WSConstants.PW_TEXT); + } + interceptor.setValidationCallbackHandler(callbackHandler); + interceptor.afterPropertiesSet(); + return interceptor; + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorX509TestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorX509TestCase.java index b7bd91ff..7d6b0cad 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorX509TestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jMessageInterceptorX509TestCase.java @@ -27,46 +27,46 @@ import org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean; public abstract class Wss4jMessageInterceptorX509TestCase extends Wss4jTestCase { - protected Wss4jSecurityInterceptor interceptor; + protected Wss4jSecurityInterceptor interceptor; - @Override - protected void onSetup() throws Exception { - interceptor = new Wss4jSecurityInterceptor(); - interceptor.setSecurementActions("Signature"); - interceptor.setValidationActions("Signature"); - CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean(); - cryptoFactoryBean.setCryptoProvider(Merlin.class); - cryptoFactoryBean.setKeyStoreType("jceks"); - cryptoFactoryBean.setKeyStorePassword("123456"); - cryptoFactoryBean.setKeyStoreLocation(new ClassPathResource("private.jks")); + @Override + protected void onSetup() throws Exception { + interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("Signature"); + interceptor.setValidationActions("Signature"); + CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean(); + cryptoFactoryBean.setCryptoProvider(Merlin.class); + cryptoFactoryBean.setKeyStoreType("jceks"); + cryptoFactoryBean.setKeyStorePassword("123456"); + cryptoFactoryBean.setKeyStoreLocation(new ClassPathResource("private.jks")); - cryptoFactoryBean.afterPropertiesSet(); - interceptor.setSecurementSignatureCrypto(cryptoFactoryBean - .getObject()); - interceptor.setValidationSignatureCrypto(cryptoFactoryBean - .getObject()); - interceptor.afterPropertiesSet(); + cryptoFactoryBean.afterPropertiesSet(); + interceptor.setSecurementSignatureCrypto(cryptoFactoryBean + .getObject()); + interceptor.setValidationSignatureCrypto(cryptoFactoryBean + .getObject()); + interceptor.afterPropertiesSet(); - } + } - @Test - public void testAddCertificate() throws Exception { + @Test + public void testAddCertificate() throws Exception { - interceptor.setSecurementPassword("123456"); - interceptor.setSecurementUsername("rsaKey"); - SoapMessage message = loadSoap11Message("empty-soap.xml"); - MessageContext messageContext = getSoap11MessageContext(message); + interceptor.setSecurementPassword("123456"); + interceptor.setSecurementUsername("rsaKey"); + SoapMessage message = loadSoap11Message("empty-soap.xml"); + MessageContext messageContext = getSoap11MessageContext(message); - interceptor.setSecurementSignatureKeyIdentifier("DirectReference"); + interceptor.setSecurementSignatureKeyIdentifier("DirectReference"); - interceptor.secureMessage(message, messageContext); - Document document = getDocument(message); + interceptor.secureMessage(message, messageContext); + Document document = getDocument(message); - assertXpathExists("Absent BinarySecurityToken element", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", document); + assertXpathExists("Absent BinarySecurityToken element", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", document); - // lets verify the signature that we've just generated - interceptor.validateMessage(message, messageContext); - } + // lets verify the signature that we've just generated + interceptor.validateMessage(message, messageContext); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jTestCase.java old mode 100755 new mode 100644 index 22822765..5c9d826e --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/Wss4jTestCase.java @@ -54,228 +54,228 @@ import static org.junit.Assert.assertTrue; public abstract class Wss4jTestCase { - protected MessageFactory saajSoap11MessageFactory; + protected MessageFactory saajSoap11MessageFactory; - protected MessageFactory saajSoap12MessageFactory; + protected MessageFactory saajSoap12MessageFactory; - protected final boolean axiomTest = this.getClass().getSimpleName().startsWith("Axiom"); + protected final boolean axiomTest = this.getClass().getSimpleName().startsWith("Axiom"); - protected final boolean saajTest = this.getClass().getSimpleName().startsWith("Saaj"); + protected final boolean saajTest = this.getClass().getSimpleName().startsWith("Saaj"); - protected Jaxp13XPathTemplate xpathTemplate = new Jaxp13XPathTemplate(); + protected Jaxp13XPathTemplate xpathTemplate = new Jaxp13XPathTemplate(); - @Before - public final void setUp() throws Exception { - if (!axiomTest && !saajTest) { - throw new IllegalArgumentException("test class name must start with either Axiom or Saaj"); - } - saajSoap11MessageFactory = MessageFactory.newInstance(); - saajSoap12MessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); - Map namespaces = new HashMap(); - namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); - namespaces.put("wsse", - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); - namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); - namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#"); - namespaces.put("wsse11", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"); - namespaces.put("echo", "http://www.springframework.org/spring-ws/samples/echo"); - namespaces.put("wsu", - "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); - namespaces.put("test", "http://test"); - xpathTemplate.setNamespaces(namespaces); - onSetup(); - } + @Before + public final void setUp() throws Exception { + if (!axiomTest && !saajTest) { + throw new IllegalArgumentException("test class name must start with either Axiom or Saaj"); + } + saajSoap11MessageFactory = MessageFactory.newInstance(); + saajSoap12MessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + Map namespaces = new HashMap(); + namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); + namespaces.put("wsse", + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); + namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); + namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#"); + namespaces.put("wsse11", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"); + namespaces.put("echo", "http://www.springframework.org/spring-ws/samples/echo"); + namespaces.put("wsu", + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); + namespaces.put("test", "http://test"); + xpathTemplate.setNamespaces(namespaces); + onSetup(); + } - protected void assertXpathEvaluatesTo(String message, - String expectedValue, - String xpathExpression, - Document document) { - String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new DOMSource(document)); - Assert.assertEquals(message, expectedValue, actualValue); - } + protected void assertXpathEvaluatesTo(String message, + String expectedValue, + String xpathExpression, + Document document) { + String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new DOMSource(document)); + Assert.assertEquals(message, expectedValue, actualValue); + } - protected void assertXpathEvaluatesTo(String message, - String expectedValue, - String xpathExpression, - String document) { - String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new StringSource(document)); - Assert.assertEquals(message, expectedValue, actualValue); - } + protected void assertXpathEvaluatesTo(String message, + String expectedValue, + String xpathExpression, + String document) { + String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new StringSource(document)); + Assert.assertEquals(message, expectedValue, actualValue); + } - protected void assertXpathExists(String message, String xpathExpression, Document document) { - Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document)); - Assert.assertNotNull(message, node); - } + protected void assertXpathExists(String message, String xpathExpression, Document document) { + Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document)); + Assert.assertNotNull(message, node); + } - protected void assertXpathNotExists(String message, String xpathExpression, Document document) { - Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document)); - Assert.assertNull(message, node); - } + protected void assertXpathNotExists(String message, String xpathExpression, Document document) { + Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document)); + Assert.assertNull(message, node); + } - protected void assertXpathNotExists(String message, String xpathExpression, String document) { - Node node = xpathTemplate.evaluateAsNode(xpathExpression, new StringSource(document)); - Assert.assertNull(message, node); - } + protected void assertXpathNotExists(String message, String xpathExpression, String document) { + Node node = xpathTemplate.evaluateAsNode(xpathExpression, new StringSource(document)); + Assert.assertNull(message, node); + } - protected SaajSoapMessage loadSaaj11Message(String fileName) throws Exception { - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader("Content-Type", "text/xml"); - Resource resource = new ClassPathResource(fileName, getClass()); - InputStream is = resource.getInputStream(); - try { - assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists()); - is = resource.getInputStream(); - return new SaajSoapMessage(saajSoap11MessageFactory.createMessage(mimeHeaders, is), saajSoap11MessageFactory); - } - finally { - is.close(); - } - } - - protected SaajSoapMessage loadSaaj12Message(String fileName) throws Exception { - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader("Content-Type", "application/soap+xml"); - Resource resource = new ClassPathResource(fileName, getClass()); - InputStream is = resource.getInputStream(); - try { - assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists()); - is = resource.getInputStream(); - return new SaajSoapMessage(saajSoap12MessageFactory.createMessage(mimeHeaders, is), saajSoap12MessageFactory); - } - finally { - is.close(); - } - } + protected SaajSoapMessage loadSaaj11Message(String fileName) throws Exception { + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader("Content-Type", "text/xml"); + Resource resource = new ClassPathResource(fileName, getClass()); + InputStream is = resource.getInputStream(); + try { + assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists()); + is = resource.getInputStream(); + return new SaajSoapMessage(saajSoap11MessageFactory.createMessage(mimeHeaders, is), saajSoap11MessageFactory); + } + finally { + is.close(); + } + } + + protected SaajSoapMessage loadSaaj12Message(String fileName) throws Exception { + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader("Content-Type", "application/soap+xml"); + Resource resource = new ClassPathResource(fileName, getClass()); + InputStream is = resource.getInputStream(); + try { + assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists()); + is = resource.getInputStream(); + return new SaajSoapMessage(saajSoap12MessageFactory.createMessage(mimeHeaders, is), saajSoap12MessageFactory); + } + finally { + is.close(); + } + } - protected AxiomSoapMessage loadAxiom11Message(String fileName) throws Exception { - Resource resource = new ClassPathResource(fileName, getClass()); - InputStream is = resource.getInputStream(); - try { - assertTrue("Could not load Axiom message [" + resource + "]", resource.exists()); - is = resource.getInputStream(); + protected AxiomSoapMessage loadAxiom11Message(String fileName) throws Exception { + Resource resource = new ClassPathResource(fileName, getClass()); + InputStream is = resource.getInputStream(); + try { + assertTrue("Could not load Axiom message [" + resource + "]", resource.exists()); + is = resource.getInputStream(); - XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is); - StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, null); - org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage(); - return new AxiomSoapMessage(soapMessage, "", true, true); - } - finally { - is.close(); - } - } + XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is); + StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, null); + org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage(); + return new AxiomSoapMessage(soapMessage, "", true, true); + } + finally { + is.close(); + } + } - @SuppressWarnings("Since15") - protected AxiomSoapMessage loadAxiom12Message(String fileName) throws Exception { - Resource resource = new ClassPathResource(fileName, getClass()); - InputStream is = resource.getInputStream(); - try { - assertTrue("Could not load Axiom message [" + resource + "]", resource.exists()); - is = resource.getInputStream(); + @SuppressWarnings("Since15") + protected AxiomSoapMessage loadAxiom12Message(String fileName) throws Exception { + Resource resource = new ClassPathResource(fileName, getClass()); + InputStream is = resource.getInputStream(); + try { + assertTrue("Could not load Axiom message [" + resource + "]", resource.exists()); + is = resource.getInputStream(); - XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is); - StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI); - org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage(); - return new AxiomSoapMessage(soapMessage, "", true, true); - } - finally { - is.close(); - } - } + XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is); + StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI); + org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage(); + return new AxiomSoapMessage(soapMessage, "", true, true); + } + finally { + is.close(); + } + } - protected Object getMessage(SoapMessage soapMessage) { - if (soapMessage instanceof SaajSoapMessage) { - return ((SaajSoapMessage) soapMessage).getSaajMessage(); - } - if (soapMessage instanceof AxiomSoapMessage) { - return ((AxiomSoapMessage) soapMessage).getAxiomMessage(); + protected Object getMessage(SoapMessage soapMessage) { + if (soapMessage instanceof SaajSoapMessage) { + return ((SaajSoapMessage) soapMessage).getSaajMessage(); + } + if (soapMessage instanceof AxiomSoapMessage) { + return ((AxiomSoapMessage) soapMessage).getAxiomMessage(); - } - throw new IllegalArgumentException("Illegal message: " + soapMessage); - } + } + throw new IllegalArgumentException("Illegal message: " + soapMessage); + } - protected void setMessage(SoapMessage soapMessage, Object message) { - if (soapMessage instanceof SaajSoapMessage) { - ((SaajSoapMessage) soapMessage).setSaajMessage((SOAPMessage) message); - return; - } - if (soapMessage instanceof AxiomSoapMessage) { - ((AxiomSoapMessage) soapMessage).setAxiomMessage((org.apache.axiom.soap.SOAPMessage) message); - return; - } - throw new IllegalArgumentException("Illegal message: " + message); - } + protected void setMessage(SoapMessage soapMessage, Object message) { + if (soapMessage instanceof SaajSoapMessage) { + ((SaajSoapMessage) soapMessage).setSaajMessage((SOAPMessage) message); + return; + } + if (soapMessage instanceof AxiomSoapMessage) { + ((AxiomSoapMessage) soapMessage).setAxiomMessage((org.apache.axiom.soap.SOAPMessage) message); + return; + } + throw new IllegalArgumentException("Illegal message: " + message); + } - protected void onSetup() throws Exception { - } + protected void onSetup() throws Exception { + } - protected SoapMessage loadSoap11Message(String fileName) throws Exception { - if (axiomTest) { - return loadAxiom11Message(fileName); - } - if (saajTest) { - return loadSaaj11Message(fileName); - } - throw new IllegalArgumentException(); - } + protected SoapMessage loadSoap11Message(String fileName) throws Exception { + if (axiomTest) { + return loadAxiom11Message(fileName); + } + if (saajTest) { + return loadSaaj11Message(fileName); + } + throw new IllegalArgumentException(); + } - protected SoapMessage loadSoap12Message(String fileName) throws Exception { - if (axiomTest) { - return loadAxiom12Message(fileName); - } - if (saajTest) { - return loadSaaj12Message(fileName); - } - throw new IllegalArgumentException(); - } + protected SoapMessage loadSoap12Message(String fileName) throws Exception { + if (axiomTest) { + return loadAxiom12Message(fileName); + } + if (saajTest) { + return loadSaaj12Message(fileName); + } + throw new IllegalArgumentException(); + } - protected SoapMessageFactory getSoap11MessageFactory() throws Exception { - if (axiomTest) { - return new AxiomSoapMessageFactory(); - } - if (saajTest) { - return new SaajSoapMessageFactory(saajSoap11MessageFactory); - } - throw new IllegalArgumentException(); - } + protected SoapMessageFactory getSoap11MessageFactory() throws Exception { + if (axiomTest) { + return new AxiomSoapMessageFactory(); + } + if (saajTest) { + return new SaajSoapMessageFactory(saajSoap11MessageFactory); + } + throw new IllegalArgumentException(); + } - protected SoapMessageFactory getSoap12MessageFactory() throws Exception { - SoapMessageFactory messageFactory; - if (axiomTest) { - messageFactory = new AxiomSoapMessageFactory(); - } else if (saajTest) { - messageFactory = new SaajSoapMessageFactory(saajSoap12MessageFactory); - } else - throw new IllegalArgumentException(); - messageFactory.setSoapVersion(SoapVersion.SOAP_12); - return messageFactory; - } - - protected Document getDocument(SoapMessage message) throws Exception { - if (axiomTest) { - return AxiomUtils.toDocument(((AxiomSoapMessage) message).getAxiomMessage().getSOAPEnvelope()); - } - if (saajTest) { - return ((SaajSoapMessage) message).getSaajMessage().getSOAPPart(); - } - throw new IllegalArgumentException(); - } + protected SoapMessageFactory getSoap12MessageFactory() throws Exception { + SoapMessageFactory messageFactory; + if (axiomTest) { + messageFactory = new AxiomSoapMessageFactory(); + } else if (saajTest) { + messageFactory = new SaajSoapMessageFactory(saajSoap12MessageFactory); + } else + throw new IllegalArgumentException(); + messageFactory.setSoapVersion(SoapVersion.SOAP_12); + return messageFactory; + } + + protected Document getDocument(SoapMessage message) throws Exception { + if (axiomTest) { + return AxiomUtils.toDocument(((AxiomSoapMessage) message).getAxiomMessage().getSOAPEnvelope()); + } + if (saajTest) { + return ((SaajSoapMessage) message).getSaajMessage().getSOAPPart(); + } + throw new IllegalArgumentException(); + } - protected MessageContext getSoap11MessageContext(final SoapMessage response) throws Exception { - return new DefaultMessageContext(response, getSoap11MessageFactory()) { - @Override - public WebServiceMessage getResponse() { - return response; - } - }; - } + protected MessageContext getSoap11MessageContext(final SoapMessage response) throws Exception { + return new DefaultMessageContext(response, getSoap11MessageFactory()) { + @Override + public WebServiceMessage getResponse() { + return response; + } + }; + } - protected MessageContext getSoap12MessageContext(final SoapMessage response) throws Exception { - return new DefaultMessageContext(response, getSoap12MessageFactory()) { - @Override - public WebServiceMessage getResponse() { - return response; - } - }; - } + protected MessageContext getSoap12MessageContext(final SoapMessage response) throws Exception { + return new DefaultMessageContext(response, getSoap12MessageFactory()) { + @Override + public WebServiceMessage getResponse() { + return response; + } + }; + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandlerTest.java index e7bfd4c7..ca725eff 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/KeyStoreCallbackHandlerTest.java @@ -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, @@ -28,29 +28,29 @@ import org.junit.Test; public class KeyStoreCallbackHandlerTest { - private KeyStoreCallbackHandler callbackHandler; + private KeyStoreCallbackHandler callbackHandler; - private WSPasswordCallback callback; + private WSPasswordCallback callback; - @Before - public void setUp() throws Exception { - callbackHandler = new KeyStoreCallbackHandler(); - callback = new WSPasswordCallback("secretkey", WSPasswordCallback.SECRET_KEY); + @Before + public void setUp() throws Exception { + callbackHandler = new KeyStoreCallbackHandler(); + callback = new WSPasswordCallback("secretkey", WSPasswordCallback.SECRET_KEY); - KeyStoreFactoryBean factory = new KeyStoreFactoryBean(); - factory.setLocation(new ClassPathResource("private.jks")); - factory.setPassword("123456"); - factory.setType("JCEKS"); - factory.afterPropertiesSet(); - KeyStore keyStore = factory.getObject(); - callbackHandler.setKeyStore(keyStore); - callbackHandler.setSymmetricKeyPassword("123456"); - } + KeyStoreFactoryBean factory = new KeyStoreFactoryBean(); + factory.setLocation(new ClassPathResource("private.jks")); + factory.setPassword("123456"); + factory.setType("JCEKS"); + factory.afterPropertiesSet(); + KeyStore keyStore = factory.getObject(); + callbackHandler.setKeyStore(keyStore); + callbackHandler.setSymmetricKeyPassword("123456"); + } - @Test - public void testHandleKeyName() throws Exception { - callbackHandler.handleInternal(callback); - Assert.assertNotNull("symmetric key must not be null", callback.getKey()); - } + @Test + public void testHandleKeyName() throws Exception { + callbackHandler.handleInternal(callback); + Assert.assertNotNull("symmetric key must not be null", callback.getKey()); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandlerTest.java index bdb01020..41b1cea2 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/callback/SpringSecurityPasswordValidationCallbackHandlerTest.java @@ -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, @@ -38,44 +38,44 @@ import static org.easymock.EasyMock.*; /** @author tareq */ public class SpringSecurityPasswordValidationCallbackHandlerTest { - private SpringSecurityPasswordValidationCallbackHandler callbackHandler; + private SpringSecurityPasswordValidationCallbackHandler callbackHandler; - private SimpleGrantedAuthority grantedAuthority; + private SimpleGrantedAuthority grantedAuthority; - private UsernameTokenPrincipalCallback callback; + private UsernameTokenPrincipalCallback callback; - private UserDetails user; + private UserDetails user; - @Before - public void setUp() throws Exception { - callbackHandler = new SpringSecurityPasswordValidationCallbackHandler(); + @Before + public void setUp() throws Exception { + callbackHandler = new SpringSecurityPasswordValidationCallbackHandler(); - grantedAuthority = new SimpleGrantedAuthority("ROLE_1"); - user = new User("Ernie", "Bert", true, true, true, true, Collections.singleton(grantedAuthority)); + grantedAuthority = new SimpleGrantedAuthority("ROLE_1"); + user = new User("Ernie", "Bert", true, true, true, true, Collections.singleton(grantedAuthority)); - WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal("Ernie", true); - callback = new UsernameTokenPrincipalCallback(principal); - } + WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal("Ernie", true); + callback = new UsernameTokenPrincipalCallback(principal); + } - @Test - public void testHandleUsernameTokenPrincipal() throws Exception { - UserDetailsService userDetailsService = createMock(UserDetailsService.class); - callbackHandler.setUserDetailsService(userDetailsService); + @Test + public void testHandleUsernameTokenPrincipal() throws Exception { + UserDetailsService userDetailsService = createMock(UserDetailsService.class); + callbackHandler.setUserDetailsService(userDetailsService); - expect(userDetailsService.loadUserByUsername("Ernie")).andReturn(user).anyTimes(); + expect(userDetailsService.loadUserByUsername("Ernie")).andReturn(user).anyTimes(); - replay(userDetailsService); + replay(userDetailsService); - callbackHandler.handleUsernameTokenPrincipal(callback); - SecurityContext context = SecurityContextHolder.getContext(); - Assert.assertNotNull("SecurityContext must not be null", context); - Authentication authentication = context.getAuthentication(); - Assert.assertNotNull("Authentication must not be null", authentication); - Collection authorities = authentication.getAuthorities(); - Assert.assertTrue("GrantedAuthority[] must not be null or empty", - (authorities != null && authorities.size() > 0)); - Assert.assertEquals("Unexpected authority", grantedAuthority, authorities.iterator().next()); + callbackHandler.handleUsernameTokenPrincipal(callback); + SecurityContext context = SecurityContextHolder.getContext(); + Assert.assertNotNull("SecurityContext must not be null", context); + Authentication authentication = context.getAuthentication(); + Assert.assertNotNull("Authentication must not be null", authentication); + Collection authorities = authentication.getAuthorities(); + Assert.assertTrue("GrantedAuthority[] must not be null or empty", + (authorities != null && authorities.size() > 0)); + Assert.assertEquals("Unexpected authority", grantedAuthority, authorities.iterator().next()); - verify(userDetailsService); - } + verify(userDetailsService); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBeanTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBeanTest.java index 38e23a95..ba8ca390 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBeanTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/wss4j/support/CryptoFactoryBeanTest.java @@ -28,40 +28,40 @@ import org.junit.Test; public class CryptoFactoryBeanTest { - private CryptoFactoryBean factoryBean; + private CryptoFactoryBean factoryBean; - @Before - public void setUp() throws Exception { - factoryBean = new CryptoFactoryBean(); - } + @Before + public void setUp() throws Exception { + factoryBean = new CryptoFactoryBean(); + } - @Test - public void testSetConfiguration() throws Exception { - Properties configuration = new Properties(); - configuration.setProperty("org.apache.ws.security.crypto.provider", - "org.apache.ws.security.components.crypto.Merlin"); - configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks"); - configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456"); - configuration.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks"); + @Test + public void testSetConfiguration() throws Exception { + Properties configuration = new Properties(); + configuration.setProperty("org.apache.ws.security.crypto.provider", + "org.apache.ws.security.components.crypto.Merlin"); + configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks"); + configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456"); + configuration.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks"); - factoryBean.setConfiguration(configuration); - factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader()); - factoryBean.afterPropertiesSet(); + factoryBean.setConfiguration(configuration); + factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader()); + factoryBean.afterPropertiesSet(); - Object result = factoryBean.getObject(); - Assert.assertNotNull("No result", result); - Assert.assertTrue("Not a Merlin instance", result instanceof Merlin); - } + Object result = factoryBean.getObject(); + Assert.assertNotNull("No result", result); + Assert.assertTrue("Not a Merlin instance", result instanceof Merlin); + } - @Test - public void testProperties() throws Exception { - factoryBean.setKeyStoreType("jceks"); - factoryBean.setKeyStorePassword("123456"); - factoryBean.setKeyStoreLocation(new ClassPathResource("private.jks")); - factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader()); - factoryBean.afterPropertiesSet(); - Object result = factoryBean.getObject(); - Assert.assertNotNull("No result", result); - Assert.assertTrue("Not a Merlin instance", result instanceof Merlin); - } + @Test + public void testProperties() throws Exception { + factoryBean.setKeyStoreType("jceks"); + factoryBean.setKeyStorePassword("123456"); + factoryBean.setKeyStoreLocation(new ClassPathResource("private.jks")); + factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader()); + factoryBean.afterPropertiesSet(); + Object result = factoryBean.getObject(); + Assert.assertNotNull("No result", result); + Assert.assertTrue("Not a Merlin instance", result instanceof Merlin); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorKeyStoreTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorKeyStoreTestCase.java index be9942c6..6478dda3 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorKeyStoreTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorKeyStoreTestCase.java @@ -23,26 +23,26 @@ import java.security.cert.X509Certificate; public abstract class AbstractXwssMessageInterceptorKeyStoreTestCase extends AbstractXwssMessageInterceptorTestCase { - protected X509Certificate certificate; + protected X509Certificate certificate; - protected PrivateKey privateKey; + protected PrivateKey privateKey; - @Override - protected void onSetup() throws Exception { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - InputStream is = null; - try { - is = getClass().getResourceAsStream("test-keystore.jks"); - keyStore.load(is, "password".toCharArray()); - } - finally { - if (is != null) { - is.close(); - } - } - certificate = (X509Certificate) keyStore.getCertificate("alias"); - privateKey = (PrivateKey) keyStore.getKey("alias", "password".toCharArray()); + @Override + protected void onSetup() throws Exception { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + InputStream is = null; + try { + is = getClass().getResourceAsStream("test-keystore.jks"); + keyStore.load(is, "password".toCharArray()); + } + finally { + if (is != null) { + is.close(); + } + } + certificate = (X509Certificate) keyStore.getCertificate("alias"); + privateKey = (PrivateKey) keyStore.getKey("alias", "password".toCharArray()); - } + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorTestCase.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorTestCase.java index 380f1663..9effebd0 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorTestCase.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/AbstractXwssMessageInterceptorTestCase.java @@ -40,64 +40,64 @@ import static org.junit.Assert.assertTrue; public abstract class AbstractXwssMessageInterceptorTestCase { - protected XwsSecurityInterceptor interceptor; + protected XwsSecurityInterceptor interceptor; - private MessageFactory messageFactory; + private MessageFactory messageFactory; - private Map namespaces; + private Map namespaces; - @Before - public final void setUp() throws Exception { - interceptor = new XwsSecurityInterceptor(); - messageFactory = MessageFactory.newInstance(); - namespaces = new HashMap(4); - namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); - namespaces.put("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); - namespaces.put("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); - namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); - namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#"); - onSetup(); - } + @Before + public final void setUp() throws Exception { + interceptor = new XwsSecurityInterceptor(); + messageFactory = MessageFactory.newInstance(); + namespaces = new HashMap(4); + namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); + namespaces.put("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); + namespaces.put("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); + namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); + namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#"); + onSetup(); + } - protected void assertXpathEvaluatesTo(String message, - String expectedValue, - String xpathExpression, - SOAPMessage soapMessage) { - XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces); - Document document = soapMessage.getSOAPPart(); - String actualValue = expression.evaluateAsString(document); - Assert.assertEquals(message, expectedValue, actualValue); - } + protected void assertXpathEvaluatesTo(String message, + String expectedValue, + String xpathExpression, + SOAPMessage soapMessage) { + XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces); + Document document = soapMessage.getSOAPPart(); + String actualValue = expression.evaluateAsString(document); + Assert.assertEquals(message, expectedValue, actualValue); + } - protected void assertXpathExists(String message, String xpathExpression, SOAPMessage soapMessage) { - XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces); - Document document = soapMessage.getSOAPPart(); - Node node = expression.evaluateAsNode(document); - Assert.assertNotNull(message, node); - } + protected void assertXpathExists(String message, String xpathExpression, SOAPMessage soapMessage) { + XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces); + Document document = soapMessage.getSOAPPart(); + Node node = expression.evaluateAsNode(document); + Assert.assertNotNull(message, node); + } - protected void assertXpathNotExists(String message, String xpathExpression, SOAPMessage soapMessage) { - XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces); - Document document = soapMessage.getSOAPPart(); - Node node = expression.evaluateAsNode(document); - Assert.assertNull(message, node); - } + protected void assertXpathNotExists(String message, String xpathExpression, SOAPMessage soapMessage) { + XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces); + Document document = soapMessage.getSOAPPart(); + Node node = expression.evaluateAsNode(document); + Assert.assertNull(message, node); + } - protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException { - MimeHeaders mimeHeaders = new MimeHeaders(); - mimeHeaders.addHeader("Content-Type", "text/xml"); - Resource resource = new ClassPathResource(fileName, getClass()); - InputStream is = resource.getInputStream(); - try { - assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists()); - is = resource.getInputStream(); - return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is)); - } - finally { - is.close(); - } - } + protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException { + MimeHeaders mimeHeaders = new MimeHeaders(); + mimeHeaders.addHeader("Content-Type", "text/xml"); + Resource resource = new ClassPathResource(fileName, getClass()); + InputStream is = resource.getInputStream(); + try { + assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists()); + is = resource.getInputStream(); + return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is)); + } + finally { + is.close(); + } + } - protected void onSetup() throws Exception { - } + protected void onSetup() throws Exception { + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptorTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptorTest.java index 17384606..13b72b9f 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptorTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwsSecurityInterceptorTest.java @@ -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, @@ -33,150 +33,150 @@ import static org.junit.Assert.*; public class XwsSecurityInterceptorTest { - private MessageFactory messageFactory; + private MessageFactory messageFactory; - @Before - public void setUp() throws Exception { - messageFactory = MessageFactory.newInstance(); - } + @Before + public void setUp() throws Exception { + messageFactory = MessageFactory.newInstance(); + } - @Test - public void testHandleServerRequest() throws Exception { - final SOAPMessage request = messageFactory.createMessage(); - final SOAPMessage validatedRequest = messageFactory.createMessage(); - XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { + @Test + public void testHandleServerRequest() throws Exception { + final SOAPMessage request = messageFactory.createMessage(); + final SOAPMessage validatedRequest = messageFactory.createMessage(); + XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { - @Override - protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws XwsSecuritySecurementException { - fail("secure not expected"); - } + @Override + protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws XwsSecuritySecurementException { + fail("secure not expected"); + } - @Override - protected void validateMessage(SoapMessage message, MessageContext messageContext) - throws WsSecurityValidationException { - SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message; - assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage()); - saajSoapMessage.setSaajMessage(validatedRequest); - } + @Override + protected void validateMessage(SoapMessage message, MessageContext messageContext) + throws WsSecurityValidationException { + SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message; + assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage()); + saajSoapMessage.setSaajMessage(validatedRequest); + } - }; - MessageContext context = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - interceptor.handleRequest(context, null); - assertEquals("Invalid request", validatedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage()); - } + }; + MessageContext context = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + interceptor.handleRequest(context, null); + assertEquals("Invalid request", validatedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage()); + } - @Test - public void testHandleServerResponse() throws Exception { - final SOAPMessage securedResponse = messageFactory.createMessage(); - final boolean[] cleanupCalled = new boolean[1]; - cleanupCalled[0] = false; - XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { + @Test + public void testHandleServerResponse() throws Exception { + final SOAPMessage securedResponse = messageFactory.createMessage(); + final boolean[] cleanupCalled = new boolean[1]; + cleanupCalled[0] = false; + XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { - @Override - protected void secureMessage(SoapMessage message, MessageContext messageContext) - throws XwsSecuritySecurementException { - SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message; - saajSoapMessage.setSaajMessage(securedResponse); - } + @Override + protected void secureMessage(SoapMessage message, MessageContext messageContext) + throws XwsSecuritySecurementException { + SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message; + saajSoapMessage.setSaajMessage(securedResponse); + } - @Override - protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException { - fail("validate not expected"); - } + @Override + protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException { + fail("validate not expected"); + } - @Override - protected void cleanUp() { - cleanupCalled[0] = true; - } - }; + @Override + protected void cleanUp() { + cleanupCalled[0] = true; + } + }; - SOAPMessage request = messageFactory.createMessage(); - MessageContext context = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - context.getResponse(); - interceptor.handleResponse(context, null); - interceptor.afterCompletion(context, null, null); - assertEquals("Invalid response", securedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage()); - assertTrue("Cleanup not called", cleanupCalled[0]); - } + SOAPMessage request = messageFactory.createMessage(); + MessageContext context = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + context.getResponse(); + interceptor.handleResponse(context, null); + interceptor.afterCompletion(context, null, null); + assertEquals("Invalid response", securedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage()); + assertTrue("Cleanup not called", cleanupCalled[0]); + } - @Test - public void testHandleServerFault() throws Exception { - final boolean[] cleanupCalled = new boolean[1]; - cleanupCalled[0] = false; - XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { + @Test + public void testHandleServerFault() throws Exception { + final boolean[] cleanupCalled = new boolean[1]; + cleanupCalled[0] = false; + XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { - @Override - protected void cleanUp() { - cleanupCalled[0] = true; - } - }; + @Override + protected void cleanUp() { + cleanupCalled[0] = true; + } + }; - SOAPMessage request = messageFactory.createMessage(); - MessageContext context = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - context.getResponse(); - interceptor.handleFault(context, null); - interceptor.afterCompletion(context, null, null); - assertTrue("Cleanup not called", cleanupCalled[0]); - } + SOAPMessage request = messageFactory.createMessage(); + MessageContext context = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + context.getResponse(); + interceptor.handleFault(context, null); + interceptor.afterCompletion(context, null, null); + assertTrue("Cleanup not called", cleanupCalled[0]); + } - @Test - public void testHandleClientRequest() throws Exception { - final SOAPMessage request = messageFactory.createMessage(); - final SOAPMessage securedRequest = messageFactory.createMessage(); - XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { + @Test + public void testHandleClientRequest() throws Exception { + final SOAPMessage request = messageFactory.createMessage(); + final SOAPMessage securedRequest = messageFactory.createMessage(); + XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { - @Override - protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) - throws XwsSecuritySecurementException { - SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; - assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage()); - saajSoapMessage.setSaajMessage(securedRequest); - } + @Override + protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext) + throws XwsSecuritySecurementException { + SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; + assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage()); + saajSoapMessage.setSaajMessage(securedRequest); + } - @Override - protected void validateMessage(SoapMessage message, MessageContext messageContext) - throws WsSecurityValidationException { - fail("validate not expected"); - } + @Override + protected void validateMessage(SoapMessage message, MessageContext messageContext) + throws WsSecurityValidationException { + fail("validate not expected"); + } - }; - MessageContext context = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - interceptor.handleRequest(context); - assertEquals("Invalid request", securedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage()); - } + }; + MessageContext context = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + interceptor.handleRequest(context); + assertEquals("Invalid request", securedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage()); + } - @Test - public void testHandleClientResponse() throws Exception { - final SOAPMessage validatedResponse = messageFactory.createMessage(); - XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { + @Test + public void testHandleClientResponse() throws Exception { + final SOAPMessage validatedResponse = messageFactory.createMessage(); + XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() { - @Override - protected void secureMessage(SoapMessage message, MessageContext messageContext) - throws XwsSecuritySecurementException { - fail("secure not expected"); - } + @Override + protected void secureMessage(SoapMessage message, MessageContext messageContext) + throws XwsSecuritySecurementException { + fail("secure not expected"); + } - @Override - protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) - throws WsSecurityValidationException { - SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; - saajSoapMessage.setSaajMessage(validatedResponse); - } + @Override + protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext) + throws WsSecurityValidationException { + SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage; + saajSoapMessage.setSaajMessage(validatedResponse); + } - }; - SOAPMessage request = messageFactory.createMessage(); - MessageContext context = - new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); - context.getResponse(); - interceptor.handleResponse(context); - assertEquals("Invalid response", validatedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage()); - } + }; + SOAPMessage request = messageFactory.createMessage(); + MessageContext context = + new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory)); + context.getResponse(); + interceptor.handleResponse(context); + assertEquals("Invalid response", validatedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage()); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorEncryptTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorEncryptTest.java index 232aee2a..3cb9270e 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorEncryptTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorEncryptTest.java @@ -33,112 +33,112 @@ import static org.junit.Assert.*; public class XwssMessageInterceptorEncryptTest extends AbstractXwssMessageInterceptorKeyStoreTestCase { - @Test - @Ignore("Does not run under JDK 1.8") - public void encryptDefaultCertificate() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + @Ignore("Does not run under JDK 1.8") + public void encryptDefaultCertificate() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof EncryptionKeyCallback) { - EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback; - if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) { - EncryptionKeyCallback.AliasX509CertificateRequest request = - (EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest(); - assertEquals("Invalid alias", "", request.getAlias()); - request.setX509Certificate(certificate); - } - else { - fail("Unexpected request"); - } - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathExists("BinarySecurityToken does not exist", - "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); - assertXpathExists("Signature does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof EncryptionKeyCallback) { + EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback; + if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) { + EncryptionKeyCallback.AliasX509CertificateRequest request = + (EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest(); + assertEquals("Invalid alias", "", request.getAlias()); + request.setX509Certificate(certificate); + } + else { + fail("Unexpected request"); + } + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathExists("BinarySecurityToken does not exist", + "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); + assertXpathExists("Signature does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result); + } - @Test - @Ignore("Does not run under JDK 1.8") - public void encryptAlias() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-alias-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + @Ignore("Does not run under JDK 1.8") + public void encryptAlias() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-alias-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof EncryptionKeyCallback) { - EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback; - if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) { - EncryptionKeyCallback.AliasX509CertificateRequest request = - (EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest(); - assertEquals("Invalid alias", "alias", request.getAlias()); - request.setX509Certificate(certificate); - } - else { - fail("Unexpected request"); - } - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathExists("BinarySecurityToken does not exist", - "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); - assertXpathExists("Signature does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof EncryptionKeyCallback) { + EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback; + if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) { + EncryptionKeyCallback.AliasX509CertificateRequest request = + (EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest(); + assertEquals("Invalid alias", "alias", request.getAlias()); + request.setX509Certificate(certificate); + } + else { + fail("Unexpected request"); + } + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathExists("BinarySecurityToken does not exist", + "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); + assertXpathExists("Signature does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result); + } - @Test - @Ignore("Does not run under JDK 1.8") - public void testDecrypt() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("decrypt-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + @Ignore("Does not run under JDK 1.8") + public void testDecrypt() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("decrypt-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof DecryptionKeyCallback) { - DecryptionKeyCallback keyCallback = (DecryptionKeyCallback) callback; - if (keyCallback.getRequest() instanceof DecryptionKeyCallback.X509CertificateBasedRequest) { - DecryptionKeyCallback.X509CertificateBasedRequest request = - (DecryptionKeyCallback.X509CertificateBasedRequest) keyCallback.getRequest(); - assertEquals("Invalid certificate", certificate, request.getX509Certificate()); - request.setPrivateKey(privateKey); - } - else { - fail("Unexpected request"); - } - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("encrypted-soap.xml"); - interceptor.validateMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof DecryptionKeyCallback) { + DecryptionKeyCallback keyCallback = (DecryptionKeyCallback) callback; + if (keyCallback.getRequest() instanceof DecryptionKeyCallback.X509CertificateBasedRequest) { + DecryptionKeyCallback.X509CertificateBasedRequest request = + (DecryptionKeyCallback.X509CertificateBasedRequest) keyCallback.getRequest(); + assertEquals("Invalid certificate", certificate, request.getX509Certificate()); + request.setPrivateKey(privateKey); + } + else { + fail("Unexpected request"); + } + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("encrypted-soap.xml"); + interceptor.validateMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorSignTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorSignTest.java index a21ba904..d029debd 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorSignTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorSignTest.java @@ -33,107 +33,107 @@ import static org.junit.Assert.*; public class XwssMessageInterceptorSignTest extends AbstractXwssMessageInterceptorKeyStoreTestCase { - @Test - public void testSignDefaultCertificate() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("sign-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + public void testSignDefaultCertificate() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("sign-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof SignatureKeyCallback) { - SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback; - if (keyCallback.getRequest() instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) { - SignatureKeyCallback.DefaultPrivKeyCertRequest request = - (SignatureKeyCallback.DefaultPrivKeyCertRequest) keyCallback.getRequest(); - request.setX509Certificate(certificate); - request.setPrivateKey(privateKey); - } - else { - fail("Unexpected request"); - } - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathExists("BinarySecurityToken does not exist", - "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); - assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", - result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof SignatureKeyCallback) { + SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback; + if (keyCallback.getRequest() instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) { + SignatureKeyCallback.DefaultPrivKeyCertRequest request = + (SignatureKeyCallback.DefaultPrivKeyCertRequest) keyCallback.getRequest(); + request.setX509Certificate(certificate); + request.setPrivateKey(privateKey); + } + else { + fail("Unexpected request"); + } + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathExists("BinarySecurityToken does not exist", + "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); + assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", + result); + } - @Test - public void testSignAlias() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("sign-alias-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + public void testSignAlias() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("sign-alias-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof SignatureKeyCallback) { - SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback; - if (keyCallback.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) { - SignatureKeyCallback.AliasPrivKeyCertRequest request = - (SignatureKeyCallback.AliasPrivKeyCertRequest) keyCallback.getRequest(); - assertEquals("Invalid alias", "alias", request.getAlias()); - request.setX509Certificate(certificate); - request.setPrivateKey(privateKey); - } - else { - fail("Unexpected request"); - } - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathExists("BinarySecurityToken does not exist", - "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); - assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", - result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof SignatureKeyCallback) { + SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback; + if (keyCallback.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) { + SignatureKeyCallback.AliasPrivKeyCertRequest request = + (SignatureKeyCallback.AliasPrivKeyCertRequest) keyCallback.getRequest(); + assertEquals("Invalid alias", "alias", request.getAlias()); + request.setX509Certificate(certificate); + request.setPrivateKey(privateKey); + } + else { + fail("Unexpected request"); + } + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathExists("BinarySecurityToken does not exist", + "SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result); + assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", + result); + } - @Test - public void testValidateCertificate() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("requireSignature-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + public void testValidateCertificate() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("requireSignature-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof CertificateValidationCallback) { - CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback; - validationCallback.setValidator(new CertificateValidationCallback.CertificateValidator() { - public boolean validate(X509Certificate passedCertificate) { - assertEquals("Invalid certificate", certificate, passedCertificate); - return true; - } - }); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("signed-soap.xml"); - interceptor.validateMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof CertificateValidationCallback) { + CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback; + validationCallback.setValidator(new CertificateValidationCallback.CertificateValidator() { + public boolean validate(X509Certificate passedCertificate) { + assertEquals("Invalid certificate", certificate, passedCertificate); + return true; + } + }); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("signed-soap.xml"); + interceptor.validateMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorUsernameTokenTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorUsernameTokenTest.java index f58e4ba5..b62303a5 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorUsernameTokenTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/XwssMessageInterceptorUsernameTokenTest.java @@ -35,244 +35,244 @@ import static org.junit.Assert.*; public class XwssMessageInterceptorUsernameTokenTest extends AbstractXwssMessageInterceptorTestCase { - @Test + @Test public void testAddUsernameTokenDigest() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-digest-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-digest-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof UsernameCallback) { - ((UsernameCallback) callback).setUsername("Bert"); - } - else if (callback instanceof PasswordCallback) { - PasswordCallback passwordCallback = (PasswordCallback) callback; - passwordCallback.setPassword("Ernie"); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathEvaluatesTo("Invalid Username", "Bert", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", - result); - assertXpathExists("Password does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']", - result); - assertXpathExists("Nonce does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce", - result); - assertXpathExists("Created does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created", - result); - } - - @Test - public void testAddUsernameTokenPlainText() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-plainText-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { - - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof UsernameCallback) { - ((UsernameCallback) callback).setUsername("Bert"); - } - else if (callback instanceof PasswordCallback) { - PasswordCallback passwordCallback = (PasswordCallback) callback; - passwordCallback.setPassword("Ernie"); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathEvaluatesTo("Invalid Username", "Bert", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", result); - assertXpathEvaluatesTo("Invalid Password", "Ernie", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()", - result); - } - - @Test - public void testAddUsernameTokenPlainTextNonce() throws Exception { - interceptor.setPolicyConfiguration( - new ClassPathResource("usernameToken-plainText-nonce-config.xml", - getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { - - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof UsernameCallback) { - ((UsernameCallback) callback).setUsername("Bert"); - } - else if (callback instanceof PasswordCallback) { - PasswordCallback passwordCallback = (PasswordCallback) callback; - passwordCallback.setPassword("Ernie"); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); - interceptor.secureMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathEvaluatesTo("Invalid Username", "Bert", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", - result); - assertXpathEvaluatesTo("Invalid Password", "Ernie", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()", - result); - assertXpathExists("Nonce does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce", - result); - assertXpathExists("Created does not exist", - "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created", - result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof UsernameCallback) { + ((UsernameCallback) callback).setUsername("Bert"); + } + else if (callback instanceof PasswordCallback) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword("Ernie"); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathEvaluatesTo("Invalid Username", "Bert", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", + result); + assertXpathExists("Password does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']", + result); + assertXpathExists("Nonce does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce", + result); + assertXpathExists("Created does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created", + result); + } @Test - public void testValidateUsernameTokenPlainText() throws Exception { - interceptor - .setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + public void testAddUsernameTokenPlainText() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-plainText-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; - validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() { - public boolean validate(PasswordValidationCallback.Request request) { - if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) { - PasswordValidationCallback.PlainTextPasswordRequest passwordRequest = - (PasswordValidationCallback.PlainTextPasswordRequest) request; - assertEquals("Invalid username", "Bert", passwordRequest.getUsername()); - assertEquals("Invalid password", "Ernie", passwordRequest.getPassword()); - return true; - } - else { - fail("Unexpected request"); - return false; - } - } - }); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-soap.xml"); - interceptor.validateMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof UsernameCallback) { + ((UsernameCallback) callback).setUsername("Bert"); + } + else if (callback instanceof PasswordCallback) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword("Ernie"); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathEvaluatesTo("Invalid Username", "Bert", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", result); + assertXpathEvaluatesTo("Invalid Password", "Ernie", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()", + result); + } - @Test - public void testValidateUsernameTokenPlainTextNonce() throws Exception { - interceptor - .setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-nonce-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + public void testAddUsernameTokenPlainTextNonce() throws Exception { + interceptor.setPolicyConfiguration( + new ClassPathResource("usernameToken-plainText-nonce-config.xml", + getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; - validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() { - public boolean validate(PasswordValidationCallback.Request request) { - if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) { - PasswordValidationCallback.PlainTextPasswordRequest passwordRequest = - (PasswordValidationCallback.PlainTextPasswordRequest) request; - assertEquals("Invalid username", "Bert", passwordRequest.getUsername()); - assertEquals("Invalid password", "Ernie", passwordRequest.getPassword()); - return true; - } - else { - fail("Unexpected request"); - return false; - } - } - }); - } - else if (callback instanceof TimestampValidationCallback) { - TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback; - validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() { - public void validate(TimestampValidationCallback.Request request) { - } - }); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-nonce-soap.xml"); - interceptor.validateMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof UsernameCallback) { + ((UsernameCallback) callback).setUsername("Bert"); + } + else if (callback instanceof PasswordCallback) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword("Ernie"); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("empty-soap.xml"); + interceptor.secureMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathEvaluatesTo("Invalid Username", "Bert", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", + result); + assertXpathEvaluatesTo("Invalid Password", "Ernie", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()", + result); + assertXpathExists("Nonce does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce", + result); + assertXpathExists("Created does not exist", + "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created", + result); + } - @Test - public void testValidateUsernameTokenDigest() throws Exception { - interceptor.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-digest-config.xml", getClass())); - CallbackHandler handler = new AbstractCallbackHandler() { + @Test + public void testValidateUsernameTokenPlainText() throws Exception { + interceptor + .setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { - @Override - protected void handleInternal(Callback callback) { - if (callback instanceof PasswordValidationCallback) { - PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; - if (validationCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) { - PasswordValidationCallback.DigestPasswordRequest passwordRequest = - (PasswordValidationCallback.DigestPasswordRequest) validationCallback.getRequest(); - assertEquals("Invalid username", "Bert", passwordRequest.getUsername()); - passwordRequest.setPassword("Ernie"); - validationCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator()); - } - else { - fail("Unexpected request"); - } - } - else if (callback instanceof TimestampValidationCallback) { - TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback; - validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() { - public void validate(TimestampValidationCallback.Request request) { - } - }); - } - else { - fail("Unexpected callback"); - } - } - }; - interceptor.setCallbackHandler(handler); - interceptor.afterPropertiesSet(); - SaajSoapMessage message = loadSaajMessage("usernameTokenDigest-soap.xml"); - interceptor.validateMessage(message, null); - SOAPMessage result = message.getSaajMessage(); - assertNotNull("No result returned", result); - assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); - } + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; + validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() { + public boolean validate(PasswordValidationCallback.Request request) { + if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) { + PasswordValidationCallback.PlainTextPasswordRequest passwordRequest = + (PasswordValidationCallback.PlainTextPasswordRequest) request; + assertEquals("Invalid username", "Bert", passwordRequest.getUsername()); + assertEquals("Invalid password", "Ernie", passwordRequest.getPassword()); + return true; + } + else { + fail("Unexpected request"); + return false; + } + } + }); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-soap.xml"); + interceptor.validateMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); + } + + @Test + public void testValidateUsernameTokenPlainTextNonce() throws Exception { + interceptor + .setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-nonce-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { + + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; + validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() { + public boolean validate(PasswordValidationCallback.Request request) { + if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) { + PasswordValidationCallback.PlainTextPasswordRequest passwordRequest = + (PasswordValidationCallback.PlainTextPasswordRequest) request; + assertEquals("Invalid username", "Bert", passwordRequest.getUsername()); + assertEquals("Invalid password", "Ernie", passwordRequest.getPassword()); + return true; + } + else { + fail("Unexpected request"); + return false; + } + } + }); + } + else if (callback instanceof TimestampValidationCallback) { + TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback; + validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() { + public void validate(TimestampValidationCallback.Request request) { + } + }); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-nonce-soap.xml"); + interceptor.validateMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); + } + + @Test + public void testValidateUsernameTokenDigest() throws Exception { + interceptor.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-digest-config.xml", getClass())); + CallbackHandler handler = new AbstractCallbackHandler() { + + @Override + protected void handleInternal(Callback callback) { + if (callback instanceof PasswordValidationCallback) { + PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback; + if (validationCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) { + PasswordValidationCallback.DigestPasswordRequest passwordRequest = + (PasswordValidationCallback.DigestPasswordRequest) validationCallback.getRequest(); + assertEquals("Invalid username", "Bert", passwordRequest.getUsername()); + passwordRequest.setPassword("Ernie"); + validationCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator()); + } + else { + fail("Unexpected request"); + } + } + else if (callback instanceof TimestampValidationCallback) { + TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback; + validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() { + public void validate(TimestampValidationCallback.Request request) { + } + }); + } + else { + fail("Unexpected callback"); + } + } + }; + interceptor.setCallbackHandler(handler); + interceptor.afterPropertiesSet(); + SaajSoapMessage message = loadSaajMessage("usernameTokenDigest-soap.xml"); + interceptor.validateMessage(message, null); + SOAPMessage result = message.getSaajMessage(); + assertNotNull("No result returned", result); + assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidatorTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidatorTest.java index 25c875af..b3102378 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidatorTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/DefaultTimestampValidatorTest.java @@ -22,24 +22,24 @@ import org.junit.Test; public class DefaultTimestampValidatorTest { - private DefaultTimestampValidator validator; + private DefaultTimestampValidator validator; - @Before - public void setUp() throws Exception { - validator = new DefaultTimestampValidator(); - } + @Before + public void setUp() throws Exception { + validator = new DefaultTimestampValidator(); + } - @Test - public void testValidate() throws Exception { - TimestampValidationCallback.Request request = new TimestampValidationCallback.UTCTimestampRequest( - "2006-09-25T20:42:50Z", "2107-09-25T20:42:50Z", 100, Long.MAX_VALUE); - validator.validate(request); - } + @Test + public void testValidate() throws Exception { + TimestampValidationCallback.Request request = new TimestampValidationCallback.UTCTimestampRequest( + "2006-09-25T20:42:50Z", "2107-09-25T20:42:50Z", 100, Long.MAX_VALUE); + validator.validate(request); + } - @Test - public void testValidateNoExpired() throws Exception { - TimestampValidationCallback.Request request = - new TimestampValidationCallback.UTCTimestampRequest("2006-09-25T20:42:50Z", null, 100, Long.MAX_VALUE); - validator.validate(request); - } + @Test + public void testValidateNoExpired() throws Exception { + TimestampValidationCallback.Request request = + new TimestampValidationCallback.UTCTimestampRequest("2006-09-25T20:42:50Z", null, 100, Long.MAX_VALUE); + validator.validate(request); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandlerTest.java index 6310eb6f..5725a697 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/KeyStoreCallbackHandlerTest.java @@ -21,17 +21,17 @@ import org.junit.Test; public class KeyStoreCallbackHandlerTest { - private KeyStoreCallbackHandler handler; + private KeyStoreCallbackHandler handler; - @Before - public void setUp() throws Exception { - handler = new KeyStoreCallbackHandler(); - } + @Before + public void setUp() throws Exception { + handler = new KeyStoreCallbackHandler(); + } - @Test - public void testLoadDefaultTrustStore() throws Exception { - System.setProperty("javax.net.ssl.trustStore", - "/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/"); - handler.loadDefaultTrustStore(); - } + @Test + public void testLoadDefaultTrustStore() throws Exception { + System.setProperty("javax.net.ssl.trustStore", + "/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/"); + handler.loadDefaultTrustStore(); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandlerTest.java index 3a85192d..1c6985f7 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimplePasswordValidationCallbackHandlerTest.java @@ -25,73 +25,73 @@ import org.junit.Test; public class SimplePasswordValidationCallbackHandlerTest { - private SimplePasswordValidationCallbackHandler handler; + private SimplePasswordValidationCallbackHandler handler; - @Before - public void setUp() throws Exception { - handler = new SimplePasswordValidationCallbackHandler(); - Properties users = new Properties(); - users.setProperty("Bert", "Ernie"); - handler.setUsers(users); - } + @Before + public void setUp() throws Exception { + handler = new SimplePasswordValidationCallbackHandler(); + Properties users = new Properties(); + users.setProperty("Bert", "Ernie"); + handler.setUsers(users); + } - @Test - public void testPlainTextPasswordValid() throws Exception { - PasswordValidationCallback.PlainTextPasswordRequest request = - new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie"); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - handler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Not authenticated", authenticated); - } + @Test + public void testPlainTextPasswordValid() throws Exception { + PasswordValidationCallback.PlainTextPasswordRequest request = + new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie"); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + handler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Not authenticated", authenticated); + } - @Test - public void testPlainTextPasswordInvalid() throws Exception { - PasswordValidationCallback.PlainTextPasswordRequest request = - new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird"); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - handler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - } + @Test + public void testPlainTextPasswordInvalid() throws Exception { + PasswordValidationCallback.PlainTextPasswordRequest request = + new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird"); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + handler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + } - @Test - public void testPlainTextPasswordNoSuchUser() throws Exception { - PasswordValidationCallback.PlainTextPasswordRequest request = - new PasswordValidationCallback.PlainTextPasswordRequest("Big bird", "Bert"); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - handler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - } + @Test + public void testPlainTextPasswordNoSuchUser() throws Exception { + PasswordValidationCallback.PlainTextPasswordRequest request = + new PasswordValidationCallback.PlainTextPasswordRequest("Big bird", "Bert"); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + handler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + } - @Test - public void testDigestPasswordValid() throws Exception { - String username = "Bert"; - String nonce = "9mdsYDCrjjYRur0rxzYt2oD7"; - String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk="; - String creationTime = "2006-06-01T23:48:42Z"; - PasswordValidationCallback.DigestPasswordRequest request = - new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - handler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Authenticated", authenticated); + @Test + public void testDigestPasswordValid() throws Exception { + String username = "Bert"; + String nonce = "9mdsYDCrjjYRur0rxzYt2oD7"; + String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk="; + String creationTime = "2006-06-01T23:48:42Z"; + PasswordValidationCallback.DigestPasswordRequest request = + new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + handler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Authenticated", authenticated); - } + } - @Test - public void testDigestPasswordInvalid() throws Exception { - String username = "Bert"; - String nonce = "9mdsYDCrjjYRur0rxzYt2oD7"; - String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk"; - String creationTime = "2006-06-01T23:48:42Z"; - PasswordValidationCallback.DigestPasswordRequest request = - new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - handler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); + @Test + public void testDigestPasswordInvalid() throws Exception { + String username = "Bert"; + String nonce = "9mdsYDCrjjYRur0rxzYt2oD7"; + String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk"; + String creationTime = "2006-06-01T23:48:42Z"; + PasswordValidationCallback.DigestPasswordRequest request = + new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + handler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); - } + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandlerTest.java index b0494e3f..6e160e99 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SimpleUsernamePasswordCallbackHandlerTest.java @@ -24,26 +24,26 @@ import org.junit.Test; public class SimpleUsernamePasswordCallbackHandlerTest { - private SimpleUsernamePasswordCallbackHandler handler; + private SimpleUsernamePasswordCallbackHandler handler; - @Before - public void setUp() throws Exception { - handler = new SimpleUsernamePasswordCallbackHandler(); - handler.setUsername("Bert"); - handler.setPassword("Ernie"); - } + @Before + public void setUp() throws Exception { + handler = new SimpleUsernamePasswordCallbackHandler(); + handler.setUsername("Bert"); + handler.setPassword("Ernie"); + } - @Test - public void testUsernameCallback() throws Exception { - UsernameCallback usernameCallback = new UsernameCallback(); - handler.handleInternal(usernameCallback); - Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername()); - } + @Test + public void testUsernameCallback() throws Exception { + UsernameCallback usernameCallback = new UsernameCallback(); + handler.handleInternal(usernameCallback); + Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername()); + } - @Test - public void testPasswordCallback() throws Exception { - PasswordCallback passwordCallback = new PasswordCallback(); - handler.handleInternal(passwordCallback); - Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword()); - } + @Test + public void testPasswordCallback() throws Exception { + PasswordCallback passwordCallback = new PasswordCallback(); + handler.handleInternal(passwordCallback); + Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword()); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandlerTest.java index 310384b7..9633534d 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringCertificateValidationCallbackHandlerTest.java @@ -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, @@ -40,78 +40,78 @@ import static org.easymock.EasyMock.*; public class SpringCertificateValidationCallbackHandlerTest { - private SpringCertificateValidationCallbackHandler callbackHandler; + private SpringCertificateValidationCallbackHandler callbackHandler; - private AuthenticationManager authenticationManager; + private AuthenticationManager authenticationManager; - private X509Certificate certificate; + private X509Certificate certificate; - private CertificateValidationCallback callback; + private CertificateValidationCallback callback; - @Before - public void setUp() throws Exception { - callbackHandler = new SpringCertificateValidationCallbackHandler(); - authenticationManager = createMock(AuthenticationManager.class); - callbackHandler.setAuthenticationManager(authenticationManager); - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - InputStream is = null; - try { - is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream(); - keyStore.load(is, "password".toCharArray()); - } - finally { - if (is != null) { - is.close(); - } - } - certificate = (X509Certificate) keyStore.getCertificate("alias"); - callback = new CertificateValidationCallback(certificate); - } + @Before + public void setUp() throws Exception { + callbackHandler = new SpringCertificateValidationCallbackHandler(); + authenticationManager = createMock(AuthenticationManager.class); + callbackHandler.setAuthenticationManager(authenticationManager); + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + InputStream is = null; + try { + is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream(); + keyStore.load(is, "password".toCharArray()); + } + finally { + if (is != null) { + is.close(); + } + } + certificate = (X509Certificate) keyStore.getCertificate("alias"); + callback = new CertificateValidationCallback(certificate); + } - @After - public void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } + @After + public void tearDown() throws Exception { + SecurityContextHolder.clearContext(); + } - @Test - public void testValidateCertificateValid() throws Exception { - expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class))) - .andReturn(new TestingAuthenticationToken(certificate, null, Collections.emptyList())); + @Test + public void testValidateCertificateValid() throws Exception { + expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class))) + .andReturn(new TestingAuthenticationToken(certificate, null, Collections.emptyList())); - replay(authenticationManager); + replay(authenticationManager); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Not authenticated", authenticated); - Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Not authenticated", authenticated); + Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(authenticationManager); - } + verify(authenticationManager); + } - @Test - public void testValidateCertificateInvalid() throws Exception { - expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class))) - .andThrow(new BadCredentialsException("")); + @Test + public void testValidateCertificateInvalid() throws Exception { + expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class))) + .andThrow(new BadCredentialsException("")); - replay(authenticationManager); + replay(authenticationManager); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(authenticationManager); - } + verify(authenticationManager); + } - @Test - public void testCleanUp() throws Exception { - TestingAuthenticationToken authentication = - new TestingAuthenticationToken(new Object(), new Object(), Collections.emptyList()); - SecurityContextHolder.getContext().setAuthentication(authentication); + @Test + public void testCleanUp() throws Exception { + TestingAuthenticationToken authentication = + new TestingAuthenticationToken(new Object(), new Object(), Collections.emptyList()); + SecurityContextHolder.getContext().setAuthentication(authentication); - CleanupCallback cleanupCallback = new CleanupCallback(); - callbackHandler.handleInternal(cleanupCallback); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - } + CleanupCallback cleanupCallback = new CleanupCallback(); + callbackHandler.handleInternal(cleanupCallback); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandlerTest.java index 50165912..f89bae2a 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringDigestPasswordValidationCallbackHandlerTest.java @@ -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, @@ -37,105 +37,105 @@ import static org.easymock.EasyMock.*; public class SpringDigestPasswordValidationCallbackHandlerTest { - private SpringDigestPasswordValidationCallbackHandler callbackHandler; + private SpringDigestPasswordValidationCallbackHandler callbackHandler; - private UserDetailsService userDetailsService; + private UserDetailsService userDetailsService; - private String username; + private String username; - private String password; + private String password; - private PasswordValidationCallback callback; + private PasswordValidationCallback callback; - @Before - public void setUp() throws Exception { - callbackHandler = new SpringDigestPasswordValidationCallbackHandler(); - userDetailsService = createMock(UserDetailsService.class); - callbackHandler.setUserDetailsService(userDetailsService); - username = "Bert"; - password = "Ernie"; - String nonce = "9mdsYDCrjjYRur0rxzYt2oD7"; - String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk="; - String creationTime = "2006-06-01T23:48:42Z"; - PasswordValidationCallback.DigestPasswordRequest request = - new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime); - callback = new PasswordValidationCallback(request); - } + @Before + public void setUp() throws Exception { + callbackHandler = new SpringDigestPasswordValidationCallbackHandler(); + userDetailsService = createMock(UserDetailsService.class); + callbackHandler.setUserDetailsService(userDetailsService); + username = "Bert"; + password = "Ernie"; + String nonce = "9mdsYDCrjjYRur0rxzYt2oD7"; + String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk="; + String creationTime = "2006-06-01T23:48:42Z"; + PasswordValidationCallback.DigestPasswordRequest request = + new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime); + callback = new PasswordValidationCallback(request); + } - @After - public void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } + @After + public void tearDown() throws Exception { + SecurityContextHolder.clearContext(); + } - @Test - public void testAuthenticateUserDigestUserNotFound() throws Exception { - expect(userDetailsService.loadUserByUsername(username)).andThrow(new UsernameNotFoundException(username)); + @Test + public void testAuthenticateUserDigestUserNotFound() throws Exception { + expect(userDetailsService.loadUserByUsername(username)).andThrow(new UsernameNotFoundException(username)); - replay(userDetailsService); + replay(userDetailsService); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(userDetailsService); - } + verify(userDetailsService); + } - @Test - public void testAuthenticateUserDigestValid() throws Exception { - User user = new User(username, password, true, true, true, true, Collections.emptyList()); - expect(userDetailsService.loadUserByUsername(username)).andReturn(user); + @Test + public void testAuthenticateUserDigestValid() throws Exception { + User user = new User(username, password, true, true, true, true, Collections.emptyList()); + expect(userDetailsService.loadUserByUsername(username)).andReturn(user); - replay(userDetailsService); + replay(userDetailsService); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Not authenticated", authenticated); - Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Not authenticated", authenticated); + Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(userDetailsService); - } + verify(userDetailsService); + } - @Test - public void testAuthenticateUserDigestValidInvalid() throws Exception { - User user = new User(username, "Big bird", true, true, true, true, Collections.emptyList()); - expect(userDetailsService.loadUserByUsername(username)).andReturn(user); + @Test + public void testAuthenticateUserDigestValidInvalid() throws Exception { + User user = new User(username, "Big bird", true, true, true, true, Collections.emptyList()); + expect(userDetailsService.loadUserByUsername(username)).andReturn(user); - replay(userDetailsService); + replay(userDetailsService); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(userDetailsService); - } + verify(userDetailsService); + } - @Test - public void testAuthenticateUserDigestDisabled() throws Exception { - User user = new User(username, "Ernie", false, true, true, true, Collections.emptyList()); - expect(userDetailsService.loadUserByUsername(username)).andReturn(user); + @Test + public void testAuthenticateUserDigestDisabled() throws Exception { + User user = new User(username, "Ernie", false, true, true, true, Collections.emptyList()); + expect(userDetailsService.loadUserByUsername(username)).andReturn(user); - replay(userDetailsService); + replay(userDetailsService); - try { - callbackHandler.handleInternal(callback); - Assert.fail("disabled user authenticated"); - } catch (DisabledException expected) { - // expected - } - verify(userDetailsService); - } + try { + callbackHandler.handleInternal(callback); + Assert.fail("disabled user authenticated"); + } catch (DisabledException expected) { + // expected + } + verify(userDetailsService); + } - @Test - public void testCleanUp() throws Exception { - TestingAuthenticationToken authentication = - new TestingAuthenticationToken(new Object(), new Object(), Collections.emptyList()); - SecurityContextHolder.getContext().setAuthentication(authentication); + @Test + public void testCleanUp() throws Exception { + TestingAuthenticationToken authentication = + new TestingAuthenticationToken(new Object(), new Object(), Collections.emptyList()); + SecurityContextHolder.getContext().setAuthentication(authentication); - CleanupCallback cleanupCallback = new CleanupCallback(); - callbackHandler.handleInternal(cleanupCallback); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - } + CleanupCallback cleanupCallback = new CleanupCallback(); + callbackHandler.handleInternal(cleanupCallback); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandlerTest.java index d7a96c93..42f54d07 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringPlainTextPasswordValidationCallbackHandlerTest.java @@ -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, @@ -37,72 +37,72 @@ import static org.easymock.EasyMock.*; public class SpringPlainTextPasswordValidationCallbackHandlerTest { - private SpringPlainTextPasswordValidationCallbackHandler callbackHandler; + private SpringPlainTextPasswordValidationCallbackHandler callbackHandler; - private AuthenticationManager authenticationManager; + private AuthenticationManager authenticationManager; - private PasswordValidationCallback callback; + private PasswordValidationCallback callback; - private String username; + private String username; - private String password; + private String password; - @Before - public void setUp() throws Exception { - callbackHandler = new SpringPlainTextPasswordValidationCallbackHandler(); - authenticationManager = createMock(AuthenticationManager.class); - callbackHandler.setAuthenticationManager(authenticationManager); - username = "Bert"; - password = "Ernie"; - PasswordValidationCallback.PlainTextPasswordRequest request = - new PasswordValidationCallback.PlainTextPasswordRequest(username, password); - callback = new PasswordValidationCallback(request); - } + @Before + public void setUp() throws Exception { + callbackHandler = new SpringPlainTextPasswordValidationCallbackHandler(); + authenticationManager = createMock(AuthenticationManager.class); + callbackHandler.setAuthenticationManager(authenticationManager); + username = "Bert"; + password = "Ernie"; + PasswordValidationCallback.PlainTextPasswordRequest request = + new PasswordValidationCallback.PlainTextPasswordRequest(username, password); + callback = new PasswordValidationCallback(request); + } - @After - public void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } + @After + public void tearDown() throws Exception { + SecurityContextHolder.clearContext(); + } - @Test - public void testAuthenticateUserPlainTextValid() throws Exception { - Authentication authResult = new TestingAuthenticationToken(username, password, Collections - .emptyList()); - expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andReturn(authResult); + @Test + public void testAuthenticateUserPlainTextValid() throws Exception { + Authentication authResult = new TestingAuthenticationToken(username, password, Collections + .emptyList()); + expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andReturn(authResult); - replay(authenticationManager); + replay(authenticationManager); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Not authenticated", authenticated); - Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Not authenticated", authenticated); + Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(authenticationManager); - } + verify(authenticationManager); + } - @Test - public void testAuthenticateUserPlainTextInvalid() throws Exception { - expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andThrow(new BadCredentialsException("")); + @Test + public void testAuthenticateUserPlainTextInvalid() throws Exception { + expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andThrow(new BadCredentialsException("")); - replay(authenticationManager); + replay(authenticationManager); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - verify(authenticationManager); - } + verify(authenticationManager); + } - @Test - public void testCleanUp() throws Exception { - TestingAuthenticationToken authentication = - new TestingAuthenticationToken(new Object(), new Object(), Collections.emptyList()); - SecurityContextHolder.getContext().setAuthentication(authentication); + @Test + public void testCleanUp() throws Exception { + TestingAuthenticationToken authentication = + new TestingAuthenticationToken(new Object(), new Object(), Collections.emptyList()); + SecurityContextHolder.getContext().setAuthentication(authentication); - CleanupCallback cleanupCallback = new CleanupCallback(); - callbackHandler.handleInternal(cleanupCallback); - Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); - } + CleanupCallback cleanupCallback = new CleanupCallback(); + callbackHandler.handleInternal(cleanupCallback); + Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication()); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandlerTest.java index e310d9ed..e4d56e4c 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/SpringUsernamePasswordCallbackHandlerTest.java @@ -29,31 +29,31 @@ import org.junit.Test; public class SpringUsernamePasswordCallbackHandlerTest { - private SpringUsernamePasswordCallbackHandler handler; + private SpringUsernamePasswordCallbackHandler handler; - @Before - public void setUp() throws Exception { - handler = new SpringUsernamePasswordCallbackHandler(); - Authentication authentication = new UsernamePasswordAuthenticationToken("Bert", "Ernie"); - SecurityContextHolder.getContext().setAuthentication(authentication); - } + @Before + public void setUp() throws Exception { + handler = new SpringUsernamePasswordCallbackHandler(); + Authentication authentication = new UsernamePasswordAuthenticationToken("Bert", "Ernie"); + SecurityContextHolder.getContext().setAuthentication(authentication); + } - @After - public void tearDown() throws Exception { - SecurityContextHolder.clearContext(); - } + @After + public void tearDown() throws Exception { + SecurityContextHolder.clearContext(); + } - @Test - public void testUsernameCallback() throws Exception { - UsernameCallback usernameCallback = new UsernameCallback(); - handler.handleInternal(usernameCallback); - Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername()); - } + @Test + public void testUsernameCallback() throws Exception { + UsernameCallback usernameCallback = new UsernameCallback(); + handler.handleInternal(usernameCallback); + Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername()); + } - @Test - public void testPasswordCallback() throws Exception { - PasswordCallback passwordCallback = new PasswordCallback(); - handler.handleInternal(passwordCallback); - Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword()); - } + @Test + public void testPasswordCallback() throws Exception { + PasswordCallback passwordCallback = new PasswordCallback(); + handler.handleInternal(passwordCallback); + Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword()); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/CertificateLoginModule.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/CertificateLoginModule.java index a2055137..585bc5a2 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/CertificateLoginModule.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/CertificateLoginModule.java @@ -26,59 +26,59 @@ import javax.security.auth.x500.X500Principal; public class CertificateLoginModule implements LoginModule { - private Subject subject; + private Subject subject; - private boolean loginSuccessful = false; + private boolean loginSuccessful = false; - @Override - public boolean abort() { - return true; - } + @Override + public boolean abort() { + return true; + } - @Override - public boolean commit() { - if (!loginSuccessful) { - subject.getPrincipals().clear(); - subject.getPrivateCredentials().clear(); - return false; - } - return true; - } + @Override + public boolean commit() { + if (!loginSuccessful) { + subject.getPrincipals().clear(); + subject.getPrivateCredentials().clear(); + return false; + } + return true; + } - @Override - public void initialize(Subject subject, - CallbackHandler callbackHandler, - java.util.Map sharedState, - java.util.Map options) { - this.subject = subject; - } + @Override + public void initialize(Subject subject, + CallbackHandler callbackHandler, + java.util.Map sharedState, + java.util.Map options) { + this.subject = subject; + } - @Override - public boolean login() throws LoginException { - if (subject == null) { - return false; - } + @Override + public boolean login() throws LoginException { + if (subject == null) { + return false; + } - String name = getName(subject); + String name = getName(subject); - loginSuccessful = "CN=Arjen Poutsma,OU=Spring-WS,O=Interface21,L=Amsterdam,ST=Unknown,C=NL".equals(name); - return loginSuccessful; - } + loginSuccessful = "CN=Arjen Poutsma,OU=Spring-WS,O=Interface21,L=Amsterdam,ST=Unknown,C=NL".equals(name); + return loginSuccessful; + } - @Override - public boolean logout() { - subject.getPrincipals().clear(); - subject.getPrivateCredentials().clear(); - return true; - } + @Override + public boolean logout() { + subject.getPrincipals().clear(); + subject.getPrivateCredentials().clear(); + return true; + } - private String getName(Subject subject) { - for (Iterator iterator = subject.getPrincipals().iterator(); iterator.hasNext();) { - Principal principal = (Principal) iterator.next(); - if (principal instanceof X500Principal) { - return principal.getName(); - } - } - return null; - } + private String getName(Subject subject) { + for (Iterator iterator = subject.getPrincipals().iterator(); iterator.hasNext();) { + Principal principal = (Principal) iterator.next(); + if (principal instanceof X500Principal) { + return principal.getName(); + } + } + return null; + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandlerTest.java index 8f60b478..d28eb4f6 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasCertificateValidationCallbackHandlerTest.java @@ -29,35 +29,35 @@ import org.junit.Test; public class JaasCertificateValidationCallbackHandlerTest { - private JaasCertificateValidationCallbackHandler callbackHandler; + private JaasCertificateValidationCallbackHandler callbackHandler; - private CertificateValidationCallback callback; + private CertificateValidationCallback callback; - @Before - public void setUp() throws Exception { - System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString()); - callbackHandler = new JaasCertificateValidationCallbackHandler(); - callbackHandler.setLoginContextName("Certificate"); - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - InputStream is = null; - try { - is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream(); - keyStore.load(is, "password".toCharArray()); - } - finally { - if (is != null) { - is.close(); - } - } - X509Certificate certificate = (X509Certificate) keyStore.getCertificate("alias"); - callback = new CertificateValidationCallback(certificate); - } + @Before + public void setUp() throws Exception { + System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString()); + callbackHandler = new JaasCertificateValidationCallbackHandler(); + callbackHandler.setLoginContextName("Certificate"); + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + InputStream is = null; + try { + is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream(); + keyStore.load(is, "password".toCharArray()); + } + finally { + if (is != null) { + is.close(); + } + } + X509Certificate certificate = (X509Certificate) keyStore.getCertificate("alias"); + callback = new CertificateValidationCallback(certificate); + } - @Test - public void testValidateCertificateValid() throws Exception { - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Not authenticated", authenticated); - } + @Test + public void testValidateCertificateValid() throws Exception { + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Not authenticated", authenticated); + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandlerTest.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandlerTest.java index 8a967452..9d95ea06 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandlerTest.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/JaasPlainTextPasswordValidationCallbackHandlerTest.java @@ -23,33 +23,33 @@ import org.junit.Test; public class JaasPlainTextPasswordValidationCallbackHandlerTest { - private JaasPlainTextPasswordValidationCallbackHandler callbackHandler; + private JaasPlainTextPasswordValidationCallbackHandler callbackHandler; - @Before - public void setUp() throws Exception { - System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString()); - callbackHandler = new JaasPlainTextPasswordValidationCallbackHandler(); - callbackHandler.setLoginContextName("PlainText"); - } + @Before + public void setUp() throws Exception { + System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString()); + callbackHandler = new JaasPlainTextPasswordValidationCallbackHandler(); + callbackHandler.setLoginContextName("PlainText"); + } - @Test - public void testAuthenticateUserPlainTextValid() throws Exception { - PasswordValidationCallback.PlainTextPasswordRequest request = - new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie"); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertTrue("Not authenticated", authenticated); - } + @Test + public void testAuthenticateUserPlainTextValid() throws Exception { + PasswordValidationCallback.PlainTextPasswordRequest request = + new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie"); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertTrue("Not authenticated", authenticated); + } - @Test - public void testAuthenticateUserPlainTextInvalid() throws Exception { - PasswordValidationCallback.PlainTextPasswordRequest request = - new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird"); - PasswordValidationCallback callback = new PasswordValidationCallback(request); - callbackHandler.handleInternal(callback); - boolean authenticated = callback.getResult(); - Assert.assertFalse("Authenticated", authenticated); - } + @Test + public void testAuthenticateUserPlainTextInvalid() throws Exception { + PasswordValidationCallback.PlainTextPasswordRequest request = + new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird"); + PasswordValidationCallback callback = new PasswordValidationCallback(request); + callbackHandler.handleInternal(callback); + boolean authenticated = callback.getResult(); + Assert.assertFalse("Authenticated", authenticated); + } } \ No newline at end of file diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/PlainTextLoginModule.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/PlainTextLoginModule.java index 69571d37..0cd7bae0 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/PlainTextLoginModule.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/PlainTextLoginModule.java @@ -30,110 +30,110 @@ import javax.security.auth.spi.LoginModule; public class PlainTextLoginModule implements LoginModule { - private Subject subject; + private Subject subject; - private CallbackHandler callbackHandler; + private CallbackHandler callbackHandler; - private boolean success; + private boolean success; - private List principals = new ArrayList(); + private List principals = new ArrayList(); - @Override - public boolean abort() { - success = false; - logout(); - return true; - } + @Override + public boolean abort() { + success = false; + logout(); + return true; + } - @Override - public boolean commit() throws LoginException { - if (success) { - if (subject.isReadOnly()) { - throw new LoginException("Subject is read-only"); - } - try { - subject.getPrincipals().addAll(principals); - principals.clear(); - return true; - } - catch (Exception e) { - throw new LoginException(e.getMessage()); - } - } - else { - principals.clear(); - } - return true; - } + @Override + public boolean commit() throws LoginException { + if (success) { + if (subject.isReadOnly()) { + throw new LoginException("Subject is read-only"); + } + try { + subject.getPrincipals().addAll(principals); + principals.clear(); + return true; + } + catch (Exception e) { + throw new LoginException(e.getMessage()); + } + } + else { + principals.clear(); + } + return true; + } - @Override - public void initialize(Subject subject, - CallbackHandler callbackHandler, - java.util.Map sharedState, - java.util.Map options) { - this.subject = subject; - this.callbackHandler = callbackHandler; - } + @Override + public void initialize(Subject subject, + CallbackHandler callbackHandler, + java.util.Map sharedState, + java.util.Map options) { + this.subject = subject; + this.callbackHandler = callbackHandler; + } - @Override - public boolean login() throws LoginException { - if (callbackHandler == null) { - return false; - } - try { - NameCallback nameCallback = new NameCallback("Username: "); - PasswordCallback passwordCallback = new PasswordCallback("Password: ", false); - Callback[] callbacks = new Callback[]{nameCallback, passwordCallback}; + @Override + public boolean login() throws LoginException { + if (callbackHandler == null) { + return false; + } + try { + NameCallback nameCallback = new NameCallback("Username: "); + PasswordCallback passwordCallback = new PasswordCallback("Password: ", false); + Callback[] callbacks = new Callback[]{nameCallback, passwordCallback}; - callbackHandler.handle(callbacks); + callbackHandler.handle(callbacks); - String username = nameCallback.getName(); - String password = new String(passwordCallback.getPassword()); + String username = nameCallback.getName(); + String password = new String(passwordCallback.getPassword()); - ((PasswordCallback) callbacks[1]).clearPassword(); + ((PasswordCallback) callbacks[1]).clearPassword(); - success = validate(username, password); + success = validate(username, password); - callbacks[0] = null; - callbacks[1] = null; + callbacks[0] = null; + callbacks[1] = null; - if (!success) { - throw new LoginException("Authentication failed: Password does not match"); - } + if (!success) { + throw new LoginException("Authentication failed: Password does not match"); + } - return true; - } - catch (LoginException ex) { - throw ex; - } - catch (Exception ex) { - success = false; - throw new LoginException(ex.getMessage()); - } - } + return true; + } + catch (LoginException ex) { + throw ex; + } + catch (Exception ex) { + success = false; + throw new LoginException(ex.getMessage()); + } + } - private boolean validate(String username, String password) { - if ("Bert".equals(username) && "Ernie".equals(password)) { - this.principals.add(new SimplePrincipal(username)); - return true; - } - else { - return false; - } - } + private boolean validate(String username, String password) { + if ("Bert".equals(username) && "Ernie".equals(password)) { + this.principals.add(new SimplePrincipal(username)); + return true; + } + else { + return false; + } + } - @Override - public boolean logout() { - principals.clear(); + @Override + public boolean logout() { + principals.clear(); - Iterator iterator = subject.getPrincipals(SimplePrincipal.class).iterator(); - while (iterator.hasNext()) { - SimplePrincipal principal = (SimplePrincipal) iterator.next(); - subject.getPrincipals().remove(principal); - } + Iterator iterator = subject.getPrincipals(SimplePrincipal.class).iterator(); + while (iterator.hasNext()) { + SimplePrincipal principal = (SimplePrincipal) iterator.next(); + subject.getPrincipals().remove(principal); + } - return true; - } + return true; + } } diff --git a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/SimplePrincipal.java b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/SimplePrincipal.java index 4fc2144a..62d4194a 100644 --- a/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/SimplePrincipal.java +++ b/spring-ws-security/src/test/java/org/springframework/ws/soap/security/xwss/callback/jaas/SimplePrincipal.java @@ -20,33 +20,33 @@ import java.security.Principal; public final class SimplePrincipal implements Principal { - private String name; + private String name; - public SimplePrincipal() { - name = ""; - } + public SimplePrincipal() { + name = ""; + } - public SimplePrincipal(String name) { - this.name = name; - } + public SimplePrincipal(String name) { + this.name = name; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - public int hashCode() { - return name.hashCode(); - } + public int hashCode() { + return name.hashCode(); + } - public boolean equals(Object o) { - if (!(o instanceof SimplePrincipal)) { - return false; - } - return name.equals(((SimplePrincipal) o).name); - } + public boolean equals(Object o) { + if (!(o instanceof SimplePrincipal)) { + return false; + } + return name.equals(((SimplePrincipal) o).name); + } - public String toString() { - return name; - } + public String toString() { + return name; + } } \ No newline at end of file diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpExchangeConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpExchangeConnection.java index cad7ef05..419b1251 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpExchangeConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpExchangeConnection.java @@ -45,137 +45,137 @@ import org.springframework.ws.transport.WebServiceConnection; * @since 1.5.0 */ public class HttpExchangeConnection extends AbstractReceiverConnection - implements EndpointAwareWebServiceConnection, FaultAwareWebServiceConnection { + implements EndpointAwareWebServiceConnection, FaultAwareWebServiceConnection { - private final HttpExchange httpExchange; + private final HttpExchange httpExchange; - private ByteArrayOutputStream responseBuffer; + private ByteArrayOutputStream responseBuffer; - private int responseStatusCode = HttpTransportConstants.STATUS_ACCEPTED; + private int responseStatusCode = HttpTransportConstants.STATUS_ACCEPTED; - private boolean chunkedEncoding; + private boolean chunkedEncoding; - /** Constructs a new exchange connection with the given {@code HttpExchange}. */ - protected HttpExchangeConnection(HttpExchange httpExchange) { - Assert.notNull(httpExchange, "'httpExchange' must not be null"); - this.httpExchange = httpExchange; - } + /** Constructs a new exchange connection with the given {@code HttpExchange}. */ + protected HttpExchangeConnection(HttpExchange httpExchange) { + Assert.notNull(httpExchange, "'httpExchange' must not be null"); + this.httpExchange = httpExchange; + } - /** Returns the {@code HttpExchange} for this connection. */ - public HttpExchange getHttpExchange() { - return httpExchange; - } + /** Returns the {@code HttpExchange} for this connection. */ + public HttpExchange getHttpExchange() { + return httpExchange; + } - @Override - public URI getUri() throws URISyntaxException { - return httpExchange.getRequestURI(); - } + @Override + public URI getUri() throws URISyntaxException { + return httpExchange.getRequestURI(); + } - void setChunkedEncoding(boolean chunkedEncoding) { - this.chunkedEncoding = chunkedEncoding; - } + void setChunkedEncoding(boolean chunkedEncoding) { + this.chunkedEncoding = chunkedEncoding; + } - @Override - public void endpointNotFound() { - responseStatusCode = HttpTransportConstants.STATUS_NOT_FOUND; - } + @Override + public void endpointNotFound() { + responseStatusCode = HttpTransportConstants.STATUS_NOT_FOUND; + } - /* - * Errors - */ + /* + * Errors + */ - @Override - public boolean hasError() throws IOException { - return false; - } + @Override + public boolean hasError() throws IOException { + return false; + } - @Override - public String getErrorMessage() throws IOException { - return null; - } + @Override + public String getErrorMessage() throws IOException { + return null; + } - /* - * Receiving request - */ + /* + * Receiving request + */ - @Override - protected Iterator getRequestHeaderNames() throws IOException { - return httpExchange.getRequestHeaders().keySet().iterator(); - } + @Override + protected Iterator getRequestHeaderNames() throws IOException { + return httpExchange.getRequestHeaders().keySet().iterator(); + } - @Override - protected Iterator getRequestHeaders(String name) throws IOException { - List headers = httpExchange.getRequestHeaders().get(name); - return headers != null ? headers.iterator() : Collections.emptyList().iterator(); - } + @Override + protected Iterator getRequestHeaders(String name) throws IOException { + List headers = httpExchange.getRequestHeaders().get(name); + return headers != null ? headers.iterator() : Collections.emptyList().iterator(); + } - @Override - protected InputStream getRequestInputStream() throws IOException { - return httpExchange.getRequestBody(); - } + @Override + protected InputStream getRequestInputStream() throws IOException { + return httpExchange.getRequestBody(); + } - /* - * Sending response - */ + /* + * Sending response + */ - @Override - protected void addResponseHeader(String name, String value) throws IOException { - httpExchange.getResponseHeaders().add(name, value); - } + @Override + protected void addResponseHeader(String name, String value) throws IOException { + httpExchange.getResponseHeaders().add(name, value); + } - @Override - protected OutputStream getResponseOutputStream() throws IOException { - if (chunkedEncoding) { - httpExchange.sendResponseHeaders(responseStatusCode, 0); - return httpExchange.getResponseBody(); - } - else { - if (responseBuffer == null) { - responseBuffer = new ByteArrayOutputStream(); - } - return responseBuffer; - } - } + @Override + protected OutputStream getResponseOutputStream() throws IOException { + if (chunkedEncoding) { + httpExchange.sendResponseHeaders(responseStatusCode, 0); + return httpExchange.getResponseBody(); + } + else { + if (responseBuffer == null) { + responseBuffer = new ByteArrayOutputStream(); + } + return responseBuffer; + } + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - if (!chunkedEncoding) { - byte[] buf = responseBuffer.toByteArray(); - httpExchange.sendResponseHeaders(responseStatusCode, buf.length); - OutputStream responseBody = httpExchange.getResponseBody(); - FileCopyUtils.copy(buf, responseBody); - } - responseBuffer = null; - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + if (!chunkedEncoding) { + byte[] buf = responseBuffer.toByteArray(); + httpExchange.sendResponseHeaders(responseStatusCode, buf.length); + OutputStream responseBody = httpExchange.getResponseBody(); + FileCopyUtils.copy(buf, responseBody); + } + responseBuffer = null; + } - @Override - public void onClose() throws IOException { - if (responseStatusCode == HttpTransportConstants.STATUS_ACCEPTED || - responseStatusCode == HttpTransportConstants.STATUS_NOT_FOUND) { - httpExchange.sendResponseHeaders(responseStatusCode, -1); - } - httpExchange.close(); - } + @Override + public void onClose() throws IOException { + if (responseStatusCode == HttpTransportConstants.STATUS_ACCEPTED || + responseStatusCode == HttpTransportConstants.STATUS_NOT_FOUND) { + httpExchange.sendResponseHeaders(responseStatusCode, -1); + } + httpExchange.close(); + } - /* - * Faults - */ + /* + * Faults + */ - @Override - public boolean hasFault() throws IOException { - return responseStatusCode == HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR; - } + @Override + public boolean hasFault() throws IOException { + return responseStatusCode == HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR; + } - @Override - @Deprecated - public void setFault(boolean fault) throws IOException { - if (fault) { - responseStatusCode = HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR; - } - else { - responseStatusCode = HttpTransportConstants.STATUS_OK; - } - } + @Override + @Deprecated + public void setFault(boolean fault) throws IOException { + if (fault) { + responseStatusCode = HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR; + } + else { + responseStatusCode = HttpTransportConstants.STATUS_OK; + } + } @Override public void setFaultCode(QName faultCode) throws IOException { diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsTransportException.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsTransportException.java index d2c53fd2..7a0c38f6 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsTransportException.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsTransportException.java @@ -25,11 +25,11 @@ package org.springframework.ws.transport.http; @SuppressWarnings("serial") public class HttpsTransportException extends HttpTransportException { - public HttpsTransportException(String msg) { - super(msg); - } + public HttpsTransportException(String msg) { + super(msg); + } - public HttpsTransportException(String msg, Throwable cause) { - super(msg, cause); - } + public HttpsTransportException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsUrlConnectionMessageSender.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsUrlConnectionMessageSender.java index 27bcb704..d6e0d7c1 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsUrlConnectionMessageSender.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/HttpsUrlConnectionMessageSender.java @@ -43,138 +43,138 @@ import org.springframework.util.StringUtils; */ public class HttpsUrlConnectionMessageSender extends HttpUrlConnectionMessageSender implements InitializingBean { - /** The default SSL protocol. */ - public static final String DEFAULT_SSL_PROTOCOL = "ssl"; + /** The default SSL protocol. */ + public static final String DEFAULT_SSL_PROTOCOL = "ssl"; - private String sslProtocol = DEFAULT_SSL_PROTOCOL; + private String sslProtocol = DEFAULT_SSL_PROTOCOL; - private String sslProvider; + private String sslProvider; - private KeyManager[] keyManagers; + private KeyManager[] keyManagers; - private TrustManager[] trustManagers; + private TrustManager[] trustManagers; - private HostnameVerifier hostnameVerifier; + private HostnameVerifier hostnameVerifier; - private SecureRandom rnd; + private SecureRandom rnd; - private SSLSocketFactory sslSocketFactory; + private SSLSocketFactory sslSocketFactory; - /** - * Sets the SSL protocol to use. Default is {@code ssl}. - * - * @see SSLContext#getInstance(String, String) - */ - public void setSslProtocol(String sslProtocol) { - Assert.hasLength(sslProtocol, "'sslProtocol' must not be empty"); - this.sslProtocol = sslProtocol; - } + /** + * Sets the SSL protocol to use. Default is {@code ssl}. + * + * @see SSLContext#getInstance(String, String) + */ + public void setSslProtocol(String sslProtocol) { + Assert.hasLength(sslProtocol, "'sslProtocol' must not be empty"); + this.sslProtocol = sslProtocol; + } - /** - * Sets the SSL provider to use. Default is empty, to use the default provider. - * - * @see SSLContext#getInstance(String, String) - */ - public void setSslProvider(String sslProvider) { - this.sslProvider = sslProvider; - } + /** + * Sets the SSL provider to use. Default is empty, to use the default provider. + * + * @see SSLContext#getInstance(String, String) + */ + public void setSslProvider(String sslProvider) { + this.sslProvider = sslProvider; + } - /** - * Specifies the key managers to use for this message sender. - * - *

Setting either this property or {@link #setTrustManagers(TrustManager[]) trustManagers} is required. - * - * @see SSLContext#init(KeyManager[], TrustManager[], SecureRandom) - */ - public void setKeyManagers(KeyManager[] keyManagers) { - this.keyManagers = keyManagers; - } + /** + * Specifies the key managers to use for this message sender. + * + *

Setting either this property or {@link #setTrustManagers(TrustManager[]) trustManagers} is required. + * + * @see SSLContext#init(KeyManager[], TrustManager[], SecureRandom) + */ + public void setKeyManagers(KeyManager[] keyManagers) { + this.keyManagers = keyManagers; + } - /** - * Specifies the trust managers to use for this message sender. - * - *

Setting either this property or {@link #setKeyManagers(KeyManager[]) keyManagers} is required. - * - * @see SSLContext#init(KeyManager[], TrustManager[], SecureRandom) - */ - public void setTrustManagers(TrustManager[] trustManagers) { - this.trustManagers = trustManagers; - } + /** + * Specifies the trust managers to use for this message sender. + * + *

Setting either this property or {@link #setKeyManagers(KeyManager[]) keyManagers} is required. + * + * @see SSLContext#init(KeyManager[], TrustManager[], SecureRandom) + */ + public void setTrustManagers(TrustManager[] trustManagers) { + this.trustManagers = trustManagers; + } - /** - * Specifies the host name verifier to use for this message sender. - * - * @see HttpsURLConnection#setHostnameVerifier(HostnameVerifier) - */ - public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - } + /** + * Specifies the host name verifier to use for this message sender. + * + * @see HttpsURLConnection#setHostnameVerifier(HostnameVerifier) + */ + public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { + this.hostnameVerifier = hostnameVerifier; + } - /** - * Specifies the secure random to use for this message sender. - * - * @see SSLContext#init(KeyManager[], TrustManager[], SecureRandom) - */ - public void setSecureRandom(SecureRandom rnd) { - this.rnd = rnd; - } + /** + * Specifies the secure random to use for this message sender. + * + * @see SSLContext#init(KeyManager[], TrustManager[], SecureRandom) + */ + public void setSecureRandom(SecureRandom rnd) { + this.rnd = rnd; + } - /** - * Specifies the SSLSocketFactory to use for this message sender. - * - * @see HttpsURLConnection#setSSLSocketFactory(SSLSocketFactory sf) - */ - public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - } + /** + * Specifies the SSLSocketFactory to use for this message sender. + * + * @see HttpsURLConnection#setSSLSocketFactory(SSLSocketFactory sf) + */ + public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { + this.sslSocketFactory = sslSocketFactory; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.isTrue( - !(ObjectUtils.isEmpty(keyManagers) && ObjectUtils.isEmpty(trustManagers) && (sslSocketFactory == null)), - "Setting either 'keyManagers', 'trustManagers' or 'sslSocketFactory' is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.isTrue( + !(ObjectUtils.isEmpty(keyManagers) && ObjectUtils.isEmpty(trustManagers) && (sslSocketFactory == null)), + "Setting either 'keyManagers', 'trustManagers' or 'sslSocketFactory' is required"); + } - @Override - protected void prepareConnection(HttpURLConnection connection) throws IOException { - super.prepareConnection(connection); - if (connection instanceof HttpsURLConnection) { - HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; - httpsConnection.setSSLSocketFactory(createSslSocketFactory()); + @Override + protected void prepareConnection(HttpURLConnection connection) throws IOException { + super.prepareConnection(connection); + if (connection instanceof HttpsURLConnection) { + HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; + httpsConnection.setSSLSocketFactory(createSslSocketFactory()); - if (hostnameVerifier != null) { - httpsConnection.setHostnameVerifier(hostnameVerifier); - } - } - } + if (hostnameVerifier != null) { + httpsConnection.setHostnameVerifier(hostnameVerifier); + } + } + } - private SSLSocketFactory createSslSocketFactory() throws HttpsTransportException { - if (this.sslSocketFactory != null) { - return this.sslSocketFactory; - } - try { - SSLContext sslContext = - StringUtils.hasLength(sslProvider) ? SSLContext.getInstance(sslProtocol, sslProvider) : - SSLContext.getInstance(sslProtocol); - sslContext.init(keyManagers, trustManagers, rnd); - if (logger.isDebugEnabled()) { - logger.debug("Initialized SSL Context with key managers [" + - StringUtils.arrayToCommaDelimitedString(keyManagers) + "] trust managers [" + - StringUtils.arrayToCommaDelimitedString(trustManagers) + "] secure random [" + rnd + - "]"); - } - return sslContext.getSocketFactory(); - } - catch (NoSuchAlgorithmException ex) { - throw new HttpsTransportException("Could not create SSLContext: " + ex.getMessage(), ex); - } - catch (NoSuchProviderException ex) { - throw new HttpsTransportException("Could not create SSLContext: " + ex.getMessage(), ex); - } - catch (KeyManagementException ex) { - throw new HttpsTransportException("Could not initialize SSLContext: " + ex.getMessage(), ex); - } + private SSLSocketFactory createSslSocketFactory() throws HttpsTransportException { + if (this.sslSocketFactory != null) { + return this.sslSocketFactory; + } + try { + SSLContext sslContext = + StringUtils.hasLength(sslProvider) ? SSLContext.getInstance(sslProtocol, sslProvider) : + SSLContext.getInstance(sslProtocol); + sslContext.init(keyManagers, trustManagers, rnd); + if (logger.isDebugEnabled()) { + logger.debug("Initialized SSL Context with key managers [" + + StringUtils.arrayToCommaDelimitedString(keyManagers) + "] trust managers [" + + StringUtils.arrayToCommaDelimitedString(trustManagers) + "] secure random [" + rnd + + "]"); + } + return sslContext.getSocketFactory(); + } + catch (NoSuchAlgorithmException ex) { + throw new HttpsTransportException("Could not create SSLContext: " + ex.getMessage(), ex); + } + catch (NoSuchProviderException ex) { + throw new HttpsTransportException("Could not create SSLContext: " + ex.getMessage(), ex); + } + catch (KeyManagementException ex) { + throw new HttpsTransportException("Could not initialize SSLContext: " + ex.getMessage(), ex); + } - } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHttpHandler.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHttpHandler.java index b57ece85..e21d7999 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHttpHandler.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WebServiceMessageReceiverHttpHandler.java @@ -37,30 +37,30 @@ import org.springframework.ws.transport.support.SimpleWebServiceMessageReceiverO * @since 1.5.0 */ public class WebServiceMessageReceiverHttpHandler extends SimpleWebServiceMessageReceiverObjectSupport - implements HttpHandler { + implements HttpHandler { - private boolean chunkedEncoding = false; + private boolean chunkedEncoding = false; - /** Enables chunked encoding on response bodies. Defaults to {@code false}. */ - public void setChunkedEncoding(boolean chunkedEncoding) { - this.chunkedEncoding = chunkedEncoding; - } + /** Enables chunked encoding on response bodies. Defaults to {@code false}. */ + public void setChunkedEncoding(boolean chunkedEncoding) { + this.chunkedEncoding = chunkedEncoding; + } - @Override - public void handle(HttpExchange httpExchange) throws IOException { - if (HttpTransportConstants.METHOD_POST.equals(httpExchange.getRequestMethod())) { - HttpExchangeConnection connection = new HttpExchangeConnection(httpExchange); - connection.setChunkedEncoding(chunkedEncoding); - try { - handleConnection(connection); - } - catch (Exception ex) { - logger.error(ex); - } - } - else { - httpExchange.sendResponseHeaders(HttpTransportConstants.STATUS_METHOD_NOT_ALLOWED, -1); - httpExchange.close(); - } - } + @Override + public void handle(HttpExchange httpExchange) throws IOException { + if (HttpTransportConstants.METHOD_POST.equals(httpExchange.getRequestMethod())) { + HttpExchangeConnection connection = new HttpExchangeConnection(httpExchange); + connection.setChunkedEncoding(chunkedEncoding); + try { + handleConnection(connection); + } + catch (Exception ex) { + logger.error(ex); + } + } + else { + httpExchange.sendResponseHeaders(HttpTransportConstants.STATUS_METHOD_NOT_ALLOWED, -1); + httpExchange.close(); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHttpHandler.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHttpHandler.java index 047fe950..0e033a0e 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHttpHandler.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/http/WsdlDefinitionHttpHandler.java @@ -37,47 +37,47 @@ import org.springframework.xml.transform.TransformerObjectSupport; */ public class WsdlDefinitionHttpHandler extends TransformerObjectSupport implements HttpHandler, InitializingBean { - private static final String CONTENT_TYPE = "text/xml"; + private static final String CONTENT_TYPE = "text/xml"; - private WsdlDefinition definition; + private WsdlDefinition definition; - public WsdlDefinitionHttpHandler() { - } + public WsdlDefinitionHttpHandler() { + } - public WsdlDefinitionHttpHandler(WsdlDefinition definition) { - this.definition = definition; - } + public WsdlDefinitionHttpHandler(WsdlDefinition definition) { + this.definition = definition; + } - public void setDefinition(WsdlDefinition definition) { - this.definition = definition; - } + public void setDefinition(WsdlDefinition definition) { + this.definition = definition; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(definition, "'definition' is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(definition, "'definition' is required"); + } - @Override - public void handle(HttpExchange httpExchange) throws IOException { - try { - if (HttpTransportConstants.METHOD_GET.equals(httpExchange.getRequestMethod())) { - Headers headers = httpExchange.getResponseHeaders(); - headers.set(HttpTransportConstants.HEADER_CONTENT_TYPE, CONTENT_TYPE); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - transform(definition.getSource(), new StreamResult(os)); - byte[] buf = os.toByteArray(); - httpExchange.sendResponseHeaders(HttpTransportConstants.STATUS_OK, buf.length); - FileCopyUtils.copy(buf, httpExchange.getResponseBody()); - } - else { - httpExchange.sendResponseHeaders(HttpTransportConstants.STATUS_METHOD_NOT_ALLOWED, -1); - } - } - catch (TransformerException ex) { - logger.error(ex, ex); - } - finally { - httpExchange.close(); - } - } + @Override + public void handle(HttpExchange httpExchange) throws IOException { + try { + if (HttpTransportConstants.METHOD_GET.equals(httpExchange.getRequestMethod())) { + Headers headers = httpExchange.getResponseHeaders(); + headers.set(HttpTransportConstants.HEADER_CONTENT_TYPE, CONTENT_TYPE); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + transform(definition.getSource(), new StreamResult(os)); + byte[] buf = os.toByteArray(); + httpExchange.sendResponseHeaders(HttpTransportConstants.STATUS_OK, buf.length); + FileCopyUtils.copy(buf, httpExchange.getResponseBody()); + } + else { + httpExchange.sendResponseHeaders(HttpTransportConstants.STATUS_METHOD_NOT_ALLOWED, -1); + } + } + catch (TransformerException ex) { + logger.error(ex, ex); + } + finally { + httpExchange.close(); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageInputStream.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageInputStream.java index a53be4cb..523ff291 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageInputStream.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageInputStream.java @@ -32,48 +32,48 @@ import org.springframework.util.Assert; */ class BytesMessageInputStream extends InputStream { - private final BytesMessage message; + private final BytesMessage message; - BytesMessageInputStream(BytesMessage message) { - Assert.notNull(message, "'message' must not be null"); - this.message = message; - } + BytesMessageInputStream(BytesMessage message) { + Assert.notNull(message, "'message' must not be null"); + this.message = message; + } - @Override - public int read(byte b[]) throws IOException { - try { - return message.readBytes(b); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + @Override + public int read(byte b[]) throws IOException { + try { + return message.readBytes(b); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } - @Override - public int read(byte b[], int off, int len) throws IOException { - if (off == 0) { - try { - return message.readBytes(b, len); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } - else { - return super.read(b, off, len); - } - } + @Override + public int read(byte b[], int off, int len) throws IOException { + if (off == 0) { + try { + return message.readBytes(b, len); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } + else { + return super.read(b, off, len); + } + } - @Override - public int read() throws IOException { - try { - return message.readByte(); - } - catch (MessageEOFException ex) { - return -1; - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + @Override + public int read() throws IOException { + try { + return message.readByte(); + } + catch (MessageEOFException ex) { + return -1; + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageOutputStream.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageOutputStream.java index f179683c..42904226 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageOutputStream.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/BytesMessageOutputStream.java @@ -31,40 +31,40 @@ import org.springframework.util.Assert; */ class BytesMessageOutputStream extends OutputStream { - private final BytesMessage message; + private final BytesMessage message; - BytesMessageOutputStream(BytesMessage message) { - Assert.notNull(message, "'message' must not be null"); - this.message = message; - } + BytesMessageOutputStream(BytesMessage message) { + Assert.notNull(message, "'message' must not be null"); + this.message = message; + } - @Override - public void write(byte b[]) throws IOException { - try { - message.writeBytes(b); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + @Override + public void write(byte b[]) throws IOException { + try { + message.writeBytes(b); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } - @Override - public void write(byte b[], int off, int len) throws IOException { - try { - message.writeBytes(b, off, len); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + @Override + public void write(byte b[], int off, int len) throws IOException { + try { + message.writeBytes(b, off, len); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } - @Override - public void write(int b) throws IOException { - try { - message.writeByte((byte) b); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + @Override + public void write(int b) throws IOException { + try { + message.writeByte((byte) b); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageReceiver.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageReceiver.java index 9352c159..1ff90770 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageReceiver.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageReceiver.java @@ -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, @@ -38,47 +38,47 @@ import org.springframework.ws.transport.support.SimpleWebServiceMessageReceiverO */ public class JmsMessageReceiver extends SimpleWebServiceMessageReceiverObjectSupport { - /** Default encoding used to read from and write to {@link TextMessage} messages. */ - public static final String DEFAULT_TEXT_MESSAGE_ENCODING = "UTF-8"; + /** Default encoding used to read from and write to {@link TextMessage} messages. */ + public static final String DEFAULT_TEXT_MESSAGE_ENCODING = "UTF-8"; - private String textMessageEncoding = DEFAULT_TEXT_MESSAGE_ENCODING; + private String textMessageEncoding = DEFAULT_TEXT_MESSAGE_ENCODING; - private MessagePostProcessor postProcessor; + private MessagePostProcessor postProcessor; - /** Sets the encoding used to read from and write to {@link TextMessage} messages. Defaults to {@code UTF-8}. */ - public void setTextMessageEncoding(String textMessageEncoding) { - this.textMessageEncoding = textMessageEncoding; - } + /** Sets the encoding used to read from and write to {@link TextMessage} messages. Defaults to {@code UTF-8}. */ + public void setTextMessageEncoding(String textMessageEncoding) { + this.textMessageEncoding = textMessageEncoding; + } - /** - * Sets the optional {@link MessagePostProcessor} to further modify outgoing messages after the XML contents has - * been set. - */ - public void setPostProcessor(MessagePostProcessor postProcessor) { - this.postProcessor = postProcessor; - } + /** + * Sets the optional {@link MessagePostProcessor} to further modify outgoing messages after the XML contents has + * been set. + */ + public void setPostProcessor(MessagePostProcessor postProcessor) { + this.postProcessor = postProcessor; + } - /** - * Handles an incoming message. Uses the given session to create a response message. - * - * @param request the incoming message - * @param session the JMS session used to create a response - * @throws IllegalArgumentException when request is not a {@link BytesMessage} - */ - protected final void handleMessage(Message request, Session session) throws Exception { - JmsReceiverConnection connection; - if (request instanceof BytesMessage) { - connection = new JmsReceiverConnection((BytesMessage) request, session); - } - else if (request instanceof TextMessage) { - connection = new JmsReceiverConnection((TextMessage) request, textMessageEncoding, session); - } - else { - throw new IllegalArgumentException("Wrong message type: [" + request.getClass() + - "]. Only BytesMessages or TextMessages can be handled."); - } - connection.setPostProcessor(postProcessor); + /** + * Handles an incoming message. Uses the given session to create a response message. + * + * @param request the incoming message + * @param session the JMS session used to create a response + * @throws IllegalArgumentException when request is not a {@link BytesMessage} + */ + protected final void handleMessage(Message request, Session session) throws Exception { + JmsReceiverConnection connection; + if (request instanceof BytesMessage) { + connection = new JmsReceiverConnection((BytesMessage) request, session); + } + else if (request instanceof TextMessage) { + connection = new JmsReceiverConnection((TextMessage) request, textMessageEncoding, session); + } + else { + throw new IllegalArgumentException("Wrong message type: [" + request.getClass() + + "]. Only BytesMessages or TextMessages can be handled."); + } + connection.setPostProcessor(postProcessor); - handleConnection(connection); - } + handleConnection(connection); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageSender.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageSender.java index f8414e9a..eff415a2 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageSender.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsMessageSender.java @@ -50,33 +50,33 @@ import org.springframework.ws.transport.jms.support.JmsTransportUtils; * the {@link #getDestinationResolver() destination resolver}. Valid param-name include: * *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
param-nameDescription
deliveryModeIndicates whether the request message is persistent or not. This may be PERSISTENT or - * NON_PERSISTENT. See {@link MessageProducer#setDeliveryMode(int)}
messageTypeThe message type. This may be BINARY_MESSAGE (the default) or TEXT_MESSAGE
priorityThe JMS priority (0-9) associated with the request message. See - * {@link MessageProducer#setPriority(int)}
replyToNameThe name of the destination to which the response message must be sent, that will be resolved by - * the {@link #getDestinationResolver() destination resolver}.
timeToLiveThe lifetime, in milliseconds, of the request message. See - * {@link MessageProducer#setTimeToLive(long)}
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
param-nameDescription
deliveryModeIndicates whether the request message is persistent or not. This may be PERSISTENT or + * NON_PERSISTENT. See {@link MessageProducer#setDeliveryMode(int)}
messageTypeThe message type. This may be BINARY_MESSAGE (the default) or TEXT_MESSAGE
priorityThe JMS priority (0-9) associated with the request message. See + * {@link MessageProducer#setPriority(int)}
replyToNameThe name of the destination to which the response message must be sent, that will be resolved by + * the {@link #getDestinationResolver() destination resolver}.
timeToLiveThe lifetime, in milliseconds, of the request message. See + * {@link MessageProducer#setTimeToLive(long)}
*
* *

If the replyToName is not set, a {@link Session#createTemporaryQueue() temporary queue} is used. @@ -96,117 +96,117 @@ import org.springframework.ws.transport.jms.support.JmsTransportUtils; */ public class JmsMessageSender extends JmsDestinationAccessor implements WebServiceMessageSender { - /** Default timeout for receive operations: -1 indicates a blocking receive without timeout. */ - public static final long DEFAULT_RECEIVE_TIMEOUT = -1; + /** Default timeout for receive operations: -1 indicates a blocking receive without timeout. */ + public static final long DEFAULT_RECEIVE_TIMEOUT = -1; - /** Default encoding used to read fromn and write to {@link TextMessage} messages. */ - public static final String DEFAULT_TEXT_MESSAGE_ENCODING = "UTF-8"; + /** Default encoding used to read fromn and write to {@link TextMessage} messages. */ + public static final String DEFAULT_TEXT_MESSAGE_ENCODING = "UTF-8"; - private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT; + private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT; - private String textMessageEncoding = DEFAULT_TEXT_MESSAGE_ENCODING; + private String textMessageEncoding = DEFAULT_TEXT_MESSAGE_ENCODING; - private MessagePostProcessor postProcessor; + private MessagePostProcessor postProcessor; - /** - * Create a new {@code JmsMessageSender} - * - *

Note: The ConnectionFactory has to be set before using the instance. This constructor can be used to - * prepare a JmsTemplate via a BeanFactory, typically setting the ConnectionFactory via {@link - * #setConnectionFactory(ConnectionFactory)}. - * - * @see #setConnectionFactory(ConnectionFactory) - */ - public JmsMessageSender() { - } + /** + * Create a new {@code JmsMessageSender} + * + *

Note: The ConnectionFactory has to be set before using the instance. This constructor can be used to + * prepare a JmsTemplate via a BeanFactory, typically setting the ConnectionFactory via {@link + * #setConnectionFactory(ConnectionFactory)}. + * + * @see #setConnectionFactory(ConnectionFactory) + */ + public JmsMessageSender() { + } - /** - * Create a new {@code JmsMessageSender}, given a ConnectionFactory. - * - * @param connectionFactory the ConnectionFactory to obtain Connections from - */ - public JmsMessageSender(ConnectionFactory connectionFactory) { - setConnectionFactory(connectionFactory); - } + /** + * Create a new {@code JmsMessageSender}, given a ConnectionFactory. + * + * @param connectionFactory the ConnectionFactory to obtain Connections from + */ + public JmsMessageSender(ConnectionFactory connectionFactory) { + setConnectionFactory(connectionFactory); + } - /** - * Set the timeout to use for receive calls. The default is -1, which means no timeout. - * - * @see MessageConsumer#receive(long) - */ - public void setReceiveTimeout(long receiveTimeout) { - this.receiveTimeout = receiveTimeout; - } + /** + * Set the timeout to use for receive calls. The default is -1, which means no timeout. + * + * @see MessageConsumer#receive(long) + */ + public void setReceiveTimeout(long receiveTimeout) { + this.receiveTimeout = receiveTimeout; + } - /** Sets the encoding used to read from {@link TextMessage} messages. Defaults to {@code UTF-8}. */ - public void setTextMessageEncoding(String textMessageEncoding) { - this.textMessageEncoding = textMessageEncoding; - } + /** Sets the encoding used to read from {@link TextMessage} messages. Defaults to {@code UTF-8}. */ + public void setTextMessageEncoding(String textMessageEncoding) { + this.textMessageEncoding = textMessageEncoding; + } - /** - * Sets the optional {@link MessagePostProcessor} to further modify outgoing messages after the XML contents has - * been set. - */ - public void setPostProcessor(MessagePostProcessor postProcessor) { - this.postProcessor = postProcessor; - } + /** + * Sets the optional {@link MessagePostProcessor} to further modify outgoing messages after the XML contents has + * been set. + */ + public void setPostProcessor(MessagePostProcessor postProcessor) { + this.postProcessor = postProcessor; + } - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - Connection jmsConnection = null; - Session jmsSession = null; - try { - jmsConnection = createConnection(); - jmsSession = createSession(jmsConnection); - Destination requestDestination = resolveRequestDestination(jmsSession, uri); - Message requestMessage = createRequestMessage(jmsSession, uri); - JmsSenderConnection wsConnection = - new JmsSenderConnection(getConnectionFactory(), jmsConnection, jmsSession, requestDestination, - requestMessage); - wsConnection.setDeliveryMode(JmsTransportUtils.getDeliveryMode(uri)); - wsConnection.setPriority(JmsTransportUtils.getPriority(uri)); - wsConnection.setReceiveTimeout(receiveTimeout); - wsConnection.setResponseDestination(resolveResponseDestination(jmsSession, uri)); - wsConnection.setTimeToLive(JmsTransportUtils.getTimeToLive(uri)); - wsConnection.setTextMessageEncoding(textMessageEncoding); - wsConnection.setSessionTransacted(isSessionTransacted()); - wsConnection.setPostProcessor(postProcessor); - return wsConnection; - } - catch (JMSException ex) { - JmsUtils.closeSession(jmsSession); - ConnectionFactoryUtils.releaseConnection(jmsConnection, getConnectionFactory(), true); - throw new JmsTransportException(ex); - } - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + Connection jmsConnection = null; + Session jmsSession = null; + try { + jmsConnection = createConnection(); + jmsSession = createSession(jmsConnection); + Destination requestDestination = resolveRequestDestination(jmsSession, uri); + Message requestMessage = createRequestMessage(jmsSession, uri); + JmsSenderConnection wsConnection = + new JmsSenderConnection(getConnectionFactory(), jmsConnection, jmsSession, requestDestination, + requestMessage); + wsConnection.setDeliveryMode(JmsTransportUtils.getDeliveryMode(uri)); + wsConnection.setPriority(JmsTransportUtils.getPriority(uri)); + wsConnection.setReceiveTimeout(receiveTimeout); + wsConnection.setResponseDestination(resolveResponseDestination(jmsSession, uri)); + wsConnection.setTimeToLive(JmsTransportUtils.getTimeToLive(uri)); + wsConnection.setTextMessageEncoding(textMessageEncoding); + wsConnection.setSessionTransacted(isSessionTransacted()); + wsConnection.setPostProcessor(postProcessor); + return wsConnection; + } + catch (JMSException ex) { + JmsUtils.closeSession(jmsSession); + ConnectionFactoryUtils.releaseConnection(jmsConnection, getConnectionFactory(), true); + throw new JmsTransportException(ex); + } + } - @Override - public boolean supports(URI uri) { - return uri.getScheme().equals(JmsTransportConstants.JMS_URI_SCHEME); - } + @Override + public boolean supports(URI uri) { + return uri.getScheme().equals(JmsTransportConstants.JMS_URI_SCHEME); + } - private Destination resolveRequestDestination(Session session, URI uri) throws JMSException { - return resolveDestinationName(session, JmsTransportUtils.getDestinationName(uri)); - } + private Destination resolveRequestDestination(Session session, URI uri) throws JMSException { + return resolveDestinationName(session, JmsTransportUtils.getDestinationName(uri)); + } - private Destination resolveResponseDestination(Session session, URI uri) throws JMSException { - String destinationName = JmsTransportUtils.getReplyToName(uri); - return StringUtils.hasLength(destinationName) ? resolveDestinationName(session, destinationName) : null; - } + private Destination resolveResponseDestination(Session session, URI uri) throws JMSException { + String destinationName = JmsTransportUtils.getReplyToName(uri); + return StringUtils.hasLength(destinationName) ? resolveDestinationName(session, destinationName) : null; + } - private Message createRequestMessage(Session session, URI uri) throws JMSException { - int messageType = JmsTransportUtils.getMessageType(uri); - if (messageType == JmsTransportConstants.BYTES_MESSAGE_TYPE) { - return session.createBytesMessage(); - } - else if (messageType == JmsTransportConstants.TEXT_MESSAGE_TYPE) { - return session.createTextMessage(); - } - else { - throw new IllegalArgumentException("Invalid message type [" + messageType + "]."); - } + private Message createRequestMessage(Session session, URI uri) throws JMSException { + int messageType = JmsTransportUtils.getMessageType(uri); + if (messageType == JmsTransportConstants.BYTES_MESSAGE_TYPE) { + return session.createBytesMessage(); + } + else if (messageType == JmsTransportConstants.TEXT_MESSAGE_TYPE) { + return session.createTextMessage(); + } + else { + throw new IllegalArgumentException("Invalid message type [" + messageType + "]."); + } - } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsReceiverConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsReceiverConnection.java index 1695b877..e17e277b 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsReceiverConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsReceiverConnection.java @@ -50,198 +50,198 @@ import org.springframework.ws.transport.jms.support.JmsTransportUtils; */ public class JmsReceiverConnection extends AbstractReceiverConnection { - private final Message requestMessage; + private final Message requestMessage; - private final Session session; + private final Session session; - private Message responseMessage; + private Message responseMessage; - private String textMessageEncoding; + private String textMessageEncoding; - private MessagePostProcessor postProcessor; + private MessagePostProcessor postProcessor; - private JmsReceiverConnection(Message requestMessage, Session session) { - Assert.notNull(requestMessage, "requestMessage must not be null"); - Assert.notNull(session, "session must not be null"); - this.requestMessage = requestMessage; - this.session = session; - } + private JmsReceiverConnection(Message requestMessage, Session session) { + Assert.notNull(requestMessage, "requestMessage must not be null"); + Assert.notNull(session, "session must not be null"); + this.requestMessage = requestMessage; + this.session = session; + } - /** - * Constructs a new JMS connection with the given {@link BytesMessage}. - * - * @param requestMessage the JMS request message - * @param session the JMS session - */ - protected JmsReceiverConnection(BytesMessage requestMessage, Session session) { - this((Message) requestMessage, session); - } + /** + * Constructs a new JMS connection with the given {@link BytesMessage}. + * + * @param requestMessage the JMS request message + * @param session the JMS session + */ + protected JmsReceiverConnection(BytesMessage requestMessage, Session session) { + this((Message) requestMessage, session); + } - /** - * Constructs a new JMS connection with the given {@link TextMessage}. - * - * @param requestMessage the JMS request message - * @param session the JMS session - */ - protected JmsReceiverConnection(TextMessage requestMessage, String encoding, Session session) { - this(requestMessage, session); - this.textMessageEncoding = encoding; - } + /** + * Constructs a new JMS connection with the given {@link TextMessage}. + * + * @param requestMessage the JMS request message + * @param session the JMS session + */ + protected JmsReceiverConnection(TextMessage requestMessage, String encoding, Session session) { + this(requestMessage, session); + this.textMessageEncoding = encoding; + } - void setPostProcessor(MessagePostProcessor postProcessor) { - this.postProcessor = postProcessor; - } + void setPostProcessor(MessagePostProcessor postProcessor) { + this.postProcessor = postProcessor; + } - + - /** Returns the request message for this connection. Returns either a {@link BytesMessage} or a {@link TextMessage}. */ - public Message getRequestMessage() { - return requestMessage; - } + /** Returns the request message for this connection. Returns either a {@link BytesMessage} or a {@link TextMessage}. */ + public Message getRequestMessage() { + return requestMessage; + } - /** - * Returns the response message, if any, for this connection. Returns either a {@link BytesMessage} or a {@link - * TextMessage}. - */ - public Message getResponseMessage() { - return responseMessage; - } + /** + * Returns the response message, if any, for this connection. Returns either a {@link BytesMessage} or a {@link + * TextMessage}. + */ + public Message getResponseMessage() { + return responseMessage; + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - try { - return JmsTransportUtils.toUri(requestMessage.getJMSDestination()); - } - catch (JMSException ex) { - throw new URISyntaxException("", ex.getMessage()); - } - } + @Override + public URI getUri() throws URISyntaxException { + try { + return JmsTransportUtils.toUri(requestMessage.getJMSDestination()); + } + catch (JMSException ex) { + throw new URISyntaxException("", ex.getMessage()); + } + } - /* - * Errors - */ + /* + * Errors + */ - @Override - public String getErrorMessage() throws IOException { - return null; - } + @Override + public String getErrorMessage() throws IOException { + return null; + } - @Override - public boolean hasError() throws IOException { - return false; - } + @Override + public boolean hasError() throws IOException { + return false; + } - /* - * Receiving - */ + /* + * Receiving + */ - @Override - protected Iterator getRequestHeaderNames() throws IOException { - try { - return JmsTransportUtils.getHeaderNames(requestMessage); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not get property names", ex); - } - } + @Override + protected Iterator getRequestHeaderNames() throws IOException { + try { + return JmsTransportUtils.getHeaderNames(requestMessage); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not get property names", ex); + } + } - @Override - protected Iterator getRequestHeaders(String name) throws IOException { - try { - return JmsTransportUtils.getHeaders(requestMessage, name); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not get property value", ex); - } - } + @Override + protected Iterator getRequestHeaders(String name) throws IOException { + try { + return JmsTransportUtils.getHeaders(requestMessage, name); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not get property value", ex); + } + } - @Override - protected InputStream getRequestInputStream() throws IOException { - if (requestMessage instanceof BytesMessage) { - return new BytesMessageInputStream((BytesMessage) requestMessage); - } - else if (requestMessage instanceof TextMessage) { - return new TextMessageInputStream((TextMessage) requestMessage, textMessageEncoding); - } - else { - throw new IllegalStateException("Unknown request message type [" + requestMessage + "]"); - } - } + @Override + protected InputStream getRequestInputStream() throws IOException { + if (requestMessage instanceof BytesMessage) { + return new BytesMessageInputStream((BytesMessage) requestMessage); + } + else if (requestMessage instanceof TextMessage) { + return new TextMessageInputStream((TextMessage) requestMessage, textMessageEncoding); + } + else { + throw new IllegalStateException("Unknown request message type [" + requestMessage + "]"); + } + } - /* - * Sending - */ + /* + * Sending + */ - @Override - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - try { - if (requestMessage instanceof BytesMessage) { - responseMessage = session.createBytesMessage(); - } - else if (requestMessage instanceof TextMessage) { - responseMessage = session.createTextMessage(); - } - else { - throw new IllegalStateException("Unknown request message type [" + requestMessage + "]"); - } - String correlation = requestMessage.getJMSCorrelationID(); - if (correlation == null) { - correlation = requestMessage.getJMSMessageID(); - } - responseMessage.setJMSCorrelationID(correlation); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not create response message", ex); - } - } + @Override + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + try { + if (requestMessage instanceof BytesMessage) { + responseMessage = session.createBytesMessage(); + } + else if (requestMessage instanceof TextMessage) { + responseMessage = session.createTextMessage(); + } + else { + throw new IllegalStateException("Unknown request message type [" + requestMessage + "]"); + } + String correlation = requestMessage.getJMSCorrelationID(); + if (correlation == null) { + correlation = requestMessage.getJMSMessageID(); + } + responseMessage.setJMSCorrelationID(correlation); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not create response message", ex); + } + } - @Override - protected void addResponseHeader(String name, String value) throws IOException { - try { - JmsTransportUtils.addHeader(responseMessage, name, value); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not set property", ex); - } - } + @Override + protected void addResponseHeader(String name, String value) throws IOException { + try { + JmsTransportUtils.addHeader(responseMessage, name, value); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not set property", ex); + } + } - @Override - protected OutputStream getResponseOutputStream() throws IOException { - if (responseMessage instanceof BytesMessage) { - return new BytesMessageOutputStream((BytesMessage) responseMessage); - } - else if (responseMessage instanceof TextMessage) { - return new TextMessageOutputStream((TextMessage) responseMessage, textMessageEncoding); - } - else { - throw new IllegalStateException("Unknown response message type [" + responseMessage + "]"); - } - } + @Override + protected OutputStream getResponseOutputStream() throws IOException { + if (responseMessage instanceof BytesMessage) { + return new BytesMessageOutputStream((BytesMessage) responseMessage); + } + else if (responseMessage instanceof TextMessage) { + return new TextMessageOutputStream((TextMessage) responseMessage, textMessageEncoding); + } + else { + throw new IllegalStateException("Unknown response message type [" + responseMessage + "]"); + } + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - MessageProducer messageProducer = null; - try { - if (requestMessage.getJMSReplyTo() != null) { - messageProducer = session.createProducer(requestMessage.getJMSReplyTo()); - messageProducer.setDeliveryMode(requestMessage.getJMSDeliveryMode()); - messageProducer.setPriority(requestMessage.getJMSPriority()); - if (postProcessor != null) { - responseMessage = postProcessor.postProcessMessage(responseMessage); - } - messageProducer.send(responseMessage); - } - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - finally { - JmsUtils.closeMessageProducer(messageProducer); - } - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + MessageProducer messageProducer = null; + try { + if (requestMessage.getJMSReplyTo() != null) { + messageProducer = session.createProducer(requestMessage.getJMSReplyTo()); + messageProducer.setDeliveryMode(requestMessage.getJMSDeliveryMode()); + messageProducer.setPriority(requestMessage.getJMSPriority()); + if (postProcessor != null) { + responseMessage = postProcessor.postProcessMessage(responseMessage); + } + messageProducer.send(responseMessage); + } + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + finally { + JmsUtils.closeMessageProducer(messageProducer); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsSenderConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsSenderConnection.java index ce8632ef..6ff80688 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsSenderConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsSenderConnection.java @@ -52,279 +52,279 @@ import org.springframework.ws.transport.jms.support.JmsTransportUtils; */ public class JmsSenderConnection extends AbstractSenderConnection { - private final ConnectionFactory connectionFactory; + private final ConnectionFactory connectionFactory; - private final Connection connection; + private final Connection connection; - private final Session session; + private final Session session; - private final Destination requestDestination; + private final Destination requestDestination; - private Message requestMessage; + private Message requestMessage; - private Destination responseDestination; + private Destination responseDestination; - private Message responseMessage; + private Message responseMessage; - private long receiveTimeout; + private long receiveTimeout; - private int deliveryMode; + private int deliveryMode; - private long timeToLive; + private long timeToLive; - private int priority; + private int priority; - private String textMessageEncoding; + private String textMessageEncoding; - private MessagePostProcessor postProcessor; + private MessagePostProcessor postProcessor; - private boolean sessionTransacted = false; + private boolean sessionTransacted = false; - private boolean temporaryResponseQueueCreated = false; + private boolean temporaryResponseQueueCreated = false; - /** Constructs a new JMS connection with the given parameters. */ - protected JmsSenderConnection(ConnectionFactory connectionFactory, - Connection connection, - Session session, - Destination requestDestination, - Message requestMessage) throws JMSException { - Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); - Assert.notNull(connection, "'connection' must not be null"); - Assert.notNull(session, "'session' must not be null"); - Assert.notNull(requestDestination, "'requestDestination' must not be null"); - Assert.notNull(requestMessage, "'requestMessage' must not be null"); - this.connectionFactory = connectionFactory; - this.connection = connection; - this.session = session; - this.requestDestination = requestDestination; - this.requestMessage = requestMessage; - } + /** Constructs a new JMS connection with the given parameters. */ + protected JmsSenderConnection(ConnectionFactory connectionFactory, + Connection connection, + Session session, + Destination requestDestination, + Message requestMessage) throws JMSException { + Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); + Assert.notNull(connection, "'connection' must not be null"); + Assert.notNull(session, "'session' must not be null"); + Assert.notNull(requestDestination, "'requestDestination' must not be null"); + Assert.notNull(requestMessage, "'requestMessage' must not be null"); + this.connectionFactory = connectionFactory; + this.connection = connection; + this.session = session; + this.requestDestination = requestDestination; + this.requestMessage = requestMessage; + } - /** Returns the request message for this connection. Returns either a {@link BytesMessage} or a {@link TextMessage}. */ - public Message getRequestMessage() { - return requestMessage; - } + /** Returns the request message for this connection. Returns either a {@link BytesMessage} or a {@link TextMessage}. */ + public Message getRequestMessage() { + return requestMessage; + } - /** - * Returns the response message, if any, for this connection. Returns either a {@link BytesMessage} or a {@link - * TextMessage}. - */ - public Message getResponseMessage() { - return responseMessage; - } + /** + * Returns the response message, if any, for this connection. Returns either a {@link BytesMessage} or a {@link + * TextMessage}. + */ + public Message getResponseMessage() { + return responseMessage; + } - /* - * Package-friendly setters - */ + /* + * Package-friendly setters + */ - void setResponseDestination(Destination responseDestination) { - this.responseDestination = responseDestination; - } + void setResponseDestination(Destination responseDestination) { + this.responseDestination = responseDestination; + } - void setTimeToLive(long timeToLive) { - this.timeToLive = timeToLive; - } + void setTimeToLive(long timeToLive) { + this.timeToLive = timeToLive; + } - void setDeliveryMode(int deliveryMode) { - this.deliveryMode = deliveryMode; - } + void setDeliveryMode(int deliveryMode) { + this.deliveryMode = deliveryMode; + } - void setPriority(int priority) { - this.priority = priority; - } + void setPriority(int priority) { + this.priority = priority; + } - void setReceiveTimeout(long receiveTimeout) { - this.receiveTimeout = receiveTimeout; - } + void setReceiveTimeout(long receiveTimeout) { + this.receiveTimeout = receiveTimeout; + } - void setTextMessageEncoding(String textMessageEncoding) { - this.textMessageEncoding = textMessageEncoding; - } + void setTextMessageEncoding(String textMessageEncoding) { + this.textMessageEncoding = textMessageEncoding; + } - void setPostProcessor(MessagePostProcessor postProcessor) { - this.postProcessor = postProcessor; - } + void setPostProcessor(MessagePostProcessor postProcessor) { + this.postProcessor = postProcessor; + } - void setSessionTransacted(boolean sessionTransacted) { - this.sessionTransacted = sessionTransacted; - } + void setSessionTransacted(boolean sessionTransacted) { + this.sessionTransacted = sessionTransacted; + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - try { - return JmsTransportUtils.toUri(requestDestination); - } - catch (JMSException ex) { - throw new URISyntaxException("", ex.getMessage()); - } - } + @Override + public URI getUri() throws URISyntaxException { + try { + return JmsTransportUtils.toUri(requestDestination); + } + catch (JMSException ex) { + throw new URISyntaxException("", ex.getMessage()); + } + } - /* - * Errors - */ + /* + * Errors + */ - @Override - public boolean hasError() throws IOException { - return false; - } + @Override + public boolean hasError() throws IOException { + return false; + } - @Override - public String getErrorMessage() throws IOException { - return null; - } + @Override + public String getErrorMessage() throws IOException { + return null; + } - /* - * Sending - */ + /* + * Sending + */ - @Override - protected void addRequestHeader(String name, String value) throws IOException { - try { - JmsTransportUtils.addHeader(requestMessage, name, value); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not set property", ex); - } - } + @Override + protected void addRequestHeader(String name, String value) throws IOException { + try { + JmsTransportUtils.addHeader(requestMessage, name, value); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not set property", ex); + } + } - @Override - protected OutputStream getRequestOutputStream() throws IOException { - if (requestMessage instanceof BytesMessage) { - return new BytesMessageOutputStream((BytesMessage) requestMessage); - } - else if (requestMessage instanceof TextMessage) { - return new TextMessageOutputStream((TextMessage) requestMessage, textMessageEncoding); - } - else { - throw new IllegalStateException("Unknown request message type [" + requestMessage + "]"); - } + @Override + protected OutputStream getRequestOutputStream() throws IOException { + if (requestMessage instanceof BytesMessage) { + return new BytesMessageOutputStream((BytesMessage) requestMessage); + } + else if (requestMessage instanceof TextMessage) { + return new TextMessageOutputStream((TextMessage) requestMessage, textMessageEncoding); + } + else { + throw new IllegalStateException("Unknown request message type [" + requestMessage + "]"); + } - } + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - MessageProducer messageProducer = null; - try { - messageProducer = session.createProducer(requestDestination); - messageProducer.setDeliveryMode(deliveryMode); - messageProducer.setTimeToLive(timeToLive); - messageProducer.setPriority(priority); - if (responseDestination == null) { - responseDestination = session.createTemporaryQueue(); - temporaryResponseQueueCreated = true; - } - requestMessage.setJMSReplyTo(responseDestination); - if (postProcessor != null) { - requestMessage = postProcessor.postProcessMessage(requestMessage); - } - connection.start(); - messageProducer.send(requestMessage); - if (session.getTransacted() && isSessionLocallyTransacted(session)) { - JmsUtils.commitIfNecessary(session); - } - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - finally { - JmsUtils.closeMessageProducer(messageProducer); - } - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + MessageProducer messageProducer = null; + try { + messageProducer = session.createProducer(requestDestination); + messageProducer.setDeliveryMode(deliveryMode); + messageProducer.setTimeToLive(timeToLive); + messageProducer.setPriority(priority); + if (responseDestination == null) { + responseDestination = session.createTemporaryQueue(); + temporaryResponseQueueCreated = true; + } + requestMessage.setJMSReplyTo(responseDestination); + if (postProcessor != null) { + requestMessage = postProcessor.postProcessMessage(requestMessage); + } + connection.start(); + messageProducer.send(requestMessage); + if (session.getTransacted() && isSessionLocallyTransacted(session)) { + JmsUtils.commitIfNecessary(session); + } + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + finally { + JmsUtils.closeMessageProducer(messageProducer); + } + } - /** @see org.springframework.jms.core.JmsTemplate#isSessionLocallyTransacted(Session) */ - private boolean isSessionLocallyTransacted(Session session) { - return sessionTransacted && !ConnectionFactoryUtils.isSessionTransactional(session, connectionFactory); - } + /** @see org.springframework.jms.core.JmsTemplate#isSessionLocallyTransacted(Session) */ + private boolean isSessionLocallyTransacted(Session session) { + return sessionTransacted && !ConnectionFactoryUtils.isSessionTransactional(session, connectionFactory); + } - /* - * Receiving - */ + /* + * Receiving + */ - @Override - protected void onReceiveBeforeRead() throws IOException { - MessageConsumer messageConsumer = null; - try { - if (temporaryResponseQueueCreated) { - messageConsumer = session.createConsumer(responseDestination); - } - else { - String messageId = requestMessage.getJMSMessageID().replaceAll("'", "''"); - String messageSelector = "JMSCorrelationID = '" + messageId + "'"; - messageConsumer = session.createConsumer(responseDestination, messageSelector); - } - Message message = receiveTimeout >= 0 ? messageConsumer.receive(receiveTimeout) : messageConsumer.receive(); - if (message instanceof BytesMessage || message instanceof TextMessage) { - responseMessage = message; - } - else if (message != null) { - throw new IllegalArgumentException( - "Wrong message type: [" + message.getClass() + "]. " + - "Only BytesMessages or TextMessages can be handled."); - } - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - finally { - JmsUtils.closeMessageConsumer(messageConsumer); - if (temporaryResponseQueueCreated) { - try { - ((TemporaryQueue) responseDestination).delete(); - } - catch (JMSException ex) { - // ignore - } - } - } - } + @Override + protected void onReceiveBeforeRead() throws IOException { + MessageConsumer messageConsumer = null; + try { + if (temporaryResponseQueueCreated) { + messageConsumer = session.createConsumer(responseDestination); + } + else { + String messageId = requestMessage.getJMSMessageID().replaceAll("'", "''"); + String messageSelector = "JMSCorrelationID = '" + messageId + "'"; + messageConsumer = session.createConsumer(responseDestination, messageSelector); + } + Message message = receiveTimeout >= 0 ? messageConsumer.receive(receiveTimeout) : messageConsumer.receive(); + if (message instanceof BytesMessage || message instanceof TextMessage) { + responseMessage = message; + } + else if (message != null) { + throw new IllegalArgumentException( + "Wrong message type: [" + message.getClass() + "]. " + + "Only BytesMessages or TextMessages can be handled."); + } + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + finally { + JmsUtils.closeMessageConsumer(messageConsumer); + if (temporaryResponseQueueCreated) { + try { + ((TemporaryQueue) responseDestination).delete(); + } + catch (JMSException ex) { + // ignore + } + } + } + } - @Override - protected boolean hasResponse() throws IOException { - return responseMessage != null; - } + @Override + protected boolean hasResponse() throws IOException { + return responseMessage != null; + } - @Override - protected Iterator getResponseHeaderNames() throws IOException { - try { - return JmsTransportUtils.getHeaderNames(responseMessage); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not get property names", ex); - } - } + @Override + protected Iterator getResponseHeaderNames() throws IOException { + try { + return JmsTransportUtils.getHeaderNames(responseMessage); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not get property names", ex); + } + } - @Override - protected Iterator getResponseHeaders(String name) throws IOException { - try { - return JmsTransportUtils.getHeaders(responseMessage, name); - } - catch (JMSException ex) { - throw new JmsTransportException("Could not get property value", ex); - } - } + @Override + protected Iterator getResponseHeaders(String name) throws IOException { + try { + return JmsTransportUtils.getHeaders(responseMessage, name); + } + catch (JMSException ex) { + throw new JmsTransportException("Could not get property value", ex); + } + } - @Override - protected InputStream getResponseInputStream() throws IOException { - if (responseMessage instanceof BytesMessage) { - return new BytesMessageInputStream((BytesMessage) responseMessage); - } - else if (responseMessage instanceof TextMessage) { - return new TextMessageInputStream((TextMessage) responseMessage, textMessageEncoding); - } - else { - throw new IllegalStateException("Unknown response message type [" + responseMessage + "]"); - } + @Override + protected InputStream getResponseInputStream() throws IOException { + if (responseMessage instanceof BytesMessage) { + return new BytesMessageInputStream((BytesMessage) responseMessage); + } + else if (responseMessage instanceof TextMessage) { + return new TextMessageInputStream((TextMessage) responseMessage, textMessageEncoding); + } + else { + throw new IllegalStateException("Unknown response message type [" + responseMessage + "]"); + } - } + } - @Override - protected void onClose() throws IOException { - JmsUtils.closeSession(session); - ConnectionFactoryUtils.releaseConnection(connection, connectionFactory, true); - } + @Override + protected void onClose() throws IOException { + JmsUtils.closeSession(session); + ConnectionFactoryUtils.releaseConnection(connection, connectionFactory, true); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportConstants.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportConstants.java index 8f1f8613..9557f7f4 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportConstants.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportConstants.java @@ -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, @@ -29,28 +29,28 @@ import org.springframework.ws.transport.TransportConstants; */ public interface JmsTransportConstants extends TransportConstants { - /** The "jms" URI scheme" */ - String JMS_URI_SCHEME = "jms"; + /** The "jms" URI scheme" */ + String JMS_URI_SCHEME = "jms"; - /** Indicates a {@link BytesMessage} type. */ - int BYTES_MESSAGE_TYPE = 1; + /** Indicates a {@link BytesMessage} type. */ + int BYTES_MESSAGE_TYPE = 1; - /** Indicates a {@link TextMessage} type. */ - int TEXT_MESSAGE_TYPE = 2; + /** Indicates a {@link TextMessage} type. */ + int TEXT_MESSAGE_TYPE = 2; - /** Prefix for JMS properties that map to transport headers. */ - String PROPERTY_PREFIX = "SOAPJMS_"; + /** Prefix for JMS properties that map to transport headers. */ + String PROPERTY_PREFIX = "SOAPJMS_"; - /** JMS property used for storing {@link #HEADER_ACCEPT_ENCODING}. */ - String PROPERTY_ACCEPT_ENCODING = PROPERTY_PREFIX + "acceptEncoding"; + /** JMS property used for storing {@link #HEADER_ACCEPT_ENCODING}. */ + String PROPERTY_ACCEPT_ENCODING = PROPERTY_PREFIX + "acceptEncoding"; - /** JMS property used for storing {@link #HEADER_SOAP_ACTION}. */ - String PROPERTY_SOAP_ACTION = PROPERTY_PREFIX + "soapAction"; + /** JMS property used for storing {@link #HEADER_SOAP_ACTION}. */ + String PROPERTY_SOAP_ACTION = PROPERTY_PREFIX + "soapAction"; - /** JMS property used for storing {@link #HEADER_CONTENT_LENGTH}. */ - String PROPERTY_CONTENT_LENGTH = PROPERTY_PREFIX + "contentLength"; + /** JMS property used for storing {@link #HEADER_CONTENT_LENGTH}. */ + String PROPERTY_CONTENT_LENGTH = PROPERTY_PREFIX + "contentLength"; - /** JMS property used for storing {@link #HEADER_CONTENT_TYPE}. */ - String PROPERTY_CONTENT_TYPE = PROPERTY_PREFIX + "contentType"; + /** JMS property used for storing {@link #HEADER_CONTENT_TYPE}. */ + String PROPERTY_CONTENT_TYPE = PROPERTY_PREFIX + "contentType"; } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportException.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportException.java index c24d61ba..76c090b0 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportException.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/JmsTransportException.java @@ -29,21 +29,21 @@ import org.springframework.ws.transport.TransportException; @SuppressWarnings("serial") public class JmsTransportException extends TransportException { - private final JMSException jmsException; + private final JMSException jmsException; - public JmsTransportException(String msg, JMSException ex) { - super(msg + ": " + ex.getMessage()); - initCause(ex); - jmsException = ex; - } + public JmsTransportException(String msg, JMSException ex) { + super(msg + ": " + ex.getMessage()); + initCause(ex); + jmsException = ex; + } - public JmsTransportException(JMSException ex) { - super(ex.getMessage()); - initCause(ex); - jmsException = ex; - } + public JmsTransportException(JMSException ex) { + super(ex.getMessage()); + initCause(ex); + jmsException = ex; + } - public JMSException getJmsException() { - return jmsException; - } + public JMSException getJmsException() { + return jmsException; + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageInputStream.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageInputStream.java index 69696091..b3703f3d 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageInputStream.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageInputStream.java @@ -33,20 +33,20 @@ import org.springframework.util.Assert; */ class TextMessageInputStream extends FilterInputStream { - TextMessageInputStream(TextMessage message, String encoding) throws IOException { - super(createInputStream(message, encoding)); - } + TextMessageInputStream(TextMessage message, String encoding) throws IOException { + super(createInputStream(message, encoding)); + } - private static InputStream createInputStream(TextMessage message, String encoding) throws IOException { - Assert.notNull(message, "'message' must not be null"); - Assert.notNull(encoding, "'encoding' must not be null"); - try { - String text = message.getText(); - byte[] contents = text != null ? text.getBytes(encoding) : new byte[0]; - return new ByteArrayInputStream(contents); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + private static InputStream createInputStream(TextMessage message, String encoding) throws IOException { + Assert.notNull(message, "'message' must not be null"); + Assert.notNull(encoding, "'encoding' must not be null"); + try { + String text = message.getText(); + byte[] contents = text != null ? text.getBytes(encoding) : new byte[0]; + return new ByteArrayInputStream(contents); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageOutputStream.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageOutputStream.java index b7e8ee14..3f4a42d2 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageOutputStream.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/TextMessageOutputStream.java @@ -32,28 +32,28 @@ import org.springframework.util.Assert; */ class TextMessageOutputStream extends FilterOutputStream { - private final TextMessage message; + private final TextMessage message; - private final String encoding; + private final String encoding; - TextMessageOutputStream(TextMessage message, String encoding) { - super(new ByteArrayOutputStream()); - Assert.notNull(message, "'message' must not be null"); - Assert.notNull(encoding, "'encoding' must not be null"); - this.message = message; - this.encoding = encoding; - } + TextMessageOutputStream(TextMessage message, String encoding) { + super(new ByteArrayOutputStream()); + Assert.notNull(message, "'message' must not be null"); + Assert.notNull(encoding, "'encoding' must not be null"); + this.message = message; + this.encoding = encoding; + } - @Override - public void flush() throws IOException { - super.flush(); - try { - ByteArrayOutputStream baos = (ByteArrayOutputStream) out; - String text = new String(baos.toByteArray(), encoding); - message.setText(text); - } - catch (JMSException ex) { - throw new JmsTransportException(ex); - } - } + @Override + public void flush() throws IOException { + super.flush(); + try { + ByteArrayOutputStream baos = (ByteArrayOutputStream) out; + String text = new String(baos.toByteArray(), encoding); + message.setText(text); + } + catch (JMSException ex) { + throw new JmsTransportException(ex); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/WebServiceMessageListener.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/WebServiceMessageListener.java index b2e3476a..995f5bf0 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/WebServiceMessageListener.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/WebServiceMessageListener.java @@ -40,19 +40,19 @@ import org.springframework.ws.transport.WebServiceMessageReceiver; */ public class WebServiceMessageListener extends JmsMessageReceiver implements SessionAwareMessageListener { - @Override - public void onMessage(Message message, Session session) throws JMSException { - try { - handleMessage(message, session); - } - catch (JmsTransportException ex) { - throw ex.getJmsException(); - } - catch (Exception ex) { - JMSException jmsException = new JMSException(ex.getMessage()); - jmsException.setLinkedException(ex); - throw jmsException; - } - } + @Override + public void onMessage(Message message, Session session) throws JMSException { + try { + handleMessage(message, session); + } + catch (JmsTransportException ex) { + throw ex.getJmsException(); + } + catch (Exception ex) { + JMSException jmsException = new JMSException(ex.getMessage()); + jmsException.setLinkedException(ex); + throw jmsException; + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/support/JmsTransportUtils.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/support/JmsTransportUtils.java index 167aafb3..7ad71346 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/support/JmsTransportUtils.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/jms/support/JmsTransportUtils.java @@ -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, @@ -43,220 +43,220 @@ import org.springframework.ws.transport.jms.JmsTransportConstants; */ public abstract class JmsTransportUtils { - private static final String[] CONVERSION_TABLE = new String[]{JmsTransportConstants.HEADER_CONTENT_TYPE, - JmsTransportConstants.PROPERTY_CONTENT_TYPE, JmsTransportConstants.HEADER_CONTENT_LENGTH, - JmsTransportConstants.PROPERTY_CONTENT_LENGTH, JmsTransportConstants.HEADER_SOAP_ACTION, - JmsTransportConstants.PROPERTY_SOAP_ACTION, JmsTransportConstants.HEADER_ACCEPT_ENCODING, - JmsTransportConstants.PROPERTY_ACCEPT_ENCODING}; + private static final String[] CONVERSION_TABLE = new String[]{JmsTransportConstants.HEADER_CONTENT_TYPE, + JmsTransportConstants.PROPERTY_CONTENT_TYPE, JmsTransportConstants.HEADER_CONTENT_LENGTH, + JmsTransportConstants.PROPERTY_CONTENT_LENGTH, JmsTransportConstants.HEADER_SOAP_ACTION, + JmsTransportConstants.PROPERTY_SOAP_ACTION, JmsTransportConstants.HEADER_ACCEPT_ENCODING, + JmsTransportConstants.PROPERTY_ACCEPT_ENCODING}; - private static final Pattern DESTINATION_NAME_PATTERN = Pattern.compile("^([^\\?]+)"); + private static final Pattern DESTINATION_NAME_PATTERN = Pattern.compile("^([^\\?]+)"); - private static final Pattern DELIVERY_MODE_PATTERN = Pattern.compile("deliveryMode=(PERSISTENT|NON_PERSISTENT)"); + private static final Pattern DELIVERY_MODE_PATTERN = Pattern.compile("deliveryMode=(PERSISTENT|NON_PERSISTENT)"); - private static final Pattern MESSAGE_TYPE_PATTERN = Pattern.compile("messageType=(BYTES_MESSAGE|TEXT_MESSAGE)"); + private static final Pattern MESSAGE_TYPE_PATTERN = Pattern.compile("messageType=(BYTES_MESSAGE|TEXT_MESSAGE)"); - private static final Pattern TIME_TO_LIVE_PATTERN = Pattern.compile("timeToLive=(\\d+)"); + private static final Pattern TIME_TO_LIVE_PATTERN = Pattern.compile("timeToLive=(\\d+)"); - private static final Pattern PRIORITY_PATTERN = Pattern.compile("priority=(\\d)"); + private static final Pattern PRIORITY_PATTERN = Pattern.compile("priority=(\\d)"); - private static final Pattern REPLY_TO_NAME_PATTERN = Pattern.compile("replyToName=([^&]+)"); + private static final Pattern REPLY_TO_NAME_PATTERN = Pattern.compile("replyToName=([^&]+)"); - private JmsTransportUtils() { - } + private JmsTransportUtils() { + } - /** - * Converts the given transport header to a JMS property name. Returns the given header name if no match is found. - * - * @param headerName the header name to transform - * @return the JMS property name - */ - public static String headerToJmsProperty(String headerName) { - for (int i = 0; i < CONVERSION_TABLE.length; i = i + 2) { - if (CONVERSION_TABLE[i].equals(headerName)) { - return CONVERSION_TABLE[i + 1]; - } - } - return headerName; - } + /** + * Converts the given transport header to a JMS property name. Returns the given header name if no match is found. + * + * @param headerName the header name to transform + * @return the JMS property name + */ + public static String headerToJmsProperty(String headerName) { + for (int i = 0; i < CONVERSION_TABLE.length; i = i + 2) { + if (CONVERSION_TABLE[i].equals(headerName)) { + return CONVERSION_TABLE[i + 1]; + } + } + return headerName; + } - /** - * Converts the given JMS property name to a transport header name. Returns the given property name if no match is - * found. - * - * @param propertyName the JMS property name to transform - * @return the transport header name - */ - public static String jmsPropertyToHeader(String propertyName) { - for (int i = 1; i < CONVERSION_TABLE.length; i = i + 2) { - if (CONVERSION_TABLE[i].equals(propertyName)) { - return CONVERSION_TABLE[i - 1]; - } - } - return propertyName; - } + /** + * Converts the given JMS property name to a transport header name. Returns the given property name if no match is + * found. + * + * @param propertyName the JMS property name to transform + * @return the transport header name + */ + public static String jmsPropertyToHeader(String propertyName) { + for (int i = 1; i < CONVERSION_TABLE.length; i = i + 2) { + if (CONVERSION_TABLE[i].equals(propertyName)) { + return CONVERSION_TABLE[i - 1]; + } + } + return propertyName; + } - /** - * Converts the given JMS destination into a {@code jms} URI. - * - * @param destination the destination - * @return a jms URI - */ - public static URI toUri(Destination destination) throws URISyntaxException, JMSException { - if (destination == null) { - return null; - } - String destinationName; - if (destination instanceof Queue) { - destinationName = ((Queue) destination).getQueueName(); - } - else if (destination instanceof Topic) { - Topic topic = (Topic) destination; - destinationName = topic.getTopicName(); - } - else { - throw new IllegalArgumentException("Destination [ " + destination + "] is neither Queue nor Topic"); - } - return new URI(JmsTransportConstants.JMS_URI_SCHEME, destinationName, null); - } + /** + * Converts the given JMS destination into a {@code jms} URI. + * + * @param destination the destination + * @return a jms URI + */ + public static URI toUri(Destination destination) throws URISyntaxException, JMSException { + if (destination == null) { + return null; + } + String destinationName; + if (destination instanceof Queue) { + destinationName = ((Queue) destination).getQueueName(); + } + else if (destination instanceof Topic) { + Topic topic = (Topic) destination; + destinationName = topic.getTopicName(); + } + else { + throw new IllegalArgumentException("Destination [ " + destination + "] is neither Queue nor Topic"); + } + return new URI(JmsTransportConstants.JMS_URI_SCHEME, destinationName, null); + } - /** Returns the destination name of the given URI. */ - public static String getDestinationName(URI uri) { - return getStringParameter(DESTINATION_NAME_PATTERN, uri); - } + /** Returns the destination name of the given URI. */ + public static String getDestinationName(URI uri) { + return getStringParameter(DESTINATION_NAME_PATTERN, uri); + } - /** Adds the given header to the specified message. */ - public static void addHeader(Message message, String name, String value) throws JMSException { - String propertyName = JmsTransportUtils.headerToJmsProperty(name); - message.setStringProperty(propertyName, value); - } + /** Adds the given header to the specified message. */ + public static void addHeader(Message message, String name, String value) throws JMSException { + String propertyName = JmsTransportUtils.headerToJmsProperty(name); + message.setStringProperty(propertyName, value); + } - /** - * Returns an iterator over all header names in the given message. Delegates to {@link - * #jmsPropertyToHeader(String)}. - */ - public static Iterator getHeaderNames(Message message) throws JMSException { - Enumeration properties = message.getPropertyNames(); - List results = new ArrayList(); - while (properties.hasMoreElements()) { - String property = (String) properties.nextElement(); - if (property.startsWith(JmsTransportConstants.PROPERTY_PREFIX)) { - String header = jmsPropertyToHeader(property); - results.add(header); - } - } - return results.iterator(); - } + /** + * Returns an iterator over all header names in the given message. Delegates to {@link + * #jmsPropertyToHeader(String)}. + */ + public static Iterator getHeaderNames(Message message) throws JMSException { + Enumeration properties = message.getPropertyNames(); + List results = new ArrayList(); + while (properties.hasMoreElements()) { + String property = (String) properties.nextElement(); + if (property.startsWith(JmsTransportConstants.PROPERTY_PREFIX)) { + String header = jmsPropertyToHeader(property); + results.add(header); + } + } + return results.iterator(); + } - /** - * Returns an iterator over all the header values of the given message and header name. Delegates to {@link - * #headerToJmsProperty(String)}. - */ - public static Iterator getHeaders(Message message, String name) throws JMSException { - String propertyName = headerToJmsProperty(name); - String value = message.getStringProperty(propertyName); - if (value != null) { - return Collections.singletonList(value).iterator(); - } - else { - return Collections.emptyList().iterator(); - } - } + /** + * Returns an iterator over all the header values of the given message and header name. Delegates to {@link + * #headerToJmsProperty(String)}. + */ + public static Iterator getHeaders(Message message, String name) throws JMSException { + String propertyName = headerToJmsProperty(name); + String value = message.getStringProperty(propertyName); + if (value != null) { + return Collections.singletonList(value).iterator(); + } + else { + return Collections.emptyList().iterator(); + } + } - /** - * Returns the delivery mode of the given URI. - * - * @see DeliveryMode#NON_PERSISTENT - * @see DeliveryMode#PERSISTENT - * @see Message#DEFAULT_DELIVERY_MODE - */ - public static int getDeliveryMode(URI uri) { - String deliveryMode = getStringParameter(DELIVERY_MODE_PATTERN, uri); - if ("NON_PERSISTENT".equals(deliveryMode)) { - return DeliveryMode.NON_PERSISTENT; - } - else if ("PERSISTENT".equals(deliveryMode)) { - return DeliveryMode.PERSISTENT; - } - else { - return Message.DEFAULT_DELIVERY_MODE; - } - } + /** + * Returns the delivery mode of the given URI. + * + * @see DeliveryMode#NON_PERSISTENT + * @see DeliveryMode#PERSISTENT + * @see Message#DEFAULT_DELIVERY_MODE + */ + public static int getDeliveryMode(URI uri) { + String deliveryMode = getStringParameter(DELIVERY_MODE_PATTERN, uri); + if ("NON_PERSISTENT".equals(deliveryMode)) { + return DeliveryMode.NON_PERSISTENT; + } + else if ("PERSISTENT".equals(deliveryMode)) { + return DeliveryMode.PERSISTENT; + } + else { + return Message.DEFAULT_DELIVERY_MODE; + } + } - /** - * Returns the message type of the given URI. Defaults to {@link JmsTransportConstants#BYTES_MESSAGE_TYPE}. - * - * @see JmsTransportConstants#BYTES_MESSAGE_TYPE - * @see JmsTransportConstants#TEXT_MESSAGE_TYPE - */ - public static int getMessageType(URI uri) { - String deliveryMode = getStringParameter(MESSAGE_TYPE_PATTERN, uri); - if ("TEXT_MESSAGE".equals(deliveryMode)) { - return JmsTransportConstants.TEXT_MESSAGE_TYPE; - } - else { - return JmsTransportConstants.BYTES_MESSAGE_TYPE; - } - } + /** + * Returns the message type of the given URI. Defaults to {@link JmsTransportConstants#BYTES_MESSAGE_TYPE}. + * + * @see JmsTransportConstants#BYTES_MESSAGE_TYPE + * @see JmsTransportConstants#TEXT_MESSAGE_TYPE + */ + public static int getMessageType(URI uri) { + String deliveryMode = getStringParameter(MESSAGE_TYPE_PATTERN, uri); + if ("TEXT_MESSAGE".equals(deliveryMode)) { + return JmsTransportConstants.TEXT_MESSAGE_TYPE; + } + else { + return JmsTransportConstants.BYTES_MESSAGE_TYPE; + } + } - /** - * Returns the lifetime, in milliseconds, of the given URI. - * - * @see Message#DEFAULT_TIME_TO_LIVE - */ - public static long getTimeToLive(URI uri) { - return getLongParameter(TIME_TO_LIVE_PATTERN, uri, Message.DEFAULT_TIME_TO_LIVE); - } + /** + * Returns the lifetime, in milliseconds, of the given URI. + * + * @see Message#DEFAULT_TIME_TO_LIVE + */ + public static long getTimeToLive(URI uri) { + return getLongParameter(TIME_TO_LIVE_PATTERN, uri, Message.DEFAULT_TIME_TO_LIVE); + } - /** - * Returns the priority of the given URI. - * - * @see Message#DEFAULT_PRIORITY - */ - public static int getPriority(URI uri) { - return getIntParameter(PRIORITY_PATTERN, uri, Message.DEFAULT_PRIORITY); - } + /** + * Returns the priority of the given URI. + * + * @see Message#DEFAULT_PRIORITY + */ + public static int getPriority(URI uri) { + return getIntParameter(PRIORITY_PATTERN, uri, Message.DEFAULT_PRIORITY); + } - /** - * Returns the reply-to name of the given URI. - * - * @see Message#setJMSReplyTo(Destination) - */ - public static String getReplyToName(URI uri) { - return getStringParameter(REPLY_TO_NAME_PATTERN, uri); - } + /** + * Returns the reply-to name of the given URI. + * + * @see Message#setJMSReplyTo(Destination) + */ + public static String getReplyToName(URI uri) { + return getStringParameter(REPLY_TO_NAME_PATTERN, uri); + } - private static String getStringParameter(Pattern pattern, URI uri) { - Matcher matcher = pattern.matcher(uri.getSchemeSpecificPart()); - if (matcher.find() && matcher.groupCount() == 1) { - return matcher.group(1); - } - return null; - } + private static String getStringParameter(Pattern pattern, URI uri) { + Matcher matcher = pattern.matcher(uri.getSchemeSpecificPart()); + if (matcher.find() && matcher.groupCount() == 1) { + return matcher.group(1); + } + return null; + } - private static int getIntParameter(Pattern pattern, URI uri, int defaultValue) { - Matcher matcher = pattern.matcher(uri.getSchemeSpecificPart()); - if (matcher.find() && matcher.groupCount() == 1) { - try { - return Integer.parseInt(matcher.group(1)); - } - catch (NumberFormatException ex) { - // fall through to default value - } - } - return defaultValue; - } + private static int getIntParameter(Pattern pattern, URI uri, int defaultValue) { + Matcher matcher = pattern.matcher(uri.getSchemeSpecificPart()); + if (matcher.find() && matcher.groupCount() == 1) { + try { + return Integer.parseInt(matcher.group(1)); + } + catch (NumberFormatException ex) { + // fall through to default value + } + } + return defaultValue; + } - private static long getLongParameter(Pattern pattern, URI uri, long defaultValue) { - Matcher matcher = pattern.matcher(uri.getSchemeSpecificPart()); - if (matcher.find() && matcher.groupCount() == 1) { - try { - return Long.parseLong(matcher.group(1)); - } - catch (NumberFormatException ex) { - // fall through to default value - } - } - return defaultValue; - } + private static long getLongParameter(Pattern pattern, URI uri, long defaultValue) { + Matcher matcher = pattern.matcher(uri.getSchemeSpecificPart()); + if (matcher.find() && matcher.groupCount() == 1) { + try { + return Long.parseLong(matcher.group(1)); + } + catch (NumberFormatException ex) { + // fall through to default value + } + } + return defaultValue; + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageReceiver.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageReceiver.java index 24e6dde4..77fdb3d7 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageReceiver.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageReceiver.java @@ -52,231 +52,231 @@ import org.springframework.ws.transport.support.AbstractAsyncStandaloneMessageRe */ public class MailMessageReceiver extends AbstractAsyncStandaloneMessageReceiver { - private Session session = Session.getInstance(new Properties(), null); + private Session session = Session.getInstance(new Properties(), null); - private URLName storeUri; + private URLName storeUri; - private URLName transportUri; + private URLName transportUri; - private Folder folder; + private Folder folder; - private Store store; + private Store store; - private InternetAddress from; + private InternetAddress from; - private MonitoringStrategy monitoringStrategy; + private MonitoringStrategy monitoringStrategy; - /** Sets the from address to use when sending response messages. */ - public void setFrom(String from) throws AddressException { - this.from = new InternetAddress(from); - } + /** Sets the from address to use when sending response messages. */ + public void setFrom(String from) throws AddressException { + this.from = new InternetAddress(from); + } - /** - * Set JavaMail properties for the {@link Session}. - * - *

A new {@link Session} will be created with those properties. Use either this method or {@link #setSession}, but - * not both. - * - *

Non-default properties in this instance will override given JavaMail properties. - */ - public void setJavaMailProperties(Properties javaMailProperties) { - session = Session.getInstance(javaMailProperties, null); - } + /** + * Set JavaMail properties for the {@link Session}. + * + *

A new {@link Session} will be created with those properties. Use either this method or {@link #setSession}, but + * not both. + * + *

Non-default properties in this instance will override given JavaMail properties. + */ + public void setJavaMailProperties(Properties javaMailProperties) { + session = Session.getInstance(javaMailProperties, null); + } - /** - * Set the JavaMail {@code Session}, possibly pulled from JNDI. - * - *

Default is a new {@code Session} without defaults, that is completely configured via this instance's - * properties. - * - *

If using a pre-configured {@code Session}, non-default properties in this instance will override the - * settings in the {@code Session}. - * - * @see #setJavaMailProperties - */ - public void setSession(Session session) { - Assert.notNull(session, "Session must not be null"); - this.session = session; - } + /** + * Set the JavaMail {@code Session}, possibly pulled from JNDI. + * + *

Default is a new {@code Session} without defaults, that is completely configured via this instance's + * properties. + * + *

If using a pre-configured {@code Session}, non-default properties in this instance will override the + * settings in the {@code Session}. + * + * @see #setJavaMailProperties + */ + public void setSession(Session session) { + Assert.notNull(session, "Session must not be null"); + this.session = session; + } - /** - * Sets the JavaMail Store URI to be used for retrieving request messages. Typically takes the form of - * {@code [imap|pop3]://user:password@host:port/INBOX}. Setting this property is required. - * - *

For example, {@code imap://john:secret@imap.example.com/INBOX} - * - * @see Session#getStore(URLName) - */ - public void setStoreUri(String storeUri) { - this.storeUri = new URLName(storeUri); - } + /** + * Sets the JavaMail Store URI to be used for retrieving request messages. Typically takes the form of + * {@code [imap|pop3]://user:password@host:port/INBOX}. Setting this property is required. + * + *

For example, {@code imap://john:secret@imap.example.com/INBOX} + * + * @see Session#getStore(URLName) + */ + public void setStoreUri(String storeUri) { + this.storeUri = new URLName(storeUri); + } - /** - * Sets the JavaMail Transport URI to be used for sending response messages. Typically takes the form of - * {@code smtp://user:password@host:port}. Setting this property is required. - * - *

For example, {@code smtp://john:secret@smtp.example.com} - * - * @see Session#getTransport(URLName) - */ - public void setTransportUri(String transportUri) { - this.transportUri = new URLName(transportUri); - } + /** + * Sets the JavaMail Transport URI to be used for sending response messages. Typically takes the form of + * {@code smtp://user:password@host:port}. Setting this property is required. + * + *

For example, {@code smtp://john:secret@smtp.example.com} + * + * @see Session#getTransport(URLName) + */ + public void setTransportUri(String transportUri) { + this.transportUri = new URLName(transportUri); + } - /** - * Sets the monitoring strategy to use for retrieving new requests. Default is the {@link - * PollingMonitoringStrategy}. - */ - public void setMonitoringStrategy(MonitoringStrategy monitoringStrategy) { - this.monitoringStrategy = monitoringStrategy; - } + /** + * Sets the monitoring strategy to use for retrieving new requests. Default is the {@link + * PollingMonitoringStrategy}. + */ + public void setMonitoringStrategy(MonitoringStrategy monitoringStrategy) { + this.monitoringStrategy = monitoringStrategy; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(storeUri, "Property 'storeUri' is required"); - Assert.notNull(transportUri, "Property 'transportUri' is required"); - if (monitoringStrategy == null) { - String protocol = storeUri.getProtocol(); - if ("pop3".equals(protocol)) { - monitoringStrategy = new Pop3PollingMonitoringStrategy(); - } - else if ("imap".equals(protocol)) { - monitoringStrategy = new PollingMonitoringStrategy(); - } - else { - throw new IllegalArgumentException("Cannot determine monitoring strategy for \"" + protocol + "\". " + - "Set the 'monitoringStrategy' explicitly."); - } - } - super.afterPropertiesSet(); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(storeUri, "Property 'storeUri' is required"); + Assert.notNull(transportUri, "Property 'transportUri' is required"); + if (monitoringStrategy == null) { + String protocol = storeUri.getProtocol(); + if ("pop3".equals(protocol)) { + monitoringStrategy = new Pop3PollingMonitoringStrategy(); + } + else if ("imap".equals(protocol)) { + monitoringStrategy = new PollingMonitoringStrategy(); + } + else { + throw new IllegalArgumentException("Cannot determine monitoring strategy for \"" + protocol + "\". " + + "Set the 'monitoringStrategy' explicitly."); + } + } + super.afterPropertiesSet(); + } - @Override - protected void onActivate() throws MessagingException { - openSession(); - openFolder(); - } + @Override + protected void onActivate() throws MessagingException { + openSession(); + openFolder(); + } - @Override - protected void onStart() { - if (logger.isInfoEnabled()) { - logger.info("Starting mail receiver [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); - } - execute(new MonitoringRunnable()); - } + @Override + protected void onStart() { + if (logger.isInfoEnabled()) { + logger.info("Starting mail receiver [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); + } + execute(new MonitoringRunnable()); + } - @Override - protected void onStop() { - if (logger.isInfoEnabled()) { - logger.info("Stopping mail receiver [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); - } - closeFolder(); - } + @Override + protected void onStop() { + if (logger.isInfoEnabled()) { + logger.info("Stopping mail receiver [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); + } + closeFolder(); + } - @Override - protected void onShutdown() { - if (logger.isInfoEnabled()) { - logger.info("Shutting down mail receiver [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); - } - closeFolder(); - closeSession(); - } + @Override + protected void onShutdown() { + if (logger.isInfoEnabled()) { + logger.info("Shutting down mail receiver [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); + } + closeFolder(); + closeSession(); + } - private void openSession() throws MessagingException { - store = session.getStore(storeUri); - if (logger.isDebugEnabled()) { - logger.debug("Connecting to store [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); - } - store.connect(); - } + private void openSession() throws MessagingException { + store = session.getStore(storeUri); + if (logger.isDebugEnabled()) { + logger.debug("Connecting to store [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); + } + store.connect(); + } - private void openFolder() throws MessagingException { - if (folder != null && folder.isOpen()) { - return; - } - folder = store.getFolder(storeUri); - if (folder == null || !folder.exists()) { - throw new IllegalStateException("No default folder to receive from"); - } - if (logger.isDebugEnabled()) { - logger.debug("Opening folder [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); - } - folder.open(monitoringStrategy.getFolderOpenMode()); - } + private void openFolder() throws MessagingException { + if (folder != null && folder.isOpen()) { + return; + } + folder = store.getFolder(storeUri); + if (folder == null || !folder.exists()) { + throw new IllegalStateException("No default folder to receive from"); + } + if (logger.isDebugEnabled()) { + logger.debug("Opening folder [" + MailTransportUtils.toPasswordProtectedString(storeUri) + "]"); + } + folder.open(monitoringStrategy.getFolderOpenMode()); + } - private void closeFolder() { - MailTransportUtils.closeFolder(folder, true); - } + private void closeFolder() { + MailTransportUtils.closeFolder(folder, true); + } - private void closeSession() { - MailTransportUtils.closeService(store); - } + private void closeSession() { + MailTransportUtils.closeService(store); + } - private class MonitoringRunnable implements SchedulingAwareRunnable { + private class MonitoringRunnable implements SchedulingAwareRunnable { - @Override - public void run() { - try { - openFolder(); - while (isRunning()) { - try { - Message[] messages = monitoringStrategy.monitor(folder); - for (Message message : messages) { - MessageHandler handler = new MessageHandler(message); - execute(handler); - } - } - catch (FolderClosedException ex) { - logger.debug("Folder closed, reopening"); - if (isRunning()) { - openFolder(); - } - } - catch (MessagingException ex) { - logger.warn(ex); - } - } - } - catch (InterruptedException ex) { - // Restore the interrupted status - Thread.currentThread().interrupt(); - } - catch (MessagingException ex) { - logger.error(ex); - } - } + @Override + public void run() { + try { + openFolder(); + while (isRunning()) { + try { + Message[] messages = monitoringStrategy.monitor(folder); + for (Message message : messages) { + MessageHandler handler = new MessageHandler(message); + execute(handler); + } + } + catch (FolderClosedException ex) { + logger.debug("Folder closed, reopening"); + if (isRunning()) { + openFolder(); + } + } + catch (MessagingException ex) { + logger.warn(ex); + } + } + } + catch (InterruptedException ex) { + // Restore the interrupted status + Thread.currentThread().interrupt(); + } + catch (MessagingException ex) { + logger.error(ex); + } + } - @Override - public boolean isLongLived() { - return true; - } - } + @Override + public boolean isLongLived() { + return true; + } + } - private class MessageHandler implements SchedulingAwareRunnable { + private class MessageHandler implements SchedulingAwareRunnable { - private final Message message; + private final Message message; - public MessageHandler(Message message) { - this.message = message; - } + public MessageHandler(Message message) { + this.message = message; + } - @Override - public void run() { - MailReceiverConnection connection = new MailReceiverConnection(message, session); - connection.setTransportUri(transportUri); - connection.setFrom(from); - try { - handleConnection(connection); - } - catch (Exception ex) { - logger.error("Could not handle incoming mail connection", ex); - } - } + @Override + public void run() { + MailReceiverConnection connection = new MailReceiverConnection(message, session); + connection.setTransportUri(transportUri); + connection.setFrom(from); + try { + handleConnection(connection); + } + catch (Exception ex) { + logger.error("Could not handle incoming mail connection", ex); + } + } - @Override - public boolean isLongLived() { - return false; - } - } + @Override + public boolean isLongLived() { + return false; + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageSender.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageSender.java index c11ef205..1d6b35b9 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageSender.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailMessageSender.java @@ -61,111 +61,111 @@ import org.springframework.ws.transport.mail.support.MailTransportUtils; */ public class MailMessageSender implements WebServiceMessageSender, InitializingBean { - /** - * Default timeout for receive operations. Set to 1000 * 60 milliseconds (i.e. 1 minute). - */ - public static final long DEFAULT_RECEIVE_TIMEOUT = 1000 * 60; + /** + * Default timeout for receive operations. Set to 1000 * 60 milliseconds (i.e. 1 minute). + */ + public static final long DEFAULT_RECEIVE_TIMEOUT = 1000 * 60; - private long receiveSleepTime = DEFAULT_RECEIVE_TIMEOUT; + private long receiveSleepTime = DEFAULT_RECEIVE_TIMEOUT; - private Session session = Session.getInstance(new Properties(), null); + private Session session = Session.getInstance(new Properties(), null); - private URLName storeUri; + private URLName storeUri; - private URLName transportUri; + private URLName transportUri; - private InternetAddress from; + private InternetAddress from; - /** - * Sets the from address to use when sending request messages. - */ - public void setFrom(String from) throws AddressException { - this.from = new InternetAddress(from); - } + /** + * Sets the from address to use when sending request messages. + */ + public void setFrom(String from) throws AddressException { + this.from = new InternetAddress(from); + } - /** - * Set JavaMail properties for the {@link Session}. - * - *

A new {@link Session} will be created with those properties. Use either this method or {@link #setSession}, but - * not both. - * - *

Non-default properties in this instance will override given JavaMail properties. - */ - public void setJavaMailProperties(Properties javaMailProperties) { - session = Session.getInstance(javaMailProperties, null); - } + /** + * Set JavaMail properties for the {@link Session}. + * + *

A new {@link Session} will be created with those properties. Use either this method or {@link #setSession}, but + * not both. + * + *

Non-default properties in this instance will override given JavaMail properties. + */ + public void setJavaMailProperties(Properties javaMailProperties) { + session = Session.getInstance(javaMailProperties, null); + } - /** - * Set the sleep time to use for receive calls, in milliseconds. The default is 1000 * 60 ms, that - * is 1 minute. - */ - public void setReceiveSleepTime(long receiveSleepTime) { - this.receiveSleepTime = receiveSleepTime; - } + /** + * Set the sleep time to use for receive calls, in milliseconds. The default is 1000 * 60 ms, that + * is 1 minute. + */ + public void setReceiveSleepTime(long receiveSleepTime) { + this.receiveSleepTime = receiveSleepTime; + } - /** - * Set the JavaMail {@code Session}, possibly pulled from JNDI. - * - *

Default is a new {@code Session} without defaults, that is completely configured via this instance's - * properties. - * - *

If using a pre-configured {@code Session}, non-default properties in this instance will override the - * settings in the {@code Session}. - * - * @see #setJavaMailProperties - */ - public void setSession(Session session) { - Assert.notNull(session, "Session must not be null"); - this.session = session; - } + /** + * Set the JavaMail {@code Session}, possibly pulled from JNDI. + * + *

Default is a new {@code Session} without defaults, that is completely configured via this instance's + * properties. + * + *

If using a pre-configured {@code Session}, non-default properties in this instance will override the + * settings in the {@code Session}. + * + * @see #setJavaMailProperties + */ + public void setSession(Session session) { + Assert.notNull(session, "Session must not be null"); + this.session = session; + } - /** - * Sets the JavaMail Store URI to be used for retrieving response messages. Typically takes the form of - * {@code [imap|pop3]://user:password@host:port/INBOX}. Setting this property is required. - * - *

For example, {@code imap://john:secret@imap.example.com/INBOX} - * - * @see Session#getStore(URLName) - */ - public void setStoreUri(String storeUri) { - this.storeUri = new URLName(storeUri); - } + /** + * Sets the JavaMail Store URI to be used for retrieving response messages. Typically takes the form of + * {@code [imap|pop3]://user:password@host:port/INBOX}. Setting this property is required. + * + *

For example, {@code imap://john:secret@imap.example.com/INBOX} + * + * @see Session#getStore(URLName) + */ + public void setStoreUri(String storeUri) { + this.storeUri = new URLName(storeUri); + } - /** - * Sets the JavaMail Transport URI to be used for sending response messages. Typically takes the form of - * {@code smtp://user:password@host:port}. Setting this property is required. - * - *

For example, {@code smtp://john:secret@smtp.example.com} - * - * @see Session#getTransport(URLName) - */ - public void setTransportUri(String transportUri) { - this.transportUri = new URLName(transportUri); - } + /** + * Sets the JavaMail Transport URI to be used for sending response messages. Typically takes the form of + * {@code smtp://user:password@host:port}. Setting this property is required. + * + *

For example, {@code smtp://john:secret@smtp.example.com} + * + * @see Session#getTransport(URLName) + */ + public void setTransportUri(String transportUri) { + this.transportUri = new URLName(transportUri); + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(transportUri, "'transportUri' is required"); - Assert.notNull(storeUri, "'storeUri' is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(transportUri, "'transportUri' is required"); + Assert.notNull(storeUri, "'storeUri' is required"); + } - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - InternetAddress to = MailTransportUtils.getTo(uri); - MailSenderConnection connection = - new MailSenderConnection(session, transportUri, storeUri, to, receiveSleepTime); - if (from != null) { - connection.setFrom(from); - } - String subject = MailTransportUtils.getSubject(uri); - if (subject != null) { - connection.setSubject(subject); - } - return connection; - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + InternetAddress to = MailTransportUtils.getTo(uri); + MailSenderConnection connection = + new MailSenderConnection(session, transportUri, storeUri, to, receiveSleepTime); + if (from != null) { + connection.setFrom(from); + } + String subject = MailTransportUtils.getSubject(uri); + if (subject != null) { + connection.setSubject(subject); + } + return connection; + } - @Override - public boolean supports(URI uri) { - return uri.getScheme().equals(MailTransportConstants.MAIL_URI_SCHEME); - } + @Override + public boolean supports(URI uri) { + return uri.getScheme().equals(MailTransportConstants.MAIL_URI_SCHEME); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailReceiverConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailReceiverConnection.java index a6fbdac6..7aac23b3 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailReceiverConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailReceiverConnection.java @@ -56,206 +56,206 @@ import org.springframework.ws.transport.mail.support.MailTransportUtils; */ public class MailReceiverConnection extends AbstractReceiverConnection { - private final Message requestMessage; + private final Message requestMessage; - private final Session session; + private final Session session; - private Message responseMessage; + private Message responseMessage; - private ByteArrayOutputStream responseBuffer; + private ByteArrayOutputStream responseBuffer; - private String responseContentType; + private String responseContentType; - private URLName transportUri; + private URLName transportUri; - private InternetAddress from; + private InternetAddress from; - /** Constructs a new Mail connection with the given parameters. */ - protected MailReceiverConnection(Message requestMessage, Session session) { - Assert.notNull(requestMessage, "'requestMessage' must not be null"); - Assert.notNull(session, "'session' must not be null"); - this.requestMessage = requestMessage; - this.session = session; - } + /** Constructs a new Mail connection with the given parameters. */ + protected MailReceiverConnection(Message requestMessage, Session session) { + Assert.notNull(requestMessage, "'requestMessage' must not be null"); + Assert.notNull(session, "'session' must not be null"); + this.requestMessage = requestMessage; + this.session = session; + } - /** Returns the request message for this connection. */ - public Message getRequestMessage() { - return requestMessage; - } + /** Returns the request message for this connection. */ + public Message getRequestMessage() { + return requestMessage; + } - /** Returns the response message, if any, for this connection. */ - public Message getResponseMessage() { - return responseMessage; - } + /** Returns the response message, if any, for this connection. */ + public Message getResponseMessage() { + return responseMessage; + } - /* - * Package-friendly setters - */ - void setTransportUri(URLName transportUri) { - this.transportUri = transportUri; - } + /* + * Package-friendly setters + */ + void setTransportUri(URLName transportUri) { + this.transportUri = transportUri; + } - void setFrom(InternetAddress from) { - this.from = from; - } + void setFrom(InternetAddress from) { + this.from = from; + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - try { - Address[] recipients = requestMessage.getRecipients(Message.RecipientType.TO); - if (!ObjectUtils.isEmpty(recipients) && recipients[0] instanceof InternetAddress) { - return MailTransportUtils.toUri((InternetAddress) recipients[0], requestMessage.getSubject()); - } - else { - throw new URISyntaxException("", "Could not determine To header"); - } - } - catch (MessagingException ex) { - throw new URISyntaxException("", ex.getMessage()); - } - } + @Override + public URI getUri() throws URISyntaxException { + try { + Address[] recipients = requestMessage.getRecipients(Message.RecipientType.TO); + if (!ObjectUtils.isEmpty(recipients) && recipients[0] instanceof InternetAddress) { + return MailTransportUtils.toUri((InternetAddress) recipients[0], requestMessage.getSubject()); + } + else { + throw new URISyntaxException("", "Could not determine To header"); + } + } + catch (MessagingException ex) { + throw new URISyntaxException("", ex.getMessage()); + } + } /* - * Errors - */ + * Errors + */ - @Override - public String getErrorMessage() throws IOException { - return null; - } + @Override + public String getErrorMessage() throws IOException { + return null; + } - @Override - public boolean hasError() throws IOException { - return false; - } + @Override + public boolean hasError() throws IOException { + return false; + } - /* - * Receiving - */ + /* + * Receiving + */ - @Override - protected Iterator getRequestHeaderNames() throws IOException { - try { - List headers = new ArrayList(); - Enumeration enumeration = requestMessage.getAllHeaders(); - while (enumeration.hasMoreElements()) { - Header header = (Header) enumeration.nextElement(); - headers.add(header.getName()); - } - return headers.iterator(); - } - catch (MessagingException ex) { - throw new IOException(ex.getMessage()); - } - } + @Override + protected Iterator getRequestHeaderNames() throws IOException { + try { + List headers = new ArrayList(); + Enumeration enumeration = requestMessage.getAllHeaders(); + while (enumeration.hasMoreElements()) { + Header header = (Header) enumeration.nextElement(); + headers.add(header.getName()); + } + return headers.iterator(); + } + catch (MessagingException ex) { + throw new IOException(ex.getMessage()); + } + } - @Override - protected Iterator getRequestHeaders(String name) throws IOException { - try { - String[] headers = requestMessage.getHeader(name); - return Arrays.asList(headers).iterator(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected Iterator getRequestHeaders(String name) throws IOException { + try { + String[] headers = requestMessage.getHeader(name); + return Arrays.asList(headers).iterator(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected InputStream getRequestInputStream() throws IOException { - try { - return requestMessage.getInputStream(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected InputStream getRequestInputStream() throws IOException { + try { + return requestMessage.getInputStream(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected void addResponseHeader(String name, String value) throws IOException { - try { - responseMessage.addHeader(name, value); - if (TransportConstants.HEADER_CONTENT_TYPE.equals(name)) { - responseContentType = value; - } - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected void addResponseHeader(String name, String value) throws IOException { + try { + responseMessage.addHeader(name, value); + if (TransportConstants.HEADER_CONTENT_TYPE.equals(name)) { + responseContentType = value; + } + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected OutputStream getResponseOutputStream() throws IOException { - return responseBuffer; - } + @Override + protected OutputStream getResponseOutputStream() throws IOException { + return responseBuffer; + } - /* - * Sending - */ + /* + * Sending + */ - @Override - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - try { - responseMessage = requestMessage.reply(false); - responseMessage.setFrom(from); + @Override + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + try { + responseMessage = requestMessage.reply(false); + responseMessage.setFrom(from); - responseBuffer = new ByteArrayOutputStream(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + responseBuffer = new ByteArrayOutputStream(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - Transport transport = null; - try { - responseMessage.setDataHandler( - new DataHandler(new ByteArrayDataSource(responseContentType, responseBuffer.toByteArray()))); - transport = session.getTransport(transportUri); - transport.connect(); - responseMessage.saveChanges(); - transport.sendMessage(responseMessage, responseMessage.getAllRecipients()); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - finally { - MailTransportUtils.closeService(transport); - } - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + Transport transport = null; + try { + responseMessage.setDataHandler( + new DataHandler(new ByteArrayDataSource(responseContentType, responseBuffer.toByteArray()))); + transport = session.getTransport(transportUri); + transport.connect(); + responseMessage.saveChanges(); + transport.sendMessage(responseMessage, responseMessage.getAllRecipients()); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + finally { + MailTransportUtils.closeService(transport); + } + } - private class ByteArrayDataSource implements DataSource { + private class ByteArrayDataSource implements DataSource { - private byte[] data; + private byte[] data; - private String contentType; + private String contentType; - public ByteArrayDataSource(String contentType, byte[] data) { - this.data = data; - this.contentType = contentType; - } + public ByteArrayDataSource(String contentType, byte[] data) { + this.data = data; + this.contentType = contentType; + } - @Override - public String getContentType() { - return contentType; - } + @Override + public String getContentType() { + return contentType; + } - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(data); - } + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(data); + } - @Override - public String getName() { - return "ByteArrayDataSource"; - } + @Override + public String getName() { + return "ByteArrayDataSource"; + } - @Override - public OutputStream getOutputStream() throws IOException { - throw new UnsupportedOperationException(); - } - } + @Override + public OutputStream getOutputStream() throws IOException { + throw new UnsupportedOperationException(); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailSenderConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailSenderConnection.java index b1d8e401..cdccd955 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailSenderConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailSenderConnection.java @@ -65,280 +65,280 @@ import org.springframework.ws.transport.mail.support.MailTransportUtils; public class MailSenderConnection extends AbstractSenderConnection { - private static final Log logger = LogFactory.getLog(MailSenderConnection.class); + private static final Log logger = LogFactory.getLog(MailSenderConnection.class); - private final Session session; + private final Session session; - private MimeMessage requestMessage; + private MimeMessage requestMessage; - private Message responseMessage; + private Message responseMessage; - private String requestContentType; + private String requestContentType; - private boolean deleteAfterReceive = false; + private boolean deleteAfterReceive = false; - private final URLName storeUri; + private final URLName storeUri; - private final URLName transportUri; + private final URLName transportUri; - private ByteArrayOutputStream requestBuffer; + private ByteArrayOutputStream requestBuffer; - private InternetAddress from; + private InternetAddress from; - private final InternetAddress to; + private final InternetAddress to; - private String subject; + private String subject; - private final long receiveTimeout; + private final long receiveTimeout; - private Store store; + private Store store; - private Folder folder; + private Folder folder; - /** Constructs a new Mail connection with the given parameters. */ - protected MailSenderConnection(Session session, - URLName transportUri, - URLName storeUri, - InternetAddress to, - long receiveTimeout) { - Assert.notNull(session, "'session' must not be null"); - Assert.notNull(transportUri, "'transportUri' must not be null"); - Assert.notNull(storeUri, "'storeUri' must not be null"); - Assert.notNull(to, "'to' must not be null"); - this.session = session; - this.transportUri = transportUri; - this.storeUri = storeUri; - this.to = to; - this.receiveTimeout = receiveTimeout; - } + /** Constructs a new Mail connection with the given parameters. */ + protected MailSenderConnection(Session session, + URLName transportUri, + URLName storeUri, + InternetAddress to, + long receiveTimeout) { + Assert.notNull(session, "'session' must not be null"); + Assert.notNull(transportUri, "'transportUri' must not be null"); + Assert.notNull(storeUri, "'storeUri' must not be null"); + Assert.notNull(to, "'to' must not be null"); + this.session = session; + this.transportUri = transportUri; + this.storeUri = storeUri; + this.to = to; + this.receiveTimeout = receiveTimeout; + } - /** Returns the request message for this connection. */ - public Message getRequestMessage() { - return requestMessage; - } + /** Returns the request message for this connection. */ + public Message getRequestMessage() { + return requestMessage; + } - /** Returns the response message, if any, for this connection. */ - public Message getResponseMessage() { - return responseMessage; - } + /** Returns the response message, if any, for this connection. */ + public Message getResponseMessage() { + return responseMessage; + } - /* - * Package-friendly setters - */ + /* + * Package-friendly setters + */ - void setFrom(InternetAddress from) { - this.from = from; - } + void setFrom(InternetAddress from) { + this.from = from; + } - void setSubject(String subject) { - this.subject = subject; - } + void setSubject(String subject) { + this.subject = subject; + } - /* - * URI - */ - @Override - public URI getUri() throws URISyntaxException { - return MailTransportUtils.toUri(to, subject); - } + /* + * URI + */ + @Override + public URI getUri() throws URISyntaxException { + return MailTransportUtils.toUri(to, subject); + } - /* - * Sending - */ - @Override - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - try { - requestMessage = new MimeMessage(session); - requestMessage.setRecipient(Message.RecipientType.TO, to); - requestMessage.setSentDate(new Date()); - if (from != null) { - requestMessage.setFrom(from); - } - if (subject != null) { - requestMessage.setSubject(subject); - } - requestBuffer = new ByteArrayOutputStream(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + /* + * Sending + */ + @Override + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + try { + requestMessage = new MimeMessage(session); + requestMessage.setRecipient(Message.RecipientType.TO, to); + requestMessage.setSentDate(new Date()); + if (from != null) { + requestMessage.setFrom(from); + } + if (subject != null) { + requestMessage.setSubject(subject); + } + requestBuffer = new ByteArrayOutputStream(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected void addRequestHeader(String name, String value) throws IOException { - try { - requestMessage.addHeader(name, value); - if (TransportConstants.HEADER_CONTENT_TYPE.equals(name)) { - requestContentType = value; - } - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected void addRequestHeader(String name, String value) throws IOException { + try { + requestMessage.addHeader(name, value); + if (TransportConstants.HEADER_CONTENT_TYPE.equals(name)) { + requestContentType = value; + } + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected OutputStream getRequestOutputStream() throws IOException { - return requestBuffer; - } + @Override + protected OutputStream getRequestOutputStream() throws IOException { + return requestBuffer; + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - Transport transport = null; - try { - requestMessage.setDataHandler( - new DataHandler(new ByteArrayDataSource(requestContentType, requestBuffer.toByteArray()))); - transport = session.getTransport(transportUri); - transport.connect(); - requestMessage.saveChanges(); - transport.sendMessage(requestMessage, requestMessage.getAllRecipients()); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - finally { - MailTransportUtils.closeService(transport); - } - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + Transport transport = null; + try { + requestMessage.setDataHandler( + new DataHandler(new ByteArrayDataSource(requestContentType, requestBuffer.toByteArray()))); + transport = session.getTransport(transportUri); + transport.connect(); + requestMessage.saveChanges(); + transport.sendMessage(requestMessage, requestMessage.getAllRecipients()); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + finally { + MailTransportUtils.closeService(transport); + } + } - /* - * Receiving - */ + /* + * Receiving + */ - @Override - protected void onReceiveBeforeRead() throws IOException { - try { - String requestMessageId = requestMessage.getMessageID(); - Assert.hasLength(requestMessageId, "No Message-ID found on request message [" + requestMessage + "]"); - try { - Thread.sleep(receiveTimeout); - } - catch (InterruptedException e) { - // Re-interrupt current thread, to allow other threads to react. - Thread.currentThread().interrupt(); - } - openFolder(); - SearchTerm searchTerm = new HeaderTerm(MailTransportConstants.HEADER_IN_REPLY_TO, requestMessageId); - Message[] responses = folder.search(searchTerm); - if (responses.length > 0) { - if (responses.length > 1) { - logger.warn("Received more than one response for request with ID [" + requestMessageId + "]"); - } - responseMessage = responses[0]; - } - if (deleteAfterReceive) { - responseMessage.setFlag(Flags.Flag.DELETED, true); - } - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected void onReceiveBeforeRead() throws IOException { + try { + String requestMessageId = requestMessage.getMessageID(); + Assert.hasLength(requestMessageId, "No Message-ID found on request message [" + requestMessage + "]"); + try { + Thread.sleep(receiveTimeout); + } + catch (InterruptedException e) { + // Re-interrupt current thread, to allow other threads to react. + Thread.currentThread().interrupt(); + } + openFolder(); + SearchTerm searchTerm = new HeaderTerm(MailTransportConstants.HEADER_IN_REPLY_TO, requestMessageId); + Message[] responses = folder.search(searchTerm); + if (responses.length > 0) { + if (responses.length > 1) { + logger.warn("Received more than one response for request with ID [" + requestMessageId + "]"); + } + responseMessage = responses[0]; + } + if (deleteAfterReceive) { + responseMessage.setFlag(Flags.Flag.DELETED, true); + } + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - private void openFolder() throws MessagingException { - store = session.getStore(storeUri); - store.connect(); - folder = store.getFolder(storeUri); - if (folder == null || !folder.exists()) { - throw new IllegalStateException("No default folder to receive from"); - } - if (deleteAfterReceive) { - folder.open(Folder.READ_WRITE); - } - else { - folder.open(Folder.READ_ONLY); - } - } + private void openFolder() throws MessagingException { + store = session.getStore(storeUri); + store.connect(); + folder = store.getFolder(storeUri); + if (folder == null || !folder.exists()) { + throw new IllegalStateException("No default folder to receive from"); + } + if (deleteAfterReceive) { + folder.open(Folder.READ_WRITE); + } + else { + folder.open(Folder.READ_ONLY); + } + } - @Override - protected boolean hasResponse() throws IOException { - return responseMessage != null; - } + @Override + protected boolean hasResponse() throws IOException { + return responseMessage != null; + } - @Override - protected Iterator getResponseHeaderNames() throws IOException { - try { - List headers = new ArrayList(); - Enumeration enumeration = responseMessage.getAllHeaders(); - while (enumeration.hasMoreElements()) { - Header header = (Header) enumeration.nextElement(); - headers.add(header.getName()); - } - return headers.iterator(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected Iterator getResponseHeaderNames() throws IOException { + try { + List headers = new ArrayList(); + Enumeration enumeration = responseMessage.getAllHeaders(); + while (enumeration.hasMoreElements()) { + Header header = (Header) enumeration.nextElement(); + headers.add(header.getName()); + } + return headers.iterator(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - protected Iterator getResponseHeaders(String name) throws IOException { - try { - String[] headers = responseMessage.getHeader(name); - return Arrays.asList(headers).iterator(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); + @Override + protected Iterator getResponseHeaders(String name) throws IOException { + try { + String[] headers = responseMessage.getHeader(name); + return Arrays.asList(headers).iterator(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); - } - } + } + } - @Override - protected InputStream getResponseInputStream() throws IOException { - try { - return responseMessage.getDataHandler().getInputStream(); - } - catch (MessagingException ex) { - throw new MailTransportException(ex); - } - } + @Override + protected InputStream getResponseInputStream() throws IOException { + try { + return responseMessage.getDataHandler().getInputStream(); + } + catch (MessagingException ex) { + throw new MailTransportException(ex); + } + } - @Override - public boolean hasError() throws IOException { - return false; - } + @Override + public boolean hasError() throws IOException { + return false; + } - @Override - public String getErrorMessage() throws IOException { - return null; - } + @Override + public String getErrorMessage() throws IOException { + return null; + } - @Override - public void onClose() throws IOException { - MailTransportUtils.closeFolder(folder, deleteAfterReceive); - MailTransportUtils.closeService(store); - } + @Override + public void onClose() throws IOException { + MailTransportUtils.closeFolder(folder, deleteAfterReceive); + MailTransportUtils.closeService(store); + } - private class ByteArrayDataSource implements DataSource { + private class ByteArrayDataSource implements DataSource { - private byte[] data; + private byte[] data; - private String contentType; + private String contentType; - public ByteArrayDataSource(String contentType, byte[] data) { - this.data = data; - this.contentType = contentType; - } + public ByteArrayDataSource(String contentType, byte[] data) { + this.data = data; + this.contentType = contentType; + } - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(data); - } + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(data); + } - @Override - public OutputStream getOutputStream() throws IOException { - throw new UnsupportedOperationException(); - } + @Override + public OutputStream getOutputStream() throws IOException { + throw new UnsupportedOperationException(); + } - @Override - public String getContentType() { - return contentType; - } + @Override + public String getContentType() { + return contentType; + } - @Override - public String getName() { - return "ByteArrayDataSource"; - } - } + @Override + public String getName() { + return "ByteArrayDataSource"; + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportConstants.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportConstants.java index 5e8e1632..5fa12bf7 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportConstants.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportConstants.java @@ -26,13 +26,13 @@ import org.springframework.ws.transport.TransportConstants; */ public interface MailTransportConstants extends TransportConstants { - /** - * The "mail" URI scheme. - */ - String MAIL_URI_SCHEME = "mailto"; + /** + * The "mail" URI scheme. + */ + String MAIL_URI_SCHEME = "mailto"; - /** - * The "In-Reply-To" header. - */ - String HEADER_IN_REPLY_TO = "In-Reply-To"; + /** + * The "In-Reply-To" header. + */ + String HEADER_IN_REPLY_TO = "In-Reply-To"; } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportException.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportException.java index b0ea8059..a5ea2a6a 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportException.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/MailTransportException.java @@ -29,21 +29,21 @@ import org.springframework.ws.transport.TransportException; @SuppressWarnings("serial") public class MailTransportException extends TransportException { - private final MessagingException messagingException; + private final MessagingException messagingException; - public MailTransportException(String msg, MessagingException ex) { - super(msg + ": " + ex.getMessage()); - initCause(ex); - messagingException = ex; - } + public MailTransportException(String msg, MessagingException ex) { + super(msg + ": " + ex.getMessage()); + initCause(ex); + messagingException = ex; + } - public MailTransportException(MessagingException ex) { - super(ex.getMessage()); - initCause(ex); - messagingException = ex; - } + public MailTransportException(MessagingException ex) { + super(ex.getMessage()); + initCause(ex); + messagingException = ex; + } - public MessagingException getMessagingException() { - return messagingException; - } + public MessagingException getMessagingException() { + return messagingException; + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/AbstractMonitoringStrategy.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/AbstractMonitoringStrategy.java index e1c5eb4a..3c265843 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/AbstractMonitoringStrategy.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/AbstractMonitoringStrategy.java @@ -37,130 +37,130 @@ import org.apache.commons.logging.LogFactory; */ public abstract class AbstractMonitoringStrategy implements MonitoringStrategy { - /** Logger available to subclasses. */ - protected final Log logger = LogFactory.getLog(getClass()); + /** Logger available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); - private boolean deleteMessages = true; + private boolean deleteMessages = true; - /** - * Sets whether messages should be marked as {@link javax.mail.Flags.Flag#DELETED DELETED} after they have been - * read. Default is {@code true}. - */ - public void setDeleteMessages(boolean deleteMessages) { - this.deleteMessages = deleteMessages; - } + /** + * Sets whether messages should be marked as {@link javax.mail.Flags.Flag#DELETED DELETED} after they have been + * read. Default is {@code true}. + */ + public void setDeleteMessages(boolean deleteMessages) { + this.deleteMessages = deleteMessages; + } - @Override - public int getFolderOpenMode() { - return deleteMessages ? Folder.READ_WRITE : Folder.READ_ONLY; - } + @Override + public int getFolderOpenMode() { + return deleteMessages ? Folder.READ_WRITE : Folder.READ_ONLY; + } - /** - * Monitors the given folder, and returns any new messages when they arrive. This implementation calls {@link - * #waitForNewMessages(Folder)}, then searches for new messages using {@link #searchForNewMessages(Folder)}, fetches - * the messages using {@link #fetchMessages(Folder, Message[])}, and finally {@link #setDeleteMessages(boolean) - * deletes} the messages, if {@link #setDeleteMessages(boolean) deleteMessages} is {@code true}. - * - * @param folder the folder to monitor - * @return the new messages - * @throws MessagingException in case of JavaMail errors - * @throws InterruptedException when a thread is interrupted - */ - @Override - public final Message[] monitor(Folder folder) throws MessagingException, InterruptedException { - waitForNewMessages(folder); - Message[] messages = searchForNewMessages(folder); - if (logger.isDebugEnabled()) { - logger.debug("Found " + messages.length + " new messages"); - } - if (messages.length > 0) { - fetchMessages(folder, messages); - } - if (deleteMessages) { - deleteMessages(folder, messages); - } - return messages; - } + /** + * Monitors the given folder, and returns any new messages when they arrive. This implementation calls {@link + * #waitForNewMessages(Folder)}, then searches for new messages using {@link #searchForNewMessages(Folder)}, fetches + * the messages using {@link #fetchMessages(Folder, Message[])}, and finally {@link #setDeleteMessages(boolean) + * deletes} the messages, if {@link #setDeleteMessages(boolean) deleteMessages} is {@code true}. + * + * @param folder the folder to monitor + * @return the new messages + * @throws MessagingException in case of JavaMail errors + * @throws InterruptedException when a thread is interrupted + */ + @Override + public final Message[] monitor(Folder folder) throws MessagingException, InterruptedException { + waitForNewMessages(folder); + Message[] messages = searchForNewMessages(folder); + if (logger.isDebugEnabled()) { + logger.debug("Found " + messages.length + " new messages"); + } + if (messages.length > 0) { + fetchMessages(folder, messages); + } + if (deleteMessages) { + deleteMessages(folder, messages); + } + return messages; + } - /** - * Template method that blocks until new messages arrive in the given folder. Typical implementations use {@link - * Thread#sleep(long)} or the IMAP IDLE command. - * - * @param folder the folder to monitor - * @throws MessagingException in case of JavaMail errors - * @throws InterruptedException when a thread is interrupted - */ - protected abstract void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException; + /** + * Template method that blocks until new messages arrive in the given folder. Typical implementations use {@link + * Thread#sleep(long)} or the IMAP IDLE command. + * + * @param folder the folder to monitor + * @throws MessagingException in case of JavaMail errors + * @throws InterruptedException when a thread is interrupted + */ + protected abstract void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException; - /** - * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for - * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link - * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term - * is used to {@link Folder#search(SearchTerm) search} for new messages. - * - * @param folder the folder to retrieve new messages from - * @return the new messages - * @throws MessagingException in case of JavaMail errors - */ - protected Message[] searchForNewMessages(Folder folder) throws MessagingException { - if (!folder.isOpen()) { - return new Message[0]; - } - Flags supportedFlags = folder.getPermanentFlags(); - SearchTerm searchTerm = null; - if (supportedFlags != null) { - if (supportedFlags.contains(Flags.Flag.RECENT)) { - searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true); - } - if (supportedFlags.contains(Flags.Flag.ANSWERED)) { - FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false); - if (searchTerm == null) { - searchTerm = answeredTerm; - } - else { - searchTerm = new AndTerm(searchTerm, answeredTerm); - } - } - if (supportedFlags.contains(Flags.Flag.DELETED)) { - FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false); - if (searchTerm == null) { - searchTerm = deletedTerm; - } - else { - searchTerm = new AndTerm(searchTerm, deletedTerm); - } - } - } - return searchTerm != null ? folder.search(searchTerm) : folder.getMessages(); - } + /** + * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for + * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link + * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term + * is used to {@link Folder#search(SearchTerm) search} for new messages. + * + * @param folder the folder to retrieve new messages from + * @return the new messages + * @throws MessagingException in case of JavaMail errors + */ + protected Message[] searchForNewMessages(Folder folder) throws MessagingException { + if (!folder.isOpen()) { + return new Message[0]; + } + Flags supportedFlags = folder.getPermanentFlags(); + SearchTerm searchTerm = null; + if (supportedFlags != null) { + if (supportedFlags.contains(Flags.Flag.RECENT)) { + searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true); + } + if (supportedFlags.contains(Flags.Flag.ANSWERED)) { + FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false); + if (searchTerm == null) { + searchTerm = answeredTerm; + } + else { + searchTerm = new AndTerm(searchTerm, answeredTerm); + } + } + if (supportedFlags.contains(Flags.Flag.DELETED)) { + FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false); + if (searchTerm == null) { + searchTerm = deletedTerm; + } + else { + searchTerm = new AndTerm(searchTerm, deletedTerm); + } + } + } + return searchTerm != null ? folder.search(searchTerm) : folder.getMessages(); + } - /** - * Fetches the specified messages from the specified folder. Default implementation {@link Folder#fetch(Message[], - * FetchProfile) fetches} every {@link javax.mail.FetchProfile.Item}. - * - * @param folder the folder to fetch messages from - * @param messages the messages to fetch - * @throws MessagingException in case of JavMail errors - */ - protected void fetchMessages(Folder folder, Message[] messages) throws MessagingException { - FetchProfile contentsProfile = new FetchProfile(); - contentsProfile.add(FetchProfile.Item.ENVELOPE); - contentsProfile.add(FetchProfile.Item.CONTENT_INFO); - contentsProfile.add(FetchProfile.Item.FLAGS); - folder.fetch(messages, contentsProfile); - } + /** + * Fetches the specified messages from the specified folder. Default implementation {@link Folder#fetch(Message[], + * FetchProfile) fetches} every {@link javax.mail.FetchProfile.Item}. + * + * @param folder the folder to fetch messages from + * @param messages the messages to fetch + * @throws MessagingException in case of JavMail errors + */ + protected void fetchMessages(Folder folder, Message[] messages) throws MessagingException { + FetchProfile contentsProfile = new FetchProfile(); + contentsProfile.add(FetchProfile.Item.ENVELOPE); + contentsProfile.add(FetchProfile.Item.CONTENT_INFO); + contentsProfile.add(FetchProfile.Item.FLAGS); + folder.fetch(messages, contentsProfile); + } - /** - * Deletes the given messages from the given folder. Only invoked when {@link #setDeleteMessages(boolean)} is - * {@code true}. - * - * @param folder the folder to delete messages from - * @param messages the messages to delete - * @throws MessagingException in case of JavaMail errors - */ - protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException { - for (Message message : messages) { - message.setFlag(Flags.Flag.DELETED, true); - } - } + /** + * Deletes the given messages from the given folder. Only invoked when {@link #setDeleteMessages(boolean)} is + * {@code true}. + * + * @param folder the folder to delete messages from + * @param messages the messages to delete + * @throws MessagingException in case of JavaMail errors + */ + protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException { + for (Message message : messages) { + message.setFlag(Flags.Flag.DELETED, true); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/ImapIdleMonitoringStrategy.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/ImapIdleMonitoringStrategy.java index 8e8fee05..493516d3 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/ImapIdleMonitoringStrategy.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/ImapIdleMonitoringStrategy.java @@ -39,43 +39,43 @@ import com.sun.mail.imap.IMAPFolder; */ public class ImapIdleMonitoringStrategy extends AbstractMonitoringStrategy { - private MessageCountListener messageCountListener; + private MessageCountListener messageCountListener; - @Override - protected void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException { - Assert.isInstanceOf(IMAPFolder.class, folder); - IMAPFolder imapFolder = (IMAPFolder) folder; - // retrieve unseen messages before we enter the blocking idle call - if (searchForNewMessages(folder).length > 0) { - return; - } - if (messageCountListener == null) { - createMessageCountListener(); - } - folder.addMessageCountListener(messageCountListener); - try { - imapFolder.idle(); - } - finally { - folder.removeMessageCountListener(messageCountListener); - } - } + @Override + protected void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException { + Assert.isInstanceOf(IMAPFolder.class, folder); + IMAPFolder imapFolder = (IMAPFolder) folder; + // retrieve unseen messages before we enter the blocking idle call + if (searchForNewMessages(folder).length > 0) { + return; + } + if (messageCountListener == null) { + createMessageCountListener(); + } + folder.addMessageCountListener(messageCountListener); + try { + imapFolder.idle(); + } + finally { + folder.removeMessageCountListener(messageCountListener); + } + } - private void createMessageCountListener() { - messageCountListener = new MessageCountAdapter() { - @Override - public void messagesAdded(MessageCountEvent e) { - Message[] messages = e.getMessages(); - for (Message message : messages) { - try { - // this will return the flow to the idle call, above - message.getLineCount(); - } - catch (MessagingException ex) { - // ignore - } - } - } - }; - } + private void createMessageCountListener() { + messageCountListener = new MessageCountAdapter() { + @Override + public void messagesAdded(MessageCountEvent e) { + Message[] messages = e.getMessages(); + for (Message message : messages) { + try { + // this will return the flow to the idle call, above + message.getLineCount(); + } + catch (MessagingException ex) { + // ignore + } + } + } + }; + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/MonitoringStrategy.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/MonitoringStrategy.java index e2ba35d5..a17e2614 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/MonitoringStrategy.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/MonitoringStrategy.java @@ -28,20 +28,20 @@ import javax.mail.MessagingException; */ public interface MonitoringStrategy { - /** - * Monitors the given folder, and returns any new messages when they arrive. - * - * @param folder the folder in which to look for new messages - * @return the new messages - * @throws MessagingException in case of JavaMail errors - * @throws InterruptedException if a thread is interrupted - */ - Message[] monitor(Folder folder) throws MessagingException, InterruptedException; + /** + * Monitors the given folder, and returns any new messages when they arrive. + * + * @param folder the folder in which to look for new messages + * @return the new messages + * @throws MessagingException in case of JavaMail errors + * @throws InterruptedException if a thread is interrupted + */ + Message[] monitor(Folder folder) throws MessagingException, InterruptedException; - /** - * Returns the folder open mode to be used by this strategy. Can be either {@link Folder#READ_ONLY} or {@link - * Folder#READ_WRITE}. - */ - int getFolderOpenMode(); + /** + * Returns the folder open mode to be used by this strategy. Can be either {@link Folder#READ_ONLY} or {@link + * Folder#READ_WRITE}. + */ + int getFolderOpenMode(); } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/PollingMonitoringStrategy.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/PollingMonitoringStrategy.java index 51a58f53..457389de 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/PollingMonitoringStrategy.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/PollingMonitoringStrategy.java @@ -31,34 +31,34 @@ import javax.mail.MessagingException; */ public class PollingMonitoringStrategy extends AbstractMonitoringStrategy { - /** Defines the default polling frequency. Set to 1000 * 60 milliseconds (i.e. 1 minute). */ - public static final long DEFAULT_POLLING_FREQUENCY = 1000 * 60; + /** Defines the default polling frequency. Set to 1000 * 60 milliseconds (i.e. 1 minute). */ + public static final long DEFAULT_POLLING_FREQUENCY = 1000 * 60; - private long pollingInterval = DEFAULT_POLLING_FREQUENCY; + private long pollingInterval = DEFAULT_POLLING_FREQUENCY; - /** - * Sets the interval used in between message polls, in milliseconds. The default is 1000 * 60 ms, - * that is 1 minute. - */ - public void setPollingInterval(long pollingInterval) { - this.pollingInterval = pollingInterval; - } + /** + * Sets the interval used in between message polls, in milliseconds. The default is 1000 * 60 ms, + * that is 1 minute. + */ + public void setPollingInterval(long pollingInterval) { + this.pollingInterval = pollingInterval; + } - @Override - protected void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException { - Thread.sleep(pollingInterval); - afterSleep(folder); - } + @Override + protected void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException { + Thread.sleep(pollingInterval); + afterSleep(folder); + } - /** - * Invoked after the {@link Thread#sleep(long)} method has been invoked. This implementation calls {@link - * Folder#getMessageCount()}, to force new messages to be seen. - * - * @param folder the folder to check for new messages - * @throws MessagingException in case of JavaMail errors - */ - protected void afterSleep(Folder folder) throws MessagingException { - folder.getMessageCount(); - } + /** + * Invoked after the {@link Thread#sleep(long)} method has been invoked. This implementation calls {@link + * Folder#getMessageCount()}, to force new messages to be seen. + * + * @param folder the folder to check for new messages + * @throws MessagingException in case of JavaMail errors + */ + protected void afterSleep(Folder folder) throws MessagingException { + folder.getMessageCount(); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/Pop3PollingMonitoringStrategy.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/Pop3PollingMonitoringStrategy.java index 1a5f7bf4..24d31bb3 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/Pop3PollingMonitoringStrategy.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/monitor/Pop3PollingMonitoringStrategy.java @@ -37,46 +37,46 @@ import org.springframework.ws.transport.mail.support.MailTransportUtils; */ public class Pop3PollingMonitoringStrategy extends PollingMonitoringStrategy { - public Pop3PollingMonitoringStrategy() { - super.setDeleteMessages(true); - } + public Pop3PollingMonitoringStrategy() { + super.setDeleteMessages(true); + } - @Override - public void setDeleteMessages(boolean deleteMessages) { - } + @Override + public void setDeleteMessages(boolean deleteMessages) { + } - /** - * Re-opens the folder, if it closed. - */ - @Override - protected void afterSleep(Folder folder) throws MessagingException { - if (!folder.isOpen()) { - folder.open(Folder.READ_WRITE); - } - } + /** + * Re-opens the folder, if it closed. + */ + @Override + protected void afterSleep(Folder folder) throws MessagingException { + if (!folder.isOpen()) { + folder.open(Folder.READ_WRITE); + } + } - /** - * Simply returns {@link Folder#getMessages()}. - */ - @Override - protected Message[] searchForNewMessages(Folder folder) throws MessagingException { - return folder.getMessages(); - } + /** + * Simply returns {@link Folder#getMessages()}. + */ + @Override + protected Message[] searchForNewMessages(Folder folder) throws MessagingException { + return folder.getMessages(); + } - /** - * Deletes the given messages from the given folder, and closes it to expunge deleted messages. - * - * @param folder the folder to delete messages from - * @param messages the messages to delete - * @throws MessagingException in case of JavaMail errors - */ - @Override - protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException { - super.deleteMessages(folder, messages); - // expunge deleted mails, and make sure we've retrieved them before closing the folder - for (Message message : messages) { - new MimeMessage((MimeMessage) message); - } - MailTransportUtils.closeFolder(folder, true); - } + /** + * Deletes the given messages from the given folder, and closes it to expunge deleted messages. + * + * @param folder the folder to delete messages from + * @param messages the messages to delete + * @throws MessagingException in case of JavaMail errors + */ + @Override + protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException { + super.deleteMessages(folder, messages); + // expunge deleted mails, and make sure we've retrieved them before closing the folder + for (Message message : messages) { + new MimeMessage((MimeMessage) message); + } + MailTransportUtils.closeFolder(folder, true); + } } \ No newline at end of file diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/support/MailTransportUtils.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/support/MailTransportUtils.java index afa6c841..22bd7ba9 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/support/MailTransportUtils.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/mail/support/MailTransportUtils.java @@ -43,146 +43,146 @@ import org.apache.commons.logging.LogFactory; */ public abstract class MailTransportUtils { - private static final Pattern TO_PATTERN = Pattern.compile("^([^\\?]+)"); + private static final Pattern TO_PATTERN = Pattern.compile("^([^\\?]+)"); - private static final Pattern SUBJECT_PATTERN = Pattern.compile("subject=([^\\&]+)"); + private static final Pattern SUBJECT_PATTERN = Pattern.compile("subject=([^\\&]+)"); - private static final Log logger = LogFactory.getLog(MailTransportUtils.class); + private static final Log logger = LogFactory.getLog(MailTransportUtils.class); - private MailTransportUtils() { - } + private MailTransportUtils() { + } - public static InternetAddress getTo(URI uri) { - Matcher matcher = TO_PATTERN.matcher(uri.getSchemeSpecificPart()); - if (matcher.find()) { - for (int i = 1; i <= matcher.groupCount(); i++) { - String group = matcher.group(i); - if (group != null) { - try { - return new InternetAddress(group); - } - catch (AddressException e) { - // try next group - } - } - } - } - return null; - } + public static InternetAddress getTo(URI uri) { + Matcher matcher = TO_PATTERN.matcher(uri.getSchemeSpecificPart()); + if (matcher.find()) { + for (int i = 1; i <= matcher.groupCount(); i++) { + String group = matcher.group(i); + if (group != null) { + try { + return new InternetAddress(group); + } + catch (AddressException e) { + // try next group + } + } + } + } + return null; + } - public static String getSubject(URI uri) { - Matcher matcher = SUBJECT_PATTERN.matcher(uri.getSchemeSpecificPart()); - if (matcher.find()) { - return matcher.group(1); - } - return null; - } + public static String getSubject(URI uri) { + Matcher matcher = SUBJECT_PATTERN.matcher(uri.getSchemeSpecificPart()); + if (matcher.find()) { + return matcher.group(1); + } + return null; + } - /** - * Close the given JavaMail Service and ignore any thrown exception. This is useful for typical {@code finally} - * blocks in manual JavaMail code. - * - * @param service the JavaMail Service to close (may be {@code null}) - * @see Transport - * @see Store - */ - public static void closeService(Service service) { - if (service != null) { - try { - service.close(); - } - catch (MessagingException ex) { - logger.debug("Could not close JavaMail Service", ex); - } - } - } + /** + * Close the given JavaMail Service and ignore any thrown exception. This is useful for typical {@code finally} + * blocks in manual JavaMail code. + * + * @param service the JavaMail Service to close (may be {@code null}) + * @see Transport + * @see Store + */ + public static void closeService(Service service) { + if (service != null) { + try { + service.close(); + } + catch (MessagingException ex) { + logger.debug("Could not close JavaMail Service", ex); + } + } + } - /** - * Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical {@code finally} - * blocks in manual JavaMail code. - * - * @param folder the JavaMail Folder to close (may be {@code null}) - */ + /** + * Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical {@code finally} + * blocks in manual JavaMail code. + * + * @param folder the JavaMail Folder to close (may be {@code null}) + */ - public static void closeFolder(Folder folder) { - closeFolder(folder, false); - } + public static void closeFolder(Folder folder) { + closeFolder(folder, false); + } - /** - * Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical {@code finally} - * blocks in manual JavaMail code. - * - * @param folder the JavaMail Folder to close (may be {@code null}) - * @param expunge whether all deleted messages should be expunged from the folder - */ - public static void closeFolder(Folder folder, boolean expunge) { - if (folder != null && folder.isOpen()) { - try { - folder.close(expunge); - } - catch (MessagingException ex) { - logger.debug("Could not close JavaMail Folder", ex); - } - } - } + /** + * Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical {@code finally} + * blocks in manual JavaMail code. + * + * @param folder the JavaMail Folder to close (may be {@code null}) + * @param expunge whether all deleted messages should be expunged from the folder + */ + public static void closeFolder(Folder folder, boolean expunge) { + if (folder != null && folder.isOpen()) { + try { + folder.close(expunge); + } + catch (MessagingException ex) { + logger.debug("Could not close JavaMail Folder", ex); + } + } + } - /** Returns a string representation of the given {@link URLName}, where the password has been protected. */ - public static String toPasswordProtectedString(URLName name) { - String protocol = name.getProtocol(); - String username = name.getUsername(); - String password = name.getPassword(); - String host = name.getHost(); - int port = name.getPort(); - String file = name.getFile(); - String ref = name.getRef(); - StringBuilder tempURL = new StringBuilder(); - if (protocol != null) { - tempURL.append(protocol).append(':'); - } + /** Returns a string representation of the given {@link URLName}, where the password has been protected. */ + public static String toPasswordProtectedString(URLName name) { + String protocol = name.getProtocol(); + String username = name.getUsername(); + String password = name.getPassword(); + String host = name.getHost(); + int port = name.getPort(); + String file = name.getFile(); + String ref = name.getRef(); + StringBuilder tempURL = new StringBuilder(); + if (protocol != null) { + tempURL.append(protocol).append(':'); + } - if (StringUtils.hasLength(username) || StringUtils.hasLength(host)) { - tempURL.append("//"); - if (StringUtils.hasLength(username)) { - tempURL.append(username); - if (StringUtils.hasLength(password)) { - tempURL.append(":*****"); - } - tempURL.append("@"); - } - if (StringUtils.hasLength(host)) { - tempURL.append(host); - } - if (port != -1) { - tempURL.append(':').append(Integer.toString(port)); - } - if (StringUtils.hasLength(file)) { - tempURL.append('/'); - } - } - if (StringUtils.hasLength(file)) { - tempURL.append(file); - } - if (StringUtils.hasLength(ref)) { - tempURL.append('#').append(ref); - } - return tempURL.toString(); - } + if (StringUtils.hasLength(username) || StringUtils.hasLength(host)) { + tempURL.append("//"); + if (StringUtils.hasLength(username)) { + tempURL.append(username); + if (StringUtils.hasLength(password)) { + tempURL.append(":*****"); + } + tempURL.append("@"); + } + if (StringUtils.hasLength(host)) { + tempURL.append(host); + } + if (port != -1) { + tempURL.append(':').append(Integer.toString(port)); + } + if (StringUtils.hasLength(file)) { + tempURL.append('/'); + } + } + if (StringUtils.hasLength(file)) { + tempURL.append(file); + } + if (StringUtils.hasLength(ref)) { + tempURL.append('#').append(ref); + } + return tempURL.toString(); + } - /** - * Converts the given internet address into a {@code mailto} URI. - * - * @param to the To: address - * @param subject the subject, may be {@code null} - * @return a mailto URI - */ - public static URI toUri(InternetAddress to, String subject) throws URISyntaxException { - if (StringUtils.hasLength(subject)) { - return new URI(MailTransportConstants.MAIL_URI_SCHEME, to.getAddress() + "?subject=" + subject, null); - } - else { - return new URI(MailTransportConstants.MAIL_URI_SCHEME, to.getAddress(), null); - } - } + /** + * Converts the given internet address into a {@code mailto} URI. + * + * @param to the To: address + * @param subject the subject, may be {@code null} + * @return a mailto URI + */ + public static URI toUri(InternetAddress to, String subject) throws URISyntaxException { + if (StringUtils.hasLength(subject)) { + return new URI(MailTransportConstants.MAIL_URI_SCHEME, to.getAddress() + "?subject=" + subject, null); + } + else { + return new URI(MailTransportConstants.MAIL_URI_SCHEME, to.getAddress(), null); + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractAsyncStandaloneMessageReceiver.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractAsyncStandaloneMessageReceiver.java index 0e19e07f..45e5da38 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractAsyncStandaloneMessageReceiver.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractAsyncStandaloneMessageReceiver.java @@ -28,58 +28,58 @@ import org.springframework.util.ClassUtils; * @author Arjen Poutsma */ public abstract class AbstractAsyncStandaloneMessageReceiver extends AbstractStandaloneMessageReceiver - implements BeanNameAware { + implements BeanNameAware { - /** Default thread name prefix. */ - public final String DEFAULT_THREAD_NAME_PREFIX = ClassUtils.getShortName(getClass()) + "-"; + /** Default thread name prefix. */ + public final String DEFAULT_THREAD_NAME_PREFIX = ClassUtils.getShortName(getClass()) + "-"; - private TaskExecutor taskExecutor; + private TaskExecutor taskExecutor; - private String beanName; + private String beanName; - /** - * Set the Spring {@link TaskExecutor} to use for running the listener threads. Default is {@link - * SimpleAsyncTaskExecutor}, starting up a number of new threads. - * - *

Specify an alternative task executor for integration with an existing thread pool, such as the {@link - * org.springframework.scheduling.commonj.WorkManagerTaskExecutor} to integrate with WebSphere or WebLogic. - */ - public void setTaskExecutor(TaskExecutor taskExecutor) { - this.taskExecutor = taskExecutor; - } + /** + * Set the Spring {@link TaskExecutor} to use for running the listener threads. Default is {@link + * SimpleAsyncTaskExecutor}, starting up a number of new threads. + * + *

Specify an alternative task executor for integration with an existing thread pool, such as the {@link + * org.springframework.scheduling.commonj.WorkManagerTaskExecutor} to integrate with WebSphere or WebLogic. + */ + public void setTaskExecutor(TaskExecutor taskExecutor) { + this.taskExecutor = taskExecutor; + } - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } + @Override + public void setBeanName(String beanName) { + this.beanName = beanName; + } - @Override - public void afterPropertiesSet() throws Exception { - if (taskExecutor == null) { - taskExecutor = createDefaultTaskExecutor(); - } - super.afterPropertiesSet(); - } + @Override + public void afterPropertiesSet() throws Exception { + if (taskExecutor == null) { + taskExecutor = createDefaultTaskExecutor(); + } + super.afterPropertiesSet(); + } - /** - * Create a default TaskExecutor. Called if no explicit TaskExecutor has been specified. - * - *

The default implementation builds a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} with the - * specified bean name (or the class name, if no bean name specified) as thread name prefix. - * - * @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String) - */ - protected TaskExecutor createDefaultTaskExecutor() { - String threadNamePrefix = beanName != null ? beanName + "-" : DEFAULT_THREAD_NAME_PREFIX; - return new SimpleAsyncTaskExecutor(threadNamePrefix); - } + /** + * Create a default TaskExecutor. Called if no explicit TaskExecutor has been specified. + * + *

The default implementation builds a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} with the + * specified bean name (or the class name, if no bean name specified) as thread name prefix. + * + * @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String) + */ + protected TaskExecutor createDefaultTaskExecutor() { + String threadNamePrefix = beanName != null ? beanName + "-" : DEFAULT_THREAD_NAME_PREFIX; + return new SimpleAsyncTaskExecutor(threadNamePrefix); + } - /** - * Executes the given {@link Runnable} via this receiver's {@link TaskExecutor}. - * - * @see #setTaskExecutor(TaskExecutor) - */ - protected void execute(Runnable runnable) { - taskExecutor.execute(runnable); - } + /** + * Executes the given {@link Runnable} via this receiver's {@link TaskExecutor}. + * + * @see #setTaskExecutor(TaskExecutor) + */ + protected void execute(Runnable runnable) { + taskExecutor.execute(runnable); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractStandaloneMessageReceiver.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractStandaloneMessageReceiver.java index 2e72a069..7f1eaa6d 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractStandaloneMessageReceiver.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/support/AbstractStandaloneMessageReceiver.java @@ -27,106 +27,106 @@ import org.springframework.context.Lifecycle; * @since 1.5.0 */ public abstract class AbstractStandaloneMessageReceiver extends SimpleWebServiceMessageReceiverObjectSupport - implements Lifecycle, DisposableBean { + implements Lifecycle, DisposableBean { - private volatile boolean active = false; + private volatile boolean active = false; - private boolean autoStartup = true; + private boolean autoStartup = true; - private boolean running = false; + private boolean running = false; - private final Object lifecycleMonitor = new Object(); + private final Object lifecycleMonitor = new Object(); - /** Return whether this server is currently active, that is, whether it has been set up but not shut down yet. */ - public final boolean isActive() { - synchronized (lifecycleMonitor) { - return active; - } - } + /** Return whether this server is currently active, that is, whether it has been set up but not shut down yet. */ + public final boolean isActive() { + synchronized (lifecycleMonitor) { + return active; + } + } - /** Return whether this server is currently running, that is, whether it has been started and not stopped yet. */ - @Override - public final boolean isRunning() { - synchronized (lifecycleMonitor) { - return running; - } - } + /** Return whether this server is currently running, that is, whether it has been started and not stopped yet. */ + @Override + public final boolean isRunning() { + synchronized (lifecycleMonitor) { + return running; + } + } - /** - * Set whether to automatically start the receiver after initialization. - * - *

Default is {@code true}; set this to {@code false} to allow for manual startup. - */ - public void setAutoStartup(boolean autoStartup) { - this.autoStartup = autoStartup; - } + /** + * Set whether to automatically start the receiver after initialization. + * + *

Default is {@code true}; set this to {@code false} to allow for manual startup. + */ + public void setAutoStartup(boolean autoStartup) { + this.autoStartup = autoStartup; + } - /** Calls {@link #activate()} when the BeanFactory initializes the receiver instance. */ - @Override - public void afterPropertiesSet() throws Exception { - activate(); - } + /** Calls {@link #activate()} when the BeanFactory initializes the receiver instance. */ + @Override + public void afterPropertiesSet() throws Exception { + activate(); + } - /** Calls {@link #shutdown()} when the BeanFactory destroys the receiver instance. */ - @Override - public void destroy() { - shutdown(); - } + /** Calls {@link #shutdown()} when the BeanFactory destroys the receiver instance. */ + @Override + public void destroy() { + shutdown(); + } - /** - * Initialize this server. Starts the server if {@link #setAutoStartup(boolean) autoStartup} hasn't been turned - * off. - */ - public final void activate() throws Exception { - synchronized (lifecycleMonitor) { - active = true; - } - onActivate(); - if (autoStartup) { - start(); - } - } + /** + * Initialize this server. Starts the server if {@link #setAutoStartup(boolean) autoStartup} hasn't been turned + * off. + */ + public final void activate() throws Exception { + synchronized (lifecycleMonitor) { + active = true; + } + onActivate(); + if (autoStartup) { + start(); + } + } - /** Start this server. */ - @Override - public final void start() { - synchronized (lifecycleMonitor) { - running = true; - } - onStart(); - } + /** Start this server. */ + @Override + public final void start() { + synchronized (lifecycleMonitor) { + running = true; + } + onStart(); + } - /** Stop this server. */ - @Override - public final void stop() { - synchronized (lifecycleMonitor) { - running = false; - } - onStop(); - } + /** Stop this server. */ + @Override + public final void stop() { + synchronized (lifecycleMonitor) { + running = false; + } + onStop(); + } - /** Shut down this server. */ - public final void shutdown() { - synchronized (lifecycleMonitor) { - running = false; - active = false; - } - onShutdown(); - } + /** Shut down this server. */ + public final void shutdown() { + synchronized (lifecycleMonitor) { + running = false; + active = false; + } + onShutdown(); + } - /** - * Template method invoked when {@link #activate()} is invoked. - * - * @throws Exception in case of errors - */ - protected abstract void onActivate() throws Exception; + /** + * Template method invoked when {@link #activate()} is invoked. + * + * @throws Exception in case of errors + */ + protected abstract void onActivate() throws Exception; - /** Template method invoked when {@link #start()} is invoked. */ - protected abstract void onStart(); + /** Template method invoked when {@link #start()} is invoked. */ + protected abstract void onStart(); - /** Template method invoked when {@link #stop()} is invoked. */ - protected abstract void onStop(); + /** Template method invoked when {@link #stop()} is invoked. */ + protected abstract void onStop(); - /** Template method invoked when {@link #shutdown()} is invoked. */ - protected abstract void onShutdown(); + /** Template method invoked when {@link #shutdown()} is invoked. */ + protected abstract void onShutdown(); } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/support/SimpleWebServiceMessageReceiverObjectSupport.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/support/SimpleWebServiceMessageReceiverObjectSupport.java index 57522b86..9e5a6cbe 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/support/SimpleWebServiceMessageReceiverObjectSupport.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/support/SimpleWebServiceMessageReceiverObjectSupport.java @@ -29,32 +29,32 @@ import org.springframework.ws.transport.WebServiceMessageReceiver; * @since 1.5.0 */ public abstract class SimpleWebServiceMessageReceiverObjectSupport extends WebServiceMessageReceiverObjectSupport - implements InitializingBean { + implements InitializingBean { - private WebServiceMessageReceiver messageReceiver; + private WebServiceMessageReceiver messageReceiver; - /** - * Returns the {@code WebServiceMessageReceiver} used by this listener. - */ - public WebServiceMessageReceiver getMessageReceiver() { - return messageReceiver; - } + /** + * Returns the {@code WebServiceMessageReceiver} used by this listener. + */ + public WebServiceMessageReceiver getMessageReceiver() { + return messageReceiver; + } - /** - * Sets the {@code WebServiceMessageReceiver} used by this listener. - */ - public void setMessageReceiver(WebServiceMessageReceiver messageReceiver) { - this.messageReceiver = messageReceiver; - } + /** + * Sets the {@code WebServiceMessageReceiver} used by this listener. + */ + public void setMessageReceiver(WebServiceMessageReceiver messageReceiver) { + this.messageReceiver = messageReceiver; + } - @Override - public void afterPropertiesSet() throws Exception { - super.afterPropertiesSet(); - Assert.notNull(getMessageReceiver(), "messageReceiver must not be null"); - } + @Override + public void afterPropertiesSet() throws Exception { + super.afterPropertiesSet(); + Assert.notNull(getMessageReceiver(), "messageReceiver must not be null"); + } - protected final void handleConnection(WebServiceConnection connection) throws Exception { - handleConnection(connection, getMessageReceiver()); - } + protected final void handleConnection(WebServiceConnection connection) throws Exception { + handleConnection(connection, getMessageReceiver()); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageInputStream.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageInputStream.java index a22ff4f1..e85acf98 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageInputStream.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageInputStream.java @@ -34,17 +34,17 @@ import org.jivesoftware.smack.packet.Message; */ class MessageInputStream extends FilterInputStream { - MessageInputStream(Message message, String encoding) throws IOException { - super(createInputStream(message, encoding)); - } + MessageInputStream(Message message, String encoding) throws IOException { + super(createInputStream(message, encoding)); + } - private static InputStream createInputStream(Message message, String encoding) throws IOException { - Assert.notNull(message, "'message' must not be null"); - Assert.notNull(encoding, "'encoding' must not be null"); - String text = message.getBody(); - byte[] contents = text != null ? text.getBytes(encoding) : new byte[0]; - return new ByteArrayInputStream(contents); - } + private static InputStream createInputStream(Message message, String encoding) throws IOException { + Assert.notNull(message, "'message' must not be null"); + Assert.notNull(encoding, "'encoding' must not be null"); + String text = message.getBody(); + byte[] contents = text != null ? text.getBytes(encoding) : new byte[0]; + return new ByteArrayInputStream(contents); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageOutputStream.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageOutputStream.java index d6379cc5..943fd29e 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageOutputStream.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/MessageOutputStream.java @@ -33,23 +33,23 @@ import org.jivesoftware.smack.packet.Message; */ class MessageOutputStream extends FilterOutputStream { - private final Message message; + private final Message message; - private final String encoding; + private final String encoding; - MessageOutputStream(Message message, String encoding) { - super(new ByteArrayOutputStream()); - Assert.notNull(message, "'message' must not be null"); - Assert.notNull(encoding, "'encoding' must not be null"); - this.message = message; - this.encoding = encoding; - } + MessageOutputStream(Message message, String encoding) { + super(new ByteArrayOutputStream()); + Assert.notNull(message, "'message' must not be null"); + Assert.notNull(encoding, "'encoding' must not be null"); + this.message = message; + this.encoding = encoding; + } - @Override - public void flush() throws IOException { - super.flush(); - ByteArrayOutputStream bos = (ByteArrayOutputStream) out; - String text = new String(bos.toByteArray(), encoding); - message.setBody(text); - } + @Override + public void flush() throws IOException { + super.flush(); + ByteArrayOutputStream bos = (ByteArrayOutputStream) out; + String text = new String(bos.toByteArray(), encoding); + message.setBody(text); + } } \ No newline at end of file diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageReceiver.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageReceiver.java index e4939e19..30373d40 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageReceiver.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageReceiver.java @@ -27,7 +27,7 @@ import org.jivesoftware.smack.packet.Packet; import org.springframework.ws.transport.support.AbstractStandaloneMessageReceiver; /** - * Server-side component for receiving XMPP (Jabber) messages. Requires a {@linkplain #setConnection(XMPPConnection) + * Server-side component for receiving XMPP (Jabber) messages. Requires a {@linkplain #setConnection(XMPPConnection) * connection} to be set, in addition to the {@link #setMessageFactory(org.springframework.ws.WebServiceMessageFactory) * messageFactory} and {@link #setMessageReceiver(org.springframework.ws.transport.WebServiceMessageReceiver) * messageReceiver} required by the base class. @@ -39,76 +39,76 @@ import org.springframework.ws.transport.support.AbstractStandaloneMessageReceive */ public class XmppMessageReceiver extends AbstractStandaloneMessageReceiver { - /** Default encoding used to read from and write to {@link org.jivesoftware.smack.packet.Message} messages. */ - public static final String DEFAULT_MESSAGE_ENCODING = "UTF-8"; + /** Default encoding used to read from and write to {@link org.jivesoftware.smack.packet.Message} messages. */ + public static final String DEFAULT_MESSAGE_ENCODING = "UTF-8"; - private XMPPConnection connection; + private XMPPConnection connection; - private WebServicePacketListener packetListener; + private WebServicePacketListener packetListener; - private String messageEncoding = DEFAULT_MESSAGE_ENCODING; + private String messageEncoding = DEFAULT_MESSAGE_ENCODING; - public XmppMessageReceiver() { - } + public XmppMessageReceiver() { + } - /** Sets the {@code XMPPConnection} to use. Setting this property is required. */ - public void setConnection(XMPPConnection connection) { - this.connection = connection; - } + /** Sets the {@code XMPPConnection} to use. Setting this property is required. */ + public void setConnection(XMPPConnection connection) { + this.connection = connection; + } - @Override - protected void onActivate() throws XMPPException { - if (!connection.isConnected()) { - connection.connect(); - } - } + @Override + protected void onActivate() throws XMPPException { + if (!connection.isConnected()) { + connection.connect(); + } + } - @Override - protected void onStart() { - if (logger.isInfoEnabled()) { - logger.info("Starting XMPP receiver [" + connection.getUser() + "]"); - } - packetListener = new WebServicePacketListener(); - PacketFilter packetFilter = new PacketTypeFilter(Message.class); - connection.addPacketListener(packetListener, packetFilter); - } + @Override + protected void onStart() { + if (logger.isInfoEnabled()) { + logger.info("Starting XMPP receiver [" + connection.getUser() + "]"); + } + packetListener = new WebServicePacketListener(); + PacketFilter packetFilter = new PacketTypeFilter(Message.class); + connection.addPacketListener(packetListener, packetFilter); + } - @Override - protected void onStop() { - if (logger.isInfoEnabled()) { - logger.info("Stopping XMPP receiver [" + connection.getUser() + "]"); - } - connection.removePacketListener(packetListener); - packetListener = null; - } + @Override + protected void onStop() { + if (logger.isInfoEnabled()) { + logger.info("Stopping XMPP receiver [" + connection.getUser() + "]"); + } + connection.removePacketListener(packetListener); + packetListener = null; + } - @Override - protected void onShutdown() { - if (logger.isInfoEnabled()) { - logger.info("Shutting down XMPP receiver [" + connection.getUser() + "]"); - } - if (connection.isConnected()) { - connection.disconnect(); - } - } + @Override + protected void onShutdown() { + if (logger.isInfoEnabled()) { + logger.info("Shutting down XMPP receiver [" + connection.getUser() + "]"); + } + if (connection.isConnected()) { + connection.disconnect(); + } + } - private class WebServicePacketListener implements PacketListener { + private class WebServicePacketListener implements PacketListener { - @Override - public void processPacket(Packet packet) { - logger.info("Received " + packet); - if (packet instanceof Message) { - Message message = (Message) packet; - try { - XmppReceiverConnection wsConnection = new XmppReceiverConnection(connection, message); - wsConnection.setMessageEncoding(messageEncoding); - handleConnection(wsConnection); - } - catch (Exception ex) { - logger.error(ex); - } - } - } - } + @Override + public void processPacket(Packet packet) { + logger.info("Received " + packet); + if (packet instanceof Message) { + Message message = (Message) packet; + try { + XmppReceiverConnection wsConnection = new XmppReceiverConnection(connection, message); + wsConnection.setMessageEncoding(messageEncoding); + handleConnection(wsConnection); + } + catch (Exception ex) { + logger.error(ex); + } + } + } + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageSender.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageSender.java index 4e6d549d..0dc49971 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageSender.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppMessageSender.java @@ -41,61 +41,61 @@ import org.springframework.ws.transport.xmpp.support.XmppTransportUtils; */ public class XmppMessageSender implements WebServiceMessageSender, InitializingBean { - /** Default timeout for receive operations: -1 indicates a blocking receive without timeout. */ - public static final long DEFAULT_RECEIVE_TIMEOUT = -1; + /** Default timeout for receive operations: -1 indicates a blocking receive without timeout. */ + public static final long DEFAULT_RECEIVE_TIMEOUT = -1; - /** Default encoding used to read from and write to {@link org.jivesoftware.smack.packet.Message} messages. */ - public static final String DEFAULT_MESSAGE_ENCODING = "UTF-8"; + /** Default encoding used to read from and write to {@link org.jivesoftware.smack.packet.Message} messages. */ + public static final String DEFAULT_MESSAGE_ENCODING = "UTF-8"; - private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT; + private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT; - private String messageEncoding = DEFAULT_MESSAGE_ENCODING; + private String messageEncoding = DEFAULT_MESSAGE_ENCODING; - private XMPPConnection connection; + private XMPPConnection connection; - /** Sets the {@code XMPPConnection}. Setting this property is required. */ - public void setConnection(XMPPConnection connection) { - this.connection = connection; - } + /** Sets the {@code XMPPConnection}. Setting this property is required. */ + public void setConnection(XMPPConnection connection) { + this.connection = connection; + } - /** - * Set the timeout to use for receive calls. The default is -1, which means no timeout. - * - * @see org.jivesoftware.smack.PacketCollector#nextResult(long) - */ - public void setReceiveTimeout(long receiveTimeout) { - this.receiveTimeout = receiveTimeout; - } + /** + * Set the timeout to use for receive calls. The default is -1, which means no timeout. + * + * @see org.jivesoftware.smack.PacketCollector#nextResult(long) + */ + public void setReceiveTimeout(long receiveTimeout) { + this.receiveTimeout = receiveTimeout; + } - /** - * Sets the encoding used to read from {@link org.jivesoftware.smack.packet.Message} object. Defaults to - * {@code UTF-8}. - */ - public void setMessageEncoding(String messageEncoding) { - this.messageEncoding = messageEncoding; - } + /** + * Sets the encoding used to read from {@link org.jivesoftware.smack.packet.Message} object. Defaults to + * {@code UTF-8}. + */ + public void setMessageEncoding(String messageEncoding) { + this.messageEncoding = messageEncoding; + } - @Override - public void afterPropertiesSet() throws Exception { - Assert.notNull(connection, "'connection' is required"); - } + @Override + public void afterPropertiesSet() throws Exception { + Assert.notNull(connection, "'connection' is required"); + } - @Override - public WebServiceConnection createConnection(URI uri) throws IOException { - String to = XmppTransportUtils.getTo(uri); - String thread = createThread(); - XmppSenderConnection connection = new XmppSenderConnection(this.connection, to, thread); - connection.setReceiveTimeout(receiveTimeout); - connection.setMessageEncoding(messageEncoding); - return connection; - } + @Override + public WebServiceConnection createConnection(URI uri) throws IOException { + String to = XmppTransportUtils.getTo(uri); + String thread = createThread(); + XmppSenderConnection connection = new XmppSenderConnection(this.connection, to, thread); + connection.setReceiveTimeout(receiveTimeout); + connection.setMessageEncoding(messageEncoding); + return connection; + } - @Override - public boolean supports(URI uri) { - return uri.getScheme().equals(XmppTransportConstants.XMPP_URI_SCHEME); - } + @Override + public boolean supports(URI uri) { + return uri.getScheme().equals(XmppTransportConstants.XMPP_URI_SCHEME); + } - protected String createThread() { - return UUID.randomUUID().toString(); - } + protected String createThread() { + return UUID.randomUUID().toString(); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppReceiverConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppReceiverConnection.java index 3263a05b..b6810ed5 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppReceiverConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppReceiverConnection.java @@ -41,104 +41,104 @@ import org.springframework.ws.transport.xmpp.support.XmppTransportUtils; */ public class XmppReceiverConnection extends AbstractReceiverConnection { - private final XMPPConnection connection; + private final XMPPConnection connection; - private final Message requestMessage; + private final Message requestMessage; - private Message responseMessage; + private Message responseMessage; - private String messageEncoding; + private String messageEncoding; - public XmppReceiverConnection(XMPPConnection connection, Message requestMessage) { - Assert.notNull(connection, "'connection' must not be null"); - Assert.notNull(requestMessage, "'requestMessage' must not be null"); - this.connection = connection; - this.requestMessage = requestMessage; - } + public XmppReceiverConnection(XMPPConnection connection, Message requestMessage) { + Assert.notNull(connection, "'connection' must not be null"); + Assert.notNull(requestMessage, "'requestMessage' must not be null"); + this.connection = connection; + this.requestMessage = requestMessage; + } - /** Returns the request message for this connection. */ - public Message getRequestMessage() { - return requestMessage; - } + /** Returns the request message for this connection. */ + public Message getRequestMessage() { + return requestMessage; + } - /** Returns the response message, if any, for this connection. */ - public Message getResponseMessage() { - return responseMessage; - } + /** Returns the response message, if any, for this connection. */ + public Message getResponseMessage() { + return responseMessage; + } - /* - * Package-friendly setters - */ + /* + * Package-friendly setters + */ - void setMessageEncoding(String messageEncoding) { - this.messageEncoding = messageEncoding; - } + void setMessageEncoding(String messageEncoding) { + this.messageEncoding = messageEncoding; + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - return XmppTransportUtils.toUri(requestMessage); - } + @Override + public URI getUri() throws URISyntaxException { + return XmppTransportUtils.toUri(requestMessage); + } - /* - * Errors - */ + /* + * Errors + */ - @Override - public boolean hasError() { - return XmppTransportUtils.hasError(responseMessage); - } + @Override + public boolean hasError() { + return XmppTransportUtils.hasError(responseMessage); + } - @Override - public String getErrorMessage() { - return XmppTransportUtils.getErrorMessage(responseMessage); - } + @Override + public String getErrorMessage() { + return XmppTransportUtils.getErrorMessage(responseMessage); + } - /* - * Receiving - */ + /* + * Receiving + */ - @Override - protected Iterator getRequestHeaderNames() throws IOException { - return XmppTransportUtils.getHeaderNames(requestMessage); - } + @Override + protected Iterator getRequestHeaderNames() throws IOException { + return XmppTransportUtils.getHeaderNames(requestMessage); + } - @Override - protected Iterator getRequestHeaders(String name) throws IOException { - return XmppTransportUtils.getHeaders(requestMessage, name); - } + @Override + protected Iterator getRequestHeaders(String name) throws IOException { + return XmppTransportUtils.getHeaders(requestMessage, name); + } - @Override - protected InputStream getRequestInputStream() throws IOException { - return new MessageInputStream(requestMessage, messageEncoding); - } + @Override + protected InputStream getRequestInputStream() throws IOException { + return new MessageInputStream(requestMessage, messageEncoding); + } - /* - * Sending - */ + /* + * Sending + */ - @Override - protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { - responseMessage = new Message(requestMessage.getFrom(), Message.Type.chat); - responseMessage.setFrom(connection.getUser()); - responseMessage.setThread(requestMessage.getThread()); - } + @Override + protected void onSendBeforeWrite(WebServiceMessage message) throws IOException { + responseMessage = new Message(requestMessage.getFrom(), Message.Type.chat); + responseMessage.setFrom(connection.getUser()); + responseMessage.setThread(requestMessage.getThread()); + } - @Override - protected void addResponseHeader(String name, String value) throws IOException { - XmppTransportUtils.addHeader(responseMessage, name, value); - } + @Override + protected void addResponseHeader(String name, String value) throws IOException { + XmppTransportUtils.addHeader(responseMessage, name, value); + } - @Override - protected OutputStream getResponseOutputStream() throws IOException { - return new MessageOutputStream(responseMessage, messageEncoding); - } + @Override + protected OutputStream getResponseOutputStream() throws IOException { + return new MessageOutputStream(responseMessage, messageEncoding); + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - connection.sendPacket(responseMessage); - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + connection.sendPacket(responseMessage); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppSenderConnection.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppSenderConnection.java index 0818e2ba..de043d77 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppSenderConnection.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppSenderConnection.java @@ -47,134 +47,134 @@ import org.springframework.ws.transport.xmpp.support.XmppTransportUtils; */ public class XmppSenderConnection extends AbstractSenderConnection { - private final Message requestMessage; + private final Message requestMessage; - private final XMPPConnection connection; + private final XMPPConnection connection; - private Message responseMessage; + private Message responseMessage; - private String messageEncoding; + private String messageEncoding; - private long receiveTimeout; + private long receiveTimeout; - protected XmppSenderConnection(XMPPConnection connection, String to, String thread) { - Assert.notNull(connection, "'connection' must not be null"); - Assert.hasLength(to, "'to' must not be empty"); - Assert.hasLength(thread, "'thread' must not be empty"); - this.connection = connection; - this.requestMessage = new Message(to, Message.Type.chat); - this.requestMessage.setThread(thread); - } + protected XmppSenderConnection(XMPPConnection connection, String to, String thread) { + Assert.notNull(connection, "'connection' must not be null"); + Assert.hasLength(to, "'to' must not be empty"); + Assert.hasLength(thread, "'thread' must not be empty"); + this.connection = connection; + this.requestMessage = new Message(to, Message.Type.chat); + this.requestMessage.setThread(thread); + } - /** Returns the request message for this connection. */ - public Message getRequestMessage() { - return requestMessage; - } + /** Returns the request message for this connection. */ + public Message getRequestMessage() { + return requestMessage; + } - /** Returns the response message, if any, for this connection. */ - public Message getResponseMessage() { - return responseMessage; - } + /** Returns the response message, if any, for this connection. */ + public Message getResponseMessage() { + return responseMessage; + } - /* - * Package-friendly setters - */ + /* + * Package-friendly setters + */ - void setMessageEncoding(String messageEncoding) { - this.messageEncoding = messageEncoding; - } + void setMessageEncoding(String messageEncoding) { + this.messageEncoding = messageEncoding; + } - void setReceiveTimeout(long receiveTimeout) { - this.receiveTimeout = receiveTimeout; - } + void setReceiveTimeout(long receiveTimeout) { + this.receiveTimeout = receiveTimeout; + } - /* - * URI - */ + /* + * URI + */ - @Override - public URI getUri() throws URISyntaxException { - return XmppTransportUtils.toUri(requestMessage); - } + @Override + public URI getUri() throws URISyntaxException { + return XmppTransportUtils.toUri(requestMessage); + } - /* - * Errors - */ + /* + * Errors + */ - @Override - public boolean hasError() { - return XmppTransportUtils.hasError(responseMessage); - } + @Override + public boolean hasError() { + return XmppTransportUtils.hasError(responseMessage); + } - @Override - public String getErrorMessage() { - return XmppTransportUtils.getErrorMessage(responseMessage); - } + @Override + public String getErrorMessage() { + return XmppTransportUtils.getErrorMessage(responseMessage); + } - /* - * Sending - */ + /* + * Sending + */ - @Override - protected void addRequestHeader(String name, String value) { - XmppTransportUtils.addHeader(requestMessage, name, value); - } + @Override + protected void addRequestHeader(String name, String value) { + XmppTransportUtils.addHeader(requestMessage, name, value); + } - @Override - protected OutputStream getRequestOutputStream() throws IOException { - return new MessageOutputStream(requestMessage, messageEncoding); - } + @Override + protected OutputStream getRequestOutputStream() throws IOException { + return new MessageOutputStream(requestMessage, messageEncoding); + } - @Override - protected void onSendAfterWrite(WebServiceMessage message) throws IOException { - requestMessage.setFrom(connection.getUser()); - connection.sendPacket(requestMessage); - } + @Override + protected void onSendAfterWrite(WebServiceMessage message) throws IOException { + requestMessage.setFrom(connection.getUser()); + connection.sendPacket(requestMessage); + } - /* - * Receiving - */ + /* + * Receiving + */ - @Override - protected void onReceiveBeforeRead() throws IOException { - PacketFilter packetFilter = createPacketFilter(); + @Override + protected void onReceiveBeforeRead() throws IOException { + PacketFilter packetFilter = createPacketFilter(); - PacketCollector collector = connection.createPacketCollector(packetFilter); - Packet packet = receiveTimeout >= 0 ? collector.nextResult(receiveTimeout) : collector.nextResult(); - if (packet instanceof Message) { - responseMessage = (Message) packet; - } - else if (packet != null) { - throw new IllegalArgumentException( - "Wrong packet type: [" + packet.getClass() + "]. Only Messages can be handled."); - } - } + PacketCollector collector = connection.createPacketCollector(packetFilter); + Packet packet = receiveTimeout >= 0 ? collector.nextResult(receiveTimeout) : collector.nextResult(); + if (packet instanceof Message) { + responseMessage = (Message) packet; + } + else if (packet != null) { + throw new IllegalArgumentException( + "Wrong packet type: [" + packet.getClass() + "]. Only Messages can be handled."); + } + } - private PacketFilter createPacketFilter() { - AndFilter andFilter = new AndFilter(); - andFilter.addFilter(new PacketTypeFilter(Message.class)); - andFilter.addFilter(new ThreadFilter(requestMessage.getThread())); - return andFilter; - } + private PacketFilter createPacketFilter() { + AndFilter andFilter = new AndFilter(); + andFilter.addFilter(new PacketTypeFilter(Message.class)); + andFilter.addFilter(new ThreadFilter(requestMessage.getThread())); + return andFilter; + } - @Override - protected boolean hasResponse() throws IOException { - return responseMessage != null; - } + @Override + protected boolean hasResponse() throws IOException { + return responseMessage != null; + } - @Override - protected Iterator getResponseHeaderNames() { - return XmppTransportUtils.getHeaderNames(responseMessage); - } + @Override + protected Iterator getResponseHeaderNames() { + return XmppTransportUtils.getHeaderNames(responseMessage); + } - @Override - protected Iterator getResponseHeaders(String name) throws IOException { - return XmppTransportUtils.getHeaders(responseMessage, name); - } + @Override + protected Iterator getResponseHeaders(String name) throws IOException { + return XmppTransportUtils.getHeaders(responseMessage, name); + } - @Override - protected InputStream getResponseInputStream() throws IOException { - return new MessageInputStream(responseMessage, messageEncoding); - } + @Override + protected InputStream getResponseInputStream() throws IOException { + return new MessageInputStream(responseMessage, messageEncoding); + } } diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppTransportConstants.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppTransportConstants.java index 4bf74a79..3b234119 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppTransportConstants.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/XmppTransportConstants.java @@ -26,9 +26,9 @@ import org.springframework.ws.transport.TransportConstants; */ public interface XmppTransportConstants extends TransportConstants { - /** - * The "xmpp" URI scheme. - */ - String XMPP_URI_SCHEME = "xmpp"; + /** + * The "xmpp" URI scheme. + */ + String XMPP_URI_SCHEME = "xmpp"; } \ No newline at end of file diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBean.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBean.java index 412849d4..f816b6ab 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBean.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBean.java @@ -35,107 +35,107 @@ import org.springframework.util.StringUtils; */ public class XmppConnectionFactoryBean implements FactoryBean, InitializingBean, DisposableBean { - private static final int DEFAULT_PORT = 5222; + private static final int DEFAULT_PORT = 5222; - private XMPPConnection connection; + private XMPPConnection connection; - private String host; + private String host; - private int port = DEFAULT_PORT; + private int port = DEFAULT_PORT; - private String serviceName; + private String serviceName; - private String username; + private String username; - private String password; + private String password; - private String resource; + private String resource; - /** Sets the server host to connect to. */ - public void setHost(String host) { - this.host = host; - } + /** Sets the server host to connect to. */ + public void setHost(String host) { + this.host = host; + } - /** - * Sets the the server port to connect to. - * - *

Defaults to {@code 5222}. - */ - public void setPort(int port) { - Assert.isTrue(port > 0, "'port' must be larger than 0"); - this.port = port; - } + /** + * Sets the the server port to connect to. + * + *

Defaults to {@code 5222}. + */ + public void setPort(int port) { + Assert.isTrue(port > 0, "'port' must be larger than 0"); + this.port = port; + } - /** Sets the service name to connect to. */ - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } + /** Sets the service name to connect to. */ + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - public void setResource(String resource) { - this.resource = resource; - } + public void setResource(String resource) { + this.resource = resource; + } - @Override - public void afterPropertiesSet() throws XMPPException { - ConnectionConfiguration configuration = createConnectionConfiguration(host, port, serviceName); - Assert.notNull(configuration, "'configuration' must not be null"); - Assert.hasText(username, "'username' must not be empty"); - Assert.hasText(password, "'password' must not be empty"); + @Override + public void afterPropertiesSet() throws XMPPException { + ConnectionConfiguration configuration = createConnectionConfiguration(host, port, serviceName); + Assert.notNull(configuration, "'configuration' must not be null"); + Assert.hasText(username, "'username' must not be empty"); + Assert.hasText(password, "'password' must not be empty"); - connection = new XMPPConnection(configuration); - connection.connect(); - if (StringUtils.hasText(resource)) { - connection.login(username, password, resource); - } - else { - connection.login(username, password); - } - } + connection = new XMPPConnection(configuration); + connection.connect(); + if (StringUtils.hasText(resource)) { + connection.login(username, password, resource); + } + else { + connection.login(username, password); + } + } - @Override - public void destroy() { - connection.disconnect(); - } + @Override + public void destroy() { + connection.disconnect(); + } - @Override - public XMPPConnection getObject() { - return connection; - } + @Override + public XMPPConnection getObject() { + return connection; + } - @Override - public Class getObjectType() { - return XMPPConnection.class; - } + @Override + public Class getObjectType() { + return XMPPConnection.class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } - /** - * Creates the {@code ConnectionConfiguration} from the given parameters. - * - * @param host the host to connect to - * @param port the port to connect to - * @param serviceName the name of the service to connect to. May be {@code null} - */ - protected ConnectionConfiguration createConnectionConfiguration(String host, int port, String serviceName) { - Assert.hasText(host, "'host' must not be empty"); - if (StringUtils.hasText(serviceName)) { - return new ConnectionConfiguration(host, port, serviceName); - } - else { - return new ConnectionConfiguration(host, port); - } - } + /** + * Creates the {@code ConnectionConfiguration} from the given parameters. + * + * @param host the host to connect to + * @param port the port to connect to + * @param serviceName the name of the service to connect to. May be {@code null} + */ + protected ConnectionConfiguration createConnectionConfiguration(String host, int port, String serviceName) { + Assert.hasText(host, "'host' must not be empty"); + if (StringUtils.hasText(serviceName)) { + return new ConnectionConfiguration(host, port, serviceName); + } + else { + return new ConnectionConfiguration(host, port); + } + } } \ No newline at end of file diff --git a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppTransportUtils.java b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppTransportUtils.java index 8d49fdf4..8321ca62 100644 --- a/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppTransportUtils.java +++ b/spring-ws-support/src/main/java/org/springframework/ws/transport/xmpp/support/XmppTransportUtils.java @@ -34,51 +34,51 @@ import org.jivesoftware.smack.packet.Message; */ public abstract class XmppTransportUtils { - private XmppTransportUtils() { - } + private XmppTransportUtils() { + } - /** - * Converts the given XMPP destination into a {@code xmpp} URI. - */ - public static URI toUri(Message requestMessage) throws URISyntaxException { - return new URI(XmppTransportConstants.XMPP_URI_SCHEME, requestMessage.getTo(), null); - } + /** + * Converts the given XMPP destination into a {@code xmpp} URI. + */ + public static URI toUri(Message requestMessage) throws URISyntaxException { + return new URI(XmppTransportConstants.XMPP_URI_SCHEME, requestMessage.getTo(), null); + } - public static String getTo(URI uri) { - return uri.getSchemeSpecificPart(); - } + public static String getTo(URI uri) { + return uri.getSchemeSpecificPart(); + } - public static boolean hasError(Message message) { - return message != null && Message.Type.error.equals(message.getType()); - } + public static boolean hasError(Message message) { + return message != null && Message.Type.error.equals(message.getType()); + } - public static String getErrorMessage(Message message) { - if (message == null || !Message.Type.error.equals(message.getType())) { - return null; - } - else { - return message.getBody(); - } - } + public static String getErrorMessage(Message message) { + if (message == null || !Message.Type.error.equals(message.getType())) { + return null; + } + else { + return message.getBody(); + } + } - public static void addHeader(Message message, String name, String value) { - message.setProperty(name, value); - } + public static void addHeader(Message message, String name, String value) { + message.setProperty(name, value); + } - public static Iterator getHeaderNames(Message message) { - Assert.notNull(message, "'message' must not be null"); - return message.getPropertyNames().iterator(); - } + public static Iterator getHeaderNames(Message message) { + Assert.notNull(message, "'message' must not be null"); + return message.getPropertyNames().iterator(); + } - public static Iterator getHeaders(Message message, String name) { - Assert.notNull(message, "'message' must not be null"); - String value = message.getProperty(name).toString(); - if (value != null) { - return Collections.singletonList(value).iterator(); - } - else { - return Collections.emptyList().iterator(); - } - } + public static Iterator getHeaders(Message message, String name) { + Assert.notNull(message, "'message' must not be null"); + String value = message.getProperty(name).toString(); + if (value != null) { + return Collections.singletonList(value).iterator(); + } + else { + return Collections.emptyList().iterator(); + } + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/SimpleTestingMessageReceiver.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/SimpleTestingMessageReceiver.java index fe6f9664..0491b871 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/SimpleTestingMessageReceiver.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/SimpleTestingMessageReceiver.java @@ -24,12 +24,12 @@ import org.springframework.xml.transform.TransformerObjectSupport; public class SimpleTestingMessageReceiver extends TransformerObjectSupport implements WebServiceMessageReceiver { - @Override - public void receive(MessageContext messageContext) throws Exception { - Assert.notNull(messageContext, "MessageContext is null"); - logger.info("Received " + messageContext.getRequest()); - Transformer transformer = createTransformer(); - transformer.transform(messageContext.getRequest().getPayloadSource(), - messageContext.getResponse().getPayloadResult()); - } + @Override + public void receive(MessageContext messageContext) throws Exception { + Assert.notNull(messageContext, "MessageContext is null"); + logger.info("Received " + messageContext.getRequest()); + Transformer transformer = createTransformer(); + transformer.transform(messageContext.getRequest().getPayloadSource(), + messageContext.getResponse().getPayloadResult()); + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/FaultEndpoint.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/FaultEndpoint.java index 3086996c..2797e01c 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/FaultEndpoint.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/FaultEndpoint.java @@ -24,9 +24,9 @@ import org.springframework.ws.soap.SoapMessage; public class FaultEndpoint implements MessageEndpoint { - @Override - public void invoke(MessageContext messageContext) throws Exception { - SoapMessage response = (SoapMessage) messageContext.getResponse(); - response.getSoapBody().addServerOrReceiverFault("Something went wrong", Locale.ENGLISH); - } + @Override + public void invoke(MessageContext messageContext) throws Exception { + SoapMessage response = (SoapMessage) messageContext.getResponse(); + response.getSoapBody().addServerOrReceiverFault("Something went wrong", Locale.ENGLISH); + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/NoResponseEndpoint.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/NoResponseEndpoint.java index d462238f..8bbdf3dd 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/NoResponseEndpoint.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/NoResponseEndpoint.java @@ -22,7 +22,7 @@ import org.springframework.ws.server.endpoint.MessageEndpoint; /** @author Arjen Poutsma */ public class NoResponseEndpoint implements MessageEndpoint { - @Override - public void invoke(MessageContext messageContext) throws Exception { - } + @Override + public void invoke(MessageContext messageContext) throws Exception { + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/ResponseEndpoint.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/ResponseEndpoint.java index a05ba31f..b62bc1fe 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/ResponseEndpoint.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/ResponseEndpoint.java @@ -22,8 +22,8 @@ import org.springframework.ws.server.endpoint.MessageEndpoint; /** @author Arjen Poutsma */ public class ResponseEndpoint implements MessageEndpoint { - @Override - public void invoke(MessageContext messageContext) throws Exception { - messageContext.getResponse(); - } + @Override + public void invoke(MessageContext messageContext) throws Exception { + messageContext.getResponse(); + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/WebServiceHttpHandlerIntegrationTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/WebServiceHttpHandlerIntegrationTest.java index e0ebc881..5b9991b4 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/http/WebServiceHttpHandlerIntegrationTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/http/WebServiceHttpHandlerIntegrationTest.java @@ -40,79 +40,79 @@ import static org.junit.Assert.assertTrue; @ContextConfiguration("httpserver-applicationContext.xml") public class WebServiceHttpHandlerIntegrationTest { - private HttpClient client; + private HttpClient client; - @Autowired - private int port; + @Autowired + private int port; - private String url; + private String url; - @Before - public void createHttpClient() throws Exception { - client = new HttpClient(); - url = "http://localhost:" + port + "/service"; - } + @Before + public void createHttpClient() throws Exception { + client = new HttpClient(); + url = "http://localhost:" + port + "/service"; + } - @Test - public void testInvalidMethod() throws IOException { - GetMethod getMethod = new GetMethod(url); - client.executeMethod(getMethod); - assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_METHOD_NOT_ALLOWED, - getMethod.getStatusCode()); - assertEquals("Response retrieved", 0, getMethod.getResponseContentLength()); - } + @Test + public void testInvalidMethod() throws IOException { + GetMethod getMethod = new GetMethod(url); + client.executeMethod(getMethod); + assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_METHOD_NOT_ALLOWED, + getMethod.getStatusCode()); + assertEquals("Response retrieved", 0, getMethod.getResponseContentLength()); + } - @Test - public void testNoResponse() throws IOException { - PostMethod postMethod = new PostMethod(url); - postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); - postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, - "http://springframework.org/spring-ws/NoResponse"); - Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); - postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); - client.executeMethod(postMethod); - assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_ACCEPTED, postMethod.getStatusCode()); - assertEquals("Response retrieved", 0, postMethod.getResponseContentLength()); - } + @Test + public void testNoResponse() throws IOException { + PostMethod postMethod = new PostMethod(url); + postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); + postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, + "http://springframework.org/spring-ws/NoResponse"); + Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); + postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); + client.executeMethod(postMethod); + assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_ACCEPTED, postMethod.getStatusCode()); + assertEquals("Response retrieved", 0, postMethod.getResponseContentLength()); + } - @Test - public void testResponse() throws IOException { - PostMethod postMethod = new PostMethod(url); - postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); - postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, - "http://springframework.org/spring-ws/Response"); - Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); - postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); - client.executeMethod(postMethod); - assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_OK, postMethod.getStatusCode()); - assertTrue("No Response retrieved", postMethod.getResponseContentLength() > 0); - } + @Test + public void testResponse() throws IOException { + PostMethod postMethod = new PostMethod(url); + postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); + postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, + "http://springframework.org/spring-ws/Response"); + Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); + postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); + client.executeMethod(postMethod); + assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_OK, postMethod.getStatusCode()); + assertTrue("No Response retrieved", postMethod.getResponseContentLength() > 0); + } - @Test - public void testNoEndpoint() throws IOException { - PostMethod postMethod = new PostMethod(url); - postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); - postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, - "http://springframework.org/spring-ws/NoEndpoint"); - Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); - postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); - client.executeMethod(postMethod); - assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_NOT_FOUND, postMethod.getStatusCode()); - assertEquals("Response retrieved", 0, postMethod.getResponseContentLength()); - } + @Test + public void testNoEndpoint() throws IOException { + PostMethod postMethod = new PostMethod(url); + postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); + postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, + "http://springframework.org/spring-ws/NoEndpoint"); + Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); + postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); + client.executeMethod(postMethod); + assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_NOT_FOUND, postMethod.getStatusCode()); + assertEquals("Response retrieved", 0, postMethod.getResponseContentLength()); + } - @Test - public void testFault() throws IOException { - PostMethod postMethod = new PostMethod(url); - postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); - postMethod - .addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, "http://springframework.org/spring-ws/Fault"); - Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); - postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); - client.executeMethod(postMethod); - assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR, - postMethod.getStatusCode()); - assertTrue("No Response retrieved", postMethod.getResponseContentLength() > 0); - } + @Test + public void testFault() throws IOException { + PostMethod postMethod = new PostMethod(url); + postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml"); + postMethod + .addRequestHeader(TransportConstants.HEADER_SOAP_ACTION, "http://springframework.org/spring-ws/Fault"); + Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class); + postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream())); + client.executeMethod(postMethod); + assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_INTERNAL_SERVER_ERROR, + postMethod.getStatusCode()); + assertTrue("No Response retrieved", postMethod.getResponseContentLength() > 0); + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsIntegrationTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsIntegrationTest.java index ae5660ac..d138105c 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsIntegrationTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsIntegrationTest.java @@ -31,28 +31,28 @@ import org.junit.runner.RunWith; @ContextConfiguration("jms-applicationContext.xml") public class JmsIntegrationTest { - @Autowired - private WebServiceTemplate webServiceTemplate; + @Autowired + private WebServiceTemplate webServiceTemplate; - public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) { - this.webServiceTemplate = webServiceTemplate; - } + public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) { + this.webServiceTemplate = webServiceTemplate; + } - @Test - public void testTemporaryQueue() throws Exception { - String content = ""; - StringResult result = new StringResult(); - webServiceTemplate.sendSourceAndReceiveToResult(new StringSource(content), result); - XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); - } + @Test + public void testTemporaryQueue() throws Exception { + String content = ""; + StringResult result = new StringResult(); + webServiceTemplate.sendSourceAndReceiveToResult(new StringSource(content), result); + XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); + } - @Test - public void testPermanentQueue() throws Exception { - String url = "jms:RequestQueue?deliveryMode=NON_PERSISTENT;replyToName=ResponseQueue"; - String content = ""; - StringResult result = new StringResult(); - webServiceTemplate.sendSourceAndReceiveToResult(url, new StringSource(content), result); - XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); - } + @Test + public void testPermanentQueue() throws Exception { + String url = "jms:RequestQueue?deliveryMode=NON_PERSISTENT;replyToName=ResponseQueue"; + String content = ""; + StringResult result = new StringResult(); + webServiceTemplate.sendSourceAndReceiveToResult(url, new StringSource(content), result); + XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsMessageSenderIntegrationTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsMessageSenderIntegrationTest.java index 2798f7c9..887ac2d6 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsMessageSenderIntegrationTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/JmsMessageSenderIntegrationTest.java @@ -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,190 +48,190 @@ import static org.junit.Assert.*; @ContextConfiguration("jms-sender-applicationContext.xml") public class JmsMessageSenderIntegrationTest { - @Autowired - private JmsMessageSender messageSender; + @Autowired + private JmsMessageSender messageSender; - @Autowired - private JmsTemplate jmsTemplate; + @Autowired + private JmsTemplate jmsTemplate; - private MessageFactory messageFactory; + private MessageFactory messageFactory; - private static final String SOAP_ACTION = "\"http://springframework.org/DoIt\""; + private static final String SOAP_ACTION = "\"http://springframework.org/DoIt\""; - @Before - public void createMessageFactory() throws Exception { - messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - } + @Before + public void createMessageFactory() throws Exception { + messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + } - @Test - public void testSendAndReceiveQueueBytesMessageTemporaryQueue() throws Exception { - WebServiceConnection connection = null; - try { - URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT"); - connection = messageSender.createConnection(uri); - SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); - soapRequest.setSoapAction(SOAP_ACTION); - connection.send(soapRequest); + @Test + public void testSendAndReceiveQueueBytesMessageTemporaryQueue() throws Exception { + WebServiceConnection connection = null; + try { + URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT"); + connection = messageSender.createConnection(uri); + SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); + soapRequest.setSoapAction(SOAP_ACTION); + connection.send(soapRequest); - BytesMessage request = (BytesMessage) jmsTemplate.receive(); - assertNotNull("No message received", request); - assertTrue("No message content received", request.readByte() != -1); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - messageFactory.createMessage().writeTo(bos); - final byte[] buf = bos.toByteArray(); - jmsTemplate.send(request.getJMSReplyTo(), new MessageCreator() { + BytesMessage request = (BytesMessage) jmsTemplate.receive(); + assertNotNull("No message received", request); + assertTrue("No message content received", request.readByte() != -1); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + messageFactory.createMessage().writeTo(bos); + final byte[] buf = bos.toByteArray(); + jmsTemplate.send(request.getJMSReplyTo(), new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - BytesMessage response = session.createBytesMessage(); - response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION); - response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, - SoapVersion.SOAP_11.getContentType()); - response.writeBytes(buf); - return response; - } - }); - SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); - assertNotNull("No response received", response); - assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction()); - assertFalse("Message is fault", response.hasFault()); - } - finally { - if (connection != null) { - connection.close(); - } - } - } + public Message createMessage(Session session) throws JMSException { + BytesMessage response = session.createBytesMessage(); + response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION); + response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, + SoapVersion.SOAP_11.getContentType()); + response.writeBytes(buf); + return response; + } + }); + SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); + assertNotNull("No response received", response); + assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction()); + assertFalse("Message is fault", response.hasFault()); + } + finally { + if (connection != null) { + connection.close(); + } + } + } - @Test - public void testSendAndReceiveQueueBytesMessagePermanentQueue() throws Exception { - WebServiceConnection connection = null; - try { - String responseQueueName = "SenderResponseQueue"; - URI uri = new URI( - "jms:SenderRequestQueue?replyToName=" + responseQueueName + "&deliveryMode=NON_PERSISTENT"); - connection = messageSender.createConnection(uri); - SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); - soapRequest.setSoapAction(SOAP_ACTION); - connection.send(soapRequest); + @Test + public void testSendAndReceiveQueueBytesMessagePermanentQueue() throws Exception { + WebServiceConnection connection = null; + try { + String responseQueueName = "SenderResponseQueue"; + URI uri = new URI( + "jms:SenderRequestQueue?replyToName=" + responseQueueName + "&deliveryMode=NON_PERSISTENT"); + connection = messageSender.createConnection(uri); + SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); + soapRequest.setSoapAction(SOAP_ACTION); + connection.send(soapRequest); - final BytesMessage request = (BytesMessage) jmsTemplate.receive(); - assertNotNull("No message received", request); - assertTrue("No message content received", request.readByte() != -1); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - messageFactory.createMessage().writeTo(bos); - final byte[] buf = bos.toByteArray(); - jmsTemplate.send(responseQueueName, new MessageCreator() { + final BytesMessage request = (BytesMessage) jmsTemplate.receive(); + assertNotNull("No message received", request); + assertTrue("No message content received", request.readByte() != -1); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + messageFactory.createMessage().writeTo(bos); + final byte[] buf = bos.toByteArray(); + jmsTemplate.send(responseQueueName, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - BytesMessage response = session.createBytesMessage(); - response.setJMSCorrelationID(request.getJMSMessageID()); - response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION); - response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, - SoapVersion.SOAP_11.getContentType()); - response.writeBytes(buf); - return response; - } - }); - SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); - assertNotNull("No response received", response); - assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction()); - assertFalse("Message is fault", response.hasFault()); - } - finally { - if (connection != null) { - connection.close(); - } - } - } + public Message createMessage(Session session) throws JMSException { + BytesMessage response = session.createBytesMessage(); + response.setJMSCorrelationID(request.getJMSMessageID()); + response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION); + response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, + SoapVersion.SOAP_11.getContentType()); + response.writeBytes(buf); + return response; + } + }); + SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); + assertNotNull("No response received", response); + assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction()); + assertFalse("Message is fault", response.hasFault()); + } + finally { + if (connection != null) { + connection.close(); + } + } + } - @Test - public void testSendAndReceiveQueueTextMessage() throws Exception { - WebServiceConnection connection = null; - try { - URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT&messageType=TEXT_MESSAGE"); - connection = messageSender.createConnection(uri); - SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); - soapRequest.setSoapAction(SOAP_ACTION); - connection.send(soapRequest); + @Test + public void testSendAndReceiveQueueTextMessage() throws Exception { + WebServiceConnection connection = null; + try { + URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT&messageType=TEXT_MESSAGE"); + connection = messageSender.createConnection(uri); + SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); + soapRequest.setSoapAction(SOAP_ACTION); + connection.send(soapRequest); - TextMessage request = (TextMessage) jmsTemplate.receive(); - assertNotNull("No message received", request); - assertNotNull("No message content received", request.getText()); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - messageFactory.createMessage().writeTo(bos); - final String text = new String(bos.toByteArray(), "UTF-8"); - jmsTemplate.send(request.getJMSReplyTo(), new MessageCreator() { + TextMessage request = (TextMessage) jmsTemplate.receive(); + assertNotNull("No message received", request); + assertNotNull("No message content received", request.getText()); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + messageFactory.createMessage().writeTo(bos); + final String text = new String(bos.toByteArray(), "UTF-8"); + jmsTemplate.send(request.getJMSReplyTo(), new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage response = session.createTextMessage(); - response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION); - response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, - SoapVersion.SOAP_11.getContentType()); - response.setText(text); - return response; - } - }); - SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); - assertNotNull("No response received", response); - assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction()); - assertFalse("Message is fault", response.hasFault()); - } - finally { - if (connection != null) { - connection.close(); - } - } - } + public Message createMessage(Session session) throws JMSException { + TextMessage response = session.createTextMessage(); + response.setStringProperty(JmsTransportConstants.PROPERTY_SOAP_ACTION, SOAP_ACTION); + response.setStringProperty(JmsTransportConstants.PROPERTY_CONTENT_TYPE, + SoapVersion.SOAP_11.getContentType()); + response.setText(text); + return response; + } + }); + SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); + assertNotNull("No response received", response); + assertEquals("Invalid SOAPAction", SOAP_ACTION, response.getSoapAction()); + assertFalse("Message is fault", response.hasFault()); + } + finally { + if (connection != null) { + connection.close(); + } + } + } - @Test - public void testSendNoResponse() throws Exception { - WebServiceConnection connection = null; - try { - URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT"); - connection = messageSender.createConnection(uri); - SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); - soapRequest.setSoapAction(SOAP_ACTION); - connection.send(soapRequest); + @Test + public void testSendNoResponse() throws Exception { + WebServiceConnection connection = null; + try { + URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT"); + connection = messageSender.createConnection(uri); + SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); + soapRequest.setSoapAction(SOAP_ACTION); + connection.send(soapRequest); - BytesMessage request = (BytesMessage) jmsTemplate.receive(); - assertNotNull("No message received", request); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - messageFactory.createMessage().writeTo(bos); - SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); - assertNull("Response received", response); - } - finally { - if (connection != null) { - connection.close(); - } - } - } + BytesMessage request = (BytesMessage) jmsTemplate.receive(); + assertNotNull("No message received", request); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + messageFactory.createMessage().writeTo(bos); + SoapMessage response = (SoapMessage) connection.receive(new SaajSoapMessageFactory(messageFactory)); + assertNull("Response received", response); + } + finally { + if (connection != null) { + connection.close(); + } + } + } - @Test - public void testPostProcessor() throws Exception { - MessagePostProcessor processor = new MessagePostProcessor() { - public Message postProcessMessage(Message message) throws JMSException { - message.setBooleanProperty("processed", true); - return message; - } - }; - JmsSenderConnection connection = null; - try { - URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT"); - connection = (JmsSenderConnection) messageSender.createConnection(uri); - connection.setPostProcessor(processor); - SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); - connection.send(soapRequest); + @Test + public void testPostProcessor() throws Exception { + MessagePostProcessor processor = new MessagePostProcessor() { + public Message postProcessMessage(Message message) throws JMSException { + message.setBooleanProperty("processed", true); + return message; + } + }; + JmsSenderConnection connection = null; + try { + URI uri = new URI("jms:SenderRequestQueue?deliveryMode=NON_PERSISTENT"); + connection = (JmsSenderConnection) messageSender.createConnection(uri); + connection.setPostProcessor(processor); + SoapMessage soapRequest = new SaajSoapMessage(messageFactory.createMessage()); + connection.send(soapRequest); - BytesMessage request = (BytesMessage) jmsTemplate.receive(); - assertNotNull("No message received", request); - assertTrue("Message not processed", request.getBooleanProperty("processed")); - } - finally { - if (connection != null) { - connection.close(); - } - } + BytesMessage request = (BytesMessage) jmsTemplate.receive(); + assertNotNull("No message received", request); + assertTrue("Message not processed", request.getBooleanProperty("processed")); + } + finally { + if (connection != null) { + connection.close(); + } + } - } + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/WebServiceMessageListenerIntegrationTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/WebServiceMessageListenerIntegrationTest.java index b4e190fc..1705b212 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/WebServiceMessageListenerIntegrationTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/WebServiceMessageListenerIntegrationTest.java @@ -40,63 +40,63 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration("jms-receiver-applicationContext.xml") public class WebServiceMessageListenerIntegrationTest { - private static final String CONTENT = - "" + "\n" + - "\n" + - "DIS\n" + "\n" + ""; + private static final String CONTENT = + "" + "\n" + + "\n" + + "DIS\n" + "\n" + ""; - @Autowired - private JmsTemplate jmsTemplate; + @Autowired + private JmsTemplate jmsTemplate; - @Resource - private Queue responseQueue; + @Resource + private Queue responseQueue; - @Resource - private Queue requestQueue; + @Resource + private Queue requestQueue; - @Autowired - private Topic requestTopic; + @Autowired + private Topic requestTopic; - @Test - public void testReceiveQueueBytesMessage() throws Exception { - final byte[] b = CONTENT.getBytes("UTF-8"); - jmsTemplate.send(requestQueue, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - BytesMessage request = session.createBytesMessage(); - request.setJMSReplyTo(responseQueue); - request.writeBytes(b); - return request; - } - }); - BytesMessage response = (BytesMessage) jmsTemplate.receive(responseQueue); - assertNotNull("No response received", response); - } + @Test + public void testReceiveQueueBytesMessage() throws Exception { + final byte[] b = CONTENT.getBytes("UTF-8"); + jmsTemplate.send(requestQueue, new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + BytesMessage request = session.createBytesMessage(); + request.setJMSReplyTo(responseQueue); + request.writeBytes(b); + return request; + } + }); + BytesMessage response = (BytesMessage) jmsTemplate.receive(responseQueue); + assertNotNull("No response received", response); + } - @Test - public void testReceiveQueueTextMessage() throws Exception { - jmsTemplate.send(requestQueue, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - TextMessage request = session.createTextMessage(CONTENT); - request.setJMSReplyTo(responseQueue); - return request; - } - }); - TextMessage response = (TextMessage) jmsTemplate.receive(responseQueue); - assertNotNull("No response received", response); - } + @Test + public void testReceiveQueueTextMessage() throws Exception { + jmsTemplate.send(requestQueue, new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + TextMessage request = session.createTextMessage(CONTENT); + request.setJMSReplyTo(responseQueue); + return request; + } + }); + TextMessage response = (TextMessage) jmsTemplate.receive(responseQueue); + assertNotNull("No response received", response); + } - @Test - public void testReceiveTopic() throws Exception { - final byte[] b = CONTENT.getBytes("UTF-8"); - jmsTemplate.send(requestTopic, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - BytesMessage request = session.createBytesMessage(); - request.writeBytes(b); - return request; - } - }); - Thread.sleep(100); - } + @Test + public void testReceiveTopic() throws Exception { + final byte[] b = CONTENT.getBytes("UTF-8"); + jmsTemplate.send(requestTopic, new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + BytesMessage request = session.createBytesMessage(); + request.writeBytes(b); + return request; + } + }); + Thread.sleep(100); + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/support/JmsTransportUtilsTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/support/JmsTransportUtilsTest.java index 9867c6cb..9300c1e4 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/support/JmsTransportUtilsTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/jms/support/JmsTransportUtilsTest.java @@ -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, @@ -29,87 +29,87 @@ import static org.junit.Assert.assertEquals; public class JmsTransportUtilsTest { - @Test - public void getDestinationName() throws Exception { - URI uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); - String destinationName = JmsTransportUtils.getDestinationName(uri); - assertEquals("Invalid destination", "RequestQueue", destinationName); + @Test + public void getDestinationName() throws Exception { + URI uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); + String destinationName = JmsTransportUtils.getDestinationName(uri); + assertEquals("Invalid destination", "RequestQueue", destinationName); - uri = new URI("jms:RequestQueue"); - destinationName = JmsTransportUtils.getDestinationName(uri); - assertEquals("Invalid destination", "RequestQueue", destinationName); - } + uri = new URI("jms:RequestQueue"); + destinationName = JmsTransportUtils.getDestinationName(uri); + assertEquals("Invalid destination", "RequestQueue", destinationName); + } - @Test - public void getDeliveryMode() throws Exception { - URI uri = new URI("jms:RequestQueue?deliveryMode=NON_PERSISTENT"); - int deliveryMode = JmsTransportUtils.getDeliveryMode(uri); - assertEquals("Invalid deliveryMode", DeliveryMode.NON_PERSISTENT, deliveryMode); + @Test + public void getDeliveryMode() throws Exception { + URI uri = new URI("jms:RequestQueue?deliveryMode=NON_PERSISTENT"); + int deliveryMode = JmsTransportUtils.getDeliveryMode(uri); + assertEquals("Invalid deliveryMode", DeliveryMode.NON_PERSISTENT, deliveryMode); - uri = new URI("jms:RequestQueue?deliveryMode=PERSISTENT"); - deliveryMode = JmsTransportUtils.getDeliveryMode(uri); - assertEquals("Invalid deliveryMode", DeliveryMode.PERSISTENT, deliveryMode); + uri = new URI("jms:RequestQueue?deliveryMode=PERSISTENT"); + deliveryMode = JmsTransportUtils.getDeliveryMode(uri); + assertEquals("Invalid deliveryMode", DeliveryMode.PERSISTENT, deliveryMode); - uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); - deliveryMode = JmsTransportUtils.getDeliveryMode(uri); - assertEquals("Invalid deliveryMode", Message.DEFAULT_DELIVERY_MODE, deliveryMode); - } + uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); + deliveryMode = JmsTransportUtils.getDeliveryMode(uri); + assertEquals("Invalid deliveryMode", Message.DEFAULT_DELIVERY_MODE, deliveryMode); + } - @Test - public void getMessageType() throws Exception { - URI uri = new URI("jms:RequestQueue?messageType=BYTESMESSAGE"); - int messageType = JmsTransportUtils.getMessageType(uri); - assertEquals("Invalid messageType", JmsTransportConstants.BYTES_MESSAGE_TYPE, messageType); + @Test + public void getMessageType() throws Exception { + URI uri = new URI("jms:RequestQueue?messageType=BYTESMESSAGE"); + int messageType = JmsTransportUtils.getMessageType(uri); + assertEquals("Invalid messageType", JmsTransportConstants.BYTES_MESSAGE_TYPE, messageType); - uri = new URI("jms:RequestQueue?messageType=TEXT_MESSAGE"); - messageType = JmsTransportUtils.getMessageType(uri); - assertEquals("Invalid messageType", JmsTransportConstants.TEXT_MESSAGE_TYPE, messageType); + uri = new URI("jms:RequestQueue?messageType=TEXT_MESSAGE"); + messageType = JmsTransportUtils.getMessageType(uri); + assertEquals("Invalid messageType", JmsTransportConstants.TEXT_MESSAGE_TYPE, messageType); - uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); - messageType = JmsTransportUtils.getMessageType(uri); - assertEquals("Invalid messageType", JmsTransportConstants.BYTES_MESSAGE_TYPE, messageType); - } + uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); + messageType = JmsTransportUtils.getMessageType(uri); + assertEquals("Invalid messageType", JmsTransportConstants.BYTES_MESSAGE_TYPE, messageType); + } - @Test - public void getTimeToLive() throws Exception { - URI uri = new URI("jms:RequestQueue?timeToLive=100"); - long timeToLive = JmsTransportUtils.getTimeToLive(uri); - assertEquals("Invalid timeToLive", 100, timeToLive); + @Test + public void getTimeToLive() throws Exception { + URI uri = new URI("jms:RequestQueue?timeToLive=100"); + long timeToLive = JmsTransportUtils.getTimeToLive(uri); + assertEquals("Invalid timeToLive", 100, timeToLive); - uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); - timeToLive = JmsTransportUtils.getTimeToLive(uri); - assertEquals("Invalid timeToLive", Message.DEFAULT_TIME_TO_LIVE, timeToLive); - } + uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); + timeToLive = JmsTransportUtils.getTimeToLive(uri); + assertEquals("Invalid timeToLive", Message.DEFAULT_TIME_TO_LIVE, timeToLive); + } - @Test - public void getPriority() throws Exception { - URI uri = new URI("jms:RequestQueue?priority=5"); - int priority = JmsTransportUtils.getPriority(uri); - assertEquals("Invalid priority", 5, priority); + @Test + public void getPriority() throws Exception { + URI uri = new URI("jms:RequestQueue?priority=5"); + int priority = JmsTransportUtils.getPriority(uri); + assertEquals("Invalid priority", 5, priority); - uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); - priority = JmsTransportUtils.getPriority(uri); - assertEquals("Invalid priority", Message.DEFAULT_PRIORITY, priority); - } + uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); + priority = JmsTransportUtils.getPriority(uri); + assertEquals("Invalid priority", Message.DEFAULT_PRIORITY, priority); + } - @Test - public void getReplyToName() throws Exception { - URI uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); - String replyToName = JmsTransportUtils.getReplyToName(uri); - assertEquals("Invalid replyToName", "RESP_QUEUE", replyToName); + @Test + public void getReplyToName() throws Exception { + URI uri = new URI("jms:RequestQueue?replyToName=RESP_QUEUE"); + String replyToName = JmsTransportUtils.getReplyToName(uri); + assertEquals("Invalid replyToName", "RESP_QUEUE", replyToName); - uri = new URI("jms:RequestQueue?priority=5"); - replyToName = JmsTransportUtils.getReplyToName(uri); - Assert.assertNull("Invalid replyToName", replyToName); - } + uri = new URI("jms:RequestQueue?priority=5"); + replyToName = JmsTransportUtils.getReplyToName(uri); + Assert.assertNull("Invalid replyToName", replyToName); + } - @Test - public void jndi() throws Exception { - URI uri = new URI("jms:jms/REQUEST_QUEUE?replyToName=jms/REPLY_QUEUE"); - String destination = JmsTransportUtils.getDestinationName(uri); - assertEquals("Invalid destination name", "jms/REQUEST_QUEUE", destination); + @Test + public void jndi() throws Exception { + URI uri = new URI("jms:jms/REQUEST_QUEUE?replyToName=jms/REPLY_QUEUE"); + String destination = JmsTransportUtils.getDestinationName(uri); + assertEquals("Invalid destination name", "jms/REQUEST_QUEUE", destination); - String replyTo = JmsTransportUtils.getReplyToName(uri); - assertEquals("Invalid reply to name", "jms/REPLY_QUEUE", replyTo); - } + String replyTo = JmsTransportUtils.getReplyToName(uri); + assertEquals("Invalid reply to name", "jms/REPLY_QUEUE", replyTo); + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailIntegrationTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailIntegrationTest.java index 6aa84ca4..986af38f 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailIntegrationTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailIntegrationTest.java @@ -36,28 +36,28 @@ import static org.junit.Assert.assertEquals; @ContextConfiguration("mail-applicationContext.xml") public class MailIntegrationTest { - @Autowired - private WebServiceTemplate webServiceTemplate; + @Autowired + private WebServiceTemplate webServiceTemplate; - @Autowired - private GenericApplicationContext applicationContext; + @Autowired + private GenericApplicationContext applicationContext; - @After - public void clearMailbox() throws Exception { - Mailbox.clearAll(); - } + @After + public void clearMailbox() throws Exception { + Mailbox.clearAll(); + } - @Test - public void testMailTransport() throws Exception { - String content = ""; - StringResult result = new StringResult(); - webServiceTemplate.sendSourceAndReceiveToResult(new StringSource(content), result); - applicationContext.close(); - assertEquals("Server mail message not deleted", 0, Mailbox.get("server@example.com").size()); - assertEquals("No client mail message received", 1, Mailbox.get("client@example.com").size()); - XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); + @Test + public void testMailTransport() throws Exception { + String content = ""; + StringResult result = new StringResult(); + webServiceTemplate.sendSourceAndReceiveToResult(new StringSource(content), result); + applicationContext.close(); + assertEquals("Server mail message not deleted", 0, Mailbox.get("server@example.com").size()); + assertEquals("No client mail message received", 1, Mailbox.get("client@example.com").size()); + XMLAssert.assertXMLEqual("Invalid content received", content, result.toString()); - } + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailMessageSenderIntegrationTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailMessageSenderIntegrationTest.java index ec1f0725..feab1085 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailMessageSenderIntegrationTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/MailMessageSenderIntegrationTest.java @@ -34,45 +34,45 @@ import org.jvnet.mock_javamail.Mailbox; public class MailMessageSenderIntegrationTest { - private MailMessageSender messageSender; + private MailMessageSender messageSender; - private MessageFactory messageFactory; + private MessageFactory messageFactory; - private static final String SOAP_ACTION = "http://springframework.org/DoIt"; + private static final String SOAP_ACTION = "http://springframework.org/DoIt"; - @Before - public void setUp() throws Exception { - messageSender = new MailMessageSender(); - messageSender.setFrom("Spring-WS SOAP Client "); - messageSender.setTransportUri("smtp://smtp.example.com"); - messageSender.setStoreUri("imap://imap.example.com/INBOX"); - messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); - messageSender.afterPropertiesSet(); - } + @Before + public void setUp() throws Exception { + messageSender = new MailMessageSender(); + messageSender.setFrom("Spring-WS SOAP Client "); + messageSender.setTransportUri("smtp://smtp.example.com"); + messageSender.setStoreUri("imap://imap.example.com/INBOX"); + messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + messageSender.afterPropertiesSet(); + } - @After - public void tearDown() throws Exception { - Mailbox.clearAll(); - } + @After + public void tearDown() throws Exception { + Mailbox.clearAll(); + } - @Test - public void testSendAndReceiveQueueNoResponse() throws Exception { - WebServiceConnection connection = null; - try { - URI mailTo = new URI("mailto:server@example.com?subject=SOAP%20Test"); - connection = messageSender.createConnection(mailTo); - SOAPMessage saajMessage = messageFactory.createMessage(); - saajMessage.getSOAPBody().addBodyElement(new QName("http://springframework.org", "test")); - SoapMessage soapRequest = new SaajSoapMessage(saajMessage); - soapRequest.setSoapAction(SOAP_ACTION); - connection.send(soapRequest); - Assert.assertEquals("No mail message sent", 1, Mailbox.get("server@example.com").size()); - } - finally { - if (connection != null) { - connection.close(); - } - } - } + @Test + public void testSendAndReceiveQueueNoResponse() throws Exception { + WebServiceConnection connection = null; + try { + URI mailTo = new URI("mailto:server@example.com?subject=SOAP%20Test"); + connection = messageSender.createConnection(mailTo); + SOAPMessage saajMessage = messageFactory.createMessage(); + saajMessage.getSOAPBody().addBodyElement(new QName("http://springframework.org", "test")); + SoapMessage soapRequest = new SaajSoapMessage(saajMessage); + soapRequest.setSoapAction(SOAP_ACTION); + connection.send(soapRequest); + Assert.assertEquals("No mail message sent", 1, Mailbox.get("server@example.com").size()); + } + finally { + if (connection != null) { + connection.close(); + } + } + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/support/MailTransportUtilsTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/support/MailTransportUtilsTest.java index ff731eaf..8035b9c8 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/support/MailTransportUtilsTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/mail/support/MailTransportUtilsTest.java @@ -25,32 +25,32 @@ import org.junit.Test; public class MailTransportUtilsTest { - @Test - public void testToPasswordProtectedString() throws Exception { - URLName name = new URLName("imap://john:secret@imap.example.com/INBOX"); - String result = MailTransportUtils.toPasswordProtectedString(name); - Assert.assertEquals("Password found in string", -1, result.indexOf("secret")); - } + @Test + public void testToPasswordProtectedString() throws Exception { + URLName name = new URLName("imap://john:secret@imap.example.com/INBOX"); + String result = MailTransportUtils.toPasswordProtectedString(name); + Assert.assertEquals("Password found in string", -1, result.indexOf("secret")); + } - @Test - public void testGetTo() throws Exception { - URI uri = new URI("mailto:infobot@example.com?subject=current-issue"); - InternetAddress to = MailTransportUtils.getTo(uri); - Assert.assertEquals("Invalid destination", new InternetAddress("infobot@example.com"), to); + @Test + public void testGetTo() throws Exception { + URI uri = new URI("mailto:infobot@example.com?subject=current-issue"); + InternetAddress to = MailTransportUtils.getTo(uri); + Assert.assertEquals("Invalid destination", new InternetAddress("infobot@example.com"), to); - uri = new URI("mailto:infobot@example.com"); - to = MailTransportUtils.getTo(uri); - Assert.assertEquals("Invalid destination", new InternetAddress("infobot@example.com"), to); - } + uri = new URI("mailto:infobot@example.com"); + to = MailTransportUtils.getTo(uri); + Assert.assertEquals("Invalid destination", new InternetAddress("infobot@example.com"), to); + } - @Test - public void testGetSubject() throws Exception { - URI uri = new URI("mailto:infobot@example.com?subject=current-issue"); - String subject = MailTransportUtils.getSubject(uri); - Assert.assertEquals("Invalid destination", "current-issue", subject); + @Test + public void testGetSubject() throws Exception { + URI uri = new URI("mailto:infobot@example.com?subject=current-issue"); + String subject = MailTransportUtils.getSubject(uri); + Assert.assertEquals("Invalid destination", "current-issue", subject); - uri = new URI("mailto:infobot@example.com"); - subject = MailTransportUtils.getSubject(uri); - Assert.assertNull("Invalid destination", subject); - } + uri = new URI("mailto:infobot@example.com"); + subject = MailTransportUtils.getSubject(uri); + Assert.assertNull("Invalid destination", subject); + } } \ No newline at end of file diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java index 200e0f7e..4daa46b9 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/support/EchoPayloadEndpoint.java @@ -22,8 +22,8 @@ import org.springframework.ws.server.endpoint.PayloadEndpoint; public class EchoPayloadEndpoint implements PayloadEndpoint { - @Override - public Source invoke(Source request) throws Exception { - return request; - } + @Override + public Source invoke(Source request) throws Exception { + return request; + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java index 514b3620..b4a6768e 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/support/FreePortScanner.java @@ -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,69 +31,69 @@ import org.springframework.util.Assert; */ public abstract class FreePortScanner { - private static final int MIN_SAFE_PORT = 1024; + private static final int MIN_SAFE_PORT = 1024; - private static final int MAX_PORT = 65535; + private static final int MAX_PORT = 65535; - private static final Random random = new Random(); + private static final Random random = new Random(); - /** - * Returns the number of a free port in the default range. - */ - public static int getFreePort() { - return getFreePort(MIN_SAFE_PORT, MAX_PORT); - } + /** + * Returns the number of a free port in the default range. + */ + public static int getFreePort() { + return getFreePort(MIN_SAFE_PORT, MAX_PORT); + } - /** - * Returns the number of a free port in the given range. - */ - public static int getFreePort(int minPort, int maxPort) { - Assert.isTrue(minPort > 0, "'minPort' must be larger than 0"); - Assert.isTrue(maxPort > minPort, "'maxPort' must be larger than minPort"); - int portRange = maxPort - minPort; - int candidatePort; - int searchCounter = 0; - do { - if (++searchCounter > portRange) { - throw new IllegalStateException( - String.format("There were no ports available in the range %d to %d", minPort, maxPort)); - } - candidatePort = getRandomPort(minPort, portRange); - } - while (!isPortAvailable(candidatePort)); + /** + * Returns the number of a free port in the given range. + */ + public static int getFreePort(int minPort, int maxPort) { + Assert.isTrue(minPort > 0, "'minPort' must be larger than 0"); + Assert.isTrue(maxPort > minPort, "'maxPort' must be larger than minPort"); + int portRange = maxPort - minPort; + int candidatePort; + int searchCounter = 0; + do { + if (++searchCounter > portRange) { + throw new IllegalStateException( + String.format("There were no ports available in the range %d to %d", minPort, maxPort)); + } + candidatePort = getRandomPort(minPort, portRange); + } + while (!isPortAvailable(candidatePort)); - return candidatePort; - } + return candidatePort; + } - private static int getRandomPort(int minPort, int portRange) { - return minPort + random.nextInt(portRange); - } + private static int getRandomPort(int minPort, int portRange) { + return minPort + random.nextInt(portRange); + } - private static boolean isPortAvailable(int port) { - ServerSocket serverSocket; - try { - serverSocket = new ServerSocket(); - } - catch (IOException ex) { - throw new IllegalStateException("Unable to create ServerSocket.", ex); - } + private static boolean isPortAvailable(int port) { + ServerSocket serverSocket; + try { + serverSocket = new ServerSocket(); + } + catch (IOException ex) { + throw new IllegalStateException("Unable to create ServerSocket.", ex); + } - try { - InetSocketAddress sa = new InetSocketAddress(port); - serverSocket.bind(sa); - return true; - } - catch (IOException ex) { - return false; - } - finally { - try { - serverSocket.close(); - } - catch (IOException ex) { - // ignore - } - } - } + try { + InetSocketAddress sa = new InetSocketAddress(port); + serverSocket.bind(sa); + return true; + } + catch (IOException ex) { + return false; + } + finally { + try { + serverSocket.close(); + } + catch (IOException ex) { + // ignore + } + } + } } diff --git a/spring-ws-support/src/test/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBeanTest.java b/spring-ws-support/src/test/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBeanTest.java index dde42953..9df0fd33 100644 --- a/spring-ws-support/src/test/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBeanTest.java +++ b/spring-ws-support/src/test/java/org/springframework/ws/transport/xmpp/support/XmppConnectionFactoryBeanTest.java @@ -23,26 +23,26 @@ import org.junit.Test; /** @author Arjen Poutsma */ public class XmppConnectionFactoryBeanTest { - private XmppConnectionFactoryBean factoryBean; + private XmppConnectionFactoryBean factoryBean; - @Before - public void createFactoryBean() { - factoryBean = new XmppConnectionFactoryBean(); - } - @Test(expected = IllegalArgumentException.class) - public void noHost() throws XMPPException { - factoryBean.afterPropertiesSet(); - } + @Before + public void createFactoryBean() { + factoryBean = new XmppConnectionFactoryBean(); + } + @Test(expected = IllegalArgumentException.class) + public void noHost() throws XMPPException { + factoryBean.afterPropertiesSet(); + } - @Test(expected = IllegalArgumentException.class) - public void noUsername() throws XMPPException { - factoryBean.setHost("jabber.org"); - factoryBean.afterPropertiesSet(); - } + @Test(expected = IllegalArgumentException.class) + public void noUsername() throws XMPPException { + factoryBean.setHost("jabber.org"); + factoryBean.afterPropertiesSet(); + } - @Test(expected = IllegalArgumentException.class) - public void wrongPort() throws XMPPException { - factoryBean.setPort(-10); - } + @Test(expected = IllegalArgumentException.class) + public void wrongPort() throws XMPPException { + factoryBean.setPort(-10); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/AbstractResponseCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/AbstractResponseCreator.java index 2574b478..f2a1dd80 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/AbstractResponseCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/AbstractResponseCreator.java @@ -33,24 +33,24 @@ import org.springframework.ws.WebServiceMessageFactory; */ abstract class AbstractResponseCreator implements ResponseCreator { - @Override - public final WebServiceMessage createResponse(URI uri, - WebServiceMessage request, - WebServiceMessageFactory messageFactory) throws IOException { - WebServiceMessage response = messageFactory.createWebServiceMessage(); - doWithResponse(uri, request, response); - return response; - } + @Override + public final WebServiceMessage createResponse(URI uri, + WebServiceMessage request, + WebServiceMessageFactory messageFactory) throws IOException { + WebServiceMessage response = messageFactory.createWebServiceMessage(); + doWithResponse(uri, request, response); + return response; + } - /** - * Execute any number of operations on the supplied response, given the request and URI. - * - * @param uri the URI - * @param request the request message - * @param response the response message - * @throws IOException in case of I/O errors - */ - protected abstract void doWithResponse(URI uri, WebServiceMessage request, WebServiceMessage response) - throws IOException; + /** + * Execute any number of operations on the supplied response, given the request and URI. + * + * @param uri the URI + * @param request the request message + * @param response the response message + * @throws IOException in case of I/O errors + */ + protected abstract void doWithResponse(URI uri, WebServiceMessage request, WebServiceMessage response) + throws IOException; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ErrorResponseCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ErrorResponseCreator.java index c300ad8a..d1660d84 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ErrorResponseCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ErrorResponseCreator.java @@ -31,21 +31,21 @@ import org.springframework.ws.WebServiceMessageFactory; */ class ErrorResponseCreator implements ResponseCreator { - private final String errorMessage; + private final String errorMessage; - ErrorResponseCreator(String errorMessage) { - this.errorMessage = errorMessage; - } + ErrorResponseCreator(String errorMessage) { + this.errorMessage = errorMessage; + } - @Override - public WebServiceMessage createResponse(URI uri, - WebServiceMessage request, - WebServiceMessageFactory factory) throws IOException { - // Do nothing - return null; - } + @Override + public WebServiceMessage createResponse(URI uri, + WebServiceMessage request, + WebServiceMessageFactory factory) throws IOException { + // Do nothing + return null; + } - String getErrorMessage() { - return errorMessage; - } + String getErrorMessage() { + return errorMessage; + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ExceptionResponseCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ExceptionResponseCreator.java index 109325a9..eab4e654 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ExceptionResponseCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ExceptionResponseCreator.java @@ -31,25 +31,25 @@ import org.springframework.ws.WebServiceMessageFactory; */ class ExceptionResponseCreator implements ResponseCreator { - private final Exception exception; + private final Exception exception; - ExceptionResponseCreator(IOException exception) { - this.exception = exception; - } + ExceptionResponseCreator(IOException exception) { + this.exception = exception; + } - ExceptionResponseCreator(RuntimeException exception) { - this.exception = exception; - } + ExceptionResponseCreator(RuntimeException exception) { + this.exception = exception; + } - @Override - public WebServiceMessage createResponse(URI uri, - WebServiceMessage request, - WebServiceMessageFactory factory) throws IOException { - if (exception instanceof IOException) { - throw (IOException) exception; - } - else { - throw (RuntimeException) exception; - } - } + @Override + public WebServiceMessage createResponse(URI uri, + WebServiceMessage request, + WebServiceMessageFactory factory) throws IOException { + if (exception instanceof IOException) { + throw (IOException) exception; + } + else { + throw (RuntimeException) exception; + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockSenderConnection.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockSenderConnection.java index b8a4e513..eda08db2 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockSenderConnection.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockSenderConnection.java @@ -35,91 +35,91 @@ import org.springframework.ws.transport.WebServiceConnection; */ class MockSenderConnection implements WebServiceConnection, ResponseActions { - private final List requestMatchers = new LinkedList(); + private final List requestMatchers = new LinkedList(); - private URI uri; + private URI uri; - private WebServiceMessage request; + private WebServiceMessage request; - private ResponseCreator responseCreator; + private ResponseCreator responseCreator; - void addRequestMatcher(RequestMatcher requestMatcher) { - Assert.notNull(requestMatcher, "'requestMatcher' must not be null"); - requestMatchers.add(requestMatcher); - } + void addRequestMatcher(RequestMatcher requestMatcher) { + Assert.notNull(requestMatcher, "'requestMatcher' must not be null"); + requestMatchers.add(requestMatcher); + } - void setUri(URI uri) { - Assert.notNull(uri, "'uri' must not be null"); - this.uri = uri; - } + void setUri(URI uri) { + Assert.notNull(uri, "'uri' must not be null"); + this.uri = uri; + } - // ResponseActions implementation + // ResponseActions implementation - @Override - public ResponseActions andExpect(RequestMatcher requestMatcher) { - addRequestMatcher(requestMatcher); - return this; - } + @Override + public ResponseActions andExpect(RequestMatcher requestMatcher) { + addRequestMatcher(requestMatcher); + return this; + } - @Override - public void andRespond(ResponseCreator responseCreator) { - Assert.notNull(responseCreator, "'responseCreator' must not be null"); - this.responseCreator = responseCreator; - } + @Override + public void andRespond(ResponseCreator responseCreator) { + Assert.notNull(responseCreator, "'responseCreator' must not be null"); + this.responseCreator = responseCreator; + } - // FaultAwareWebServiceConnection implementation + // FaultAwareWebServiceConnection implementation - @Override - @SuppressWarnings("unchecked") - public void send(WebServiceMessage message) throws IOException { - if (!requestMatchers.isEmpty()) { - for (RequestMatcher requestMatcher : requestMatchers) { - requestMatcher.match(uri, message); - } - } - else { - throw new AssertionError("Unexpected send() for [" + message + "]"); - } - this.request = message; - } + @Override + @SuppressWarnings("unchecked") + public void send(WebServiceMessage message) throws IOException { + if (!requestMatchers.isEmpty()) { + for (RequestMatcher requestMatcher : requestMatchers) { + requestMatcher.match(uri, message); + } + } + else { + throw new AssertionError("Unexpected send() for [" + message + "]"); + } + this.request = message; + } - @Override - @SuppressWarnings("unchecked") - public WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException { - if (responseCreator != null) { - return responseCreator.createResponse(uri, request, messageFactory); - } - else { - return null; - } - } + @Override + @SuppressWarnings("unchecked") + public WebServiceMessage receive(WebServiceMessageFactory messageFactory) throws IOException { + if (responseCreator != null) { + return responseCreator.createResponse(uri, request, messageFactory); + } + else { + return null; + } + } - @Override - public URI getUri() { - return uri; - } + @Override + public URI getUri() { + return uri; + } - @Override - public boolean hasError() throws IOException { - return responseCreator instanceof ErrorResponseCreator; - } + @Override + public boolean hasError() throws IOException { + return responseCreator instanceof ErrorResponseCreator; + } - @Override - public String getErrorMessage() throws IOException { - if (responseCreator instanceof ErrorResponseCreator) { - return ((ErrorResponseCreator) responseCreator).getErrorMessage(); - } - else { - return null; - } - } + @Override + public String getErrorMessage() throws IOException { + if (responseCreator instanceof ErrorResponseCreator) { + return ((ErrorResponseCreator) responseCreator).getErrorMessage(); + } + else { + return null; + } + } - @Override - public void close() throws IOException { - requestMatchers.clear(); - request = null; - responseCreator = null; - uri = null; - } + @Override + public void close() throws IOException { + requestMatchers.clear(); + request = null; + responseCreator = null; + uri = null; + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceMessageSender.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceMessageSender.java index 1bbc6846..b380a46e 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceMessageSender.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceMessageSender.java @@ -35,47 +35,47 @@ import org.springframework.ws.transport.WebServiceMessageSender; */ class MockWebServiceMessageSender implements WebServiceMessageSender { - private final List expectedConnections = new LinkedList(); + private final List expectedConnections = new LinkedList(); - private Iterator connectionIterator; + private Iterator connectionIterator; - @Override - public MockSenderConnection createConnection(URI uri) throws IOException { - Assert.notNull(uri, "'uri' must not be null"); - if (connectionIterator == null) { - connectionIterator = expectedConnections.iterator(); - } - if (!connectionIterator.hasNext()) { - throw new AssertionError("No further connections expected"); - } + @Override + public MockSenderConnection createConnection(URI uri) throws IOException { + Assert.notNull(uri, "'uri' must not be null"); + if (connectionIterator == null) { + connectionIterator = expectedConnections.iterator(); + } + if (!connectionIterator.hasNext()) { + throw new AssertionError("No further connections expected"); + } - MockSenderConnection currentConnection = connectionIterator.next(); - currentConnection.setUri(uri); - return currentConnection; - } + MockSenderConnection currentConnection = connectionIterator.next(); + currentConnection.setUri(uri); + return currentConnection; + } - /** - * Always returns {@code true}. - */ - @Override - public boolean supports(URI uri) { - return true; - } + /** + * Always returns {@code true}. + */ + @Override + public boolean supports(URI uri) { + return true; + } - MockSenderConnection expectNewConnection() { - Assert.state(connectionIterator == null, "Can not expect another connection, the test is already underway"); - MockSenderConnection connection = new MockSenderConnection(); - expectedConnections.add(connection); - return connection; - } + MockSenderConnection expectNewConnection() { + Assert.state(connectionIterator == null, "Can not expect another connection, the test is already underway"); + MockSenderConnection connection = new MockSenderConnection(); + expectedConnections.add(connection); + return connection; + } - void verifyConnections() { - if (expectedConnections.isEmpty()) { - return; - } - if (connectionIterator == null || connectionIterator.hasNext()) { - throw new AssertionError("Further connection(s) expected"); - } - } + void verifyConnections() { + if (expectedConnections.isEmpty()) { + return; + } + if (connectionIterator == null || connectionIterator.hasNext()) { + throw new AssertionError("Further connection(s) expected"); + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceServer.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceServer.java index 10e5ea6e..bfae56cc 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceServer.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/MockWebServiceServer.java @@ -56,33 +56,33 @@ import org.springframework.ws.test.support.MockStrategiesHelper; * @ContextConfiguration("applicationContext.xml") * public class MyWebServiceClientIntegrationTest { * - * // MyWebServiceClient extends WebServiceGatewaySupport, and is configured in applicationContext.xml - * @Autowired - * private MyWebServiceClient client; + * // MyWebServiceClient extends WebServiceGatewaySupport, and is configured in applicationContext.xml + * @Autowired + * private MyWebServiceClient client; * - * private MockWebServiceServer mockServer; + * private MockWebServiceServer mockServer; * - * @Before - * public void createServer() throws Exception { - * mockServer = MockWebServiceServer.createServer(client); - * } + * @Before + * public void createServer() throws Exception { + * mockServer = MockWebServiceServer.createServer(client); + * } * - * @Test - * public void getCustomerCount() throws Exception { - * Source expectedRequestPayload = - * new StringSource("<customerCountRequest xmlns=\"http://springframework.org/spring-ws/test\" />"); - * Source responsePayload = new StringSource("<customerCountResponse xmlns='http://springframework.org/spring-ws/test'>" + - * "<customerCount>10</customerCount>" + - * "</customerCountResponse>"); + * @Test + * public void getCustomerCount() throws Exception { + * Source expectedRequestPayload = + * new StringSource("<customerCountRequest xmlns=\"http://springframework.org/spring-ws/test\" />"); + * Source responsePayload = new StringSource("<customerCountResponse xmlns='http://springframework.org/spring-ws/test'>" + + * "<customerCount>10</customerCount>" + + * "</customerCountResponse>"); * - * mockServer.expect(payload(expectedRequestPayload)).andRespond(withPayload(responsePayload)); + * mockServer.expect(payload(expectedRequestPayload)).andRespond(withPayload(responsePayload)); * - * // client.getCustomerCount() uses the WebServiceTemplate - * int customerCount = client.getCustomerCount(); - * assertEquals(10, response.getCustomerCount()); + * // client.getCustomerCount() uses the WebServiceTemplate + * int customerCount = client.getCustomerCount(); + * assertEquals(10, response.getCustomerCount()); * - * mockServer.verify(); - * } + * mockServer.verify(); + * } * } * * @@ -92,87 +92,87 @@ import org.springframework.ws.test.support.MockStrategiesHelper; */ public class MockWebServiceServer { - private final MockWebServiceMessageSender mockMessageSender; + private final MockWebServiceMessageSender mockMessageSender; - private MockWebServiceServer(MockWebServiceMessageSender mockMessageSender) { - Assert.notNull(mockMessageSender, "'mockMessageSender' must not be null"); - this.mockMessageSender = mockMessageSender; - } + private MockWebServiceServer(MockWebServiceMessageSender mockMessageSender) { + Assert.notNull(mockMessageSender, "'mockMessageSender' must not be null"); + this.mockMessageSender = mockMessageSender; + } - /** - * Creates a {@code MockWebServiceServer} instance based on the given {@link WebServiceTemplate}. - * - * @param webServiceTemplate the web service template - * @return the created server - */ - public static MockWebServiceServer createServer(WebServiceTemplate webServiceTemplate) { - Assert.notNull(webServiceTemplate, "'webServiceTemplate' must not be null"); + /** + * Creates a {@code MockWebServiceServer} instance based on the given {@link WebServiceTemplate}. + * + * @param webServiceTemplate the web service template + * @return the created server + */ + public static MockWebServiceServer createServer(WebServiceTemplate webServiceTemplate) { + Assert.notNull(webServiceTemplate, "'webServiceTemplate' must not be null"); - MockWebServiceMessageSender mockMessageSender = new MockWebServiceMessageSender(); - webServiceTemplate.setMessageSender(mockMessageSender); + MockWebServiceMessageSender mockMessageSender = new MockWebServiceMessageSender(); + webServiceTemplate.setMessageSender(mockMessageSender); - return new MockWebServiceServer(mockMessageSender); - } + return new MockWebServiceServer(mockMessageSender); + } - /** - * Creates a {@code MockWebServiceServer} instance based on the given {@link WebServiceGatewaySupport}. - * - * @param gatewaySupport the client class - * @return the created server - */ - public static MockWebServiceServer createServer(WebServiceGatewaySupport gatewaySupport) { - Assert.notNull(gatewaySupport, "'gatewaySupport' must not be null"); - return createServer(gatewaySupport.getWebServiceTemplate()); - } + /** + * Creates a {@code MockWebServiceServer} instance based on the given {@link WebServiceGatewaySupport}. + * + * @param gatewaySupport the client class + * @return the created server + */ + public static MockWebServiceServer createServer(WebServiceGatewaySupport gatewaySupport) { + Assert.notNull(gatewaySupport, "'gatewaySupport' must not be null"); + return createServer(gatewaySupport.getWebServiceTemplate()); + } - /** - * Creates a {@code MockWebServiceServer} instance based on the given {@link ApplicationContext}. - * - *

This factory method will try and find a configured {@link WebServiceTemplate} in the given application context. - * If no template can be found, it will try and find a {@link WebServiceGatewaySupport}, and use its configured - * template. If neither can be found, an exception is thrown. - * - * @param applicationContext the application context to base the client on - * @return the created server - * @throws IllegalArgumentException if the given application context contains neither a {@link WebServiceTemplate} - * nor a {@link WebServiceGatewaySupport}. - */ - public static MockWebServiceServer createServer(ApplicationContext applicationContext) { - MockStrategiesHelper strategiesHelper = new MockStrategiesHelper(applicationContext); - WebServiceTemplate webServiceTemplate = strategiesHelper.getStrategy(WebServiceTemplate.class); - if (webServiceTemplate != null) { - return createServer(webServiceTemplate); - } - WebServiceGatewaySupport gatewaySupport = strategiesHelper.getStrategy(WebServiceGatewaySupport.class); - if (gatewaySupport != null) { - return createServer(gatewaySupport); - } - throw new IllegalArgumentException( - "Could not find either WebServiceTemplate or WebServiceGatewaySupport in application context"); - } + /** + * Creates a {@code MockWebServiceServer} instance based on the given {@link ApplicationContext}. + * + *

This factory method will try and find a configured {@link WebServiceTemplate} in the given application context. + * If no template can be found, it will try and find a {@link WebServiceGatewaySupport}, and use its configured + * template. If neither can be found, an exception is thrown. + * + * @param applicationContext the application context to base the client on + * @return the created server + * @throws IllegalArgumentException if the given application context contains neither a {@link WebServiceTemplate} + * nor a {@link WebServiceGatewaySupport}. + */ + public static MockWebServiceServer createServer(ApplicationContext applicationContext) { + MockStrategiesHelper strategiesHelper = new MockStrategiesHelper(applicationContext); + WebServiceTemplate webServiceTemplate = strategiesHelper.getStrategy(WebServiceTemplate.class); + if (webServiceTemplate != null) { + return createServer(webServiceTemplate); + } + WebServiceGatewaySupport gatewaySupport = strategiesHelper.getStrategy(WebServiceGatewaySupport.class); + if (gatewaySupport != null) { + return createServer(gatewaySupport); + } + throw new IllegalArgumentException( + "Could not find either WebServiceTemplate or WebServiceGatewaySupport in application context"); + } - /** - * Records an expectation specified by the given {@link RequestMatcher}. Returns a {@link ResponseActions} object - * that allows for creating the response, or to set up more expectations. - * - * @param requestMatcher the request matcher expected - * @return the response actions - */ - public ResponseActions expect(RequestMatcher requestMatcher) { - MockSenderConnection connection = mockMessageSender.expectNewConnection(); - connection.addRequestMatcher(requestMatcher); - return connection; - } + /** + * Records an expectation specified by the given {@link RequestMatcher}. Returns a {@link ResponseActions} object + * that allows for creating the response, or to set up more expectations. + * + * @param requestMatcher the request matcher expected + * @return the response actions + */ + public ResponseActions expect(RequestMatcher requestMatcher) { + MockSenderConnection connection = mockMessageSender.expectNewConnection(); + connection.addRequestMatcher(requestMatcher); + return connection; + } - /** - * Verifies that all expectations were met. - * - * @throws AssertionError in case of unmet expectations - */ - public void verify() { - mockMessageSender.verifyConnections(); - } - + /** + * Verifies that all expectations were met. + * + * @throws AssertionError in case of unmet expectations + */ + public void verify() { + mockMessageSender.verifyConnections(); + } + diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatcher.java index b70f2962..5c96e7e5 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatcher.java @@ -30,15 +30,15 @@ import org.springframework.ws.WebServiceMessage; */ public interface RequestMatcher { - /** - * Matches the given request message against the expectations. Implementations typically make use of JUnit-based - * assertions. - * - * @param uri the uri connected to - * @param request the request message to make assertions on - * @throws IOException in case of I/O errors - * @throws AssertionError if expectations are not met - */ - void match(URI uri, WebServiceMessage request) throws IOException, AssertionError; + /** + * Matches the given request message against the expectations. Implementations typically make use of JUnit-based + * assertions. + * + * @param uri the uri connected to + * @param request the request message to make assertions on + * @throws IOException in case of I/O errors + * @throws AssertionError if expectations are not met + */ + void match(URI uri, WebServiceMessage request) throws IOException, AssertionError; } \ No newline at end of file diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatchers.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatchers.java index 9bff03f4..514027fd 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatchers.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestMatchers.java @@ -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, @@ -40,136 +40,136 @@ import org.springframework.xml.transform.ResourceSource; */ public abstract class RequestMatchers { - private RequestMatchers() { - } + private RequestMatchers() { + } /** - * Expects any request. - * - * @return the request matcher - */ - public static RequestMatcher anything() { - return new RequestMatcher() { - public void match(URI uri, WebServiceMessage request) throws IOException, AssertionError { - } - }; - } + * Expects any request. + * + * @return the request matcher + */ + public static RequestMatcher anything() { + return new RequestMatcher() { + public void match(URI uri, WebServiceMessage request) throws IOException, AssertionError { + } + }; + } - // Payload + // Payload - /** - * Expects the given {@link javax.xml.transform.Source} XML payload. - * - * @param payload the XML payload - * @return the request matcher - */ - public static RequestMatcher payload(Source payload) { - Assert.notNull(payload, "'payload' must not be null"); - return new WebServiceMessageMatcherAdapter(new PayloadDiffMatcher(payload)); - } + /** + * Expects the given {@link javax.xml.transform.Source} XML payload. + * + * @param payload the XML payload + * @return the request matcher + */ + public static RequestMatcher payload(Source payload) { + Assert.notNull(payload, "'payload' must not be null"); + return new WebServiceMessageMatcherAdapter(new PayloadDiffMatcher(payload)); + } - /** - * Expects the given {@link org.springframework.core.io.Resource} XML payload. - * - * @param payload the XML payload - * @return the request matcher - */ - public static RequestMatcher payload(Resource payload) throws IOException { - Assert.notNull(payload, "'payload' must not be null"); - return payload(new ResourceSource(payload)); - } + /** + * Expects the given {@link org.springframework.core.io.Resource} XML payload. + * + * @param payload the XML payload + * @return the request matcher + */ + public static RequestMatcher payload(Resource payload) throws IOException { + Assert.notNull(payload, "'payload' must not be null"); + return payload(new ResourceSource(payload)); + } - /** - * Expects the payload to validate against the given XSD schema(s). - * - * @param schema the schema - * @param furtherSchemas further schemas, if necessary - * @return the request matcher - */ - public static RequestMatcher validPayload(Resource schema, Resource... furtherSchemas) throws IOException { - return new WebServiceMessageMatcherAdapter(new SchemaValidatingMatcher(schema, furtherSchemas)); - } + /** + * Expects the payload to validate against the given XSD schema(s). + * + * @param schema the schema + * @param furtherSchemas further schemas, if necessary + * @return the request matcher + */ + public static RequestMatcher validPayload(Resource schema, Resource... furtherSchemas) throws IOException { + return new WebServiceMessageMatcherAdapter(new SchemaValidatingMatcher(schema, furtherSchemas)); + } - /** - * Expects the given XPath expression to (not) exist or be evaluated to a value. - * - * @param xpathExpression the XPath expression - * @return the XPath expectations, to be further configured - */ - public static RequestXPathExpectations xpath(String xpathExpression) { - return new XPathExpectationsHelperAdapter(xpathExpression, null); - } + /** + * Expects the given XPath expression to (not) exist or be evaluated to a value. + * + * @param xpathExpression the XPath expression + * @return the XPath expectations, to be further configured + */ + public static RequestXPathExpectations xpath(String xpathExpression) { + return new XPathExpectationsHelperAdapter(xpathExpression, null); + } - /** - * Expects the given XPath expression to (not) exist or be evaluated to a value. - * - * @param xpathExpression the XPath expression - * @param namespaceMapping the namespaces - * @return the XPath expectations, to be further configured - */ - public static RequestXPathExpectations xpath(String xpathExpression, Map namespaceMapping) { - return new XPathExpectationsHelperAdapter(xpathExpression, namespaceMapping); - } + /** + * Expects the given XPath expression to (not) exist or be evaluated to a value. + * + * @param xpathExpression the XPath expression + * @param namespaceMapping the namespaces + * @return the XPath expectations, to be further configured + */ + public static RequestXPathExpectations xpath(String xpathExpression, Map namespaceMapping) { + return new XPathExpectationsHelperAdapter(xpathExpression, namespaceMapping); + } - // SOAP + // SOAP - /** - * Expects the given {@link javax.xml.transform.Source} XML SOAP envelope. - * - * @param soapEnvelope the XML SOAP envelope - * @return the request matcher - * @since 2.1.1 - */ - public static RequestMatcher soapEnvelope(Source soapEnvelope) { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - return new WebServiceMessageMatcherAdapter(new SoapEnvelopeDiffMatcher(soapEnvelope)); - } + /** + * Expects the given {@link javax.xml.transform.Source} XML SOAP envelope. + * + * @param soapEnvelope the XML SOAP envelope + * @return the request matcher + * @since 2.1.1 + */ + public static RequestMatcher soapEnvelope(Source soapEnvelope) { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + return new WebServiceMessageMatcherAdapter(new SoapEnvelopeDiffMatcher(soapEnvelope)); + } - /** - * Expects the given {@link org.springframework.core.io.Resource} XML SOAP envelope. - * - * @param soapEnvelope the XML SOAP envelope - * @return the request matcher - * @since 2.1.1 - */ - public static RequestMatcher soapEnvelope(Resource soapEnvelope) throws IOException { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - return soapEnvelope(new ResourceSource(soapEnvelope)); - } + /** + * Expects the given {@link org.springframework.core.io.Resource} XML SOAP envelope. + * + * @param soapEnvelope the XML SOAP envelope + * @return the request matcher + * @since 2.1.1 + */ + public static RequestMatcher soapEnvelope(Resource soapEnvelope) throws IOException { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + return soapEnvelope(new ResourceSource(soapEnvelope)); + } - /** - * Expects the given SOAP header in the outgoing message. - * - * @param soapHeaderName the qualified name of the SOAP header to expect - * @return the request matcher - */ - public static RequestMatcher soapHeader(QName soapHeaderName) { - Assert.notNull(soapHeaderName, "'soapHeaderName' must not be null"); - return new WebServiceMessageMatcherAdapter(new SoapHeaderMatcher(soapHeaderName)); - } + /** + * Expects the given SOAP header in the outgoing message. + * + * @param soapHeaderName the qualified name of the SOAP header to expect + * @return the request matcher + */ + public static RequestMatcher soapHeader(QName soapHeaderName) { + Assert.notNull(soapHeaderName, "'soapHeaderName' must not be null"); + return new WebServiceMessageMatcherAdapter(new SoapHeaderMatcher(soapHeaderName)); + } - // Other + // Other - /** - * Expects a connection to the given URI. - * - * @param uri the String uri expected to connect to - * @return the request matcher - */ - public static RequestMatcher connectionTo(String uri) { - Assert.notNull(uri, "'uri' must not be null"); - return connectionTo(URI.create(uri)); - } + /** + * Expects a connection to the given URI. + * + * @param uri the String uri expected to connect to + * @return the request matcher + */ + public static RequestMatcher connectionTo(String uri) { + Assert.notNull(uri, "'uri' must not be null"); + return connectionTo(URI.create(uri)); + } - /** - * Expects a connection to the given URI. - * - * @param uri the String uri expected to connect to - * @return the request matcher - */ - public static RequestMatcher connectionTo(URI uri) { - Assert.notNull(uri, "'uri' must not be null"); - return new UriMatcher(uri); - } + /** + * Expects a connection to the given URI. + * + * @param uri the String uri expected to connect to + * @return the request matcher + */ + public static RequestMatcher connectionTo(URI uri) { + Assert.notNull(uri, "'uri' must not be null"); + return new UriMatcher(uri); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestXPathExpectations.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestXPathExpectations.java index a8e7ccc3..6e2f0497 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestXPathExpectations.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/RequestXPathExpectations.java @@ -31,50 +31,50 @@ package org.springframework.ws.test.client; */ public interface RequestXPathExpectations { - /** - * Expects the XPath expression to exist. - * - * @return the request matcher - */ - RequestMatcher exists(); + /** + * Expects the XPath expression to exist. + * + * @return the request matcher + */ + RequestMatcher exists(); - /** - * Expects the XPath expression to not exist. - * - * @return the request matcher - */ - RequestMatcher doesNotExist(); + /** + * Expects the XPath expression to not exist. + * + * @return the request matcher + */ + RequestMatcher doesNotExist(); - /** - * Expects the XPath expression to evaluate to the given boolean. - * - * @param expectedValue the expected value - * @return the request matcher - */ - RequestMatcher evaluatesTo(final boolean expectedValue); + /** + * Expects the XPath expression to evaluate to the given boolean. + * + * @param expectedValue the expected value + * @return the request matcher + */ + RequestMatcher evaluatesTo(final boolean expectedValue); - /** - * Expects the XPath expression to evaluate to the given integer. - * - * @param expectedValue the expected value - * @return the request matcher - */ - RequestMatcher evaluatesTo(int expectedValue); + /** + * Expects the XPath expression to evaluate to the given integer. + * + * @param expectedValue the expected value + * @return the request matcher + */ + RequestMatcher evaluatesTo(int expectedValue); - /** - * Expects the XPath expression to evaluate to the given double. - * - * @param expectedValue the expected value - * @return the request matcher - */ - RequestMatcher evaluatesTo(double expectedValue); + /** + * Expects the XPath expression to evaluate to the given double. + * + * @param expectedValue the expected value + * @return the request matcher + */ + RequestMatcher evaluatesTo(double expectedValue); - /** - * Expects the XPath expression to evaluate to the given string. - * - * @param expectedValue the expected value - * @return the request matcher - */ - RequestMatcher evaluatesTo(String expectedValue); + /** + * Expects the XPath expression to evaluate to the given string. + * + * @param expectedValue the expected value + * @return the request matcher + */ + RequestMatcher evaluatesTo(String expectedValue); } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseActions.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseActions.java index 7caca304..71270a51 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseActions.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseActions.java @@ -25,18 +25,18 @@ package org.springframework.ws.test.client; * @since 2.0 */ public interface ResponseActions { - /** - * Allows for further expectations to be set on the request. - * - * @return the request expectations - */ - ResponseActions andExpect(RequestMatcher requestMatcher); + /** + * Allows for further expectations to be set on the request. + * + * @return the request expectations + */ + ResponseActions andExpect(RequestMatcher requestMatcher); - /** - * Sets the {@link ResponseCreator} for this mock. - * - * @param responseCreator the response creator - */ - void andRespond(ResponseCreator responseCreator); + /** + * Sets the {@link ResponseCreator} for this mock. + * + * @param responseCreator the response creator + */ + void andRespond(ResponseCreator responseCreator); } \ No newline at end of file diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreator.java index 690e1e50..1b7fb4fe 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreator.java @@ -31,14 +31,14 @@ import org.springframework.ws.WebServiceMessageFactory; */ public interface ResponseCreator { - /** - * Create a response for the given the request and URI. - * - * @param uri the URI - * @param request the request message - * @param messageFactory the message that can be used to create responses - * @throws IOException in case of I/O errors - */ - WebServiceMessage createResponse(URI uri, WebServiceMessage request, WebServiceMessageFactory messageFactory) throws IOException; + /** + * Create a response for the given the request and URI. + * + * @param uri the URI + * @param request the request message + * @param messageFactory the message that can be used to create responses + * @throws IOException in case of I/O errors + */ + WebServiceMessage createResponse(URI uri, WebServiceMessage request, WebServiceMessageFactory messageFactory) throws IOException; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreators.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreators.java index ce1f83dd..7246e076 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreators.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/ResponseCreators.java @@ -40,183 +40,183 @@ import org.springframework.xml.transform.ResourceSource; */ public abstract class ResponseCreators { - private ResponseCreators() { - } + private ResponseCreators() { + } - // Payload + // Payload - /** - * Respond with the given {@link javax.xml.transform.Source} XML as payload response. - * - * @param payload the response payload - * @return the response callback - */ - public static ResponseCreator withPayload(Source payload) { - Assert.notNull(payload, "'payload' must not be null"); - return new WebServiceMessageCreatorAdapter(new PayloadMessageCreator(payload)); - } + /** + * Respond with the given {@link javax.xml.transform.Source} XML as payload response. + * + * @param payload the response payload + * @return the response callback + */ + public static ResponseCreator withPayload(Source payload) { + Assert.notNull(payload, "'payload' must not be null"); + return new WebServiceMessageCreatorAdapter(new PayloadMessageCreator(payload)); + } - /** - * Respond with the given {@link org.springframework.core.io.Resource} XML as payload response. - * - * @param payload the response payload - * @return the response callback - */ - public static ResponseCreator withPayload(Resource payload) throws IOException { - Assert.notNull(payload, "'payload' must not be null"); - return withPayload(new ResourceSource(payload)); - } + /** + * Respond with the given {@link org.springframework.core.io.Resource} XML as payload response. + * + * @param payload the response payload + * @return the response callback + */ + public static ResponseCreator withPayload(Resource payload) throws IOException { + Assert.notNull(payload, "'payload' must not be null"); + return withPayload(new ResourceSource(payload)); + } - // Error/Exception - - /** - * Respond with an error. - * - * @param errorMessage the error message - * @return the response callback - * @see org.springframework.ws.transport.WebServiceConnection#hasError() - * @see org.springframework.ws.transport.WebServiceConnection#getErrorMessage() - */ - public static ResponseCreator withError(String errorMessage) { - Assert.hasLength(errorMessage, "'errorMessage' must not be empty"); - return new ErrorResponseCreator(errorMessage); - } + // Error/Exception + + /** + * Respond with an error. + * + * @param errorMessage the error message + * @return the response callback + * @see org.springframework.ws.transport.WebServiceConnection#hasError() + * @see org.springframework.ws.transport.WebServiceConnection#getErrorMessage() + */ + public static ResponseCreator withError(String errorMessage) { + Assert.hasLength(errorMessage, "'errorMessage' must not be empty"); + return new ErrorResponseCreator(errorMessage); + } - /** - * Respond with an {@link java.io.IOException}. - * - * @param ioException the exception to be thrown - * @return the response callback - */ - public static ResponseCreator withException(IOException ioException) { - Assert.notNull(ioException, "'ioException' must not be null"); - return new ExceptionResponseCreator(ioException); - } + /** + * Respond with an {@link java.io.IOException}. + * + * @param ioException the exception to be thrown + * @return the response callback + */ + public static ResponseCreator withException(IOException ioException) { + Assert.notNull(ioException, "'ioException' must not be null"); + return new ExceptionResponseCreator(ioException); + } - /** - * Respond with an {@link RuntimeException}. - * - * @param ex the runtime exception to be thrown - * @return the response callback - */ - public static ResponseCreator withException(RuntimeException ex) { - Assert.notNull(ex, "'ex' must not be null"); - return new ExceptionResponseCreator(ex); - } + /** + * Respond with an {@link RuntimeException}. + * + * @param ex the runtime exception to be thrown + * @return the response callback + */ + public static ResponseCreator withException(RuntimeException ex) { + Assert.notNull(ex, "'ex' must not be null"); + return new ExceptionResponseCreator(ex); + } - // SOAP + // SOAP - /** - * Respond with the given {@link javax.xml.transform.Source} XML as SOAP envelope response. - * - * @param soapEnvelope the response SOAP envelope - * @return the response callback - * @since 2.1.1 - */ - public static ResponseCreator withSoapEnvelope(Source soapEnvelope) { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - return new WebServiceMessageCreatorAdapter(new SoapEnvelopeMessageCreator(soapEnvelope)); - } + /** + * Respond with the given {@link javax.xml.transform.Source} XML as SOAP envelope response. + * + * @param soapEnvelope the response SOAP envelope + * @return the response callback + * @since 2.1.1 + */ + public static ResponseCreator withSoapEnvelope(Source soapEnvelope) { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + return new WebServiceMessageCreatorAdapter(new SoapEnvelopeMessageCreator(soapEnvelope)); + } - /** - * Respond with the given {@link org.springframework.core.io.Resource} XML as SOAP envelope response. - * - * @param soapEnvelope the response SOAP envelope - * @return the response callback - * @since 2.1.1 - */ - public static ResponseCreator withSoapEnvelope(Resource soapEnvelope) throws IOException { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - return withSoapEnvelope(new ResourceSource(soapEnvelope)); - } + /** + * Respond with the given {@link org.springframework.core.io.Resource} XML as SOAP envelope response. + * + * @param soapEnvelope the response SOAP envelope + * @return the response callback + * @since 2.1.1 + */ + public static ResponseCreator withSoapEnvelope(Resource soapEnvelope) throws IOException { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + return withSoapEnvelope(new ResourceSource(soapEnvelope)); + } - /** - * Respond with a {@code MustUnderstand} fault. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @see SoapBody#addMustUnderstandFault(String, java.util.Locale) - */ - public static ResponseCreator withMustUnderstandFault(final String faultStringOrReason, final Locale locale) { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - return new SoapFaultResponseCreator() { - @Override - public void addSoapFault(SoapBody soapBody) { - soapBody.addMustUnderstandFault(faultStringOrReason, locale); - } - }; - } + /** + * Respond with a {@code MustUnderstand} fault. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @see SoapBody#addMustUnderstandFault(String, java.util.Locale) + */ + public static ResponseCreator withMustUnderstandFault(final String faultStringOrReason, final Locale locale) { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + return new SoapFaultResponseCreator() { + @Override + public void addSoapFault(SoapBody soapBody) { + soapBody.addMustUnderstandFault(faultStringOrReason, locale); + } + }; + } - /** - * Respond with a {@code Client} (SOAP 1.1) or {@code Sender} (SOAP 1.2) fault. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) - */ - public static ResponseCreator withClientOrSenderFault(final String faultStringOrReason, final Locale locale) { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - return new SoapFaultResponseCreator() { - @Override - public void addSoapFault(SoapBody soapBody) { - soapBody.addClientOrSenderFault(faultStringOrReason, locale); - } - }; - } + /** + * Respond with a {@code Client} (SOAP 1.1) or {@code Sender} (SOAP 1.2) fault. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) + */ + public static ResponseCreator withClientOrSenderFault(final String faultStringOrReason, final Locale locale) { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + return new SoapFaultResponseCreator() { + @Override + public void addSoapFault(SoapBody soapBody) { + soapBody.addClientOrSenderFault(faultStringOrReason, locale); + } + }; + } - /** - * Respond with a {@code Server} (SOAP 1.1) or {@code Receiver} (SOAP 1.2) fault. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String, Locale) - */ - public static ResponseCreator withServerOrReceiverFault(final String faultStringOrReason, final Locale locale) { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - return new SoapFaultResponseCreator() { - @Override - public void addSoapFault(SoapBody soapBody) { - soapBody.addServerOrReceiverFault(faultStringOrReason, locale); - } - }; - } + /** + * Respond with a {@code Server} (SOAP 1.1) or {@code Receiver} (SOAP 1.2) fault. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String, Locale) + */ + public static ResponseCreator withServerOrReceiverFault(final String faultStringOrReason, final Locale locale) { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + return new SoapFaultResponseCreator() { + @Override + public void addSoapFault(SoapBody soapBody) { + soapBody.addServerOrReceiverFault(faultStringOrReason, locale); + } + }; + } - /** - * Respond with a {@code VersionMismatch} fault. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text - * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 - * @see org.springframework.ws.soap.SoapBody#addVersionMismatchFault(String, Locale) - */ - public static ResponseCreator withVersionMismatchFault(final String faultStringOrReason, final Locale locale) { - Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); - return new SoapFaultResponseCreator() { - @Override - public void addSoapFault(SoapBody soapBody) { - soapBody.addVersionMismatchFault(faultStringOrReason, locale); - } - }; - } + /** + * Respond with a {@code VersionMismatch} fault. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text + * @param locale the language of faultStringOrReason. Optional for SOAP 1.1 + * @see org.springframework.ws.soap.SoapBody#addVersionMismatchFault(String, Locale) + */ + public static ResponseCreator withVersionMismatchFault(final String faultStringOrReason, final Locale locale) { + Assert.hasLength(faultStringOrReason, "'faultStringOrReason' must not be empty"); + return new SoapFaultResponseCreator() { + @Override + public void addSoapFault(SoapBody soapBody) { + soapBody.addVersionMismatchFault(faultStringOrReason, locale); + } + }; + } - /** - * Adapts a {@link WebServiceMessageCreator} to the {@link ResponseCreator} contract. - */ - private static class WebServiceMessageCreatorAdapter implements ResponseCreator { + /** + * Adapts a {@link WebServiceMessageCreator} to the {@link ResponseCreator} contract. + */ + private static class WebServiceMessageCreatorAdapter implements ResponseCreator { - private final WebServiceMessageCreator adaptee; + private final WebServiceMessageCreator adaptee; - private WebServiceMessageCreatorAdapter(WebServiceMessageCreator adaptee) { - this.adaptee = adaptee; - } + private WebServiceMessageCreatorAdapter(WebServiceMessageCreator adaptee) { + this.adaptee = adaptee; + } - @Override - public WebServiceMessage createResponse(URI uri, - WebServiceMessage request, - WebServiceMessageFactory messageFactory) throws IOException { - return adaptee.createMessage(messageFactory); - } - } + @Override + public WebServiceMessage createResponse(URI uri, + WebServiceMessage request, + WebServiceMessageFactory messageFactory) throws IOException { + return adaptee.createMessage(messageFactory); + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/SoapFaultResponseCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/SoapFaultResponseCreator.java index edaf6632..dbef33b2 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/SoapFaultResponseCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/SoapFaultResponseCreator.java @@ -33,24 +33,24 @@ import static org.springframework.ws.test.support.AssertionErrors.fail; */ abstract class SoapFaultResponseCreator extends AbstractResponseCreator { - @Override - protected void doWithResponse(URI uri, WebServiceMessage request, WebServiceMessage response) throws IOException { - if (!(response instanceof SoapMessage)) { - fail("Response is not a SOAP message"); - return; - } - SoapMessage soapResponse = (SoapMessage) response; - SoapBody responseBody = soapResponse.getSoapBody(); - if (responseBody == null) { - fail("SOAP message [" + response + "] does not contain SOAP body"); - } - addSoapFault(responseBody); - } + @Override + protected void doWithResponse(URI uri, WebServiceMessage request, WebServiceMessage response) throws IOException { + if (!(response instanceof SoapMessage)) { + fail("Response is not a SOAP message"); + return; + } + SoapMessage soapResponse = (SoapMessage) response; + SoapBody responseBody = soapResponse.getSoapBody(); + if (responseBody == null) { + fail("SOAP message [" + response + "] does not contain SOAP body"); + } + addSoapFault(responseBody); + } - /** - * Abstract template method that allows subclasses to add a SOAP Fault to the given Body. - * - * @param soapBody the body to attach a fault to - */ - protected abstract void addSoapFault(SoapBody soapBody); + /** + * Abstract template method that allows subclasses to add a SOAP Fault to the given Body. + * + * @param soapBody the body to attach a fault to + */ + protected abstract void addSoapFault(SoapBody soapBody); } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/UriMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/UriMatcher.java index 1fe7838a..f7717311 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/UriMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/UriMatcher.java @@ -30,14 +30,14 @@ import org.springframework.ws.WebServiceMessage; */ class UriMatcher implements RequestMatcher { - private final URI expected; + private final URI expected; - UriMatcher(URI expected) { - this.expected = expected; - } + UriMatcher(URI expected) { + this.expected = expected; + } - @Override - public void match(URI actual, WebServiceMessage request) { - assertEquals("Unexpected connection", expected, actual, "Payload", request.getPayloadSource()); - } + @Override + public void match(URI actual, WebServiceMessage request) { + assertEquals("Unexpected connection", expected, actual, "Payload", request.getPayloadSource()); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapter.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapter.java index 8edc4939..b2d5e640 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapter.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapter.java @@ -31,15 +31,15 @@ import org.springframework.ws.test.support.matcher.WebServiceMessageMatcher; */ class WebServiceMessageMatcherAdapter implements RequestMatcher { - private final WebServiceMessageMatcher adaptee; + private final WebServiceMessageMatcher adaptee; - WebServiceMessageMatcherAdapter(WebServiceMessageMatcher adaptee) { - Assert.notNull(adaptee, "'adaptee' must not be null"); - this.adaptee = adaptee; - } + WebServiceMessageMatcherAdapter(WebServiceMessageMatcher adaptee) { + Assert.notNull(adaptee, "'adaptee' must not be null"); + this.adaptee = adaptee; + } - @Override - public void match(URI uri, WebServiceMessage request) throws IOException, AssertionError { - adaptee.match(request); - } + @Override + public void match(URI uri, WebServiceMessage request) throws IOException, AssertionError { + adaptee.match(request); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/client/XPathExpectationsHelperAdapter.java b/spring-ws-test/src/main/java/org/springframework/ws/test/client/XPathExpectationsHelperAdapter.java index ff949a0b..ab78e8b9 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/client/XPathExpectationsHelperAdapter.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/client/XPathExpectationsHelperAdapter.java @@ -28,40 +28,40 @@ import org.springframework.ws.test.support.matcher.XPathExpectationsHelper; */ class XPathExpectationsHelperAdapter implements RequestXPathExpectations { - private final XPathExpectationsHelper helper; + private final XPathExpectationsHelper helper; - XPathExpectationsHelperAdapter(String expression, Map namespaces) { - helper = new XPathExpectationsHelper(expression, namespaces); - } + XPathExpectationsHelperAdapter(String expression, Map namespaces) { + helper = new XPathExpectationsHelper(expression, namespaces); + } - @Override - public RequestMatcher exists() { - return new WebServiceMessageMatcherAdapter(helper.exists()); - } + @Override + public RequestMatcher exists() { + return new WebServiceMessageMatcherAdapter(helper.exists()); + } - @Override - public RequestMatcher doesNotExist() { - return new WebServiceMessageMatcherAdapter(helper.doesNotExist()); - } + @Override + public RequestMatcher doesNotExist() { + return new WebServiceMessageMatcherAdapter(helper.doesNotExist()); + } - @Override - public RequestMatcher evaluatesTo(boolean expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public RequestMatcher evaluatesTo(boolean expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } - @Override - public RequestMatcher evaluatesTo(int expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public RequestMatcher evaluatesTo(int expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } - @Override - public RequestMatcher evaluatesTo(double expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public RequestMatcher evaluatesTo(double expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } - @Override - public RequestMatcher evaluatesTo(String expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public RequestMatcher evaluatesTo(String expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/MockWebServiceClient.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/MockWebServiceClient.java index 49706ce8..b7b80a44 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/MockWebServiceClient.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/MockWebServiceClient.java @@ -67,32 +67,32 @@ import org.springframework.ws.transport.WebServiceMessageReceiver; * @ContextConfiguration("applicationContext.xml") * public class MyWebServiceIntegrationTest { * - * // a standard MessageDispatcherServlet application context, containing endpoints, mappings, etc. - * @Autowired - * private ApplicationContext applicationContext; + * // a standard MessageDispatcherServlet application context, containing endpoints, mappings, etc. + * @Autowired + * private ApplicationContext applicationContext; * - * private MockWebServiceClient mockClient; + * private MockWebServiceClient mockClient; * - * @Before - * public void createClient() throws Exception { - * mockClient = MockWebServiceClient.createClient(applicationContext); - * } + * @Before + * public void createClient() throws Exception { + * mockClient = MockWebServiceClient.createClient(applicationContext); + * } * - * // test the CustomerCountEndpoint, which is wired up in the application context above - * // and handles <customerCount/> messages - * @Test - * public void customerCountEndpoint() throws Exception { - * Source requestPayload = new StringSource( - * "<customerCountRequest xmlns='http://springframework.org/spring-ws'>" + - * "<customerName>John Doe</customerName>" + - * "</customerCountRequest>"); - * Source expectedResponsePayload = new StringSource( - * "<customerCountResponse xmlns='http://springframework.org/spring-ws'>" + - * "<customerCount>42</customerCount>" + - * "</customerCountResponse>"); + * // test the CustomerCountEndpoint, which is wired up in the application context above + * // and handles <customerCount/> messages + * @Test + * public void customerCountEndpoint() throws Exception { + * Source requestPayload = new StringSource( + * "<customerCountRequest xmlns='http://springframework.org/spring-ws'>" + + * "<customerName>John Doe</customerName>" + + * "</customerCountRequest>"); + * Source expectedResponsePayload = new StringSource( + * "<customerCountResponse xmlns='http://springframework.org/spring-ws'>" + + * "<customerCount>42</customerCount>" + + * "</customerCountResponse>"); * - * mockClient.sendMessage(withPayload(requestPayload)).andExpect(payload(expectedResponsePayload)); - * } + * mockClient.sendMessage(withPayload(requestPayload)).andExpect(payload(expectedResponsePayload)); + * } * } * * @@ -102,120 +102,120 @@ import org.springframework.ws.transport.WebServiceMessageReceiver; */ public class MockWebServiceClient { - private static final Log logger = LogFactory.getLog(MockWebServiceClient.class); + private static final Log logger = LogFactory.getLog(MockWebServiceClient.class); - private final WebServiceMessageReceiver messageReceiver; + private final WebServiceMessageReceiver messageReceiver; - private final WebServiceMessageFactory messageFactory; + private final WebServiceMessageFactory messageFactory; - // Constructors + // Constructors - private MockWebServiceClient(WebServiceMessageReceiver messageReceiver, WebServiceMessageFactory messageFactory) { - Assert.notNull(messageReceiver, "'messageReceiver' must not be null"); - Assert.notNull(messageFactory, "'messageFactory' must not be null"); - this.messageReceiver = messageReceiver; - this.messageFactory = messageFactory; - } + private MockWebServiceClient(WebServiceMessageReceiver messageReceiver, WebServiceMessageFactory messageFactory) { + Assert.notNull(messageReceiver, "'messageReceiver' must not be null"); + Assert.notNull(messageFactory, "'messageFactory' must not be null"); + this.messageReceiver = messageReceiver; + this.messageFactory = messageFactory; + } - // Factory methods + // Factory methods - /** - * Creates a {@code MockWebServiceClient} instance based on the given {@link WebServiceMessageReceiver} and {@link - * WebServiceMessageFactory}. - * - * @param messageReceiver the message receiver, typically a {@link SoapMessageDispatcher} - * @param messageFactory the message factory - * @return the created client - */ - public static MockWebServiceClient createClient(WebServiceMessageReceiver messageReceiver, - WebServiceMessageFactory messageFactory) { - return new MockWebServiceClient(messageReceiver, messageFactory); - } + /** + * Creates a {@code MockWebServiceClient} instance based on the given {@link WebServiceMessageReceiver} and {@link + * WebServiceMessageFactory}. + * + * @param messageReceiver the message receiver, typically a {@link SoapMessageDispatcher} + * @param messageFactory the message factory + * @return the created client + */ + public static MockWebServiceClient createClient(WebServiceMessageReceiver messageReceiver, + WebServiceMessageFactory messageFactory) { + return new MockWebServiceClient(messageReceiver, messageFactory); + } - /** - * Creates a {@code MockWebServiceClient} instance based on the given {@link ApplicationContext}. - * - * This factory method works in a similar fashion as the standard - * {@link org.springframework.ws.transport.http.MessageDispatcherServlet MessageDispatcherServlet}. That is: - *

    - *
  • If a {@link WebServiceMessageReceiver} is configured in the given application context, it will use that. - * If no message receiver is configured, it will create a default {@link SoapMessageDispatcher}.
  • - *
  • If a {@link WebServiceMessageFactory} is configured in the given application context, it will use that. - * If no message factory is configured, it will create a default {@link SaajSoapMessageFactory}.
  • - *
- * - * @param applicationContext the application context to base the client on - * @return the created client - */ - public static MockWebServiceClient createClient(ApplicationContext applicationContext) { - Assert.notNull(applicationContext, "'applicationContext' must not be null"); + /** + * Creates a {@code MockWebServiceClient} instance based on the given {@link ApplicationContext}. + * + * This factory method works in a similar fashion as the standard + * {@link org.springframework.ws.transport.http.MessageDispatcherServlet MessageDispatcherServlet}. That is: + *
    + *
  • If a {@link WebServiceMessageReceiver} is configured in the given application context, it will use that. + * If no message receiver is configured, it will create a default {@link SoapMessageDispatcher}.
  • + *
  • If a {@link WebServiceMessageFactory} is configured in the given application context, it will use that. + * If no message factory is configured, it will create a default {@link SaajSoapMessageFactory}.
  • + *
+ * + * @param applicationContext the application context to base the client on + * @return the created client + */ + public static MockWebServiceClient createClient(ApplicationContext applicationContext) { + Assert.notNull(applicationContext, "'applicationContext' must not be null"); - MockStrategiesHelper strategiesHelper = new MockStrategiesHelper(applicationContext); + MockStrategiesHelper strategiesHelper = new MockStrategiesHelper(applicationContext); - WebServiceMessageReceiver messageReceiver = - strategiesHelper.getStrategy(WebServiceMessageReceiver.class, SoapMessageDispatcher.class); - WebServiceMessageFactory messageFactory = - strategiesHelper.getStrategy(WebServiceMessageFactory.class, SaajSoapMessageFactory.class); - return new MockWebServiceClient(messageReceiver, messageFactory); - } + WebServiceMessageReceiver messageReceiver = + strategiesHelper.getStrategy(WebServiceMessageReceiver.class, SoapMessageDispatcher.class); + WebServiceMessageFactory messageFactory = + strategiesHelper.getStrategy(WebServiceMessageFactory.class, SaajSoapMessageFactory.class); + return new MockWebServiceClient(messageReceiver, messageFactory); + } - // Sending + // Sending - /** - * Sends a request message by using the given {@link RequestCreator}. Typically called by using the default request - * creators provided by {@link RequestCreators}. - * - * @param requestCreator the request creator - * @return the response actions - * @see RequestCreators - */ - public ResponseActions sendRequest(RequestCreator requestCreator) { - Assert.notNull(requestCreator, "'requestCreator' must not be null"); - try { - WebServiceMessage request = requestCreator.createRequest(messageFactory); - MessageContext messageContext = new DefaultMessageContext(request, messageFactory); + /** + * Sends a request message by using the given {@link RequestCreator}. Typically called by using the default request + * creators provided by {@link RequestCreators}. + * + * @param requestCreator the request creator + * @return the response actions + * @see RequestCreators + */ + public ResponseActions sendRequest(RequestCreator requestCreator) { + Assert.notNull(requestCreator, "'requestCreator' must not be null"); + try { + WebServiceMessage request = requestCreator.createRequest(messageFactory); + MessageContext messageContext = new DefaultMessageContext(request, messageFactory); - messageReceiver.receive(messageContext); + messageReceiver.receive(messageContext); - return new MockWebServiceClientResponseActions(messageContext); - } - catch (Exception ex) { - logger.error("Could not send request", ex); - fail(ex.getMessage()); - return null; - } - } + return new MockWebServiceClientResponseActions(messageContext); + } + catch (Exception ex) { + logger.error("Could not send request", ex); + fail(ex.getMessage()); + return null; + } + } - // ResponseActions + // ResponseActions - private static class MockWebServiceClientResponseActions implements ResponseActions { + private static class MockWebServiceClientResponseActions implements ResponseActions { - private final MessageContext messageContext; + private final MessageContext messageContext; - private MockWebServiceClientResponseActions(MessageContext messageContext) { - Assert.notNull(messageContext, "'messageContext' must not be null"); - this.messageContext = messageContext; - } + private MockWebServiceClientResponseActions(MessageContext messageContext) { + Assert.notNull(messageContext, "'messageContext' must not be null"); + this.messageContext = messageContext; + } - @Override - public ResponseActions andExpect(ResponseMatcher responseMatcher) { - WebServiceMessage request = messageContext.getRequest(); - WebServiceMessage response = messageContext.getResponse(); - if (response == null) { - fail("No response received"); - return null; - } - try { - responseMatcher.match(request, response); - return this; - } - catch (IOException ex) { - logger.error("Could not match request", ex); - fail(ex.getMessage()); - return null; - } - } - } + @Override + public ResponseActions andExpect(ResponseMatcher responseMatcher) { + WebServiceMessage request = messageContext.getRequest(); + WebServiceMessage response = messageContext.getResponse(); + if (response == null) { + fail("No response received"); + return null; + } + try { + responseMatcher.match(request, response); + return this; + } + catch (IOException ex) { + logger.error("Could not match request", ex); + fail(ex.getMessage()); + return null; + } + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreator.java index 72aabfe4..b4c9d28b 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreator.java @@ -30,13 +30,13 @@ import org.springframework.ws.WebServiceMessageFactory; */ public interface RequestCreator { - /** - * Create a request. - * - * @param messageFactory the message that can be used to create responses - * @throws IOException in case of I/O errors - */ - WebServiceMessage createRequest(WebServiceMessageFactory messageFactory) throws IOException; + /** + * Create a request. + * + * @param messageFactory the message that can be used to create responses + * @throws IOException in case of I/O errors + */ + WebServiceMessage createRequest(WebServiceMessageFactory messageFactory) throws IOException; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreators.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreators.java index 57f34ab3..0e8e0808 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreators.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/RequestCreators.java @@ -37,75 +37,75 @@ import org.springframework.xml.transform.ResourceSource; */ public abstract class RequestCreators { - private RequestCreators() { - } + private RequestCreators() { + } - // Payload + // Payload - /** - * Create a request with the given {@link Source} XML as payload. - * - * @param payload the request payload - * @return the request creator - */ - public static RequestCreator withPayload(Source payload) { - Assert.notNull(payload, "'payload' must not be null"); - return new WebServiceMessageCreatorAdapter(new PayloadMessageCreator(payload)); - } + /** + * Create a request with the given {@link Source} XML as payload. + * + * @param payload the request payload + * @return the request creator + */ + public static RequestCreator withPayload(Source payload) { + Assert.notNull(payload, "'payload' must not be null"); + return new WebServiceMessageCreatorAdapter(new PayloadMessageCreator(payload)); + } - /** - * Create a request with the given {@link Resource} XML as payload. - * - * @param payload the request payload - * @return the request creator - */ - public static RequestCreator withPayload(Resource payload) throws IOException { - Assert.notNull(payload, "'payload' must not be null"); - return withPayload(new ResourceSource(payload)); - } + /** + * Create a request with the given {@link Resource} XML as payload. + * + * @param payload the request payload + * @return the request creator + */ + public static RequestCreator withPayload(Resource payload) throws IOException { + Assert.notNull(payload, "'payload' must not be null"); + return withPayload(new ResourceSource(payload)); + } - // SOAP - - /** - * Create a request with the given {@link Source} XML as SOAP envelope. - * - * @param soapEnvelope the request SOAP envelope - * @return the request creator - * @since 2.1.1 - */ - public static RequestCreator withSoapEnvelope(Source soapEnvelope) { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - return new WebServiceMessageCreatorAdapter(new SoapEnvelopeMessageCreator(soapEnvelope)); - } + // SOAP + + /** + * Create a request with the given {@link Source} XML as SOAP envelope. + * + * @param soapEnvelope the request SOAP envelope + * @return the request creator + * @since 2.1.1 + */ + public static RequestCreator withSoapEnvelope(Source soapEnvelope) { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + return new WebServiceMessageCreatorAdapter(new SoapEnvelopeMessageCreator(soapEnvelope)); + } - /** - * Create a request with the given {@link Resource} XML as SOAP envelope. - * - * @param soapEnvelope the request SOAP envelope - * @return the request creator - * @since 2.1.1 - */ - public static RequestCreator withSoapEnvelope(Resource soapEnvelope) throws IOException { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - return withSoapEnvelope(new ResourceSource(soapEnvelope)); - } + /** + * Create a request with the given {@link Resource} XML as SOAP envelope. + * + * @param soapEnvelope the request SOAP envelope + * @return the request creator + * @since 2.1.1 + */ + public static RequestCreator withSoapEnvelope(Resource soapEnvelope) throws IOException { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + return withSoapEnvelope(new ResourceSource(soapEnvelope)); + } - /** - * Adapts a {@link WebServiceMessageCreator} to the {@link RequestCreator} contract. - */ - private static class WebServiceMessageCreatorAdapter implements RequestCreator { + /** + * Adapts a {@link WebServiceMessageCreator} to the {@link RequestCreator} contract. + */ + private static class WebServiceMessageCreatorAdapter implements RequestCreator { - private final WebServiceMessageCreator adaptee; + private final WebServiceMessageCreator adaptee; - private WebServiceMessageCreatorAdapter(WebServiceMessageCreator adaptee) { - this.adaptee = adaptee; - } + private WebServiceMessageCreatorAdapter(WebServiceMessageCreator adaptee) { + this.adaptee = adaptee; + } - @Override - public WebServiceMessage createRequest(WebServiceMessageFactory messageFactory) throws IOException { - return adaptee.createMessage(messageFactory); - } - } + @Override + public WebServiceMessage createRequest(WebServiceMessageFactory messageFactory) throws IOException { + return adaptee.createMessage(messageFactory); + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseActions.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseActions.java index 57cb9193..0ee6a304 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseActions.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseActions.java @@ -25,12 +25,12 @@ package org.springframework.ws.test.server; */ public interface ResponseActions { - /** - * Sets up an expectation about the response message. - * - * @param responseMatcher the response matcher that defines expectations - * @return an instance of {@link ResponseActions}, to set up further expectations - */ - ResponseActions andExpect(ResponseMatcher responseMatcher); + /** + * Sets up an expectation about the response message. + * + * @param responseMatcher the response matcher that defines expectations + * @return an instance of {@link ResponseActions}, to set up further expectations + */ + ResponseActions andExpect(ResponseMatcher responseMatcher); } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatcher.java index ff1a1634..8a2048dd 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatcher.java @@ -29,15 +29,15 @@ import org.springframework.ws.WebServiceMessage; */ public interface ResponseMatcher { - /** - * Matches the given response message against the expectations. Implementations typically make use of JUnit-based - * assertions. - * - * @param request the request message - * @param response the response message to make assertions on - * @throws IOException in case of I/O errors - * @throws AssertionError if expectations are not met - */ - void match(WebServiceMessage request, WebServiceMessage response) throws IOException, AssertionError; + /** + * Matches the given response message against the expectations. Implementations typically make use of JUnit-based + * assertions. + * + * @param request the request message + * @param response the response message to make assertions on + * @throws IOException in case of I/O errors + * @throws AssertionError if expectations are not met + */ + void match(WebServiceMessage request, WebServiceMessage response) throws IOException, AssertionError; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatchers.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatchers.java index c75aacc2..10926645 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatchers.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseMatchers.java @@ -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, @@ -44,216 +44,216 @@ import static org.springframework.ws.test.support.AssertionErrors.fail; */ public abstract class ResponseMatchers { - private ResponseMatchers() { - } - - // Payload + private ResponseMatchers() { + } + + // Payload - /** - * Expects the given {@link Source} XML payload. - * - * @param payload the XML payload - * @return the response matcher - */ - public static ResponseMatcher payload(Source payload) { - return new WebServiceMessageMatcherAdapter(new PayloadDiffMatcher(payload)); - } + /** + * Expects the given {@link Source} XML payload. + * + * @param payload the XML payload + * @return the response matcher + */ + public static ResponseMatcher payload(Source payload) { + return new WebServiceMessageMatcherAdapter(new PayloadDiffMatcher(payload)); + } - /** - * Expects the given {@link Resource} XML payload. - * - * @param payload the XML payload - * @return the response matcher - */ - public static ResponseMatcher payload(Resource payload) throws IOException { - return payload(new ResourceSource(payload)); - } + /** + * Expects the given {@link Resource} XML payload. + * + * @param payload the XML payload + * @return the response matcher + */ + public static ResponseMatcher payload(Resource payload) throws IOException { + return payload(new ResourceSource(payload)); + } - /** - * Expects the payload to validate against the given XSD schema(s). - * - * @param schema the schema - * @param furtherSchemas further schemas, if necessary - * @return the response matcher - */ - public static ResponseMatcher validPayload(Resource schema, Resource... furtherSchemas) throws IOException { - return new WebServiceMessageMatcherAdapter(new SchemaValidatingMatcher(schema, furtherSchemas)); - } + /** + * Expects the payload to validate against the given XSD schema(s). + * + * @param schema the schema + * @param furtherSchemas further schemas, if necessary + * @return the response matcher + */ + public static ResponseMatcher validPayload(Resource schema, Resource... furtherSchemas) throws IOException { + return new WebServiceMessageMatcherAdapter(new SchemaValidatingMatcher(schema, furtherSchemas)); + } - /** - * Expects the given XPath expression to (not) exist or be evaluated to a value. - * - * @param xpathExpression the XPath expression - * @return the XPath expectations, to be further configured - */ - public static ResponseXPathExpectations xpath(String xpathExpression) { - return new XPathExpectationsHelperAdapter(xpathExpression, null); - } + /** + * Expects the given XPath expression to (not) exist or be evaluated to a value. + * + * @param xpathExpression the XPath expression + * @return the XPath expectations, to be further configured + */ + public static ResponseXPathExpectations xpath(String xpathExpression) { + return new XPathExpectationsHelperAdapter(xpathExpression, null); + } - /** - * Expects the given XPath expression to (not) exist or be evaluated to a value. - * - * @param xpathExpression the XPath expression - * @param namespaceMapping the namespaces - * @return the XPath expectations, to be further configured - */ - public static ResponseXPathExpectations xpath(String xpathExpression, Map namespaceMapping) { - return new XPathExpectationsHelperAdapter(xpathExpression, namespaceMapping); - } + /** + * Expects the given XPath expression to (not) exist or be evaluated to a value. + * + * @param xpathExpression the XPath expression + * @param namespaceMapping the namespaces + * @return the XPath expectations, to be further configured + */ + public static ResponseXPathExpectations xpath(String xpathExpression, Map namespaceMapping) { + return new XPathExpectationsHelperAdapter(xpathExpression, namespaceMapping); + } - // SOAP + // SOAP - /** - * Expects the given {@link Source} XML SOAP envelope. - * - * @param soapEnvelope the XML SOAP envelope - * @return the response matcher - * @since 2.1.1 - */ - public static ResponseMatcher soapEnvelope(Source soapEnvelope) { - return new WebServiceMessageMatcherAdapter(new SoapEnvelopeDiffMatcher(soapEnvelope)); - } + /** + * Expects the given {@link Source} XML SOAP envelope. + * + * @param soapEnvelope the XML SOAP envelope + * @return the response matcher + * @since 2.1.1 + */ + public static ResponseMatcher soapEnvelope(Source soapEnvelope) { + return new WebServiceMessageMatcherAdapter(new SoapEnvelopeDiffMatcher(soapEnvelope)); + } - /** - * Expects the given {@link Resource} XML SOAP envelope. - * - * @param soapEnvelope the XML SOAP envelope - * @return the response matcher - * @since 2.1.1 - */ - public static ResponseMatcher soapEnvelope(Resource soapEnvelope) throws IOException { - return soapEnvelope(new ResourceSource(soapEnvelope)); - } + /** + * Expects the given {@link Resource} XML SOAP envelope. + * + * @param soapEnvelope the XML SOAP envelope + * @return the response matcher + * @since 2.1.1 + */ + public static ResponseMatcher soapEnvelope(Resource soapEnvelope) throws IOException { + return soapEnvelope(new ResourceSource(soapEnvelope)); + } - /** - * Expects the given SOAP header in the outgoing message. - * - * @param soapHeaderName the qualified name of the SOAP header to expect - * @return the request matcher - */ - public static ResponseMatcher soapHeader(QName soapHeaderName) { - Assert.notNull(soapHeaderName, "'soapHeaderName' must not be null"); - return new WebServiceMessageMatcherAdapter(new SoapHeaderMatcher(soapHeaderName)); - } + /** + * Expects the given SOAP header in the outgoing message. + * + * @param soapHeaderName the qualified name of the SOAP header to expect + * @return the request matcher + */ + public static ResponseMatcher soapHeader(QName soapHeaderName) { + Assert.notNull(soapHeaderName, "'soapHeaderName' must not be null"); + return new WebServiceMessageMatcherAdapter(new SoapHeaderMatcher(soapHeaderName)); + } - /** - * Expects the response not to contain a SOAP fault. - * - * @return the response matcher - */ - public static ResponseMatcher noFault() { - return new ResponseMatcher() { - public void match(WebServiceMessage request, WebServiceMessage response) - throws IOException, AssertionError { - if (response instanceof FaultAwareWebServiceMessage) { - FaultAwareWebServiceMessage faultMessage = (FaultAwareWebServiceMessage) response; - if (faultMessage.hasFault()) { - fail("Response has a SOAP Fault: \"" + faultMessage.getFaultReason() + "\""); - } - } - } + /** + * Expects the response not to contain a SOAP fault. + * + * @return the response matcher + */ + public static ResponseMatcher noFault() { + return new ResponseMatcher() { + public void match(WebServiceMessage request, WebServiceMessage response) + throws IOException, AssertionError { + if (response instanceof FaultAwareWebServiceMessage) { + FaultAwareWebServiceMessage faultMessage = (FaultAwareWebServiceMessage) response; + if (faultMessage.hasFault()) { + fail("Response has a SOAP Fault: \"" + faultMessage.getFaultReason() + "\""); + } + } + } - }; - } + }; + } - /** - * Expects a {@code MustUnderstand} fault. - * - * @see org.springframework.ws.soap.SoapBody#addMustUnderstandFault(String, Locale) - */ - public static ResponseMatcher mustUnderstandFault() { - return mustUnderstandFault(null); - } + /** + * Expects a {@code MustUnderstand} fault. + * + * @see org.springframework.ws.soap.SoapBody#addMustUnderstandFault(String, Locale) + */ + public static ResponseMatcher mustUnderstandFault() { + return mustUnderstandFault(null); + } - /** - * Expects a {@code MustUnderstand} fault with a particular fault string or reason. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or - * reason text will not be verified - * @see org.springframework.ws.soap.SoapBody#addMustUnderstandFault(String, Locale) - */ - public static ResponseMatcher mustUnderstandFault(String faultStringOrReason) { - return new SoapFaultResponseMatcher(faultStringOrReason) { - @Override - protected QName getExpectedFaultCode(SoapVersion version) { - return version.getMustUnderstandFaultName(); - } - }; - } + /** + * Expects a {@code MustUnderstand} fault with a particular fault string or reason. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or + * reason text will not be verified + * @see org.springframework.ws.soap.SoapBody#addMustUnderstandFault(String, Locale) + */ + public static ResponseMatcher mustUnderstandFault(String faultStringOrReason) { + return new SoapFaultResponseMatcher(faultStringOrReason) { + @Override + protected QName getExpectedFaultCode(SoapVersion version) { + return version.getMustUnderstandFaultName(); + } + }; + } - /** - * Expects a {@code Client} (SOAP 1.1) or {@code Sender} (SOAP 1.2) fault. - * - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) - */ - public static ResponseMatcher clientOrSenderFault() { - return clientOrSenderFault(null); - } + /** + * Expects a {@code Client} (SOAP 1.1) or {@code Sender} (SOAP 1.2) fault. + * + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) + */ + public static ResponseMatcher clientOrSenderFault() { + return clientOrSenderFault(null); + } - /** - * Expects a {@code Client} (SOAP 1.1) or {@code Sender} (SOAP 1.2) fault with a particular fault string or reason. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or - * reason text will not be verified - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) - */ - public static ResponseMatcher clientOrSenderFault(String faultStringOrReason) { - return new SoapFaultResponseMatcher(faultStringOrReason) { - @Override - protected QName getExpectedFaultCode(SoapVersion version) { - return version.getClientOrSenderFaultName(); - } - }; - } + /** + * Expects a {@code Client} (SOAP 1.1) or {@code Sender} (SOAP 1.2) fault with a particular fault string or reason. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or + * reason text will not be verified + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) + */ + public static ResponseMatcher clientOrSenderFault(String faultStringOrReason) { + return new SoapFaultResponseMatcher(faultStringOrReason) { + @Override + protected QName getExpectedFaultCode(SoapVersion version) { + return version.getClientOrSenderFaultName(); + } + }; + } - /** - * Expects a {@code Server} (SOAP 1.1) or {@code Receiver} (SOAP 1.2) fault. - * - * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String, java.util.Locale) - */ - public static ResponseMatcher serverOrReceiverFault() { - return serverOrReceiverFault(null); - } + /** + * Expects a {@code Server} (SOAP 1.1) or {@code Receiver} (SOAP 1.2) fault. + * + * @see org.springframework.ws.soap.SoapBody#addServerOrReceiverFault(String, java.util.Locale) + */ + public static ResponseMatcher serverOrReceiverFault() { + return serverOrReceiverFault(null); + } - /** - * Expects a {@code Server} (SOAP 1.1) or {@code Receiver} (SOAP 1.2) fault with a particular fault string or reason. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or - * reason text will not be verified - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) - */ - public static ResponseMatcher serverOrReceiverFault(String faultStringOrReason) { - return new SoapFaultResponseMatcher(faultStringOrReason) { - @Override - protected QName getExpectedFaultCode(SoapVersion version) { - return version.getServerOrReceiverFaultName(); - } - }; - } + /** + * Expects a {@code Server} (SOAP 1.1) or {@code Receiver} (SOAP 1.2) fault with a particular fault string or reason. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or + * reason text will not be verified + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) + */ + public static ResponseMatcher serverOrReceiverFault(String faultStringOrReason) { + return new SoapFaultResponseMatcher(faultStringOrReason) { + @Override + protected QName getExpectedFaultCode(SoapVersion version) { + return version.getServerOrReceiverFaultName(); + } + }; + } - /** - * Expects a {@code VersionMismatch} fault. - * - * @see org.springframework.ws.soap.SoapBody#addVersionMismatchFault(String, java.util.Locale) - */ - public static ResponseMatcher versionMismatchFault() { - return versionMismatchFault(null); - } + /** + * Expects a {@code VersionMismatch} fault. + * + * @see org.springframework.ws.soap.SoapBody#addVersionMismatchFault(String, java.util.Locale) + */ + public static ResponseMatcher versionMismatchFault() { + return versionMismatchFault(null); + } - /** - * Expects a {@code VersionMismatch} fault with a particular fault string or reason. - * - * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or - * reason text will not be verified - * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) - */ - public static ResponseMatcher versionMismatchFault(String faultStringOrReason) { - return new SoapFaultResponseMatcher(faultStringOrReason) { - @Override - protected QName getExpectedFaultCode(SoapVersion version) { - return version.getVersionMismatchFaultName(); - } - }; - } + /** + * Expects a {@code VersionMismatch} fault with a particular fault string or reason. + * + * @param faultStringOrReason the SOAP 1.1 fault string or SOAP 1.2 reason text. If {@code null} the fault string or + * reason text will not be verified + * @see org.springframework.ws.soap.SoapBody#addClientOrSenderFault(String, Locale) + */ + public static ResponseMatcher versionMismatchFault(String faultStringOrReason) { + return new SoapFaultResponseMatcher(faultStringOrReason) { + @Override + protected QName getExpectedFaultCode(SoapVersion version) { + return version.getVersionMismatchFaultName(); + } + }; + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseXPathExpectations.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseXPathExpectations.java index 00430e49..b3119c10 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseXPathExpectations.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/ResponseXPathExpectations.java @@ -31,50 +31,50 @@ package org.springframework.ws.test.server; */ public interface ResponseXPathExpectations { - /** - * Expects the XPath expression to exist. - * - * @return the request matcher - */ - ResponseMatcher exists(); + /** + * Expects the XPath expression to exist. + * + * @return the request matcher + */ + ResponseMatcher exists(); - /** - * Expects the XPath expression to not exist. - * - * @return the request matcher - */ - ResponseMatcher doesNotExist(); + /** + * Expects the XPath expression to not exist. + * + * @return the request matcher + */ + ResponseMatcher doesNotExist(); - /** - * Expects the XPath expression to evaluate to the given boolean. - * - * @param expectedValue the expected value - * @return the request matcher - */ - ResponseMatcher evaluatesTo(final boolean expectedValue); + /** + * Expects the XPath expression to evaluate to the given boolean. + * + * @param expectedValue the expected value + * @return the request matcher + */ + ResponseMatcher evaluatesTo(final boolean expectedValue); - /** - * Expects the XPath expression to evaluate to the given integer. - * - * @param expectedValue the expected value - * @return the request matcher - */ - ResponseMatcher evaluatesTo(int expectedValue); + /** + * Expects the XPath expression to evaluate to the given integer. + * + * @param expectedValue the expected value + * @return the request matcher + */ + ResponseMatcher evaluatesTo(int expectedValue); - /** - * Expects the XPath expression to evaluate to the given double. - * - * @param expectedValue the expected value - * @return the request matcher - */ - ResponseMatcher evaluatesTo(double expectedValue); + /** + * Expects the XPath expression to evaluate to the given double. + * + * @param expectedValue the expected value + * @return the request matcher + */ + ResponseMatcher evaluatesTo(double expectedValue); - /** - * Expects the XPath expression to evaluate to the given string. - * - * @param expectedValue the expected value - * @return the request matcher - */ - ResponseMatcher evaluatesTo(String expectedValue); + /** + * Expects the XPath expression to evaluate to the given string. + * + * @param expectedValue the expected value + * @return the request matcher + */ + ResponseMatcher evaluatesTo(String expectedValue); } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/SoapFaultResponseMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/SoapFaultResponseMatcher.java index cd95accd..eecb5af9 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/SoapFaultResponseMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/SoapFaultResponseMatcher.java @@ -36,31 +36,31 @@ import org.springframework.ws.soap.SoapVersion; */ abstract class SoapFaultResponseMatcher implements ResponseMatcher { - private final String expectedFaultStringOrReason; + private final String expectedFaultStringOrReason; - SoapFaultResponseMatcher(String expectedFaultStringOrReason) { - this.expectedFaultStringOrReason = expectedFaultStringOrReason; - } + SoapFaultResponseMatcher(String expectedFaultStringOrReason) { + this.expectedFaultStringOrReason = expectedFaultStringOrReason; + } - @Override - public void match(WebServiceMessage request, WebServiceMessage response) throws IOException, AssertionError { - assertTrue("Response is not a SOAP message", response instanceof SoapMessage); - SoapMessage soapResponse = (SoapMessage) response; - SoapBody responseBody = soapResponse.getSoapBody(); - assertTrue("Response has no SOAP Body", responseBody != null); - assertTrue("Response has no SOAP Fault", responseBody.hasFault()); - SoapFault soapFault = responseBody.getFault(); - QName expectedFaultCode = getExpectedFaultCode(soapResponse.getVersion()); - assertEquals("Invalid SOAP Fault code", expectedFaultCode, soapFault.getFaultCode()); - if (expectedFaultStringOrReason != null) { - assertEquals("Invalid SOAP Fault string/reason", expectedFaultStringOrReason, - soapFault.getFaultStringOrReason()); - } - } + @Override + public void match(WebServiceMessage request, WebServiceMessage response) throws IOException, AssertionError { + assertTrue("Response is not a SOAP message", response instanceof SoapMessage); + SoapMessage soapResponse = (SoapMessage) response; + SoapBody responseBody = soapResponse.getSoapBody(); + assertTrue("Response has no SOAP Body", responseBody != null); + assertTrue("Response has no SOAP Fault", responseBody.hasFault()); + SoapFault soapFault = responseBody.getFault(); + QName expectedFaultCode = getExpectedFaultCode(soapResponse.getVersion()); + assertEquals("Invalid SOAP Fault code", expectedFaultCode, soapFault.getFaultCode()); + if (expectedFaultStringOrReason != null) { + assertEquals("Invalid SOAP Fault string/reason", expectedFaultStringOrReason, + soapFault.getFaultStringOrReason()); + } + } - /** - * Returns the SOAP fault code to check for, given the SOAP version. - */ - protected abstract QName getExpectedFaultCode(SoapVersion version); + /** + * Returns the SOAP fault code to check for, given the SOAP version. + */ + protected abstract QName getExpectedFaultCode(SoapVersion version); } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapter.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapter.java index 37c26b65..48764436 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapter.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapter.java @@ -30,15 +30,15 @@ import org.springframework.ws.test.support.matcher.WebServiceMessageMatcher; */ class WebServiceMessageMatcherAdapter implements ResponseMatcher { - private final WebServiceMessageMatcher adaptee; + private final WebServiceMessageMatcher adaptee; - WebServiceMessageMatcherAdapter(WebServiceMessageMatcher adaptee) { - Assert.notNull(adaptee, "'adaptee' must not be null"); - this.adaptee = adaptee; - } + WebServiceMessageMatcherAdapter(WebServiceMessageMatcher adaptee) { + Assert.notNull(adaptee, "'adaptee' must not be null"); + this.adaptee = adaptee; + } - @Override - public void match(WebServiceMessage request, WebServiceMessage response) throws IOException, AssertionError { - adaptee.match(response); - } + @Override + public void match(WebServiceMessage request, WebServiceMessage response) throws IOException, AssertionError { + adaptee.match(response); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/server/XPathExpectationsHelperAdapter.java b/spring-ws-test/src/main/java/org/springframework/ws/test/server/XPathExpectationsHelperAdapter.java index 1a1909eb..a1457150 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/server/XPathExpectationsHelperAdapter.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/server/XPathExpectationsHelperAdapter.java @@ -28,40 +28,40 @@ import org.springframework.ws.test.support.matcher.XPathExpectationsHelper; */ class XPathExpectationsHelperAdapter implements ResponseXPathExpectations { - private final XPathExpectationsHelper helper; + private final XPathExpectationsHelper helper; - XPathExpectationsHelperAdapter(String expression, Map namespaces) { - helper = new XPathExpectationsHelper(expression, namespaces); - } + XPathExpectationsHelperAdapter(String expression, Map namespaces) { + helper = new XPathExpectationsHelper(expression, namespaces); + } - @Override - public ResponseMatcher exists() { - return new WebServiceMessageMatcherAdapter(helper.exists()); - } + @Override + public ResponseMatcher exists() { + return new WebServiceMessageMatcherAdapter(helper.exists()); + } - @Override - public ResponseMatcher doesNotExist() { - return new WebServiceMessageMatcherAdapter(helper.doesNotExist()); - } + @Override + public ResponseMatcher doesNotExist() { + return new WebServiceMessageMatcherAdapter(helper.doesNotExist()); + } - @Override - public ResponseMatcher evaluatesTo(boolean expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public ResponseMatcher evaluatesTo(boolean expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } - @Override - public ResponseMatcher evaluatesTo(int expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public ResponseMatcher evaluatesTo(int expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } - @Override - public ResponseMatcher evaluatesTo(double expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public ResponseMatcher evaluatesTo(double expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } - @Override - public ResponseMatcher evaluatesTo(String expectedValue) { - return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); - } + @Override + public ResponseMatcher evaluatesTo(String expectedValue) { + return new WebServiceMessageMatcherAdapter(helper.evaluatesTo(expectedValue)); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/AssertionErrors.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/AssertionErrors.java index e44d74ea..9bdfe966 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/AssertionErrors.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/AssertionErrors.java @@ -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, @@ -27,83 +27,83 @@ import javax.xml.transform.Source; */ public abstract class AssertionErrors { - private AssertionErrors() { - } + private AssertionErrors() { + } - /** - * Fails a test with the given message. - * - * @param message the message - */ - public static void fail(String message) { - throw new AssertionError(message); - } + /** + * Fails a test with the given message. + * + * @param message the message + */ + public static void fail(String message) { + throw new AssertionError(message); + } - /** - * Fails a test with the given message and source. - * - * @param message the message - * @param source the source - */ - public static void fail(String message, String sourceLabel, Source source) { - if (source != null) { - throw new SourceAssertionError(message, sourceLabel, source); - } - else { - fail(message); - } - } + /** + * Fails a test with the given message and source. + * + * @param message the message + * @param source the source + */ + public static void fail(String message, String sourceLabel, Source source) { + if (source != null) { + throw new SourceAssertionError(message, sourceLabel, source); + } + else { + fail(message); + } + } - /** - * Asserts that a condition is {@code true}. If not, throws an {@link AssertionError} with the given message. - * - * @param message the message - * @param condition the condition to test for - */ - public static void assertTrue(String message, boolean condition) { - assertTrue(message, condition, null, null); - } + /** + * Asserts that a condition is {@code true}. If not, throws an {@link AssertionError} with the given message. + * + * @param message the message + * @param condition the condition to test for + */ + public static void assertTrue(String message, boolean condition) { + assertTrue(message, condition, null, null); + } - /** - * Asserts that a condition is {@code true}. If not, throws an {@link AssertionError} with the given message and - * source. - * - * @param message the message - * @param condition the condition to test for - */ - public static void assertTrue(String message, boolean condition, String sourceLabel, Source source) { - if (!condition) { - fail(message, sourceLabel, source); - } - } + /** + * Asserts that a condition is {@code true}. If not, throws an {@link AssertionError} with the given message and + * source. + * + * @param message the message + * @param condition the condition to test for + */ + public static void assertTrue(String message, boolean condition, String sourceLabel, Source source) { + if (!condition) { + fail(message, sourceLabel, source); + } + } - /** - * Asserts that two objects are equal. If not, an {@link AssertionError} is thrown with the given message. - * - * @param message the message - * @param expected the expected value - * @param actual the actual value - */ - public static void assertEquals(String message, Object expected, Object actual) { - assertEquals(message, expected, actual, null, null); - } + /** + * Asserts that two objects are equal. If not, an {@link AssertionError} is thrown with the given message. + * + * @param message the message + * @param expected the expected value + * @param actual the actual value + */ + public static void assertEquals(String message, Object expected, Object actual) { + assertEquals(message, expected, actual, null, null); + } - /** - * Asserts that two objects are equal. If not, an {@link AssertionError} is thrown with the given message. - * - * @param message the message - * @param expected the expected value - * @param actual the actual value - * @param source the source - */ - public static void assertEquals(String message, Object expected, Object actual, String sourceLabel, Source source) { - if (expected == null && actual == null) { - return; - } - if (expected != null && expected.equals(actual)) { - return; - } - fail(message + " expected:<" + expected + "> but was:<" + actual + ">", sourceLabel, source); - } + /** + * Asserts that two objects are equal. If not, an {@link AssertionError} is thrown with the given message. + * + * @param message the message + * @param expected the expected value + * @param actual the actual value + * @param source the source + */ + public static void assertEquals(String message, Object expected, Object actual, String sourceLabel, Source source) { + if (expected == null && actual == null) { + return; + } + if (expected != null && expected.equals(actual)) { + return; + } + fail(message + " expected:<" + expected + "> but was:<" + actual + ">", sourceLabel, source); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/MockStrategiesHelper.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/MockStrategiesHelper.java index b49f5e97..d89834af 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/MockStrategiesHelper.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/MockStrategiesHelper.java @@ -38,90 +38,90 @@ import org.apache.commons.logging.LogFactory; */ public class MockStrategiesHelper { - private static final Log logger = LogFactory.getLog(MockStrategiesHelper.class); + private static final Log logger = LogFactory.getLog(MockStrategiesHelper.class); - private final ApplicationContext applicationContext; + private final ApplicationContext applicationContext; - /** - * Creates a new instance of the {@code MockStrategiesHelper} with the given application context. - * - * @param applicationContext the application context - */ - public MockStrategiesHelper(ApplicationContext applicationContext) { - Assert.notNull(applicationContext, "'applicationContext' must not be null"); - this.applicationContext = applicationContext; - } + /** + * Creates a new instance of the {@code MockStrategiesHelper} with the given application context. + * + * @param applicationContext the application context + */ + public MockStrategiesHelper(ApplicationContext applicationContext) { + Assert.notNull(applicationContext, "'applicationContext' must not be null"); + this.applicationContext = applicationContext; + } - /** - * Returns the application context. - */ - public ApplicationContext getApplicationContext() { - return applicationContext; - } + /** + * Returns the application context. + */ + public ApplicationContext getApplicationContext() { + return applicationContext; + } - /** - * Returns a single strategy found in the given application context. - * - * @param type the type of bean to be found in the application context - * @return the bean, or {@code null} if no bean of the given type can be found - * @throws BeanInitializationException if there is more than 1 beans of the given type - */ - public T getStrategy(Class type) { - Assert.notNull(type, "'type' must not be null"); - Map map = applicationContext.getBeansOfType(type); - if (map.isEmpty()) { - return null; - } - else if (map.size() == 1) { - Map.Entry entry = map.entrySet().iterator().next(); - if (logger.isDebugEnabled()) { - logger.debug("Using " + ClassUtils.getShortName(type) + " [" + entry.getKey() + "]"); - } - return entry.getValue(); - } - else { - throw new BeanInitializationException( - "Could not find exactly 1 " + ClassUtils.getShortName(type) + " in application context"); - } - } + /** + * Returns a single strategy found in the given application context. + * + * @param type the type of bean to be found in the application context + * @return the bean, or {@code null} if no bean of the given type can be found + * @throws BeanInitializationException if there is more than 1 beans of the given type + */ + public T getStrategy(Class type) { + Assert.notNull(type, "'type' must not be null"); + Map map = applicationContext.getBeansOfType(type); + if (map.isEmpty()) { + return null; + } + else if (map.size() == 1) { + Map.Entry entry = map.entrySet().iterator().next(); + if (logger.isDebugEnabled()) { + logger.debug("Using " + ClassUtils.getShortName(type) + " [" + entry.getKey() + "]"); + } + return entry.getValue(); + } + else { + throw new BeanInitializationException( + "Could not find exactly 1 " + ClassUtils.getShortName(type) + " in application context"); + } + } - /** - * Returns a single strategy found in the given application context, or instantiates a default strategy if no - * applicable strategy was found. - * - * @param type the type of bean to be found in the application context - * @param defaultType the type to instantiate and return when no bean of the specified type could be found - * @return the bean found in the application context, or the default type if no bean of the given type can be found - * @throws BeanInitializationException if there is more than 1 beans of the given type - */ - public T getStrategy(Class type, Class defaultType) { - Assert.notNull(defaultType, "'defaultType' must not be null"); - T t = getStrategy(type); - if (t != null) { - return t; - } - else { - if (logger.isDebugEnabled()) { - logger.debug("No " + ClassUtils.getShortName(type) + " found, using default " + - ClassUtils.getShortName(defaultType)); - } - T defaultStrategy = BeanUtils.instantiateClass(defaultType); - if (defaultStrategy instanceof ApplicationContextAware) { - ApplicationContextAware applicationContextAware = (ApplicationContextAware) defaultStrategy; - applicationContextAware.setApplicationContext(applicationContext); - } - if (defaultStrategy instanceof InitializingBean) { - InitializingBean initializingBean = (InitializingBean) defaultStrategy; - try { - initializingBean.afterPropertiesSet(); - } - catch (Exception ex) { - throw new BeanCreationException("Invocation of init method failed", ex); - } - } - return defaultStrategy; - } - } + /** + * Returns a single strategy found in the given application context, or instantiates a default strategy if no + * applicable strategy was found. + * + * @param type the type of bean to be found in the application context + * @param defaultType the type to instantiate and return when no bean of the specified type could be found + * @return the bean found in the application context, or the default type if no bean of the given type can be found + * @throws BeanInitializationException if there is more than 1 beans of the given type + */ + public T getStrategy(Class type, Class defaultType) { + Assert.notNull(defaultType, "'defaultType' must not be null"); + T t = getStrategy(type); + if (t != null) { + return t; + } + else { + if (logger.isDebugEnabled()) { + logger.debug("No " + ClassUtils.getShortName(type) + " found, using default " + + ClassUtils.getShortName(defaultType)); + } + T defaultStrategy = BeanUtils.instantiateClass(defaultType); + if (defaultStrategy instanceof ApplicationContextAware) { + ApplicationContextAware applicationContextAware = (ApplicationContextAware) defaultStrategy; + applicationContextAware.setApplicationContext(applicationContext); + } + if (defaultStrategy instanceof InitializingBean) { + InitializingBean initializingBean = (InitializingBean) defaultStrategy; + try { + initializingBean.afterPropertiesSet(); + } + catch (Exception ex) { + throw new BeanCreationException("Invocation of init method failed", ex); + } + } + return defaultStrategy; + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/SourceAssertionError.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/SourceAssertionError.java index 0ce9c0e3..d75810f8 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/SourceAssertionError.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/SourceAssertionError.java @@ -35,66 +35,66 @@ import org.springframework.xml.transform.TransformerHelper; @SuppressWarnings("serial") public class SourceAssertionError extends AssertionError { - private final String sourceLabel; + private final String sourceLabel; - private final Source source; + private final Source source; - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); - /** - * Creates a new instance of the {@code SourceAssertionError} class with the given parameters. - */ - public SourceAssertionError(String detailMessage, String sourceLabel, Source source) { - super(detailMessage); - this.sourceLabel = sourceLabel; - this.source = source; - } + /** + * Creates a new instance of the {@code SourceAssertionError} class with the given parameters. + */ + public SourceAssertionError(String detailMessage, String sourceLabel, Source source) { + super(detailMessage); + this.sourceLabel = sourceLabel; + this.source = source; + } - /** - * Returns the source context of this error. - * @return the source - */ - public Source getSource() { - return source; - } + /** + * Returns the source context of this error. + * @return the source + */ + public Source getSource() { + return source; + } - @Override - public String getMessage() { - StringBuilder builder = new StringBuilder(); - builder.append(super.getMessage()); - String sourceString = getSourceString(); - if (sourceString != null) { - String newLine = System.getProperty("line.separator"); - builder.append(newLine); - String label = sourceLabel != null ? sourceLabel : "Source"; - builder.append(label); - builder.append(": "); - builder.append(sourceString); - } - return builder.toString(); - } + @Override + public String getMessage() { + StringBuilder builder = new StringBuilder(); + builder.append(super.getMessage()); + String sourceString = getSourceString(); + if (sourceString != null) { + String newLine = System.getProperty("line.separator"); + builder.append(newLine); + String label = sourceLabel != null ? sourceLabel : "Source"; + builder.append(label); + builder.append(": "); + builder.append(sourceString); + } + return builder.toString(); + } - private String getSourceString() { - if (source != null) { - try { - StringResult result = new StringResult(); - Transformer transformer = createNonIndentingTransformer(); - transformer.transform(source, result); - return result.toString(); - } - catch (TransformerException ex) { - // Ignore - } - } - return null; - } + private String getSourceString() { + if (source != null) { + try { + StringResult result = new StringResult(); + Transformer transformer = createNonIndentingTransformer(); + transformer.transform(source, result); + return result.toString(); + } + catch (TransformerException ex) { + // Ignore + } + } + return null; + } - private Transformer createNonIndentingTransformer() throws TransformerConfigurationException { - Transformer transformer = transformerHelper.createTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.setOutputProperty(OutputKeys.INDENT, "no"); - return transformer; - } + private Transformer createNonIndentingTransformer() throws TransformerConfigurationException { + Transformer transformer = transformerHelper.createTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.INDENT, "no"); + return transformer; + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/AbstractMessageCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/AbstractMessageCreator.java index e8d0f9bc..bad6bf5f 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/AbstractMessageCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/AbstractMessageCreator.java @@ -32,20 +32,20 @@ import org.springframework.ws.WebServiceMessageFactory; */ public abstract class AbstractMessageCreator implements WebServiceMessageCreator { - @Override - public final WebServiceMessage createMessage(WebServiceMessageFactory messageFactory) throws IOException { - WebServiceMessage message = messageFactory.createWebServiceMessage(); - doWithMessage(message); - return message; - } + @Override + public final WebServiceMessage createMessage(WebServiceMessageFactory messageFactory) throws IOException { + WebServiceMessage message = messageFactory.createWebServiceMessage(); + doWithMessage(message); + return message; + } - /** - * Abstract template method, invoked by {@link #createMessage(WebServiceMessageFactory)} after a message has been - * created. - * - * @param message the message - * @throws IOException in case of I/O errors - */ - protected abstract void doWithMessage(WebServiceMessage message) throws IOException; + /** + * Abstract template method, invoked by {@link #createMessage(WebServiceMessageFactory)} after a message has been + * created. + * + * @param message the message + * @throws IOException in case of I/O errors + */ + protected abstract void doWithMessage(WebServiceMessage message) throws IOException; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/PayloadMessageCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/PayloadMessageCreator.java index 70638772..f37306de 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/PayloadMessageCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/PayloadMessageCreator.java @@ -34,27 +34,27 @@ import static org.springframework.ws.test.support.AssertionErrors.fail; */ public class PayloadMessageCreator extends AbstractMessageCreator { - private final Source payload; + private final Source payload; - private TransformerHelper transformerHelper = new TransformerHelper(); + private TransformerHelper transformerHelper = new TransformerHelper(); - /** - * Creates a new instance of the {@code PayloadMessageCreator} with the given payload source. - * - * @param payload the payload source - */ - public PayloadMessageCreator(Source payload) { - Assert.notNull(payload, "'payload' must not be null"); - this.payload = payload; - } + /** + * Creates a new instance of the {@code PayloadMessageCreator} with the given payload source. + * + * @param payload the payload source + */ + public PayloadMessageCreator(Source payload) { + Assert.notNull(payload, "'payload' must not be null"); + this.payload = payload; + } - @Override - protected void doWithMessage(WebServiceMessage message) throws IOException { - try { - transformerHelper.transform(payload, message.getPayloadResult()); - } - catch (TransformerException ex) { - fail("Could not transform request payload to message: " + ex.getMessage()); - } - } + @Override + protected void doWithMessage(WebServiceMessage message) throws IOException { + try { + transformerHelper.transform(payload, message.getPayloadResult()); + } + catch (TransformerException ex) { + fail("Could not transform request payload to message: " + ex.getMessage()); + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/SoapEnvelopeMessageCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/SoapEnvelopeMessageCreator.java index 6572b5e0..d237175f 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/SoapEnvelopeMessageCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/SoapEnvelopeMessageCreator.java @@ -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, @@ -41,30 +41,30 @@ public class SoapEnvelopeMessageCreator extends AbstractMessageCreator { private final Source soapEnvelope; - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); /** - * Creates a new instance of the {@code SoapEnvelopeMessageCreator} with the given SOAP envelope source. - * - * @param soapEnvelope the SOAP envelope source - */ - public SoapEnvelopeMessageCreator(Source soapEnvelope) { - Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); - this.soapEnvelope = soapEnvelope; - } + * Creates a new instance of the {@code SoapEnvelopeMessageCreator} with the given SOAP envelope source. + * + * @param soapEnvelope the SOAP envelope source + */ + public SoapEnvelopeMessageCreator(Source soapEnvelope) { + Assert.notNull(soapEnvelope, "'soapEnvelope' must not be null"); + this.soapEnvelope = soapEnvelope; + } @Override protected void doWithMessage(WebServiceMessage message) throws IOException { assertTrue("Message created with factory is not a SOAP message", message instanceof SoapMessage); - SoapMessage soapMessage = (SoapMessage) message; + SoapMessage soapMessage = (SoapMessage) message; try { DOMResult result = new DOMResult(); - transformerHelper.transform(soapEnvelope, result); - soapMessage.setDocument((Document) result.getNode()); - } - catch (TransformerException ex) { - fail("Could not transform request SOAP envelope to message: " + ex.getMessage()); - } + transformerHelper.transform(soapEnvelope, result); + soapMessage.setDocument((Document) result.getNode()); + } + catch (TransformerException ex) { + fail("Could not transform request SOAP envelope to message: " + ex.getMessage()); + } } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/WebServiceMessageCreator.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/WebServiceMessageCreator.java index 13245ef5..5a493d7b 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/WebServiceMessageCreator.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/creator/WebServiceMessageCreator.java @@ -29,13 +29,13 @@ import org.springframework.ws.WebServiceMessageFactory; */ public interface WebServiceMessageCreator { - /** - * Create a message. - * - * @param messageFactory the message that can be used to create the message - * @throws IOException in case of I/O errors - */ - WebServiceMessage createMessage(WebServiceMessageFactory messageFactory) throws IOException; + /** + * Create a message. + * + * @param messageFactory the message that can be used to create the message + * @throws IOException in case of I/O errors + */ + WebServiceMessage createMessage(WebServiceMessageFactory messageFactory) throws IOException; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/AbstractSoapMessageMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/AbstractSoapMessageMatcher.java index 064443f6..d31d8b90 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/AbstractSoapMessageMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/AbstractSoapMessageMatcher.java @@ -34,19 +34,19 @@ import org.springframework.ws.soap.SoapMessage; */ public abstract class AbstractSoapMessageMatcher implements WebServiceMessageMatcher { - @Override - public final void match(WebServiceMessage message) throws IOException, AssertionError { - assertTrue("Message is not a SOAP message", message instanceof SoapMessage); - match((SoapMessage) message); - } + @Override + public final void match(WebServiceMessage message) throws IOException, AssertionError { + assertTrue("Message is not a SOAP message", message instanceof SoapMessage); + match((SoapMessage) message); + } - /** - * Abstract template method that gets invoked from {@link #match(WebServiceMessage)} if the given message is a - * {@link SoapMessage}. - * - * @param soapMessage the soap message - * @throws IOException in case of I/O errors - * @throws AssertionError if expectations are not met - */ - protected abstract void match(SoapMessage soapMessage) throws IOException, AssertionError; + /** + * Abstract template method that gets invoked from {@link #match(WebServiceMessage)} if the given message is a + * {@link SoapMessage}. + * + * @param soapMessage the soap message + * @throws IOException in case of I/O errors + * @throws AssertionError if expectations are not met + */ + protected abstract void match(SoapMessage soapMessage) throws IOException, AssertionError; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/DiffMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/DiffMatcher.java index cf3c37d0..937f1e65 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/DiffMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/DiffMatcher.java @@ -32,23 +32,23 @@ import org.springframework.ws.WebServiceMessage; */ public abstract class DiffMatcher implements WebServiceMessageMatcher { - static { - XMLUnit.setIgnoreWhitespace(true); - } + static { + XMLUnit.setIgnoreWhitespace(true); + } - @Override - public final void match(WebServiceMessage message) throws IOException, AssertionError { - Diff diff = createDiff(message); - assertTrue("Messages are different, " + diff.toString(), diff.similar(), "Payload", message.getPayloadSource()); - } + @Override + public final void match(WebServiceMessage message) throws IOException, AssertionError { + Diff diff = createDiff(message); + assertTrue("Messages are different, " + diff.toString(), diff.similar(), "Payload", message.getPayloadSource()); + } - /** - * Creates a {@link Diff} for the given message. - * - * @param message the message - * @return the diff - * @throws Exception in case of errors - */ - protected abstract Diff createDiff(WebServiceMessage message); + /** + * Creates a {@link Diff} for the given message. + * + * @param message the message + * @return the diff + * @throws Exception in case of errors + */ + protected abstract Diff createDiff(WebServiceMessage message); } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcher.java index d553a689..2021f21c 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcher.java @@ -38,39 +38,39 @@ import static org.springframework.ws.test.support.AssertionErrors.fail; */ public class PayloadDiffMatcher extends DiffMatcher { - private final Source expected; + private final Source expected; - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); - public PayloadDiffMatcher(Source expected) { - Assert.notNull(expected, "'expected' must not be null"); - this.expected = expected; - } + public PayloadDiffMatcher(Source expected) { + Assert.notNull(expected, "'expected' must not be null"); + this.expected = expected; + } - @Override - protected final Diff createDiff(WebServiceMessage message) { - Source payload = message.getPayloadSource(); - if (payload == null) { - fail("Request message does not contain payload"); - } - return createDiff(payload); - } + @Override + protected final Diff createDiff(WebServiceMessage message) { + Source payload = message.getPayloadSource(); + if (payload == null) { + fail("Request message does not contain payload"); + } + return createDiff(payload); + } - protected Diff createDiff(Source payload) { - Document expectedDocument = createDocumentFromSource(expected); - Document actualDocument = createDocumentFromSource(payload); - return new Diff(expectedDocument, actualDocument); - } + protected Diff createDiff(Source payload) { + Document expectedDocument = createDocumentFromSource(expected); + Document actualDocument = createDocumentFromSource(payload); + return new Diff(expectedDocument, actualDocument); + } - private Document createDocumentFromSource(Source source) { - try { - DOMResult result = new DOMResult(); - transformerHelper.transform(source, result); - return (Document) result.getNode(); - } - catch (TransformerException ex) { - fail("Could not transform source to DOMResult" + ex.getMessage()); - return null; - } - } + private Document createDocumentFromSource(Source source) { + try { + DOMResult result = new DOMResult(); + transformerHelper.transform(source, result); + return (Document) result.getNode(); + } + catch (TransformerException ex) { + fail("Could not transform source to DOMResult" + ex.getMessage()); + return null; + } + } } \ No newline at end of file diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcher.java index ba624172..17815f89 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcher.java @@ -38,29 +38,29 @@ import org.springframework.xml.validation.XmlValidatorFactory; */ public class SchemaValidatingMatcher implements WebServiceMessageMatcher { - private final XmlValidator xmlValidator; + private final XmlValidator xmlValidator; - /** - * Creates a {@code SchemaValidatingMatcher} based on the given schema resource(s). - * - * @param schema the schema - * @param furtherSchemas further schemas, if necessary - * @throws IOException in case of I/O errors - */ - public SchemaValidatingMatcher(Resource schema, Resource... furtherSchemas) throws IOException { - Assert.notNull(schema, "'schema' must not be null"); - Resource[] joinedSchemas = new Resource[furtherSchemas.length + 1]; - joinedSchemas[0] = schema; - System.arraycopy(furtherSchemas, 0, joinedSchemas, 1, furtherSchemas.length); - xmlValidator = XmlValidatorFactory.createValidator(joinedSchemas, XmlValidatorFactory.SCHEMA_W3C_XML); + /** + * Creates a {@code SchemaValidatingMatcher} based on the given schema resource(s). + * + * @param schema the schema + * @param furtherSchemas further schemas, if necessary + * @throws IOException in case of I/O errors + */ + public SchemaValidatingMatcher(Resource schema, Resource... furtherSchemas) throws IOException { + Assert.notNull(schema, "'schema' must not be null"); + Resource[] joinedSchemas = new Resource[furtherSchemas.length + 1]; + joinedSchemas[0] = schema; + System.arraycopy(furtherSchemas, 0, joinedSchemas, 1, furtherSchemas.length); + xmlValidator = XmlValidatorFactory.createValidator(joinedSchemas, XmlValidatorFactory.SCHEMA_W3C_XML); - } + } - @Override - public void match(WebServiceMessage message) throws IOException, AssertionError { - SAXParseException[] exceptions = xmlValidator.validate(message.getPayloadSource()); - if (!ObjectUtils.isEmpty(exceptions)) { - fail("XML is not valid: " + Arrays.toString(exceptions), "Payload", message.getPayloadSource()); - } - } + @Override + public void match(WebServiceMessage message) throws IOException, AssertionError { + SAXParseException[] exceptions = xmlValidator.validate(message.getPayloadSource()); + if (!ObjectUtils.isEmpty(exceptions)) { + fail("XML is not valid: " + Arrays.toString(exceptions), "Payload", message.getPayloadSource()); + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcher.java index ccdc163e..78338955 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcher.java @@ -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,35 +42,35 @@ public class SoapEnvelopeDiffMatcher extends AbstractSoapMessageMatcher { private final Source expected; - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); - static { - XMLUnit.setIgnoreWhitespace(true); - } + static { + XMLUnit.setIgnoreWhitespace(true); + } - public SoapEnvelopeDiffMatcher(Source expected) { - Assert.notNull(expected, "'expected' must not be null"); - this.expected = expected; - } - - @Override - protected void match(SoapMessage soapMessage) throws IOException, AssertionError { - Document actualDocument = soapMessage.getDocument(); - Document expectedDocument = createDocumentFromSource(expected); - Diff diff = new Diff(expectedDocument, actualDocument); - assertTrue("Envelopes are different, " + diff.toString(), diff.similar()); - } + public SoapEnvelopeDiffMatcher(Source expected) { + Assert.notNull(expected, "'expected' must not be null"); + this.expected = expected; + } + + @Override + protected void match(SoapMessage soapMessage) throws IOException, AssertionError { + Document actualDocument = soapMessage.getDocument(); + Document expectedDocument = createDocumentFromSource(expected); + Diff diff = new Diff(expectedDocument, actualDocument); + assertTrue("Envelopes are different, " + diff.toString(), diff.similar()); + } private Document createDocumentFromSource(Source source) { - try { - DOMResult result = new DOMResult(); - transformerHelper.transform(source, result); - return (Document) result.getNode(); - } - catch (TransformerException ex) { - fail("Could not transform source to DOMResult" + ex.getMessage()); - return null; - } - } + try { + DOMResult result = new DOMResult(); + transformerHelper.transform(source, result); + return (Document) result.getNode(); + } + catch (TransformerException ex) { + fail("Could not transform source to DOMResult" + ex.getMessage()); + return null; + } + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcher.java index 82bc2625..2183b670 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcher.java @@ -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, @@ -35,35 +35,35 @@ import static org.springframework.ws.test.support.AssertionErrors.assertTrue; */ public class SoapHeaderMatcher extends AbstractSoapMessageMatcher { - private final QName soapHeaderName; + private final QName soapHeaderName; - /** - * Creates a new instance of the {@code SoapHeaderMatcher} that checks for the presence of the given SOAP header - * name. - * - * @param soapHeaderName the header name to check for - */ - public SoapHeaderMatcher(QName soapHeaderName) { - Assert.notNull(soapHeaderName, "'soapHeaderName' must not be null"); - this.soapHeaderName = soapHeaderName; - } + /** + * Creates a new instance of the {@code SoapHeaderMatcher} that checks for the presence of the given SOAP header + * name. + * + * @param soapHeaderName the header name to check for + */ + public SoapHeaderMatcher(QName soapHeaderName) { + Assert.notNull(soapHeaderName, "'soapHeaderName' must not be null"); + this.soapHeaderName = soapHeaderName; + } - @Override - protected void match(SoapMessage soapMessage) throws IOException, AssertionError { - SoapHeader soapHeader = soapMessage.getSoapHeader(); - assertTrue("SOAP message [" + soapMessage + "] does not contain SOAP header", soapHeader != null, "Envelope", - soapMessage.getEnvelope().getSource()); + @Override + protected void match(SoapMessage soapMessage) throws IOException, AssertionError { + SoapHeader soapHeader = soapMessage.getSoapHeader(); + assertTrue("SOAP message [" + soapMessage + "] does not contain SOAP header", soapHeader != null, "Envelope", + soapMessage.getEnvelope().getSource()); - Iterator soapHeaderElementIterator = soapHeader.examineAllHeaderElements(); - boolean found = false; - while (soapHeaderElementIterator.hasNext()) { - SoapHeaderElement soapHeaderElement = soapHeaderElementIterator.next(); - if (soapHeaderName.equals(soapHeaderElement.getName())) { - found = true; - break; - } - } - assertTrue("SOAP header [" + soapHeaderName + "] not found", found, "Envelope", - soapMessage.getEnvelope().getSource()); - } + Iterator soapHeaderElementIterator = soapHeader.examineAllHeaderElements(); + boolean found = false; + while (soapHeaderElementIterator.hasNext()) { + SoapHeaderElement soapHeaderElement = soapHeaderElementIterator.next(); + if (soapHeaderName.equals(soapHeaderElement.getName())) { + found = true; + break; + } + } + assertTrue("SOAP header [" + soapHeaderName + "] not found", found, "Envelope", + soapMessage.getEnvelope().getSource()); + } } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/WebServiceMessageMatcher.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/WebServiceMessageMatcher.java index 4e96d7b0..7f251a12 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/WebServiceMessageMatcher.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/WebServiceMessageMatcher.java @@ -28,13 +28,13 @@ import org.springframework.ws.WebServiceMessage; */ public interface WebServiceMessageMatcher { - /** - * Matches the given message against the expectations. Implementations typically make use of JUnit-based - * assertions. - * - * @param message the message - * @throws IOException in case of I/O errors - * @throws AssertionError if expectations are not met - */ - void match(WebServiceMessage message) throws IOException, AssertionError; + /** + * Matches the given message against the expectations. Implementations typically make use of JUnit-based + * assertions. + * + * @param message the message + * @throws IOException in case of I/O errors + * @throws AssertionError if expectations are not met + */ + void match(WebServiceMessage message) throws IOException, AssertionError; } diff --git a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelper.java b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelper.java index a6780920..97a46f69 100644 --- a/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelper.java +++ b/spring-ws-test/src/main/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelper.java @@ -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, @@ -41,107 +41,107 @@ import static org.springframework.ws.test.support.AssertionErrors.fail; */ public class XPathExpectationsHelper { - private final XPathExpression expression; + private final XPathExpression expression; - private final String expressionString; + private final String expressionString; - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); - /** - * Creates a new instance of the {@code XPathExpectationsSupport} with the given XPath expression. - * - * @param expression the XPath expression - */ - public XPathExpectationsHelper(String expression) { - this(expression, null); - } - /** - * Creates a new instance of the {@code XPathExpectationsSupport} with the given XPath expression and namespaces. - * - * @param expression the XPath expression - * @param namespaces the namespaces, can be empty or {@code null} - */ - public XPathExpectationsHelper(String expression, Map namespaces) { - Assert.hasLength(expression, "'expression' must not be empty"); - this.expression = XPathExpressionFactory.createXPathExpression(expression, namespaces); - this.expressionString = expression; - } + /** + * Creates a new instance of the {@code XPathExpectationsSupport} with the given XPath expression. + * + * @param expression the XPath expression + */ + public XPathExpectationsHelper(String expression) { + this(expression, null); + } + /** + * Creates a new instance of the {@code XPathExpectationsSupport} with the given XPath expression and namespaces. + * + * @param expression the XPath expression + * @param namespaces the namespaces, can be empty or {@code null} + */ + public XPathExpectationsHelper(String expression, Map namespaces) { + Assert.hasLength(expression, "'expression' must not be empty"); + this.expression = XPathExpressionFactory.createXPathExpression(expression, namespaces); + this.expressionString = expression; + } - public WebServiceMessageMatcher exists() { - return new WebServiceMessageMatcher() { - public void match(WebServiceMessage message) throws IOException, AssertionError { - Node payload = transformToNode(message); - Node result = expression.evaluateAsNode(payload); - if (result == null) { - fail("No match for \"" + expressionString + "\" found", "Payload", message.getPayloadSource()); - } - } - }; - } + public WebServiceMessageMatcher exists() { + return new WebServiceMessageMatcher() { + public void match(WebServiceMessage message) throws IOException, AssertionError { + Node payload = transformToNode(message); + Node result = expression.evaluateAsNode(payload); + if (result == null) { + fail("No match for \"" + expressionString + "\" found", "Payload", message.getPayloadSource()); + } + } + }; + } - public WebServiceMessageMatcher doesNotExist() { - return new WebServiceMessageMatcher() { - public void match(WebServiceMessage message) throws IOException, AssertionError { - Node payload = transformToNode(message); - Node result = expression.evaluateAsNode(payload); - if (result != null) { - fail("Match for \"" + expressionString + "\" found", "Payload", message.getPayloadSource()); - } - } - }; - } + public WebServiceMessageMatcher doesNotExist() { + return new WebServiceMessageMatcher() { + public void match(WebServiceMessage message) throws IOException, AssertionError { + Node payload = transformToNode(message); + Node result = expression.evaluateAsNode(payload); + if (result != null) { + fail("Match for \"" + expressionString + "\" found", "Payload", message.getPayloadSource()); + } + } + }; + } - public WebServiceMessageMatcher evaluatesTo(final boolean expectedValue) { - return new WebServiceMessageMatcher() { - public void match(WebServiceMessage message) throws IOException, AssertionError { - Node payload = transformToNode(message); - boolean result = expression.evaluateAsBoolean(payload); - assertEquals("Evaluation of XPath expression \"" + expressionString + "\" failed.", expectedValue, - result, "Payload", message.getPayloadSource()); + public WebServiceMessageMatcher evaluatesTo(final boolean expectedValue) { + return new WebServiceMessageMatcher() { + public void match(WebServiceMessage message) throws IOException, AssertionError { + Node payload = transformToNode(message); + boolean result = expression.evaluateAsBoolean(payload); + assertEquals("Evaluation of XPath expression \"" + expressionString + "\" failed.", expectedValue, + result, "Payload", message.getPayloadSource()); - } - }; - } + } + }; + } - public WebServiceMessageMatcher evaluatesTo(int expectedValue) { - return evaluatesTo((double) expectedValue); - } + public WebServiceMessageMatcher evaluatesTo(int expectedValue) { + return evaluatesTo((double) expectedValue); + } - public WebServiceMessageMatcher evaluatesTo(final double expectedValue) { - return new WebServiceMessageMatcher() { - public void match(WebServiceMessage message) throws IOException, AssertionError { - Node payload = transformToNode(message); - double result = expression.evaluateAsNumber(payload); - assertEquals("Evaluation of XPath expression \"" + expressionString + "\" failed.", expectedValue, - result, "Payload", message.getPayloadSource()); + public WebServiceMessageMatcher evaluatesTo(final double expectedValue) { + return new WebServiceMessageMatcher() { + public void match(WebServiceMessage message) throws IOException, AssertionError { + Node payload = transformToNode(message); + double result = expression.evaluateAsNumber(payload); + assertEquals("Evaluation of XPath expression \"" + expressionString + "\" failed.", expectedValue, + result, "Payload", message.getPayloadSource()); - } - }; - } + } + }; + } - public WebServiceMessageMatcher evaluatesTo(final String expectedValue) { - Assert.notNull(expectedValue, "'expectedValue' must not be null"); - return new WebServiceMessageMatcher() { - public void match(WebServiceMessage message) throws IOException, AssertionError { - Node payload = transformToNode(message); - String result = expression.evaluateAsString(payload); - assertEquals("Evaluation of XPath expression \"" + expressionString + "\" failed.", expectedValue, - result, "Payload", message.getPayloadSource()); - } - }; - } + public WebServiceMessageMatcher evaluatesTo(final String expectedValue) { + Assert.notNull(expectedValue, "'expectedValue' must not be null"); + return new WebServiceMessageMatcher() { + public void match(WebServiceMessage message) throws IOException, AssertionError { + Node payload = transformToNode(message); + String result = expression.evaluateAsString(payload); + assertEquals("Evaluation of XPath expression \"" + expressionString + "\" failed.", expectedValue, + result, "Payload", message.getPayloadSource()); + } + }; + } - private Node transformToNode(WebServiceMessage request) { - DOMResult domResult = new DOMResult(); - try { - transformerHelper.transform(request.getPayloadSource(), domResult); - return domResult.getNode(); - } - catch (TransformerException ex) { - fail("Could not transform request payload: " + ex.getMessage()); - return null; - } - } + private Node transformToNode(WebServiceMessage request) { + DOMResult domResult = new DOMResult(); + try { + transformerHelper.transform(request.getPayloadSource(), domResult); + return domResult.getNode(); + } + catch (TransformerException ex) { + fail("Could not transform request payload: " + ex.getMessage()); + return null; + } + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/ErrorResponseCreatorTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/ErrorResponseCreatorTest.java index a00f6a61..1c86aeb9 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/ErrorResponseCreatorTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/ErrorResponseCreatorTest.java @@ -24,11 +24,11 @@ import static org.junit.Assert.assertEquals; public class ErrorResponseCreatorTest { - @Test - public void callback() throws IOException { - String errorMessage = "Error message"; - ErrorResponseCreator callback = new ErrorResponseCreator(errorMessage); - callback.createResponse(null, null, null); - assertEquals(errorMessage, callback.getErrorMessage()); - } + @Test + public void callback() throws IOException { + String errorMessage = "Error message"; + ErrorResponseCreator callback = new ErrorResponseCreator(errorMessage); + callback.createResponse(null, null, null); + assertEquals(errorMessage, callback.getErrorMessage()); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/ExceptionResponseCreatorTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/ExceptionResponseCreatorTest.java index 9b9ec11c..d4ec4efb 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/ExceptionResponseCreatorTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/ExceptionResponseCreatorTest.java @@ -22,17 +22,17 @@ import org.junit.Test; public class ExceptionResponseCreatorTest { - @Test(expected = IOException.class) - public void ioException() throws Exception { - ExceptionResponseCreator callback = new ExceptionResponseCreator(new IOException()); + @Test(expected = IOException.class) + public void ioException() throws Exception { + ExceptionResponseCreator callback = new ExceptionResponseCreator(new IOException()); - callback.createResponse(null, null, null); - } + callback.createResponse(null, null, null); + } - @Test(expected = RuntimeException.class) - public void runtimeException() throws Exception { - ExceptionResponseCreator callback = new ExceptionResponseCreator(new RuntimeException()); + @Test(expected = RuntimeException.class) + public void runtimeException() throws Exception { + ExceptionResponseCreator callback = new ExceptionResponseCreator(new RuntimeException()); - callback.createResponse(null, null, null); - } + callback.createResponse(null, null, null); + } } \ No newline at end of file diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockSenderConnectionTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockSenderConnectionTest.java index 374c41df..833ddb5c 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockSenderConnectionTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockSenderConnectionTest.java @@ -28,27 +28,27 @@ import static org.springframework.ws.test.client.ResponseCreators.withPayload; public class MockSenderConnectionTest { - @Test - public void error() throws IOException { - String testErrorMessage = "Test Error Message"; - MockSenderConnection connection = new MockSenderConnection(); - connection.andRespond(withError(testErrorMessage)); - assertTrue(connection.hasError()); - assertEquals(testErrorMessage, connection.getErrorMessage()); - } + @Test + public void error() throws IOException { + String testErrorMessage = "Test Error Message"; + MockSenderConnection connection = new MockSenderConnection(); + connection.andRespond(withError(testErrorMessage)); + assertTrue(connection.hasError()); + assertEquals(testErrorMessage, connection.getErrorMessage()); + } - @Test - public void normal() throws IOException { - MockSenderConnection connection = new MockSenderConnection(); - connection.andRespond(withPayload(new StringSource(""))); - assertFalse(connection.hasError()); - assertNull(connection.getErrorMessage()); - } + @Test + public void normal() throws IOException { + MockSenderConnection connection = new MockSenderConnection(); + connection.andRespond(withPayload(new StringSource(""))); + assertFalse(connection.hasError()); + assertNull(connection.getErrorMessage()); + } - @Test(expected = AssertionError.class) - public void noRequestMatchers() throws IOException { - MockSenderConnection connection = new MockSenderConnection(); - connection.andRespond(withPayload(new StringSource(""))); - connection.send(null); - } + @Test(expected = AssertionError.class) + public void noRequestMatchers() throws IOException { + MockSenderConnection connection = new MockSenderConnection(); + connection.andRespond(withPayload(new StringSource(""))); + connection.send(null); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceMessageSenderTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceMessageSenderTest.java index 4ce51366..73fc9c7b 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceMessageSenderTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceMessageSenderTest.java @@ -24,29 +24,29 @@ import org.junit.Test; public class MockWebServiceMessageSenderTest { - private MockWebServiceMessageSender sender; + private MockWebServiceMessageSender sender; - @Before - public void setUp() throws Exception { - sender = new MockWebServiceMessageSender(); - } + @Before + public void setUp() throws Exception { + sender = new MockWebServiceMessageSender(); + } - @Test(expected = AssertionError.class) - public void noMoreExpectedConnections() throws IOException { - sender.createConnection(URI.create("http://localhost")); - } + @Test(expected = AssertionError.class) + public void noMoreExpectedConnections() throws IOException { + sender.createConnection(URI.create("http://localhost")); + } - @Test(expected = AssertionError.class) - public void verify() throws IOException { - sender.expectNewConnection(); - sender.verifyConnections(); - } + @Test(expected = AssertionError.class) + public void verify() throws IOException { + sender.expectNewConnection(); + sender.verifyConnections(); + } - @Test(expected = AssertionError.class) - public void verifyMoteThanOne() throws IOException { - sender.expectNewConnection(); - sender.expectNewConnection(); - sender.createConnection(URI.create("http://localhost")); - sender.verifyConnections(); - } + @Test(expected = AssertionError.class) + public void verifyMoteThanOne() throws IOException { + sender.expectNewConnection(); + sender.expectNewConnection(); + sender.createConnection(URI.create("http://localhost")); + sender.verifyConnections(); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceServerTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceServerTest.java index 88ba7d64..ee78d578 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceServerTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/MockWebServiceServerTest.java @@ -52,260 +52,260 @@ import static org.springframework.ws.test.client.ResponseCreators.withPayload; public class MockWebServiceServerTest { - private WebServiceTemplate template; + private WebServiceTemplate template; - private MockWebServiceServer server; + private MockWebServiceServer server; - @Before - public void setUp() throws Exception { - template = new WebServiceTemplate(); - template.setDefaultUri("http://example.com"); + @Before + public void setUp() throws Exception { + template = new WebServiceTemplate(); + template.setDefaultUri("http://example.com"); - server = MockWebServiceServer.createServer(template); - } + server = MockWebServiceServer.createServer(template); + } - @Test - public void createServerWebServiceTemplate() throws Exception { - WebServiceTemplate template = new WebServiceTemplate(); + @Test + public void createServerWebServiceTemplate() throws Exception { + WebServiceTemplate template = new WebServiceTemplate(); - MockWebServiceServer server = MockWebServiceServer.createServer(template); - assertNotNull(server); - } + MockWebServiceServer server = MockWebServiceServer.createServer(template); + assertNotNull(server); + } - @Test - public void createServerGatewaySupport() throws Exception { - MyClient client = new MyClient(); + @Test + public void createServerGatewaySupport() throws Exception { + MyClient client = new MyClient(); - MockWebServiceServer server = MockWebServiceServer.createServer(client); - assertNotNull(server); - } + MockWebServiceServer server = MockWebServiceServer.createServer(client); + assertNotNull(server); + } - @Test - public void createServerApplicationContextWebServiceTemplate() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("webServiceTemplate", WebServiceTemplate.class); - applicationContext.refresh(); + @Test + public void createServerApplicationContextWebServiceTemplate() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("webServiceTemplate", WebServiceTemplate.class); + applicationContext.refresh(); - MockWebServiceServer server = MockWebServiceServer.createServer(applicationContext); - assertNotNull(server); - } + MockWebServiceServer server = MockWebServiceServer.createServer(applicationContext); + assertNotNull(server); + } - @Test - public void createServerApplicationContextWebServiceGatewaySupport() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("myClient", MyClient.class); - applicationContext.refresh(); + @Test + public void createServerApplicationContextWebServiceGatewaySupport() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("myClient", MyClient.class); + applicationContext.refresh(); - MockWebServiceServer server = MockWebServiceServer.createServer(applicationContext); - assertNotNull(server); - } + MockWebServiceServer server = MockWebServiceServer.createServer(applicationContext); + assertNotNull(server); + } - @Test(expected = IllegalArgumentException.class) - public void createServerApplicationContextEmpty() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.refresh(); + @Test(expected = IllegalArgumentException.class) + public void createServerApplicationContextEmpty() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.refresh(); - MockWebServiceServer server = MockWebServiceServer.createServer(applicationContext); - assertNotNull(server); - } + MockWebServiceServer server = MockWebServiceServer.createServer(applicationContext); + assertNotNull(server); + } - @Test - public void mocks() throws Exception { - URI uri = URI.create("http://example.com"); + @Test + public void mocks() throws Exception { + URI uri = URI.create("http://example.com"); - RequestMatcher requestMatcher1 = createStrictMock("requestMatcher1", RequestMatcher.class); - RequestMatcher requestMatcher2 = createStrictMock("requestMatcher2", RequestMatcher.class); - ResponseCreator responseCreator = createStrictMock(ResponseCreator.class); + RequestMatcher requestMatcher1 = createStrictMock("requestMatcher1", RequestMatcher.class); + RequestMatcher requestMatcher2 = createStrictMock("requestMatcher2", RequestMatcher.class); + ResponseCreator responseCreator = createStrictMock(ResponseCreator.class); - SaajSoapMessage response = new SaajSoapMessageFactory(MessageFactory.newInstance()).createWebServiceMessage(); + SaajSoapMessage response = new SaajSoapMessageFactory(MessageFactory.newInstance()).createWebServiceMessage(); - requestMatcher1.match(eq(uri), isA(SaajSoapMessage.class)); - requestMatcher2.match(eq(uri), isA(SaajSoapMessage.class)); - expect(responseCreator.createResponse(eq(uri), isA(SaajSoapMessage.class), isA(SaajSoapMessageFactory.class))) - .andReturn(response); + requestMatcher1.match(eq(uri), isA(SaajSoapMessage.class)); + requestMatcher2.match(eq(uri), isA(SaajSoapMessage.class)); + expect(responseCreator.createResponse(eq(uri), isA(SaajSoapMessage.class), isA(SaajSoapMessageFactory.class))) + .andReturn(response); - replay(requestMatcher1, requestMatcher2, responseCreator); + replay(requestMatcher1, requestMatcher2, responseCreator); - server.expect(requestMatcher1).andExpect(requestMatcher2).andRespond(responseCreator); - template.sendSourceAndReceiveToResult(uri.toString(), new StringSource(""), - new StringResult()); + server.expect(requestMatcher1).andExpect(requestMatcher2).andRespond(responseCreator); + template.sendSourceAndReceiveToResult(uri.toString(), new StringSource(""), + new StringResult()); - verify(requestMatcher1, requestMatcher2, responseCreator); - } + verify(requestMatcher1, requestMatcher2, responseCreator); + } - @Test - public void payloadMatch() throws Exception { - Source request = new StringSource(""); - Source response = new StringSource(""); + @Test + public void payloadMatch() throws Exception { + Source request = new StringSource(""); + Source response = new StringSource(""); - server.expect(payload(request)).andRespond(withPayload(response)); + server.expect(payload(request)).andRespond(withPayload(response)); - StringResult result = new StringResult(); - template.sendSourceAndReceiveToResult(request, result); - assertXMLEqual(result.toString(), response.toString()); - } + StringResult result = new StringResult(); + template.sendSourceAndReceiveToResult(request, result); + assertXMLEqual(result.toString(), response.toString()); + } - @Test(expected = AssertionError.class) - public void payloadNonMatch() throws Exception { - Source expected = new StringSource(""); + @Test(expected = AssertionError.class) + public void payloadNonMatch() throws Exception { + Source expected = new StringSource(""); - server.expect(payload(expected)); + server.expect(payload(expected)); - StringResult result = new StringResult(); - String actual = ""; - template.sendSourceAndReceiveToResult(new StringSource(actual), result); - } + StringResult result = new StringResult(); + String actual = ""; + template.sendSourceAndReceiveToResult(new StringSource(actual), result); + } - @Test - public void soapHeaderMatch() throws Exception { - final QName soapHeaderName = new QName("http://example.com", "mySoapHeader"); + @Test + public void soapHeaderMatch() throws Exception { + final QName soapHeaderName = new QName("http://example.com", "mySoapHeader"); - server.expect(soapHeader(soapHeaderName)); + server.expect(soapHeader(soapHeaderName)); - template.sendSourceAndReceiveToResult(new StringSource(""), - new WebServiceMessageCallback() { - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - SoapMessage soapMessage = (SoapMessage) message; - soapMessage.getSoapHeader().addHeaderElement(soapHeaderName); - } - }, new StringResult()); - } + template.sendSourceAndReceiveToResult(new StringSource(""), + new WebServiceMessageCallback() { + public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { + SoapMessage soapMessage = (SoapMessage) message; + soapMessage.getSoapHeader().addHeaderElement(soapHeaderName); + } + }, new StringResult()); + } - @Test(expected = AssertionError.class) - public void soapHeaderNonMatch() throws Exception { - QName soapHeaderName = new QName("http://example.com", "mySoapHeader"); + @Test(expected = AssertionError.class) + public void soapHeaderNonMatch() throws Exception { + QName soapHeaderName = new QName("http://example.com", "mySoapHeader"); - server.expect(soapHeader(soapHeaderName)); + server.expect(soapHeader(soapHeaderName)); - template.sendSourceAndReceiveToResult(new StringSource(""), - new StringResult()); - } + template.sendSourceAndReceiveToResult(new StringSource(""), + new StringResult()); + } - @Test - public void connectionMatch() throws Exception { - String uri = "http://example.com"; - server.expect(connectionTo(uri)); + @Test + public void connectionMatch() throws Exception { + String uri = "http://example.com"; + server.expect(connectionTo(uri)); - template.sendSourceAndReceiveToResult(uri, new StringSource(""), - new StringResult()); - } + template.sendSourceAndReceiveToResult(uri, new StringSource(""), + new StringResult()); + } - @Test(expected = AssertionError.class) - public void connectionNonMatch() throws Exception { - String expected = "http://expected.com"; - server.expect(connectionTo(expected)); + @Test(expected = AssertionError.class) + public void connectionNonMatch() throws Exception { + String expected = "http://expected.com"; + server.expect(connectionTo(expected)); - String actual = "http://actual.com"; - template.sendSourceAndReceiveToResult(actual, new StringSource(""), - new StringResult()); - } + String actual = "http://actual.com"; + template.sendSourceAndReceiveToResult(actual, new StringSource(""), + new StringResult()); + } - @Test(expected = AssertionError.class) - public void unexpectedConnection() throws Exception { - Source request = new StringSource(""); - Source response = new StringSource(""); + @Test(expected = AssertionError.class) + public void unexpectedConnection() throws Exception { + Source request = new StringSource(""); + Source response = new StringSource(""); - server.expect(payload(request)).andRespond(withPayload(response)); + server.expect(payload(request)).andRespond(withPayload(response)); - template.sendSourceAndReceiveToResult(request, new StringResult()); - template.sendSourceAndReceiveToResult(request, new StringResult()); - } + template.sendSourceAndReceiveToResult(request, new StringResult()); + template.sendSourceAndReceiveToResult(request, new StringResult()); + } - @Test - public void xsdMatch() throws Exception { - Resource schema = new ByteArrayResource( - "".getBytes()); + @Test + public void xsdMatch() throws Exception { + Resource schema = new ByteArrayResource( + "".getBytes()); - server.expect(validPayload(schema)); + server.expect(validPayload(schema)); - StringResult result = new StringResult(); - String actual = ""; - template.sendSourceAndReceiveToResult(new StringSource(actual), result); - } + StringResult result = new StringResult(); + String actual = ""; + template.sendSourceAndReceiveToResult(new StringSource(actual), result); + } - @Test(expected = AssertionError.class) - public void xsdNonMatch() throws Exception { - Resource schema = new ByteArrayResource( - "".getBytes()); + @Test(expected = AssertionError.class) + public void xsdNonMatch() throws Exception { + Resource schema = new ByteArrayResource( + "".getBytes()); - server.expect(validPayload(schema)); + server.expect(validPayload(schema)); - StringResult result = new StringResult(); - String actual = ""; - template.sendSourceAndReceiveToResult(new StringSource(actual), result); - } + StringResult result = new StringResult(); + String actual = ""; + template.sendSourceAndReceiveToResult(new StringSource(actual), result); + } - @Test - public void xpathExistsMatch() throws Exception { - final Map ns = Collections.singletonMap("ns", "http://example.com"); + @Test + public void xpathExistsMatch() throws Exception { + final Map ns = Collections.singletonMap("ns", "http://example.com"); - server.expect(xpath("/ns:request", ns).exists()); + server.expect(xpath("/ns:request", ns).exists()); - template.sendSourceAndReceiveToResult(new StringSource(""), - new StringResult()); - } + template.sendSourceAndReceiveToResult(new StringSource(""), + new StringResult()); + } - @Test(expected = AssertionError.class) - public void xpathExistsNonMatch() throws Exception { - final Map ns = Collections.singletonMap("ns", "http://example.com"); + @Test(expected = AssertionError.class) + public void xpathExistsNonMatch() throws Exception { + final Map ns = Collections.singletonMap("ns", "http://example.com"); - server.expect(xpath("/ns:foo", ns).exists()); + server.expect(xpath("/ns:foo", ns).exists()); - template.sendSourceAndReceiveToResult(new StringSource(""), - new StringResult()); - } + template.sendSourceAndReceiveToResult(new StringSource(""), + new StringResult()); + } - @Test - public void anythingMatch() throws Exception { - Source request = new StringSource(""); - Source response = new StringSource(""); + @Test + public void anythingMatch() throws Exception { + Source request = new StringSource(""); + Source response = new StringSource(""); - server.expect(anything()).andRespond(withPayload(response)); + server.expect(anything()).andRespond(withPayload(response)); - StringResult result = new StringResult(); - template.sendSourceAndReceiveToResult(request, result); - assertXMLEqual(result.toString(), response.toString()); + StringResult result = new StringResult(); + template.sendSourceAndReceiveToResult(request, result); + assertXMLEqual(result.toString(), response.toString()); - server.verify(); - } + server.verify(); + } - @Test(expected = IllegalStateException.class) - public void recordWhenReplay() throws Exception { - Source request = new StringSource(""); - Source response = new StringSource(""); + @Test(expected = IllegalStateException.class) + public void recordWhenReplay() throws Exception { + Source request = new StringSource(""); + Source response = new StringSource(""); - server.expect(anything()).andRespond(withPayload(response)); - server.expect(anything()).andRespond(withPayload(response)); + server.expect(anything()).andRespond(withPayload(response)); + server.expect(anything()).andRespond(withPayload(response)); - StringResult result = new StringResult(); - template.sendSourceAndReceiveToResult(request, result); - assertXMLEqual(result.toString(), response.toString()); + StringResult result = new StringResult(); + template.sendSourceAndReceiveToResult(request, result); + assertXMLEqual(result.toString(), response.toString()); - server.expect(anything()).andRespond(withPayload(response)); - } + server.expect(anything()).andRespond(withPayload(response)); + } - @Test(expected = AssertionError.class) - public void verifyFailure() throws Exception { - server.expect(anything()); - server.verify(); - } + @Test(expected = AssertionError.class) + public void verifyFailure() throws Exception { + server.expect(anything()); + server.verify(); + } - @Test - public void verifyOnly() throws Exception { - server.verify(); - } + @Test + public void verifyOnly() throws Exception { + server.verify(); + } - @Test(expected = SoapFaultClientException.class) - public void fault() throws Exception { - Source request = new StringSource(""); + @Test(expected = SoapFaultClientException.class) + public void fault() throws Exception { + Source request = new StringSource(""); - server.expect(anything()).andRespond(withClientOrSenderFault("reason", Locale.ENGLISH)); + server.expect(anything()).andRespond(withClientOrSenderFault("reason", Locale.ENGLISH)); - StringResult result = new StringResult(); - template.sendSourceAndReceiveToResult(request, result); - } - - public static class MyClient extends WebServiceGatewaySupport { + StringResult result = new StringResult(); + template.sendSourceAndReceiveToResult(request, result); + } + + public static class MyClient extends WebServiceGatewaySupport { - } + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/ResponseCreatorsTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/ResponseCreatorsTest.java index b55c52ce..b6591ff5 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/ResponseCreatorsTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/ResponseCreatorsTest.java @@ -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, @@ -41,41 +41,41 @@ import static org.junit.Assert.*; public class ResponseCreatorsTest { - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); - private SaajSoapMessageFactory messageFactory; + private SaajSoapMessageFactory messageFactory; - @Before - public void createMessageFactory() { - messageFactory = new SaajSoapMessageFactory(); - messageFactory.afterPropertiesSet(); - } + @Before + public void createMessageFactory() { + messageFactory = new SaajSoapMessageFactory(); + messageFactory.afterPropertiesSet(); + } - @Test - public void withPayloadSource() throws Exception { - String payload = ""; - ResponseCreator responseCreator = ResponseCreators.withPayload(new StringSource(payload)); + @Test + public void withPayloadSource() throws Exception { + String payload = ""; + ResponseCreator responseCreator = ResponseCreators.withPayload(new StringSource(payload)); - WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); + WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); - assertXMLEqual(payload, getPayloadAsString(response)); + assertXMLEqual(payload, getPayloadAsString(response)); - } + } - @Test - public void withPayloadResource() throws Exception { - String payload = ""; - ResponseCreator responseCreator = - ResponseCreators.withPayload(new ByteArrayResource(payload.getBytes("UTF-8"))); + @Test + public void withPayloadResource() throws Exception { + String payload = ""; + ResponseCreator responseCreator = + ResponseCreators.withPayload(new ByteArrayResource(payload.getBytes("UTF-8"))); - WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); + WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); - assertXMLEqual(payload, getPayloadAsString(response)); - } - - @Test - public void withSoapEnvelopeSource() throws Exception { - StringBuilder xmlBuilder = new StringBuilder(); + assertXMLEqual(payload, getPayloadAsString(response)); + } + + @Test + public void withSoapEnvelopeSource() throws Exception { + StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(""); xmlBuilder.append(""); xmlBuilder.append("
"); @@ -83,13 +83,13 @@ public class ResponseCreatorsTest { xmlBuilder.append(""); String envelope = xmlBuilder.toString(); ResponseCreator responseCreator = ResponseCreators.withSoapEnvelope(new StringSource(envelope)); - WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); - assertXMLEqual(envelope, getSoapEnvelopeAsString((SoapMessage)response)); - } - - @Test - public void withSoapEnvelopeResource() throws Exception { - StringBuilder xmlBuilder = new StringBuilder(); + WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); + assertXMLEqual(envelope, getSoapEnvelopeAsString((SoapMessage)response)); + } + + @Test + public void withSoapEnvelopeResource() throws Exception { + StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(""); xmlBuilder.append(""); xmlBuilder.append("
"); @@ -97,88 +97,88 @@ public class ResponseCreatorsTest { xmlBuilder.append(""); String envelope = xmlBuilder.toString(); ResponseCreator responseCreator = ResponseCreators.withSoapEnvelope(new ByteArrayResource(envelope.getBytes("UTF-8"))); - WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); - assertXMLEqual(envelope, getSoapEnvelopeAsString((SoapMessage)response)); - } + WebServiceMessage response = responseCreator.createResponse(null, null, messageFactory); + assertXMLEqual(envelope, getSoapEnvelopeAsString((SoapMessage)response)); + } - @Test - public void withIOException() throws Exception { - IOException expected = new IOException("Foo"); - ResponseCreator responseCreator = ResponseCreators.withException(expected); + @Test + public void withIOException() throws Exception { + IOException expected = new IOException("Foo"); + ResponseCreator responseCreator = ResponseCreators.withException(expected); - try { - responseCreator.createResponse(null, null, null); - } - catch (IOException actual) { - assertSame(expected, actual); - } - } - - @Test - public void withRuntimeException() throws Exception { - RuntimeException expected = new RuntimeException("Foo"); - ResponseCreator responseCreator = ResponseCreators.withException(expected); + try { + responseCreator.createResponse(null, null, null); + } + catch (IOException actual) { + assertSame(expected, actual); + } + } + + @Test + public void withRuntimeException() throws Exception { + RuntimeException expected = new RuntimeException("Foo"); + ResponseCreator responseCreator = ResponseCreators.withException(expected); - try { - responseCreator.createResponse(null, null, null); - } - catch (RuntimeException actual) { - assertSame(expected, actual); - } - } + try { + responseCreator.createResponse(null, null, null); + } + catch (RuntimeException actual) { + assertSame(expected, actual); + } + } - @Test - public void withMustUnderstandFault() throws Exception { - String faultString = "Foo"; - ResponseCreator responseCreator = ResponseCreators.withMustUnderstandFault(faultString, Locale.ENGLISH); + @Test + public void withMustUnderstandFault() throws Exception { + String faultString = "Foo"; + ResponseCreator responseCreator = ResponseCreators.withMustUnderstandFault(faultString, Locale.ENGLISH); - testFault(responseCreator, faultString, SoapVersion.SOAP_11.getMustUnderstandFaultName()); - } + testFault(responseCreator, faultString, SoapVersion.SOAP_11.getMustUnderstandFaultName()); + } - @Test - public void withClientOrSenderFault() throws Exception { - String faultString = "Foo"; - ResponseCreator responseCreator = ResponseCreators.withClientOrSenderFault(faultString, Locale.ENGLISH); + @Test + public void withClientOrSenderFault() throws Exception { + String faultString = "Foo"; + ResponseCreator responseCreator = ResponseCreators.withClientOrSenderFault(faultString, Locale.ENGLISH); - testFault(responseCreator, faultString, SoapVersion.SOAP_11.getClientOrSenderFaultName()); - } + testFault(responseCreator, faultString, SoapVersion.SOAP_11.getClientOrSenderFaultName()); + } - @Test - public void withServerOrReceiverFault() throws Exception { - String faultString = "Foo"; - ResponseCreator responseCreator = ResponseCreators.withServerOrReceiverFault(faultString, Locale.ENGLISH); + @Test + public void withServerOrReceiverFault() throws Exception { + String faultString = "Foo"; + ResponseCreator responseCreator = ResponseCreators.withServerOrReceiverFault(faultString, Locale.ENGLISH); - testFault(responseCreator, faultString, SoapVersion.SOAP_11.getServerOrReceiverFaultName()); - } + testFault(responseCreator, faultString, SoapVersion.SOAP_11.getServerOrReceiverFaultName()); + } - @Test - public void withVersionMismatchFault() throws Exception { - String faultString = "Foo"; - ResponseCreator responseCreator = ResponseCreators.withVersionMismatchFault(faultString, Locale.ENGLISH); + @Test + public void withVersionMismatchFault() throws Exception { + String faultString = "Foo"; + ResponseCreator responseCreator = ResponseCreators.withVersionMismatchFault(faultString, Locale.ENGLISH); - testFault(responseCreator, faultString, SoapVersion.SOAP_11.getVersionMismatchFaultName()); - } - - private void testFault(ResponseCreator responseCreator, String faultString, QName faultCode) throws IOException { - SoapMessage response = (SoapMessage) responseCreator.createResponse(null, null, messageFactory); + testFault(responseCreator, faultString, SoapVersion.SOAP_11.getVersionMismatchFaultName()); + } + + private void testFault(ResponseCreator responseCreator, String faultString, QName faultCode) throws IOException { + SoapMessage response = (SoapMessage) responseCreator.createResponse(null, null, messageFactory); - assertTrue("Response has no fault", response.hasFault()); - Soap11Fault soapFault = (Soap11Fault) response.getSoapBody().getFault(); - assertEquals("Response has invalid fault code", faultCode, soapFault.getFaultCode()); - assertEquals("Response has invalid fault string", faultString, soapFault.getFaultStringOrReason()); - assertEquals("Response has invalid fault locale", Locale.ENGLISH, soapFault.getFaultStringLocale()); - } + assertTrue("Response has no fault", response.hasFault()); + Soap11Fault soapFault = (Soap11Fault) response.getSoapBody().getFault(); + assertEquals("Response has invalid fault code", faultCode, soapFault.getFaultCode()); + assertEquals("Response has invalid fault string", faultString, soapFault.getFaultStringOrReason()); + assertEquals("Response has invalid fault locale", Locale.ENGLISH, soapFault.getFaultStringLocale()); + } - private String getPayloadAsString(WebServiceMessage message) throws TransformerException { - Result result = new StringResult(); - transformerHelper.transform(message.getPayloadSource(), result); - return result.toString(); - } - - private String getSoapEnvelopeAsString(SoapMessage message) throws TransformerException { - DOMSource source = new DOMSource(message.getDocument()); - Result result = new StringResult(); - transformerHelper.transform(source, result); - return result.toString(); - } + private String getPayloadAsString(WebServiceMessage message) throws TransformerException { + Result result = new StringResult(); + transformerHelper.transform(message.getPayloadSource(), result); + return result.toString(); + } + + private String getSoapEnvelopeAsString(SoapMessage message) throws TransformerException { + DOMSource source = new DOMSource(message.getDocument()); + Result result = new StringResult(); + transformerHelper.transform(source, result); + return result.toString(); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/UriMatcherTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/UriMatcherTest.java index 09ce1b6f..a414a3da 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/UriMatcherTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/UriMatcherTest.java @@ -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,23 +26,23 @@ import static org.easymock.EasyMock.*; public class UriMatcherTest { - private static final URI GOOD_URI = URI.create("http://localhost"); + private static final URI GOOD_URI = URI.create("http://localhost"); - @Test - public void match() { - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(null); - replay(message); - UriMatcher matcher = new UriMatcher(GOOD_URI); - matcher.match(GOOD_URI, message); - } + @Test + public void match() { + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(null); + replay(message); + UriMatcher matcher = new UriMatcher(GOOD_URI); + matcher.match(GOOD_URI, message); + } - @Test(expected = AssertionError.class) - public void nonMatch() { - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(null); - replay(message); - UriMatcher matcher = new UriMatcher(GOOD_URI); - matcher.match(URI.create("http://www.example.org"), message); - } + @Test(expected = AssertionError.class) + public void nonMatch() { + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(null); + replay(message); + UriMatcher matcher = new UriMatcher(GOOD_URI); + matcher.match(URI.create("http://www.example.org"), message); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapterTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapterTest.java index f8c3496a..d4cb4401 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapterTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/WebServiceMessageMatcherAdapterTest.java @@ -31,27 +31,27 @@ import static org.easymock.EasyMock.*; */ public class WebServiceMessageMatcherAdapterTest { - private WebServiceMessage message; + private WebServiceMessage message; - private WebServiceMessageMatcher adaptee; + private WebServiceMessageMatcher adaptee; - private WebServiceMessageMatcherAdapter adapter; + private WebServiceMessageMatcherAdapter adapter; - @Before - public void setUp() throws Exception { - message = createMock(WebServiceMessage.class); - adaptee = createMock(WebServiceMessageMatcher.class); - adapter = new WebServiceMessageMatcherAdapter(adaptee); - } - - @Test - public void match() throws IOException { - adaptee.match(message); + @Before + public void setUp() throws Exception { + message = createMock(WebServiceMessage.class); + adaptee = createMock(WebServiceMessageMatcher.class); + adapter = new WebServiceMessageMatcherAdapter(adaptee); + } + + @Test + public void match() throws IOException { + adaptee.match(message); - replay(message, adaptee); + replay(message, adaptee); - adapter.match(null, message); + adapter.match(null, message); - verify(message, adaptee); - } + verify(message, adaptee); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/ClientIntegrationTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/ClientIntegrationTest.java index cbeab0d0..0c475226 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/ClientIntegrationTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/ClientIntegrationTest.java @@ -42,31 +42,31 @@ import static org.springframework.ws.test.client.ResponseCreators.withPayload; @ContextConfiguration("integration-test.xml") public class ClientIntegrationTest { - @Autowired - private CustomerClient client; + @Autowired + private CustomerClient client; - private MockWebServiceServer mockServer; + private MockWebServiceServer mockServer; - @Before - public void createServer() throws Exception { - mockServer = MockWebServiceServer.createServer(client); - } + @Before + public void createServer() throws Exception { + mockServer = MockWebServiceServer.createServer(client); + } - @Test - public void basic() throws Exception { - Source expectedRequestPayload = new StringSource( - "" + - "John Doe" + ""); - Source responsePayload = new StringSource( - "" + - "10" + ""); + @Test + public void basic() throws Exception { + Source expectedRequestPayload = new StringSource( + "" + + "John Doe" + ""); + Source responsePayload = new StringSource( + "" + + "10" + ""); - mockServer.expect(payload(expectedRequestPayload)).andRespond(withPayload(responsePayload)); + mockServer.expect(payload(expectedRequestPayload)).andRespond(withPayload(responsePayload)); - int result = client.getCustomerCount(); - assertEquals(10, result); + int result = client.getCustomerCount(); + assertEquals(10, result); - mockServer.verify(); - } + mockServer.verify(); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/CustomerClient.java b/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/CustomerClient.java index f52e0358..d8a103f0 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/CustomerClient.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/client/integration/CustomerClient.java @@ -23,12 +23,12 @@ import org.springframework.ws.test.integration.CustomerCountResponse; public class CustomerClient extends WebServiceGatewaySupport { - public int getCustomerCount() { - CustomerCountRequest request = new CustomerCountRequest(); - request.setCustomerName("John Doe"); + public int getCustomerCount() { + CustomerCountRequest request = new CustomerCountRequest(); + request.setCustomerName("John Doe"); - CustomerCountResponse response = (CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request); - return response.getCustomerCount(); - } + CustomerCountResponse response = (CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request); + return response.getCustomerCount(); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountRequest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountRequest.java index cb685b13..f667ef09 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountRequest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountRequest.java @@ -22,14 +22,14 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace = "http://springframework.org/spring-ws") public class CustomerCountRequest { - private String customerName; + private String customerName; - @XmlElement(namespace = "http://springframework.org/spring-ws") - public String getCustomerName() { - return customerName; - } + @XmlElement(namespace = "http://springframework.org/spring-ws") + public String getCustomerName() { + return customerName; + } - public void setCustomerName(String name) { - this.customerName = name; - } + public void setCustomerName(String name) { + this.customerName = name; + } } \ No newline at end of file diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountResponse.java b/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountResponse.java index 617591cf..44bb318e 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountResponse.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/integration/CustomerCountResponse.java @@ -22,14 +22,14 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace = "http://springframework.org/spring-ws") public class CustomerCountResponse { - private int customerCount; + private int customerCount; - @XmlElement(namespace = "http://springframework.org/spring-ws") - public int getCustomerCount() { - return customerCount; - } + @XmlElement(namespace = "http://springframework.org/spring-ws") + public int getCustomerCount() { + return customerCount; + } - public void setCustomerCount(int customerCount) { - this.customerCount = customerCount; - } + public void setCustomerCount(int customerCount) { + this.customerCount = customerCount; + } } \ No newline at end of file diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/server/MockWebServiceClientTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/server/MockWebServiceClientTest.java index a6f210ea..93e342b6 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/server/MockWebServiceClientTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/server/MockWebServiceClientTest.java @@ -26,23 +26,23 @@ import static org.junit.Assert.assertNotNull; public class MockWebServiceClientTest { - @Test - public void createServerApplicationContext() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("messageDispatcher", SoapMessageDispatcher.class); - applicationContext.registerSingleton("messageFactory", SaajSoapMessageFactory.class); - applicationContext.refresh(); + @Test + public void createServerApplicationContext() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("messageDispatcher", SoapMessageDispatcher.class); + applicationContext.registerSingleton("messageFactory", SaajSoapMessageFactory.class); + applicationContext.refresh(); - MockWebServiceClient client = MockWebServiceClient.createClient(applicationContext); - assertNotNull(client); - } - - @Test - public void createServerApplicationContextDefaults() throws Exception { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.refresh(); + MockWebServiceClient client = MockWebServiceClient.createClient(applicationContext); + assertNotNull(client); + } + + @Test + public void createServerApplicationContextDefaults() throws Exception { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.refresh(); - MockWebServiceClient client = MockWebServiceClient.createClient(applicationContext); - assertNotNull(client); - } + MockWebServiceClient client = MockWebServiceClient.createClient(applicationContext); + assertNotNull(client); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapterTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapterTest.java index 5ca763ef..2a1ec5b1 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapterTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/server/WebServiceMessageMatcherAdapterTest.java @@ -31,27 +31,27 @@ import static org.easymock.EasyMock.*; */ public class WebServiceMessageMatcherAdapterTest { - private WebServiceMessage message; + private WebServiceMessage message; - private WebServiceMessageMatcher adaptee; + private WebServiceMessageMatcher adaptee; - private WebServiceMessageMatcherAdapter adapter; + private WebServiceMessageMatcherAdapter adapter; - @Before - public void setUp() throws Exception { - message = createMock(WebServiceMessage.class); - adaptee = createMock(WebServiceMessageMatcher.class); - adapter = new WebServiceMessageMatcherAdapter(adaptee); - } - - @Test - public void match() throws IOException { - adaptee.match(message); + @Before + public void setUp() throws Exception { + message = createMock(WebServiceMessage.class); + adaptee = createMock(WebServiceMessageMatcher.class); + adapter = new WebServiceMessageMatcherAdapter(adaptee); + } + + @Test + public void match() throws IOException { + adaptee.match(message); - replay(message, adaptee); + replay(message, adaptee); - adapter.match(null, message); + adapter.match(null, message); - verify(message, adaptee); - } + verify(message, adaptee); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/CustomerEndpoint.java b/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/CustomerEndpoint.java index 85f3d2ca..98b077df 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/CustomerEndpoint.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/CustomerEndpoint.java @@ -25,11 +25,11 @@ import org.springframework.ws.test.integration.CustomerCountResponse; @Endpoint public class CustomerEndpoint { - @ResponsePayload - public CustomerCountResponse getCustomerCount(@RequestPayload CustomerCountRequest request) { - CustomerCountResponse response = new CustomerCountResponse(); - response.setCustomerCount(42); - return response; - } + @ResponsePayload + public CustomerCountResponse getCustomerCount(@RequestPayload CustomerCountRequest request) { + CustomerCountResponse response = new CustomerCountResponse(); + response.setCustomerCount(42); + return response; + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/ServerIntegrationTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/ServerIntegrationTest.java index d572ba8d..3ba35537 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/ServerIntegrationTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/server/integration/ServerIntegrationTest.java @@ -39,26 +39,26 @@ import static org.springframework.ws.test.server.ResponseMatchers.payload; @ContextConfiguration("integration-test.xml") public class ServerIntegrationTest { - @Autowired - private ApplicationContext applicationContext; + @Autowired + private ApplicationContext applicationContext; - private MockWebServiceClient mockClient; + private MockWebServiceClient mockClient; - @Before - public void createClient() { - mockClient = MockWebServiceClient.createClient(applicationContext); - } + @Before + public void createClient() { + mockClient = MockWebServiceClient.createClient(applicationContext); + } - @Test - public void basic() throws Exception { - Source requestPayload = new StringSource("" + - "John Doe" + ""); - Source expectedResponsePayload = new StringSource( - "" + - "42" + ""); + @Test + public void basic() throws Exception { + Source requestPayload = new StringSource("" + + "John Doe" + ""); + Source expectedResponsePayload = new StringSource( + "" + + "42" + ""); - mockClient.sendRequest(withPayload(requestPayload)).andExpect(payload(expectedResponsePayload)); - } + mockClient.sendRequest(withPayload(requestPayload)).andExpect(payload(expectedResponsePayload)); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/support/MockStrategiesHelperTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/support/MockStrategiesHelperTest.java index 6154839b..8f084f96 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/support/MockStrategiesHelperTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/support/MockStrategiesHelperTest.java @@ -26,49 +26,49 @@ import static org.junit.Assert.assertNull; public class MockStrategiesHelperTest { - @Test - public void none() { - StaticApplicationContext applicationContext = new StaticApplicationContext(); + @Test + public void none() { + StaticApplicationContext applicationContext = new StaticApplicationContext(); - MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); - assertNull(helper.getStrategy(IMyBean.class)); - } + MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); + assertNull(helper.getStrategy(IMyBean.class)); + } - @Test - public void one() { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("myBean", MyBean.class); + @Test + public void one() { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("myBean", MyBean.class); - MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); - assertNotNull(helper.getStrategy(IMyBean.class)); - } + MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); + assertNotNull(helper.getStrategy(IMyBean.class)); + } - @Test(expected = BeanInitializationException.class) - public void many() { - StaticApplicationContext applicationContext = new StaticApplicationContext(); - applicationContext.registerSingleton("myBean1", MyBean.class); - applicationContext.registerSingleton("myBean2", MyBean.class); + @Test(expected = BeanInitializationException.class) + public void many() { + StaticApplicationContext applicationContext = new StaticApplicationContext(); + applicationContext.registerSingleton("myBean1", MyBean.class); + applicationContext.registerSingleton("myBean2", MyBean.class); - MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); - helper.getStrategy(IMyBean.class); - } - - @Test - public void noneWithDefault() { - StaticApplicationContext applicationContext = new StaticApplicationContext(); + MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); + helper.getStrategy(IMyBean.class); + } + + @Test + public void noneWithDefault() { + StaticApplicationContext applicationContext = new StaticApplicationContext(); - MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); - assertNotNull(helper.getStrategy(IMyBean.class, MyBean.class)); - } + MockStrategiesHelper helper = new MockStrategiesHelper(applicationContext); + assertNotNull(helper.getStrategy(IMyBean.class, MyBean.class)); + } - public interface IMyBean { + public interface IMyBean { - } + } - public static class MyBean implements IMyBean { + public static class MyBean implements IMyBean { - } + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcherTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcherTest.java index 327b7eb9..a781e9b5 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcherTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/PayloadDiffMatcherTest.java @@ -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, @@ -29,38 +29,38 @@ import static org.easymock.EasyMock.*; public class PayloadDiffMatcherTest { - @Test - public void match() throws Exception { - String xml = ""; - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource(xml)).times(2); - replay(message); + @Test + public void match() throws Exception { + String xml = ""; + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource(xml)).times(2); + replay(message); - PayloadDiffMatcher matcher = new PayloadDiffMatcher(new StringSource(xml)); - matcher.match(message); + PayloadDiffMatcher matcher = new PayloadDiffMatcher(new StringSource(xml)); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void nonMatch() throws Exception { - String actual = ""; - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource(actual)).times(2); - replay(message); + @Test(expected = AssertionError.class) + public void nonMatch() throws Exception { + String actual = ""; + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource(actual)).times(2); + replay(message); - String expected = ""; - PayloadDiffMatcher matcher = new PayloadDiffMatcher(new StringSource(expected)); - matcher.match(message); - } + String expected = ""; + PayloadDiffMatcher matcher = new PayloadDiffMatcher(new StringSource(expected)); + matcher.match(message); + } - @Test(expected = AssertionError.class) - public void noPayload() throws Exception { - PayloadDiffMatcher matcher = new PayloadDiffMatcher(new StringSource("")); - MessageFactory messageFactory = MessageFactory.newInstance(); - SoapMessage soapMessage = new SaajSoapMessage(messageFactory.createMessage()); + @Test(expected = AssertionError.class) + public void noPayload() throws Exception { + PayloadDiffMatcher matcher = new PayloadDiffMatcher(new StringSource("")); + MessageFactory messageFactory = MessageFactory.newInstance(); + SoapMessage soapMessage = new SaajSoapMessage(messageFactory.createMessage()); - matcher.createDiff(soapMessage); - } + matcher.createDiff(soapMessage); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcherTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcherTest.java index 338cec3f..1f2a6d3a 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcherTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SchemaValidatingMatcherTest.java @@ -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,103 +31,103 @@ import static org.easymock.EasyMock.*; public class SchemaValidatingMatcherTest { - private Resource schema; + private Resource schema; - private Resource schema1; + private Resource schema1; - private Resource schema2; + private Resource schema2; - private WebServiceMessage message; + private WebServiceMessage message; - @Before - public void setUp() { - message = createMock(WebServiceMessage.class); - schema = new ClassPathResource("schemaValidatingMatcherTest.xsd", SchemaValidatingMatcherTest.class); - schema1 = new ClassPathResource("schemaValidatingMatcherTest-1.xsd", SchemaValidatingMatcherTest.class); - schema2 = new ClassPathResource("schemaValidatingMatcherTest-2.xsd", SchemaValidatingMatcherTest.class); - } + @Before + public void setUp() { + message = createMock(WebServiceMessage.class); + schema = new ClassPathResource("schemaValidatingMatcherTest.xsd", SchemaValidatingMatcherTest.class); + schema1 = new ClassPathResource("schemaValidatingMatcherTest-1.xsd", SchemaValidatingMatcherTest.class); + schema2 = new ClassPathResource("schemaValidatingMatcherTest-2.xsd", SchemaValidatingMatcherTest.class); + } - @Test - public void singleSchemaMatch() throws IOException, AssertionError { - expect(message.getPayloadSource()).andReturn(new StringSource( - "0text")); + @Test + public void singleSchemaMatch() throws IOException, AssertionError { + expect(message.getPayloadSource()).andReturn(new StringSource( + "0text")); - SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema); + SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void singleSchemaNonMatch() throws IOException, AssertionError { - expect(message.getPayloadSource()).andReturn(new StringSource( - "atext")).times(2); + @Test(expected = AssertionError.class) + public void singleSchemaNonMatch() throws IOException, AssertionError { + expect(message.getPayloadSource()).andReturn(new StringSource( + "atext")).times(2); - SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema); + SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test - public void multipleSchemaMatch() throws IOException, AssertionError { - expect(message.getPayloadSource()).andReturn(new StringSource( - "0text")); + @Test + public void multipleSchemaMatch() throws IOException, AssertionError { + expect(message.getPayloadSource()).andReturn(new StringSource( + "0text")); - SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema1, schema2); + SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema1, schema2); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void multipleSchemaNotOk() throws IOException, AssertionError { - expect(message.getPayloadSource()).andReturn(new StringSource( - "atext")).times(2); + @Test(expected = AssertionError.class) + public void multipleSchemaNotOk() throws IOException, AssertionError { + expect(message.getPayloadSource()).andReturn(new StringSource( + "atext")).times(2); - SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema1, schema2); + SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema1, schema2); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void multipleSchemaDifferentOrderNotOk() throws IOException, AssertionError { - expect(message.getPayloadSource()).andReturn(new StringSource( - "atext")).times(2); + @Test(expected = AssertionError.class) + public void multipleSchemaDifferentOrderNotOk() throws IOException, AssertionError { + expect(message.getPayloadSource()).andReturn(new StringSource( + "atext")).times(2); - SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema1, schema2); + SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema1, schema2); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void xmlValidatorNotOk() throws IOException, AssertionError { - expect(message.getPayloadSource()).andReturn(new StringSource( - "atext")).times(2); + @Test(expected = AssertionError.class) + public void xmlValidatorNotOk() throws IOException, AssertionError { + expect(message.getPayloadSource()).andReturn(new StringSource( + "atext")).times(2); - SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema); + SchemaValidatingMatcher matcher = new SchemaValidatingMatcher(schema); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcherTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcherTest.java index fb8c4aed..e06b2634 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcherTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapEnvelopeDiffMatcherTest.java @@ -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, @@ -30,7 +30,7 @@ import static org.easymock.EasyMock.*; public class SoapEnvelopeDiffMatcherTest { @Test - public void match() throws Exception { + public void match() throws Exception { StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(""); xmlBuilder.append(""); @@ -41,18 +41,18 @@ public class SoapEnvelopeDiffMatcherTest { DOMResult result = new DOMResult(); TransformerHelper transformerHelper = new TransformerHelper(); transformerHelper.transform(new StringSource(xml), result); - SoapMessage message = createMock(SoapMessage.class); - expect(message.getDocument()).andReturn((Document)result.getNode()).once(); - replay(message); + SoapMessage message = createMock(SoapMessage.class); + expect(message.getDocument()).andReturn((Document)result.getNode()).once(); + replay(message); - SoapEnvelopeDiffMatcher matcher = new SoapEnvelopeDiffMatcher(new StringSource(xml)); - matcher.match(message); + SoapEnvelopeDiffMatcher matcher = new SoapEnvelopeDiffMatcher(new StringSource(xml)); + matcher.match(message); - verify(message); - } + verify(message); + } @Test(expected = AssertionError.class) - public void nonMatch() throws Exception { + public void nonMatch() throws Exception { StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(""); xmlBuilder.append(""); @@ -64,13 +64,13 @@ public class SoapEnvelopeDiffMatcherTest { DOMResult result = new DOMResult(); TransformerHelper transformerHelper = new TransformerHelper(); transformerHelper.transform(new StringSource(actual), result); - SoapMessage message = createMock(SoapMessage.class); - expect(message.getDocument()).andReturn((Document)result.getNode()).once(); - replay(message); + SoapMessage message = createMock(SoapMessage.class); + expect(message.getDocument()).andReturn((Document)result.getNode()).once(); + replay(message); - String expected = String.format(xml, "2"); - SoapEnvelopeDiffMatcher matcher = new SoapEnvelopeDiffMatcher(new StringSource(expected)); - matcher.match(message); - } + String expected = String.format(xml, "2"); + SoapEnvelopeDiffMatcher matcher = new SoapEnvelopeDiffMatcher(new StringSource(expected)); + matcher.match(message); + } } diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcherTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcherTest.java index caa13b97..692df069 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcherTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/SoapHeaderMatcherTest.java @@ -31,40 +31,40 @@ import static org.easymock.EasyMock.createMock; public class SoapHeaderMatcherTest { - private SoapHeaderMatcher matcher; + private SoapHeaderMatcher matcher; - private QName expectedHeaderName; + private QName expectedHeaderName; - @Before - public void setUp() throws Exception { - expectedHeaderName = new QName("http://example.com", "header"); - matcher = new SoapHeaderMatcher(expectedHeaderName); - } + @Before + public void setUp() throws Exception { + expectedHeaderName = new QName("http://example.com", "header"); + matcher = new SoapHeaderMatcher(expectedHeaderName); + } - @Test - public void match() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage saajMessage = messageFactory.createMessage(); - saajMessage.getSOAPHeader().addHeaderElement(expectedHeaderName); - SoapMessage soapMessage = new SaajSoapMessage(saajMessage); + @Test + public void match() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage saajMessage = messageFactory.createMessage(); + saajMessage.getSOAPHeader().addHeaderElement(expectedHeaderName); + SoapMessage soapMessage = new SaajSoapMessage(saajMessage); - matcher.match(soapMessage); - } + matcher.match(soapMessage); + } - @Test(expected = AssertionError.class) - public void nonMatch() throws Exception { - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage saajMessage = messageFactory.createMessage(); - SoapMessage soapMessage = new SaajSoapMessage(saajMessage); + @Test(expected = AssertionError.class) + public void nonMatch() throws Exception { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage saajMessage = messageFactory.createMessage(); + SoapMessage soapMessage = new SaajSoapMessage(saajMessage); - matcher.match(soapMessage); - } + matcher.match(soapMessage); + } - @Test(expected = AssertionError.class) - public void nonSoap() throws Exception { - WebServiceMessage message = createMock(WebServiceMessage.class); + @Test(expected = AssertionError.class) + public void nonSoap() throws Exception { + WebServiceMessage message = createMock(WebServiceMessage.class); - matcher.match(message); - } + matcher.match(message); + } } \ No newline at end of file diff --git a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelperTest.java b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelperTest.java index 5d6f3c8e..6d009e0a 100644 --- a/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelperTest.java +++ b/spring-ws-test/src/test/java/org/springframework/ws/test/support/matcher/XPathExpectationsHelperTest.java @@ -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, @@ -30,188 +30,188 @@ import static org.junit.Assert.assertNotNull; public class XPathExpectationsHelperTest { - @Test - public void existsMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b"); - WebServiceMessageMatcher matcher = helper.exists(); - assertNotNull(matcher); + @Test + public void existsMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b"); + WebServiceMessageMatcher matcher = helper.exists(); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("")); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("")); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void existsNonMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//c"); - WebServiceMessageMatcher matcher = helper.exists(); - assertNotNull(matcher); + @Test(expected = AssertionError.class) + public void existsNonMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//c"); + WebServiceMessageMatcher matcher = helper.exists(); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("")).times(2); - replay(message); + replay(message); - matcher.match(message); - } + matcher.match(message); + } - @Test - public void doesNotExistMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//c"); - WebServiceMessageMatcher matcher = helper.doesNotExist(); - assertNotNull(matcher); + @Test + public void doesNotExistMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//c"); + WebServiceMessageMatcher matcher = helper.doesNotExist(); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("")); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("")); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void doesNotExistNonMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//a"); - WebServiceMessageMatcher matcher = helper.doesNotExist(); - assertNotNull(matcher); + @Test(expected = AssertionError.class) + public void doesNotExistNonMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//a"); + WebServiceMessageMatcher matcher = helper.doesNotExist(); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("")).times(2); - replay(message); + replay(message); - matcher.match(message); - } + matcher.match(message); + } - @Test - public void evaluatesToTrueMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b=1"); - WebServiceMessageMatcher matcher = helper.evaluatesTo(true); - assertNotNull(matcher); + @Test + public void evaluatesToTrueMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b=1"); + WebServiceMessageMatcher matcher = helper.evaluatesTo(true); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void evaluatesToTrueNonMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b=2"); - WebServiceMessageMatcher matcher = helper.evaluatesTo(true); - assertNotNull(matcher); + @Test(expected = AssertionError.class) + public void evaluatesToTrueNonMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b=2"); + WebServiceMessageMatcher matcher = helper.evaluatesTo(true); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); - replay(message); + replay(message); - matcher.match(message); - } + matcher.match(message); + } - @Test - public void evaluatesToFalseMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b!=1"); - WebServiceMessageMatcher matcher = helper.evaluatesTo(false); - assertNotNull(matcher); + @Test + public void evaluatesToFalseMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b!=1"); + WebServiceMessageMatcher matcher = helper.evaluatesTo(false); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void evaluatesToFalseNonMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b!=2"); - WebServiceMessageMatcher matcher = helper.evaluatesTo(false); - assertNotNull(matcher); + @Test(expected = AssertionError.class) + public void evaluatesToFalseNonMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b!=2"); + WebServiceMessageMatcher matcher = helper.evaluatesTo(false); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); - replay(message); + replay(message); - matcher.match(message); - } + matcher.match(message); + } - @Test - public void evaluatesToIntegerMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b"); - WebServiceMessageMatcher matcher = helper.evaluatesTo(1); - assertNotNull(matcher); + @Test + public void evaluatesToIntegerMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b"); + WebServiceMessageMatcher matcher = helper.evaluatesTo(1); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void evaluatesToIntegerNonMatch() throws IOException, AssertionError { - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b"); - WebServiceMessageMatcher matcher = helper.evaluatesTo(2); - assertNotNull(matcher); + @Test(expected = AssertionError.class) + public void evaluatesToIntegerNonMatch() throws IOException, AssertionError { + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b"); + WebServiceMessageMatcher matcher = helper.evaluatesTo(2); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()).andReturn(new StringSource("1")).times(2); - replay(message); + replay(message); - matcher.match(message); - } + matcher.match(message); + } - @Test - public void existsWithNamespacesMatch() throws IOException, AssertionError { - Map ns = Collections.singletonMap("x", "http://example.org"); - XPathExpectationsHelper helper = new XPathExpectationsHelper("//x:b", ns); - WebServiceMessageMatcher matcher = helper.exists(); - assertNotNull(matcher); + @Test + public void existsWithNamespacesMatch() throws IOException, AssertionError { + Map ns = Collections.singletonMap("x", "http://example.org"); + XPathExpectationsHelper helper = new XPathExpectationsHelper("//x:b", ns); + WebServiceMessageMatcher matcher = helper.exists(); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()) - .andReturn(new StringSource("")); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()) + .andReturn(new StringSource("")); - replay(message); + replay(message); - matcher.match(message); + matcher.match(message); - verify(message); - } + verify(message); + } - @Test(expected = AssertionError.class) - public void existsWithNamespacesNonMatch() throws IOException, AssertionError { - Map ns = Collections.singletonMap("x", "http://example.org"); - XPathExpectationsHelper helper = new XPathExpectationsHelper("//b", ns); - WebServiceMessageMatcher matcher = helper.exists(); - assertNotNull(matcher); + @Test(expected = AssertionError.class) + public void existsWithNamespacesNonMatch() throws IOException, AssertionError { + Map ns = Collections.singletonMap("x", "http://example.org"); + XPathExpectationsHelper helper = new XPathExpectationsHelper("//b", ns); + WebServiceMessageMatcher matcher = helper.exists(); + assertNotNull(matcher); - WebServiceMessage message = createMock(WebServiceMessage.class); - expect(message.getPayloadSource()) - .andReturn(new StringSource("")).times(2); + WebServiceMessage message = createMock(WebServiceMessage.class); + expect(message.getPayloadSource()) + .andReturn(new StringSource("")).times(2); - replay(message); + replay(message); - matcher.match(message); - } + matcher.match(message); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/JaxpVersion.java b/spring-xml/src/main/java/org/springframework/xml/JaxpVersion.java index 37c07fe2..b8e5774f 100644 --- a/spring-xml/src/main/java/org/springframework/xml/JaxpVersion.java +++ b/spring-xml/src/main/java/org/springframework/xml/JaxpVersion.java @@ -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,64 +32,64 @@ import org.springframework.util.ClassUtils; */ public abstract class JaxpVersion { - /** - * Constant identifying JAXP 1.0. - */ - public static final int JAXP_10 = 0; + /** + * Constant identifying JAXP 1.0. + */ + public static final int JAXP_10 = 0; - /** - * Constant identifying JAXP 1.1. - */ - public static final int JAXP_11 = 1; + /** + * Constant identifying JAXP 1.1. + */ + public static final int JAXP_11 = 1; - /** - * Constant identifying JAXP 1.3. - */ - public static final int JAXP_13 = 3; + /** + * Constant identifying JAXP 1.3. + */ + public static final int JAXP_13 = 3; - /** - * Constant identifying JAXP 1.4. - */ - public static final int JAXP_14 = 4; + /** + * Constant identifying JAXP 1.4. + */ + public static final int JAXP_14 = 4; - private static final String JAXP_14_CLASS_NAME = "javax.xml.transform.stax.StAXSource"; + private static final String JAXP_14_CLASS_NAME = "javax.xml.transform.stax.StAXSource"; - private static int jaxpVersion; + private static int jaxpVersion; - static { - ClassLoader classLoader = JaxpVersion.class.getClassLoader(); - try { - ClassUtils.forName(JAXP_14_CLASS_NAME, classLoader); - jaxpVersion = JAXP_14; - } - catch (ClassNotFoundException ex) { - // leave 1.3 as default (it's either 1.3 or unknown) - jaxpVersion = JAXP_13; - } - } + static { + ClassLoader classLoader = JaxpVersion.class.getClassLoader(); + try { + ClassUtils.forName(JAXP_14_CLASS_NAME, classLoader); + jaxpVersion = JAXP_14; + } + catch (ClassNotFoundException ex) { + // leave 1.3 as default (it's either 1.3 or unknown) + jaxpVersion = JAXP_13; + } + } - /** - * Gets the JAXP version. This means we can do things like if {@code (getJaxpVersion() < JAXP_13)}. - * - * @return a code comparable to the JAXP_XX codes in this class - * @see #JAXP_10 - * @see #JAXP_11 - * @see #JAXP_13 - * @see #JAXP_14 - */ - public static int getJaxpVersion() { - return jaxpVersion; - } + /** + * Gets the JAXP version. This means we can do things like if {@code (getJaxpVersion() < JAXP_13)}. + * + * @return a code comparable to the JAXP_XX codes in this class + * @see #JAXP_10 + * @see #JAXP_11 + * @see #JAXP_13 + * @see #JAXP_14 + */ + public static int getJaxpVersion() { + return jaxpVersion; + } - /** - * Convenience method to determine if the current JAXP version is at least 1.4 (packaged with JDK 1.6). - * - * @return {@code true} if the current JAXP version is at least JAXP 1.4 - * @see #getJaxpVersion() - * @see #JAXP_14 - */ - public static boolean isAtLeastJaxp14() { - return getJaxpVersion() >= JAXP_14; - } + /** + * Convenience method to determine if the current JAXP version is at least 1.4 (packaged with JDK 1.6). + * + * @return {@code true} if the current JAXP version is at least JAXP 1.4 + * @see #getJaxpVersion() + * @see #JAXP_14 + */ + public static boolean isAtLeastJaxp14() { + return getJaxpVersion() >= JAXP_14; + } } \ No newline at end of file diff --git a/spring-xml/src/main/java/org/springframework/xml/XmlException.java b/spring-xml/src/main/java/org/springframework/xml/XmlException.java index 427c1eac..a7b637f1 100644 --- a/spring-xml/src/main/java/org/springframework/xml/XmlException.java +++ b/spring-xml/src/main/java/org/springframework/xml/XmlException.java @@ -27,22 +27,22 @@ import org.springframework.core.NestedRuntimeException; @SuppressWarnings("serial") public abstract class XmlException extends NestedRuntimeException { - /** - * Constructs a new instance of the {@code XmlException} with the specific detail message. - * - * @param message the detail message - */ - protected XmlException(String message) { - super(message); - } + /** + * Constructs a new instance of the {@code XmlException} with the specific detail message. + * + * @param message the detail message + */ + protected XmlException(String message) { + super(message); + } - /** - * Constructs a new instance of the {@code XmlException} with the specific detail message and exception. - * - * @param message the detail message - * @param throwable the wrapped exception - */ - protected XmlException(String message, Throwable throwable) { - super(message, throwable); - } + /** + * Constructs a new instance of the {@code XmlException} with the specific detail message and exception. + * + * @param message the detail message + * @param throwable the wrapped exception + */ + protected XmlException(String message, Throwable throwable) { + super(message, throwable); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/dom/DomContentHandler.java b/spring-xml/src/main/java/org/springframework/xml/dom/DomContentHandler.java index 5e355382..cf26eba1 100644 --- a/spring-xml/src/main/java/org/springframework/xml/dom/DomContentHandler.java +++ b/spring-xml/src/main/java/org/springframework/xml/dom/DomContentHandler.java @@ -40,109 +40,109 @@ import org.springframework.util.Assert; */ public class DomContentHandler implements ContentHandler { - private final Document document; + private final Document document; - private final List elements = new ArrayList(); + private final List elements = new ArrayList(); - private final Node node; + private final Node node; - /** - * Creates a new instance of the {@code DomContentHandler} with the given node. - * - * @param node the node to publish events to - */ - public DomContentHandler(Node node) { - Assert.notNull(node, "node must not be null"); - this.node = node; - if (node instanceof Document) { - document = (Document) node; - } - else { - document = node.getOwnerDocument(); - } - Assert.notNull(document, "document must not be null"); - } + /** + * Creates a new instance of the {@code DomContentHandler} with the given node. + * + * @param node the node to publish events to + */ + public DomContentHandler(Node node) { + Assert.notNull(node, "node must not be null"); + this.node = node; + if (node instanceof Document) { + document = (Document) node; + } + else { + document = node.getOwnerDocument(); + } + Assert.notNull(document, "document must not be null"); + } - private Node getParent() { - if (!elements.isEmpty()) { - return elements.get(elements.size() - 1); - } - else { - return node; - } - } + private Node getParent() { + if (!elements.isEmpty()) { + return elements.get(elements.size() - 1); + } + else { + return node; + } + } - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - Node parent = getParent(); - Element element = document.createElementNS(uri, qName); - for (int i = 0; i < attributes.getLength(); i++) { - String attrUri = attributes.getURI(i); - String attrQname = attributes.getQName(i); - String value = attributes.getValue(i); - if (!attrQname.startsWith("xmlns")) { - element.setAttributeNS(attrUri, attrQname, value); - } - } - element = (Element) parent.appendChild(element); - elements.add(element); - } + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + Node parent = getParent(); + Element element = document.createElementNS(uri, qName); + for (int i = 0; i < attributes.getLength(); i++) { + String attrUri = attributes.getURI(i); + String attrQname = attributes.getQName(i); + String value = attributes.getValue(i); + if (!attrQname.startsWith("xmlns")) { + element.setAttributeNS(attrUri, attrQname, value); + } + } + element = (Element) parent.appendChild(element); + elements.add(element); + } - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - elements.remove(elements.size() - 1); - } + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + elements.remove(elements.size() - 1); + } - @Override - public void characters(char ch[], int start, int length) throws SAXException { - String data = new String(ch, start, length); - Node parent = getParent(); - Node lastChild = parent.getLastChild(); - if (lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) { - ((Text) lastChild).appendData(data); - } - else { - Text text = document.createTextNode(data); - parent.appendChild(text); - } - } + @Override + public void characters(char ch[], int start, int length) throws SAXException { + String data = new String(ch, start, length); + Node parent = getParent(); + Node lastChild = parent.getLastChild(); + if (lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) { + ((Text) lastChild).appendData(data); + } + else { + Text text = document.createTextNode(data); + parent.appendChild(text); + } + } - @Override - public void processingInstruction(String target, String data) throws SAXException { - Node parent = getParent(); - ProcessingInstruction pi = document.createProcessingInstruction(target, data); - parent.appendChild(pi); - } + @Override + public void processingInstruction(String target, String data) throws SAXException { + Node parent = getParent(); + ProcessingInstruction pi = document.createProcessingInstruction(target, data); + parent.appendChild(pi); + } - /* - * Unsupported - */ + /* + * Unsupported + */ - @Override - public void setDocumentLocator(Locator locator) { - } + @Override + public void setDocumentLocator(Locator locator) { + } - @Override - public void startDocument() throws SAXException { - } + @Override + public void startDocument() throws SAXException { + } - @Override - public void endDocument() throws SAXException { - } + @Override + public void endDocument() throws SAXException { + } - @Override - public void startPrefixMapping(String prefix, String uri) throws SAXException { - } + @Override + public void startPrefixMapping(String prefix, String uri) throws SAXException { + } - @Override - public void endPrefixMapping(String prefix) throws SAXException { - } + @Override + public void endPrefixMapping(String prefix) throws SAXException { + } - @Override - public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { - } + @Override + public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { + } - @Override - public void skippedEntity(String name) throws SAXException { - } + @Override + public void skippedEntity(String name) throws SAXException { + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/namespace/QNameEditor.java b/spring-xml/src/main/java/org/springframework/xml/namespace/QNameEditor.java index 774c0db7..8328b421 100644 --- a/spring-xml/src/main/java/org/springframework/xml/namespace/QNameEditor.java +++ b/spring-xml/src/main/java/org/springframework/xml/namespace/QNameEditor.java @@ -47,29 +47,29 @@ import org.springframework.util.StringUtils; */ public class QNameEditor extends PropertyEditorSupport { - @Override - public void setAsText(String text) throws IllegalArgumentException { - setValue(QNameUtils.parseQNameString(text)); - } + @Override + public void setAsText(String text) throws IllegalArgumentException { + setValue(QNameUtils.parseQNameString(text)); + } - @Override - public String getAsText() { - Object value = getValue(); - if (value == null || !(value instanceof QName)) { - return ""; - } - else { - QName qName = (QName) value; - String prefix = qName.getPrefix(); - if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) { - return "{" + qName.getNamespaceURI() + "}" + prefix + ":" + qName.getLocalPart(); - } - else if (StringUtils.hasLength(qName.getNamespaceURI())) { - return "{" + qName.getNamespaceURI() + "}" + qName.getLocalPart(); - } - else { - return qName.getLocalPart(); - } - } - } + @Override + public String getAsText() { + Object value = getValue(); + if (value == null || !(value instanceof QName)) { + return ""; + } + else { + QName qName = (QName) value; + String prefix = qName.getPrefix(); + if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) { + return "{" + qName.getNamespaceURI() + "}" + prefix + ":" + qName.getLocalPart(); + } + else if (StringUtils.hasLength(qName.getNamespaceURI())) { + return "{" + qName.getNamespaceURI() + "}" + qName.getLocalPart(); + } + else { + return qName.getLocalPart(); + } + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/namespace/QNameUtils.java b/spring-xml/src/main/java/org/springframework/xml/namespace/QNameUtils.java index 748002dd..d7c5bc98 100644 --- a/spring-xml/src/main/java/org/springframework/xml/namespace/QNameUtils.java +++ b/spring-xml/src/main/java/org/springframework/xml/namespace/QNameUtils.java @@ -33,147 +33,147 @@ import org.springframework.util.StringUtils; public abstract class QNameUtils { /** - * Creates a new {@code QName} with the given parameters. Sets the prefix if possible, i.e. if the - * {@code QName(String, String, String)} constructor can be found. If this constructor is not available (as is - * the case on older implementations of JAX-RPC), the prefix is ignored. - * - * @param namespaceUri namespace URI of the {@code QName} - * @param localPart local part of the {@code QName} - * @param prefix prefix of the {@code QName}. May be ignored. - * @return the created {@code QName} - * @see QName#QName(String,String,String) + * Creates a new {@code QName} with the given parameters. Sets the prefix if possible, i.e. if the + * {@code QName(String, String, String)} constructor can be found. If this constructor is not available (as is + * the case on older implementations of JAX-RPC), the prefix is ignored. + * + * @param namespaceUri namespace URI of the {@code QName} + * @param localPart local part of the {@code QName} + * @param prefix prefix of the {@code QName}. May be ignored. + * @return the created {@code QName} + * @see QName#QName(String,String,String) * @deprecated in favor of {@link QName#QName(String, String, String)} - */ - @Deprecated - public static QName createQName(String namespaceUri, String localPart, String prefix) { - return new QName(namespaceUri, localPart, prefix); - } + */ + @Deprecated + public static QName createQName(String namespaceUri, String localPart, String prefix) { + return new QName(namespaceUri, localPart, prefix); + } - /** - * Returns the prefix of the given {@code QName}. Returns the prefix if available, i.e. if the - * {@code QName.getPrefix()} method can be found. If this method is not available (as is the case on older - * implementations of JAX-RPC), an empty string is returned. - * - * @param qName the {@code QName} to return the prefix from - * @return the prefix, if available, or an empty string - * @see javax.xml.namespace.QName#getPrefix() - * @deprecated in favor of {@link QName#getPrefix()} - */ - @Deprecated - public static String getPrefix(QName qName) { - return qName.getPrefix(); - } + /** + * Returns the prefix of the given {@code QName}. Returns the prefix if available, i.e. if the + * {@code QName.getPrefix()} method can be found. If this method is not available (as is the case on older + * implementations of JAX-RPC), an empty string is returned. + * + * @param qName the {@code QName} to return the prefix from + * @return the prefix, if available, or an empty string + * @see javax.xml.namespace.QName#getPrefix() + * @deprecated in favor of {@link QName#getPrefix()} + */ + @Deprecated + public static String getPrefix(QName qName) { + return qName.getPrefix(); + } - /** - * Validates the given String as a QName - * - * @param text the qualified name - * @return {@code true} if valid, {@code false} otherwise - */ - public static boolean validateQName(String text) { - if (!StringUtils.hasLength(text)) { - return false; - } - if (text.charAt(0) == '{') { - int i = text.indexOf('}'); + /** + * Validates the given String as a QName + * + * @param text the qualified name + * @return {@code true} if valid, {@code false} otherwise + */ + public static boolean validateQName(String text) { + if (!StringUtils.hasLength(text)) { + return false; + } + if (text.charAt(0) == '{') { + int i = text.indexOf('}'); - if (i == -1 || i == text.length() - 1) { - return false; - } - } - return true; - } + if (i == -1 || i == text.length() - 1) { + return false; + } + } + return true; + } - /** - * Returns the qualified name of the given DOM Node. - * - * @param node the node - * @return the qualified name of the node - */ - public static QName getQNameForNode(Node node) { - if (node.getNamespaceURI() != null && node.getPrefix() != null && node.getLocalName() != null) { - return new QName(node.getNamespaceURI(), node.getLocalName(), - node.getPrefix()); - } - else if (node.getNamespaceURI() != null && node.getLocalName() != null) { - return new QName(node.getNamespaceURI(), node.getLocalName()); - } - else if (node.getLocalName() != null) { - return new QName(node.getLocalName()); - } - else { - // as a last resort, use the node name - return new QName(node.getNodeName()); - } - } + /** + * Returns the qualified name of the given DOM Node. + * + * @param node the node + * @return the qualified name of the node + */ + public static QName getQNameForNode(Node node) { + if (node.getNamespaceURI() != null && node.getPrefix() != null && node.getLocalName() != null) { + return new QName(node.getNamespaceURI(), node.getLocalName(), + node.getPrefix()); + } + else if (node.getNamespaceURI() != null && node.getLocalName() != null) { + return new QName(node.getNamespaceURI(), node.getLocalName()); + } + else if (node.getLocalName() != null) { + return new QName(node.getLocalName()); + } + else { + // as a last resort, use the node name + return new QName(node.getNodeName()); + } + } - /** - * Convert a {@code QName} to a qualified name, as used by DOM and SAX. The returned string has a format of - * {@code prefix:localName} if the prefix is set, or just {@code localName} if not. - * - * @param qName the {@code QName} - * @return the qualified name - */ - public static String toQualifiedName(QName qName) { - String prefix = qName.getPrefix(); - if (!StringUtils.hasLength(prefix)) { - return qName.getLocalPart(); - } - else { - return prefix + ":" + qName.getLocalPart(); - } - } + /** + * Convert a {@code QName} to a qualified name, as used by DOM and SAX. The returned string has a format of + * {@code prefix:localName} if the prefix is set, or just {@code localName} if not. + * + * @param qName the {@code QName} + * @return the qualified name + */ + public static String toQualifiedName(QName qName) { + String prefix = qName.getPrefix(); + if (!StringUtils.hasLength(prefix)) { + return qName.getLocalPart(); + } + else { + return prefix + ":" + qName.getLocalPart(); + } + } - /** - * Convert a namespace URI and DOM or SAX qualified name to a {@code QName}. The qualified name can have the - * form {@code prefix:localname} or {@code localName}. - * - * @param namespaceUri the namespace URI - * @param qualifiedName the qualified name - * @return a QName - */ - public static QName toQName(String namespaceUri, String qualifiedName) { - int idx = qualifiedName.indexOf(':'); - if (idx == -1) { - return new QName(namespaceUri, qualifiedName); - } - else { - return new QName(namespaceUri, qualifiedName.substring(idx + 1), - qualifiedName.substring(0, idx)); - } - } + /** + * Convert a namespace URI and DOM or SAX qualified name to a {@code QName}. The qualified name can have the + * form {@code prefix:localname} or {@code localName}. + * + * @param namespaceUri the namespace URI + * @param qualifiedName the qualified name + * @return a QName + */ + public static QName toQName(String namespaceUri, String qualifiedName) { + int idx = qualifiedName.indexOf(':'); + if (idx == -1) { + return new QName(namespaceUri, qualifiedName); + } + else { + return new QName(namespaceUri, qualifiedName.substring(idx + 1), + qualifiedName.substring(0, idx)); + } + } - /** - * Parse the given qualified name string into a {@code QName}. Expects the syntax {@code localPart}, - * {@code{namespace}localPart}, or {@code{namespace}prefix:localPart}. This format resembles the - * {@code toString()} representation of {@code QName} itself, but allows for prefixes to be specified as - * well. - * - * @return a corresponding QName instance - * @throws IllegalArgumentException when the given string is {@code null} or empty. - */ - public static QName parseQNameString(String qNameString) { - Assert.hasLength(qNameString, "QName text may not be null or empty"); - if (qNameString.charAt(0) != '{') { - return new QName(qNameString); - } - else { - int endOfNamespaceURI = qNameString.indexOf('}'); - if (endOfNamespaceURI == -1) { - throw new IllegalArgumentException( - "Cannot create QName from \"" + qNameString + "\", missing closing \"}\""); - } - int prefixSeperator = qNameString.indexOf(':', endOfNamespaceURI + 1); - String namespaceURI = qNameString.substring(1, endOfNamespaceURI); - if (prefixSeperator == -1) { - return new QName(namespaceURI, qNameString.substring(endOfNamespaceURI + 1)); - } - else { - return new QName(namespaceURI, qNameString.substring(prefixSeperator + 1), - qNameString.substring(endOfNamespaceURI + 1, prefixSeperator)); - } - } + /** + * Parse the given qualified name string into a {@code QName}. Expects the syntax {@code localPart}, + * {@code{namespace}localPart}, or {@code{namespace}prefix:localPart}. This format resembles the + * {@code toString()} representation of {@code QName} itself, but allows for prefixes to be specified as + * well. + * + * @return a corresponding QName instance + * @throws IllegalArgumentException when the given string is {@code null} or empty. + */ + public static QName parseQNameString(String qNameString) { + Assert.hasLength(qNameString, "QName text may not be null or empty"); + if (qNameString.charAt(0) != '{') { + return new QName(qNameString); + } + else { + int endOfNamespaceURI = qNameString.indexOf('}'); + if (endOfNamespaceURI == -1) { + throw new IllegalArgumentException( + "Cannot create QName from \"" + qNameString + "\", missing closing \"}\""); + } + int prefixSeperator = qNameString.indexOf(':', endOfNamespaceURI + 1); + String namespaceURI = qNameString.substring(1, endOfNamespaceURI); + if (prefixSeperator == -1) { + return new QName(namespaceURI, qNameString.substring(endOfNamespaceURI + 1)); + } + else { + return new QName(namespaceURI, qNameString.substring(prefixSeperator + 1), + qNameString.substring(endOfNamespaceURI + 1, prefixSeperator)); + } + } - } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/namespace/SimpleNamespaceContext.java b/spring-xml/src/main/java/org/springframework/xml/namespace/SimpleNamespaceContext.java index 1a93ec6c..82ea5649 100644 --- a/spring-xml/src/main/java/org/springframework/xml/namespace/SimpleNamespaceContext.java +++ b/spring-xml/src/main/java/org/springframework/xml/namespace/SimpleNamespaceContext.java @@ -38,130 +38,130 @@ import org.springframework.util.Assert; */ public class SimpleNamespaceContext implements NamespaceContext { - private Map prefixToNamespaceUri = new LinkedHashMap(); + private Map prefixToNamespaceUri = new LinkedHashMap(); - private Map> namespaceUriToPrefixes = new LinkedHashMap>(); + private Map> namespaceUriToPrefixes = new LinkedHashMap>(); - @Override - public String getNamespaceURI(String prefix) { - Assert.notNull(prefix, "prefix is null"); - if (XMLConstants.XML_NS_PREFIX.equals(prefix)) { - return XMLConstants.XML_NS_URI; - } - else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { - return XMLConstants.XMLNS_ATTRIBUTE_NS_URI; - } - else if (prefixToNamespaceUri.containsKey(prefix)) { - return prefixToNamespaceUri.get(prefix); - } - return XMLConstants.NULL_NS_URI; - } + @Override + public String getNamespaceURI(String prefix) { + Assert.notNull(prefix, "prefix is null"); + if (XMLConstants.XML_NS_PREFIX.equals(prefix)) { + return XMLConstants.XML_NS_URI; + } + else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { + return XMLConstants.XMLNS_ATTRIBUTE_NS_URI; + } + else if (prefixToNamespaceUri.containsKey(prefix)) { + return prefixToNamespaceUri.get(prefix); + } + return XMLConstants.NULL_NS_URI; + } - @Override - public String getPrefix(String namespaceUri) { - Iterator iterator = getPrefixes(namespaceUri); - return iterator.hasNext() ? iterator.next() : null; - } + @Override + public String getPrefix(String namespaceUri) { + Iterator iterator = getPrefixes(namespaceUri); + return iterator.hasNext() ? iterator.next() : null; + } - @Override - public Iterator getPrefixes(String namespaceUri) { - Set prefixes = getPrefixesInternal(namespaceUri); - prefixes = Collections.unmodifiableSet(prefixes); - return prefixes.iterator(); - } + @Override + public Iterator getPrefixes(String namespaceUri) { + Set prefixes = getPrefixesInternal(namespaceUri); + prefixes = Collections.unmodifiableSet(prefixes); + return prefixes.iterator(); + } - /** - * Sets the bindings for this namespace context. The supplied map must consist of string key value pairs. - * - * @param bindings the bindings - */ - public void setBindings(Map bindings) { - for (Map.Entry entry : bindings.entrySet()) { - bindNamespaceUri(entry.getKey(), entry.getValue()); - } - } + /** + * Sets the bindings for this namespace context. The supplied map must consist of string key value pairs. + * + * @param bindings the bindings + */ + public void setBindings(Map bindings) { + for (Map.Entry entry : bindings.entrySet()) { + bindNamespaceUri(entry.getKey(), entry.getValue()); + } + } - /** - * Binds the given namespace as default namespace. - * - * @param namespaceUri the namespace uri - */ - public void bindDefaultNamespaceUri(String namespaceUri) { - bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, namespaceUri); - } + /** + * Binds the given namespace as default namespace. + * + * @param namespaceUri the namespace uri + */ + public void bindDefaultNamespaceUri(String namespaceUri) { + bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, namespaceUri); + } - /** - * Binds the given prefix to the given namespace. - * - * @param prefix the namespace prefix - * @param namespaceUri the namespace uri - */ - public void bindNamespaceUri(String prefix, String namespaceUri) { - Assert.notNull(prefix, "No prefix given"); - Assert.notNull(namespaceUri, "No namespaceUri given"); - if (XMLConstants.XML_NS_PREFIX.equals(prefix)) { - Assert.isTrue(XMLConstants.XML_NS_URI.equals(namespaceUri), "Prefix \"" + prefix + - "\" bound to namespace \"" + namespaceUri + "\" (should be \"" + XMLConstants.XML_NS_URI + "\")"); - } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { - Assert.isTrue(XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri), "Prefix \"" + prefix + - "\" bound to namespace \"" + namespaceUri + "\" (should be \"" + - XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "\")"); - } - else { - prefixToNamespaceUri.put(prefix, namespaceUri); - getPrefixesInternal(namespaceUri).add(prefix); - } - } + /** + * Binds the given prefix to the given namespace. + * + * @param prefix the namespace prefix + * @param namespaceUri the namespace uri + */ + public void bindNamespaceUri(String prefix, String namespaceUri) { + Assert.notNull(prefix, "No prefix given"); + Assert.notNull(namespaceUri, "No namespaceUri given"); + if (XMLConstants.XML_NS_PREFIX.equals(prefix)) { + Assert.isTrue(XMLConstants.XML_NS_URI.equals(namespaceUri), "Prefix \"" + prefix + + "\" bound to namespace \"" + namespaceUri + "\" (should be \"" + XMLConstants.XML_NS_URI + "\")"); + } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { + Assert.isTrue(XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri), "Prefix \"" + prefix + + "\" bound to namespace \"" + namespaceUri + "\" (should be \"" + + XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "\")"); + } + else { + prefixToNamespaceUri.put(prefix, namespaceUri); + getPrefixesInternal(namespaceUri).add(prefix); + } + } - /** Removes all declared prefixes. */ - public void clear() { - prefixToNamespaceUri.clear(); - namespaceUriToPrefixes.clear(); - } + /** Removes all declared prefixes. */ + public void clear() { + prefixToNamespaceUri.clear(); + namespaceUriToPrefixes.clear(); + } - /** - * Returns all declared prefixes. - * - * @return the declared prefixes - */ - public Iterator getBoundPrefixes() { - Set prefixes = new HashSet(prefixToNamespaceUri.keySet()); - prefixes.remove(XMLConstants.DEFAULT_NS_PREFIX); - prefixes = Collections.unmodifiableSet(prefixes); - return prefixes.iterator(); - } + /** + * Returns all declared prefixes. + * + * @return the declared prefixes + */ + public Iterator getBoundPrefixes() { + Set prefixes = new HashSet(prefixToNamespaceUri.keySet()); + prefixes.remove(XMLConstants.DEFAULT_NS_PREFIX); + prefixes = Collections.unmodifiableSet(prefixes); + return prefixes.iterator(); + } - private Set getPrefixesInternal(String namespaceUri) { - if (XMLConstants.XML_NS_URI.equals(namespaceUri)) { - return Collections.singleton(XMLConstants.XML_NS_PREFIX); - } - else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) { - return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE); - } - else { - Set set = namespaceUriToPrefixes.get(namespaceUri); - if (set == null) { - set = new LinkedHashSet(); - namespaceUriToPrefixes.put(namespaceUri, set); - } - return set; - } - } + private Set getPrefixesInternal(String namespaceUri) { + if (XMLConstants.XML_NS_URI.equals(namespaceUri)) { + return Collections.singleton(XMLConstants.XML_NS_PREFIX); + } + else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) { + return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE); + } + else { + Set set = namespaceUriToPrefixes.get(namespaceUri); + if (set == null) { + set = new LinkedHashSet(); + namespaceUriToPrefixes.put(namespaceUri, set); + } + return set; + } + } - /** - * Removes the given prefix from this context. - * - * @param prefix the prefix to be removed - */ - public void removeBinding(String prefix) { - String namespaceUri = prefixToNamespaceUri.remove(prefix); - if (namespaceUri != null) { - Set prefixes = getPrefixesInternal(namespaceUri); - prefixes.remove(prefix); - } - } + /** + * Removes the given prefix from this context. + * + * @param prefix the prefix to be removed + */ + public void removeBinding(String prefix) { + String namespaceUri = prefixToNamespaceUri.remove(prefix); + if (namespaceUri != null) { + Set prefixes = getPrefixesInternal(namespaceUri); + prefixes.remove(prefix); + } + } - public boolean hasBinding(String prefix) { - return prefixToNamespaceUri.containsKey(prefix); - } + public boolean hasBinding(String prefix) { + return prefixToNamespaceUri.containsKey(prefix); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/sax/AbstractXmlReader.java b/spring-xml/src/main/java/org/springframework/xml/sax/AbstractXmlReader.java index 968c9365..7b52866a 100644 --- a/spring-xml/src/main/java/org/springframework/xml/sax/AbstractXmlReader.java +++ b/spring-xml/src/main/java/org/springframework/xml/sax/AbstractXmlReader.java @@ -38,106 +38,106 @@ import org.xml.sax.ext.LexicalHandler; */ public abstract class AbstractXmlReader implements XMLReader { - private DTDHandler dtdHandler; + private DTDHandler dtdHandler; - private ContentHandler contentHandler; + private ContentHandler contentHandler; - private EntityResolver entityResolver; + private EntityResolver entityResolver; - private ErrorHandler errorHandler; + private ErrorHandler errorHandler; - private LexicalHandler lexicalHandler; + private LexicalHandler lexicalHandler; - @Override - public ContentHandler getContentHandler() { - return contentHandler; - } + @Override + public ContentHandler getContentHandler() { + return contentHandler; + } - @Override - public void setContentHandler(ContentHandler contentHandler) { - this.contentHandler = contentHandler; - } + @Override + public void setContentHandler(ContentHandler contentHandler) { + this.contentHandler = contentHandler; + } - @Override - public void setDTDHandler(DTDHandler dtdHandler) { - this.dtdHandler = dtdHandler; - } + @Override + public void setDTDHandler(DTDHandler dtdHandler) { + this.dtdHandler = dtdHandler; + } - @Override - public DTDHandler getDTDHandler() { - return dtdHandler; - } + @Override + public DTDHandler getDTDHandler() { + return dtdHandler; + } - @Override - public EntityResolver getEntityResolver() { - return entityResolver; - } + @Override + public EntityResolver getEntityResolver() { + return entityResolver; + } - @Override - public void setEntityResolver(EntityResolver entityResolver) { - this.entityResolver = entityResolver; - } + @Override + public void setEntityResolver(EntityResolver entityResolver) { + this.entityResolver = entityResolver; + } - @Override - public ErrorHandler getErrorHandler() { - return errorHandler; - } + @Override + public ErrorHandler getErrorHandler() { + return errorHandler; + } - @Override - public void setErrorHandler(ErrorHandler errorHandler) { - this.errorHandler = errorHandler; - } + @Override + public void setErrorHandler(ErrorHandler errorHandler) { + this.errorHandler = errorHandler; + } - protected LexicalHandler getLexicalHandler() { - return lexicalHandler; - } + protected LexicalHandler getLexicalHandler() { + return lexicalHandler; + } - /** - * Throws a {@code SAXNotRecognizedException} exception. - * - * @throws org.xml.sax.SAXNotRecognizedException - * always - */ - @Override - public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { - throw new SAXNotRecognizedException(name); - } + /** + * Throws a {@code SAXNotRecognizedException} exception. + * + * @throws org.xml.sax.SAXNotRecognizedException + * always + */ + @Override + public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { + throw new SAXNotRecognizedException(name); + } - /** - * Throws a {@code SAXNotRecognizedException} exception. - * - * @throws SAXNotRecognizedException always - */ - @Override - public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { - throw new SAXNotRecognizedException(name); - } + /** + * Throws a {@code SAXNotRecognizedException} exception. + * + * @throws SAXNotRecognizedException always + */ + @Override + public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { + throw new SAXNotRecognizedException(name); + } - /** - * Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical - * handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}. - */ - @Override - public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { - if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { - return lexicalHandler; - } - else { - throw new SAXNotRecognizedException(name); - } - } + /** + * Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical + * handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}. + */ + @Override + public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { + if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { + return lexicalHandler; + } + else { + throw new SAXNotRecognizedException(name); + } + } - /** - * Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical - * handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}. - */ - @Override - public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { - if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { - lexicalHandler = (LexicalHandler) value; - } - else { - throw new SAXNotRecognizedException(name); - } - } + /** + * Throws a {@code SAXNotRecognizedException} exception when the given property does not signify a lexical + * handler. The property name for a lexical handler is {@code http://xml.org/sax/properties/lexical-handler}. + */ + @Override + public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { + if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { + lexicalHandler = (LexicalHandler) value; + } + else { + throw new SAXNotRecognizedException(name); + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/sax/SaxUtils.java b/spring-xml/src/main/java/org/springframework/xml/sax/SaxUtils.java index b278ee20..7ca5dbf9 100644 --- a/spring-xml/src/main/java/org/springframework/xml/sax/SaxUtils.java +++ b/spring-xml/src/main/java/org/springframework/xml/sax/SaxUtils.java @@ -34,37 +34,37 @@ import org.xml.sax.InputSource; */ public abstract class SaxUtils { - private static final Log logger = LogFactory.getLog(SaxUtils.class); + private static final Log logger = LogFactory.getLog(SaxUtils.class); - /** - * Creates a SAX {@code InputSource} from the given resource. Sets the system identifier to the resource's - * {@code URL}, if available. - * - * @param resource the resource - * @return the input source created from the resource - * @throws IOException if an I/O exception occurs - * @see InputSource#setSystemId(String) - * @see #getSystemId(org.springframework.core.io.Resource) - */ - public static InputSource createInputSource(Resource resource) throws IOException { - InputSource inputSource = new InputSource(resource.getInputStream()); - inputSource.setSystemId(getSystemId(resource)); - return inputSource; - } + /** + * Creates a SAX {@code InputSource} from the given resource. Sets the system identifier to the resource's + * {@code URL}, if available. + * + * @param resource the resource + * @return the input source created from the resource + * @throws IOException if an I/O exception occurs + * @see InputSource#setSystemId(String) + * @see #getSystemId(org.springframework.core.io.Resource) + */ + public static InputSource createInputSource(Resource resource) throws IOException { + InputSource inputSource = new InputSource(resource.getInputStream()); + inputSource.setSystemId(getSystemId(resource)); + return inputSource; + } - /** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */ - public static String getSystemId(Resource resource) { - try { - return new URI(resource.getURL().toExternalForm()).toString(); - } - catch (IOException ex) { - logger.debug("Could not get System ID from [" + resource + "], ex"); - return null; - } - catch (URISyntaxException e) { - logger.debug("Could not get System ID from [" + resource + "], ex"); - return null; - } - } + /** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */ + public static String getSystemId(Resource resource) { + try { + return new URI(resource.getURL().toExternalForm()).toString(); + } + catch (IOException ex) { + logger.debug("Could not get System ID from [" + resource + "], ex"); + return null; + } + catch (URISyntaxException e) { + logger.debug("Could not get System ID from [" + resource + "], ex"); + return null; + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/transform/ResourceSource.java b/spring-xml/src/main/java/org/springframework/xml/transform/ResourceSource.java index 0a68a0f5..70217597 100644 --- a/spring-xml/src/main/java/org/springframework/xml/transform/ResourceSource.java +++ b/spring-xml/src/main/java/org/springframework/xml/transform/ResourceSource.java @@ -33,21 +33,21 @@ import org.xml.sax.XMLReader; */ public class ResourceSource extends SAXSource { - /** - * Initializes a new instance of the {@code ResourceSource} with the given resource. - * - * @param content the content - */ - public ResourceSource(Resource content) throws IOException { - super(SaxUtils.createInputSource(content)); - } + /** + * Initializes a new instance of the {@code ResourceSource} with the given resource. + * + * @param content the content + */ + public ResourceSource(Resource content) throws IOException { + super(SaxUtils.createInputSource(content)); + } - /** - * Initializes a new instance of the {@code ResourceSource} with the given {@link XMLReader} and resource. - * - * @param content the content - */ - public ResourceSource(XMLReader reader, Resource content) throws IOException { - super(reader, SaxUtils.createInputSource(content)); - } + /** + * Initializes a new instance of the {@code ResourceSource} with the given {@link XMLReader} and resource. + * + * @param content the content + */ + public ResourceSource(XMLReader reader, Resource content) throws IOException { + super(reader, SaxUtils.createInputSource(content)); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/transform/StringResult.java b/spring-xml/src/main/java/org/springframework/xml/transform/StringResult.java index bb1e7147..ca03ebc3 100644 --- a/spring-xml/src/main/java/org/springframework/xml/transform/StringResult.java +++ b/spring-xml/src/main/java/org/springframework/xml/transform/StringResult.java @@ -29,13 +29,13 @@ import javax.xml.transform.stream.StreamResult; */ public class StringResult extends StreamResult { - public StringResult() { - super(new StringWriter()); - } + public StringResult() { + super(new StringWriter()); + } - /** Returns the written XML as a string. */ - public String toString() { - return getWriter().toString(); - } + /** Returns the written XML as a string. */ + public String toString() { + return getWriter().toString(); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/transform/StringSource.java b/spring-xml/src/main/java/org/springframework/xml/transform/StringSource.java index 6b87da25..99459238 100644 --- a/spring-xml/src/main/java/org/springframework/xml/transform/StringSource.java +++ b/spring-xml/src/main/java/org/springframework/xml/transform/StringSource.java @@ -32,55 +32,55 @@ import org.springframework.util.Assert; */ public class StringSource extends StreamSource { - private final String content; + private final String content; - /** - * Initializes a new instance of the {@code StringSource} with the given string content. - * - * @param content the content - */ - public StringSource(String content) { - Assert.notNull(content, "'content' must not be null"); - this.content = content; - } + /** + * Initializes a new instance of the {@code StringSource} with the given string content. + * + * @param content the content + */ + public StringSource(String content) { + Assert.notNull(content, "'content' must not be null"); + this.content = content; + } - @Override - public Reader getReader() { - return new StringReader(content); - } + @Override + public Reader getReader() { + return new StringReader(content); + } - /** - * Throws {@link UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - public void setInputStream(InputStream inputStream) { - throw new UnsupportedOperationException("setInputStream is not supported"); - } + /** + * Throws {@link UnsupportedOperationException}. + * + * @throws UnsupportedOperationException always + */ + @Override + public void setInputStream(InputStream inputStream) { + throw new UnsupportedOperationException("setInputStream is not supported"); + } - /** - * Returns {@code null}. - * - * @return {@code null} - */ - @Override - public InputStream getInputStream() { - return null; - } + /** + * Returns {@code null}. + * + * @return {@code null} + */ + @Override + public InputStream getInputStream() { + return null; + } - /** - * Throws {@link UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - public void setReader(Reader reader) { - throw new UnsupportedOperationException("setReader is not supported"); - } + /** + * Throws {@link UnsupportedOperationException}. + * + * @throws UnsupportedOperationException always + */ + @Override + public void setReader(Reader reader) { + throw new UnsupportedOperationException("setReader is not supported"); + } - @Override - public String toString() { - return content; - } + @Override + public String toString() { + return content; + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/transform/TransformerHelper.java b/spring-xml/src/main/java/org/springframework/xml/transform/TransformerHelper.java index 0898ee96..14de3faa 100644 --- a/spring-xml/src/main/java/org/springframework/xml/transform/TransformerHelper.java +++ b/spring-xml/src/main/java/org/springframework/xml/transform/TransformerHelper.java @@ -35,107 +35,107 @@ import org.springframework.util.Assert; */ public class TransformerHelper { - private volatile TransformerFactory transformerFactory; + private volatile TransformerFactory transformerFactory; - private Class transformerFactoryClass; + private Class transformerFactoryClass; - /** - * Initializes a new instance of the {@code TransformerHelper}. - */ - public TransformerHelper() { - } + /** + * Initializes a new instance of the {@code TransformerHelper}. + */ + public TransformerHelper() { + } - /** - * Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory}. - */ - public TransformerHelper(TransformerFactory transformerFactory) { - this.transformerFactory = transformerFactory; - } + /** + * Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory}. + */ + public TransformerHelper(TransformerFactory transformerFactory) { + this.transformerFactory = transformerFactory; + } - /** - * Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory} class. - */ - public TransformerHelper(Class transformerFactoryClass) { - setTransformerFactoryClass(transformerFactoryClass); - } + /** + * Initializes a new instance of the {@code TransformerHelper} with the specified {@link TransformerFactory} class. + */ + public TransformerHelper(Class transformerFactoryClass) { + setTransformerFactoryClass(transformerFactoryClass); + } - /** - * Specify the {@code TransformerFactory} class to use. - */ - public void setTransformerFactoryClass(Class transformerFactoryClass) { - Assert.isAssignable(TransformerFactory.class, transformerFactoryClass); - this.transformerFactoryClass = transformerFactoryClass; - } + /** + * Specify the {@code TransformerFactory} class to use. + */ + public void setTransformerFactoryClass(Class transformerFactoryClass) { + Assert.isAssignable(TransformerFactory.class, transformerFactoryClass); + this.transformerFactoryClass = transformerFactoryClass; + } - /** - * Instantiate a new TransformerFactory. - * - *

The default implementation simply calls {@link TransformerFactory#newInstance()}. If a {@link - * #setTransformerFactoryClass transformerFactoryClass} has been specified explicitly, the default constructor of - * the specified class will be called instead. - * - *

Can be overridden in subclasses. - * - * @param transformerFactoryClass the specified factory class (if any) - * @return the new TransactionFactory instance - * @see #setTransformerFactoryClass - * @see #getTransformerFactory() - */ - protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) { - if (transformerFactoryClass != null) { - try { - return transformerFactoryClass.newInstance(); - } - catch (Exception ex) { - throw new TransformerFactoryConfigurationError(ex, - "Could not instantiate TransformerFactory [" + transformerFactoryClass + "]"); - } - } - else { - return TransformerFactory.newInstance(); - } - } + /** + * Instantiate a new TransformerFactory. + * + *

The default implementation simply calls {@link TransformerFactory#newInstance()}. If a {@link + * #setTransformerFactoryClass transformerFactoryClass} has been specified explicitly, the default constructor of + * the specified class will be called instead. + * + *

Can be overridden in subclasses. + * + * @param transformerFactoryClass the specified factory class (if any) + * @return the new TransactionFactory instance + * @see #setTransformerFactoryClass + * @see #getTransformerFactory() + */ + protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) { + if (transformerFactoryClass != null) { + try { + return transformerFactoryClass.newInstance(); + } + catch (Exception ex) { + throw new TransformerFactoryConfigurationError(ex, + "Could not instantiate TransformerFactory [" + transformerFactoryClass + "]"); + } + } + else { + return TransformerFactory.newInstance(); + } + } - /** - * Returns the {@code TransformerFactory}. - * - * @return the transformer factory - */ - public TransformerFactory getTransformerFactory() { - TransformerFactory result = transformerFactory; - if (result == null) { - synchronized (this) { - result = transformerFactory; - if (result == null) { - transformerFactory = result = newTransformerFactory(transformerFactoryClass); - } - } - } - return result; - } + /** + * Returns the {@code TransformerFactory}. + * + * @return the transformer factory + */ + public TransformerFactory getTransformerFactory() { + TransformerFactory result = transformerFactory; + if (result == null) { + synchronized (this) { + result = transformerFactory; + if (result == null) { + transformerFactory = result = newTransformerFactory(transformerFactoryClass); + } + } + } + return result; + } - /** - * Creates a new {@code Transformer}. Must be called per thread, as transformers are not thread-safe. - * - * @return the created transformer - * @throws TransformerConfigurationException - * if thrown by JAXP methods - */ - public Transformer createTransformer() throws TransformerConfigurationException { - return getTransformerFactory().newTransformer(); - } + /** + * Creates a new {@code Transformer}. Must be called per thread, as transformers are not thread-safe. + * + * @return the created transformer + * @throws TransformerConfigurationException + * if thrown by JAXP methods + */ + public Transformer createTransformer() throws TransformerConfigurationException { + return getTransformerFactory().newTransformer(); + } - /** - * Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every - * call, as transformers are not thread-safe. - * - * @param source the source to transform from - * @param result the result to transform to - * @throws TransformerException if thrown by JAXP methods - */ - public void transform(Source source, Result result) throws TransformerException { - Transformer transformer = createTransformer(); - transformer.transform(source, result); - } + /** + * Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every + * call, as transformers are not thread-safe. + * + * @param source the source to transform from + * @param result the result to transform to + * @throws TransformerException if thrown by JAXP methods + */ + public void transform(Source source, Result result) throws TransformerException { + Transformer transformer = createTransformer(); + transformer.transform(source, result); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/transform/TransformerObjectSupport.java b/spring-xml/src/main/java/org/springframework/xml/transform/TransformerObjectSupport.java index 1714ae25..0ef62c60 100644 --- a/spring-xml/src/main/java/org/springframework/xml/transform/TransformerObjectSupport.java +++ b/spring-xml/src/main/java/org/springframework/xml/transform/TransformerObjectSupport.java @@ -37,63 +37,63 @@ import org.apache.commons.logging.LogFactory; */ public abstract class TransformerObjectSupport { - /** - * Logger available to subclasses. - */ - protected final Log logger = LogFactory.getLog(getClass()); + /** + * Logger available to subclasses. + */ + protected final Log logger = LogFactory.getLog(getClass()); - private TransformerHelper transformerHelper = new TransformerHelper(); + private TransformerHelper transformerHelper = new TransformerHelper(); - /** - * Specify the {@code TransformerFactory} class to use. - */ - public void setTransformerFactoryClass(Class transformerFactoryClass) { - transformerHelper.setTransformerFactoryClass(transformerFactoryClass); - } + /** + * Specify the {@code TransformerFactory} class to use. + */ + public void setTransformerFactoryClass(Class transformerFactoryClass) { + transformerHelper.setTransformerFactoryClass(transformerFactoryClass); + } - /** - * Instantiate a new TransformerFactory.

The default implementation simply calls {@link - * TransformerFactory#newInstance()}. If a {@link #setTransformerFactoryClass "transformerFactoryClass"} has been - * specified explicitly, the default constructor of the specified class will be called instead.

Can be overridden - * in subclasses. - * - * @param transformerFactoryClass the specified factory class (if any) - * @return the new TransactionFactory instance - * @see #setTransformerFactoryClass - * @see #getTransformerFactory() - */ - protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) { - return transformerHelper.newTransformerFactory(transformerFactoryClass); - } + /** + * Instantiate a new TransformerFactory.

The default implementation simply calls {@link + * TransformerFactory#newInstance()}. If a {@link #setTransformerFactoryClass "transformerFactoryClass"} has been + * specified explicitly, the default constructor of the specified class will be called instead.

Can be overridden + * in subclasses. + * + * @param transformerFactoryClass the specified factory class (if any) + * @return the new TransactionFactory instance + * @see #setTransformerFactoryClass + * @see #getTransformerFactory() + */ + protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) { + return transformerHelper.newTransformerFactory(transformerFactoryClass); + } - /** - * Returns the {@code TransformerFactory}. - */ - protected TransformerFactory getTransformerFactory() { - return transformerHelper.getTransformerFactory(); - } + /** + * Returns the {@code TransformerFactory}. + */ + protected TransformerFactory getTransformerFactory() { + return transformerHelper.getTransformerFactory(); + } - /** - * Creates a new {@code Transformer}. Must be called per request, as transformers are not thread-safe. - * - * @return the created transformer - * @throws TransformerConfigurationException - * if thrown by JAXP methods - */ - protected final Transformer createTransformer() throws TransformerConfigurationException { - return transformerHelper.createTransformer(); - } + /** + * Creates a new {@code Transformer}. Must be called per request, as transformers are not thread-safe. + * + * @return the created transformer + * @throws TransformerConfigurationException + * if thrown by JAXP methods + */ + protected final Transformer createTransformer() throws TransformerConfigurationException { + return transformerHelper.createTransformer(); + } - /** - * Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every - * call, as transformers are not thread-safe. - * - * @param source the source to transform from - * @param result the result to transform to - * @throws TransformerException if thrown by JAXP methods - */ - protected final void transform(Source source, Result result) throws TransformerException { - transformerHelper.transform(source, result); - } + /** + * Transforms the given {@link Source} to the given {@link Result}. Creates a new {@link Transformer} for every + * call, as transformers are not thread-safe. + * + * @param source the source to transform from + * @param result the result to transform to + * @throws TransformerException if thrown by JAXP methods + */ + protected final void transform(Source source, Result result) throws TransformerException { + transformerHelper.transform(source, result); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/transform/TraxUtils.java b/spring-xml/src/main/java/org/springframework/xml/transform/TraxUtils.java index b7f0195f..be216674 100644 --- a/spring-xml/src/main/java/org/springframework/xml/transform/TraxUtils.java +++ b/spring-xml/src/main/java/org/springframework/xml/transform/TraxUtils.java @@ -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, @@ -53,250 +53,250 @@ import org.xml.sax.ext.LexicalHandler; */ public abstract class TraxUtils { - /** - * Returns the {@link Document} of the given {@link DOMSource}. - * - * @param source the DOM source - * @return the document - */ - public static Document getDocument(DOMSource source) { - Node node = source.getNode(); - if (node instanceof Document) { - return (Document) node; - } - else if (node != null) { - return node.getOwnerDocument(); - } - else { - return null; - } - } + /** + * Returns the {@link Document} of the given {@link DOMSource}. + * + * @param source the DOM source + * @return the document + */ + public static Document getDocument(DOMSource source) { + Node node = source.getNode(); + if (node instanceof Document) { + return (Document) node; + } + else if (node != null) { + return node.getOwnerDocument(); + } + else { + return null; + } + } - /** - * Performs the given {@linkplain SourceCallback callback} operation on a {@link Source}. Supports both the JAXP 1.4 - * {@link StAXSource} and the Spring 3.0 {@link StaxUtils#createStaxSource StaxSource}. - * - * @param source source to look at - * @param callback the callback to invoke for each kind of source - */ - public static void doWithSource(Source source, SourceCallback callback) throws Exception { - if (source instanceof DOMSource) { - callback.domSource(((DOMSource) source).getNode()); - return; - } - else if (StaxUtils.isStaxSource(source)) { - XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(source); - if (streamReader != null) { - callback.staxSource(streamReader); - return; - } - else { - XMLEventReader eventReader = StaxUtils.getXMLEventReader(source); - if (eventReader != null) { - callback.staxSource(eventReader); - return; - } - } - } - else if (source instanceof SAXSource) { - SAXSource saxSource = (SAXSource) source; - callback.saxSource(saxSource.getXMLReader(), saxSource.getInputSource()); - return; - } - else if (source instanceof StreamSource) { - StreamSource streamSource = (StreamSource) source; - if (streamSource.getInputStream() != null) { - callback.streamSource(streamSource.getInputStream()); - return; - } - else if (streamSource.getReader() != null) { - callback.streamSource(streamSource.getReader()); - return; - } - } - if (StringUtils.hasLength(source.getSystemId())) { - String systemId = source.getSystemId(); - callback.source(systemId); - } - else { - throw new IllegalArgumentException("Unknown Source type: " + source.getClass()); - } - } + /** + * Performs the given {@linkplain SourceCallback callback} operation on a {@link Source}. Supports both the JAXP 1.4 + * {@link StAXSource} and the Spring 3.0 {@link StaxUtils#createStaxSource StaxSource}. + * + * @param source source to look at + * @param callback the callback to invoke for each kind of source + */ + public static void doWithSource(Source source, SourceCallback callback) throws Exception { + if (source instanceof DOMSource) { + callback.domSource(((DOMSource) source).getNode()); + return; + } + else if (StaxUtils.isStaxSource(source)) { + XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(source); + if (streamReader != null) { + callback.staxSource(streamReader); + return; + } + else { + XMLEventReader eventReader = StaxUtils.getXMLEventReader(source); + if (eventReader != null) { + callback.staxSource(eventReader); + return; + } + } + } + else if (source instanceof SAXSource) { + SAXSource saxSource = (SAXSource) source; + callback.saxSource(saxSource.getXMLReader(), saxSource.getInputSource()); + return; + } + else if (source instanceof StreamSource) { + StreamSource streamSource = (StreamSource) source; + if (streamSource.getInputStream() != null) { + callback.streamSource(streamSource.getInputStream()); + return; + } + else if (streamSource.getReader() != null) { + callback.streamSource(streamSource.getReader()); + return; + } + } + if (StringUtils.hasLength(source.getSystemId())) { + String systemId = source.getSystemId(); + callback.source(systemId); + } + else { + throw new IllegalArgumentException("Unknown Source type: " + source.getClass()); + } + } - /** - * Performs the given {@linkplain org.springframework.xml.transform.TraxUtils.ResultCallback callback} operation on a {@link javax.xml.transform.Result}. Supports both the JAXP 1.4 - * {@link javax.xml.transform.stax.StAXResult} and the Spring 3.0 {@link org.springframework.util.xml.StaxUtils#createStaxResult StaxSource}. - * - * @param result result to look at - * @param callback the callback to invoke for each kind of result - */ - public static void doWithResult(Result result, ResultCallback callback) throws Exception { - if (result instanceof DOMResult) { - callback.domResult(((DOMResult) result).getNode()); - return; - } - else if (StaxUtils.isStaxResult(result)) { - XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(result); - if (streamWriter != null) { - callback.staxResult(streamWriter); - return; - } - else { - XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(result); - if (eventWriter != null) { - callback.staxResult(eventWriter); - return; - } - } - } - else if (result instanceof SAXResult) { - SAXResult saxSource = (SAXResult) result; - callback.saxResult(saxSource.getHandler(), saxSource.getLexicalHandler()); - return; - } - else if (result instanceof StreamResult) { - StreamResult streamSource = (StreamResult) result; - if (streamSource.getOutputStream() != null) { - callback.streamResult(streamSource.getOutputStream()); - return; - } - else if (streamSource.getWriter() != null) { - callback.streamResult(streamSource.getWriter()); - return; - } - } - if (StringUtils.hasLength(result.getSystemId())) { - String systemId = result.getSystemId(); - callback.result(systemId); - } - else { - throw new IllegalArgumentException("Unknown Result type: " + result.getClass()); - } - } + /** + * Performs the given {@linkplain org.springframework.xml.transform.TraxUtils.ResultCallback callback} operation on a {@link javax.xml.transform.Result}. Supports both the JAXP 1.4 + * {@link javax.xml.transform.stax.StAXResult} and the Spring 3.0 {@link org.springframework.util.xml.StaxUtils#createStaxResult StaxSource}. + * + * @param result result to look at + * @param callback the callback to invoke for each kind of result + */ + public static void doWithResult(Result result, ResultCallback callback) throws Exception { + if (result instanceof DOMResult) { + callback.domResult(((DOMResult) result).getNode()); + return; + } + else if (StaxUtils.isStaxResult(result)) { + XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(result); + if (streamWriter != null) { + callback.staxResult(streamWriter); + return; + } + else { + XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(result); + if (eventWriter != null) { + callback.staxResult(eventWriter); + return; + } + } + } + else if (result instanceof SAXResult) { + SAXResult saxSource = (SAXResult) result; + callback.saxResult(saxSource.getHandler(), saxSource.getLexicalHandler()); + return; + } + else if (result instanceof StreamResult) { + StreamResult streamSource = (StreamResult) result; + if (streamSource.getOutputStream() != null) { + callback.streamResult(streamSource.getOutputStream()); + return; + } + else if (streamSource.getWriter() != null) { + callback.streamResult(streamSource.getWriter()); + return; + } + } + if (StringUtils.hasLength(result.getSystemId())) { + String systemId = result.getSystemId(); + callback.result(systemId); + } + else { + throw new IllegalArgumentException("Unknown Result type: " + result.getClass()); + } + } - /** - * Callback interface invoked on each sort of {@link Source}. - * - * @see TraxUtils#doWithSource(Source, SourceCallback) - */ - public interface SourceCallback { + /** + * Callback interface invoked on each sort of {@link Source}. + * + * @see TraxUtils#doWithSource(Source, SourceCallback) + */ + public interface SourceCallback { - /** - * Perform an operation on the node contained in a {@link DOMSource}. - * - * @param node the node - */ - void domSource(Node node) throws Exception; + /** + * Perform an operation on the node contained in a {@link DOMSource}. + * + * @param node the node + */ + void domSource(Node node) throws Exception; - /** - * Perform an operation on the {@code XMLReader} and {@code InputSource} contained in a {@link SAXSource}. - * - * @param reader the reader, can be {@code null} - * @param inputSource the input source, can be {@code null} - */ - void saxSource(XMLReader reader, InputSource inputSource) throws Exception; + /** + * Perform an operation on the {@code XMLReader} and {@code InputSource} contained in a {@link SAXSource}. + * + * @param reader the reader, can be {@code null} + * @param inputSource the input source, can be {@code null} + */ + void saxSource(XMLReader reader, InputSource inputSource) throws Exception; - /** - * Perform an operation on the {@code XMLEventReader} contained in a JAXP 1.4 {@link StAXSource} or Spring - * {@link StaxUtils#createStaxSource StaxSource}. - * - * @param eventReader the reader - */ - void staxSource(XMLEventReader eventReader) throws Exception; + /** + * Perform an operation on the {@code XMLEventReader} contained in a JAXP 1.4 {@link StAXSource} or Spring + * {@link StaxUtils#createStaxSource StaxSource}. + * + * @param eventReader the reader + */ + void staxSource(XMLEventReader eventReader) throws Exception; - /** - * Perform an operation on the {@code XMLStreamReader} contained in a JAXP 1.4 {@link StAXSource} or Spring - * {@link StaxUtils#createStaxSource StaxSource}. - * - * @param streamReader the reader - */ - void staxSource(XMLStreamReader streamReader) throws Exception; + /** + * Perform an operation on the {@code XMLStreamReader} contained in a JAXP 1.4 {@link StAXSource} or Spring + * {@link StaxUtils#createStaxSource StaxSource}. + * + * @param streamReader the reader + */ + void staxSource(XMLStreamReader streamReader) throws Exception; - /** - * Perform an operation on the {@code InputStream} contained in a {@link StreamSource}. - * - * @param inputStream the input stream - */ - void streamSource(InputStream inputStream) throws Exception; + /** + * Perform an operation on the {@code InputStream} contained in a {@link StreamSource}. + * + * @param inputStream the input stream + */ + void streamSource(InputStream inputStream) throws Exception; - /** - * Perform an operation on the {@code Reader} contained in a {@link StreamSource}. - * - * @param reader the reader - */ - void streamSource(Reader reader) throws Exception; + /** + * Perform an operation on the {@code Reader} contained in a {@link StreamSource}. + * + * @param reader the reader + */ + void streamSource(Reader reader) throws Exception; - /** - * Perform an operation on the system identifier contained in any {@link Source}. - * - * @param systemId the system identifier - */ - void source(String systemId) throws Exception; + /** + * Perform an operation on the system identifier contained in any {@link Source}. + * + * @param systemId the system identifier + */ + void source(String systemId) throws Exception; - } + } - /** - * Callback interface invoked on each sort of {@link Result}. - * - * @see TraxUtils#doWithResult(Result, ResultCallback) - */ - public interface ResultCallback { + /** + * Callback interface invoked on each sort of {@link Result}. + * + * @see TraxUtils#doWithResult(Result, ResultCallback) + */ + public interface ResultCallback { - /** - * Perform an operation on the node contained in a {@link DOMResult}. - * - * @param node the node - */ - void domResult(Node node) throws Exception; + /** + * Perform an operation on the node contained in a {@link DOMResult}. + * + * @param node the node + */ + void domResult(Node node) throws Exception; - /** - * Perform an operation on the {@code ContentHandler} and {@code LexicalHandler} contained in a {@link - * SAXResult}. - * - * @param contentHandler the content handler - * @param lexicalHandler the lexicalHandler, can be {@code null} - */ - void saxResult(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws Exception; + /** + * Perform an operation on the {@code ContentHandler} and {@code LexicalHandler} contained in a {@link + * SAXResult}. + * + * @param contentHandler the content handler + * @param lexicalHandler the lexicalHandler, can be {@code null} + */ + void saxResult(ContentHandler contentHandler, LexicalHandler lexicalHandler) throws Exception; - /** - * Perform an operation on the {@code XMLEventWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring - * {@link StaxUtils#createStaxResult StaxResult}. - * - * @param eventWriter the writer - */ - void staxResult(XMLEventWriter eventWriter) throws Exception; + /** + * Perform an operation on the {@code XMLEventWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring + * {@link StaxUtils#createStaxResult StaxResult}. + * + * @param eventWriter the writer + */ + void staxResult(XMLEventWriter eventWriter) throws Exception; - /** - * Perform an operation on the {@code XMLStreamWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring - * {@link StaxUtils#createStaxResult StaxResult}. - * - * @param streamWriter the writer - */ - void staxResult(XMLStreamWriter streamWriter) throws Exception; + /** + * Perform an operation on the {@code XMLStreamWriter} contained in a JAXP 1.4 {@link StAXResult} or Spring + * {@link StaxUtils#createStaxResult StaxResult}. + * + * @param streamWriter the writer + */ + void staxResult(XMLStreamWriter streamWriter) throws Exception; - /** - * Perform an operation on the {@code OutputStream} contained in a {@link StreamResult}. - * - * @param outputStream the output stream - */ - void streamResult(OutputStream outputStream) throws Exception; + /** + * Perform an operation on the {@code OutputStream} contained in a {@link StreamResult}. + * + * @param outputStream the output stream + */ + void streamResult(OutputStream outputStream) throws Exception; - /** - * Perform an operation on the {@code Writer} contained in a {@link StreamResult}. - * - * @param writer the writer - */ - void streamResult(Writer writer) throws Exception; + /** + * Perform an operation on the {@code Writer} contained in a {@link StreamResult}. + * + * @param writer the writer + */ + void streamResult(Writer writer) throws Exception; - /** - * Perform an operation on the system identifier contained in any {@link Result}. - * - * @param systemId the system identifier - */ - void result(String systemId) throws Exception; + /** + * Perform an operation on the system identifier contained in any {@link Result}. + * + * @param systemId the system identifier + */ + void result(String systemId) throws Exception; - } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/validation/Jaxp13ValidatorFactory.java b/spring-xml/src/main/java/org/springframework/xml/validation/Jaxp13ValidatorFactory.java index f293eb3a..059c3e81 100644 --- a/spring-xml/src/main/java/org/springframework/xml/validation/Jaxp13ValidatorFactory.java +++ b/spring-xml/src/main/java/org/springframework/xml/validation/Jaxp13ValidatorFactory.java @@ -36,68 +36,68 @@ import org.springframework.core.io.Resource; */ abstract class Jaxp13ValidatorFactory { - static XmlValidator createValidator(Resource[] resources, String schemaLanguage) throws IOException { - try { - Schema schema = SchemaLoaderUtils.loadSchema(resources, schemaLanguage); - return new Jaxp13Validator(schema); - } - catch (SAXException ex) { - throw new XmlValidationException("Could not create Schema: " + ex.getMessage(), ex); - } - } + static XmlValidator createValidator(Resource[] resources, String schemaLanguage) throws IOException { + try { + Schema schema = SchemaLoaderUtils.loadSchema(resources, schemaLanguage); + return new Jaxp13Validator(schema); + } + catch (SAXException ex) { + throw new XmlValidationException("Could not create Schema: " + ex.getMessage(), ex); + } + } - private static class Jaxp13Validator implements XmlValidator { + private static class Jaxp13Validator implements XmlValidator { - private Schema schema; + private Schema schema; - public Jaxp13Validator(Schema schema) { - this.schema = schema; - } + public Jaxp13Validator(Schema schema) { + this.schema = schema; + } - @Override - public SAXParseException[] validate(Source source) throws IOException { - return validate(source, null); - } + @Override + public SAXParseException[] validate(Source source) throws IOException { + return validate(source, null); + } - @Override - public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException { - if (errorHandler == null) { - errorHandler = new DefaultValidationErrorHandler(); - } - Validator validator = schema.newValidator(); - validator.setErrorHandler(errorHandler); - try { - validator.validate(source); - return errorHandler.getErrors(); - } - catch (SAXException ex) { - throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex); - } - } - } + @Override + public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException { + if (errorHandler == null) { + errorHandler = new DefaultValidationErrorHandler(); + } + Validator validator = schema.newValidator(); + validator.setErrorHandler(errorHandler); + try { + validator.validate(source); + return errorHandler.getErrors(); + } + catch (SAXException ex) { + throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex); + } + } + } - /** {@code ErrorHandler} implementation that stores errors and fatal errors in a list. */ - private static class DefaultValidationErrorHandler implements ValidationErrorHandler { + /** {@code ErrorHandler} implementation that stores errors and fatal errors in a list. */ + private static class DefaultValidationErrorHandler implements ValidationErrorHandler { - private List errors = new ArrayList(); + private List errors = new ArrayList(); - @Override - public SAXParseException[] getErrors() { - return errors.toArray(new SAXParseException[errors.size()]); - } + @Override + public SAXParseException[] getErrors() { + return errors.toArray(new SAXParseException[errors.size()]); + } - @Override - public void warning(SAXParseException ex) throws SAXException { - } + @Override + public void warning(SAXParseException ex) throws SAXException { + } - @Override - public void error(SAXParseException ex) throws SAXException { - errors.add(ex); - } + @Override + public void error(SAXParseException ex) throws SAXException { + errors.add(ex); + } - @Override - public void fatalError(SAXParseException ex) throws SAXException { - errors.add(ex); - } - } + @Override + public void fatalError(SAXParseException ex) throws SAXException { + errors.add(ex); + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/validation/SchemaLoaderUtils.java b/spring-xml/src/main/java/org/springframework/xml/validation/SchemaLoaderUtils.java index ab737b28..b10966bc 100644 --- a/spring-xml/src/main/java/org/springframework/xml/validation/SchemaLoaderUtils.java +++ b/spring-xml/src/main/java/org/springframework/xml/validation/SchemaLoaderUtils.java @@ -37,54 +37,54 @@ import org.xml.sax.helpers.XMLReaderFactory; */ public abstract class SchemaLoaderUtils { - /** - * Load schema from the given resource. - * - * @param resource the resource to load from - * @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or - * {@code XMLConstants.RELAXNG_NS_URI}. - * @throws IOException if loading failed - * @throws SAXException if loading failed - * @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI - * @see javax.xml.XMLConstants#RELAXNG_NS_URI - */ - public static Schema loadSchema(Resource resource, String schemaLanguage) throws IOException, SAXException { - return loadSchema(new Resource[]{resource}, schemaLanguage); - } + /** + * Load schema from the given resource. + * + * @param resource the resource to load from + * @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or + * {@code XMLConstants.RELAXNG_NS_URI}. + * @throws IOException if loading failed + * @throws SAXException if loading failed + * @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI + * @see javax.xml.XMLConstants#RELAXNG_NS_URI + */ + public static Schema loadSchema(Resource resource, String schemaLanguage) throws IOException, SAXException { + return loadSchema(new Resource[]{resource}, schemaLanguage); + } - /** - * Load schema from the given resource. - * - * @param resources the resources to load from - * @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or - * {@code XMLConstants.RELAXNG_NS_URI}. - * @throws IOException if loading failed - * @throws SAXException if loading failed - * @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI - * @see javax.xml.XMLConstants#RELAXNG_NS_URI - */ - public static Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException { - Assert.notEmpty(resources, "No resources given"); - Assert.hasLength(schemaLanguage, "No schema language provided"); - Source[] schemaSources = new Source[resources.length]; - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); - xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); - for (int i = 0; i < resources.length; i++) { - Assert.notNull(resources[i], "Resource is null"); - Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist"); - schemaSources[i] = new ResourceSource(xmlReader, resources[i]); - } - SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); - return schemaFactory.newSchema(schemaSources); - } + /** + * Load schema from the given resource. + * + * @param resources the resources to load from + * @param schemaLanguage the language of the schema. Can be {@code XMLConstants.W3C_XML_SCHEMA_NS_URI} or + * {@code XMLConstants.RELAXNG_NS_URI}. + * @throws IOException if loading failed + * @throws SAXException if loading failed + * @see javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI + * @see javax.xml.XMLConstants#RELAXNG_NS_URI + */ + public static Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException { + Assert.notEmpty(resources, "No resources given"); + Assert.hasLength(schemaLanguage, "No schema language provided"); + Source[] schemaSources = new Source[resources.length]; + XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + for (int i = 0; i < resources.length; i++) { + Assert.notNull(resources[i], "Resource is null"); + Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist"); + schemaSources[i] = new ResourceSource(xmlReader, resources[i]); + } + SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); + return schemaFactory.newSchema(schemaSources); + } - /** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */ - public static String getSystemId(Resource resource) { - try { - return resource.getURL().toString(); - } - catch (IOException e) { - return null; - } - } + /** Retrieves the URL from the given resource as System ID. Returns {@code null} if it cannot be opened. */ + public static String getSystemId(Resource resource) { + try { + return resource.getURL().toString(); + } + catch (IOException e) { + return null; + } + } } \ No newline at end of file diff --git a/spring-xml/src/main/java/org/springframework/xml/validation/ValidationErrorHandler.java b/spring-xml/src/main/java/org/springframework/xml/validation/ValidationErrorHandler.java index 415a1aa9..80dc3e95 100644 --- a/spring-xml/src/main/java/org/springframework/xml/validation/ValidationErrorHandler.java +++ b/spring-xml/src/main/java/org/springframework/xml/validation/ValidationErrorHandler.java @@ -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,9 +26,9 @@ import org.xml.sax.SAXParseException; */ public interface ValidationErrorHandler extends ErrorHandler { - /** - * Returns the errors collected by this error handler. - * @return the errors - */ - SAXParseException[] getErrors(); + /** + * Returns the errors collected by this error handler. + * @return the errors + */ + SAXParseException[] getErrors(); } diff --git a/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidationException.java b/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidationException.java index 34368a5f..c8d9f96b 100644 --- a/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidationException.java +++ b/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidationException.java @@ -27,11 +27,11 @@ import org.springframework.xml.XmlException; @SuppressWarnings("serial") public class XmlValidationException extends XmlException { - public XmlValidationException(String s) { - super(s); - } + public XmlValidationException(String s) { + super(s); + } - public XmlValidationException(String s, Throwable throwable) { - super(s, throwable); - } + public XmlValidationException(String s, Throwable throwable) { + super(s, throwable); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidator.java b/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidator.java index a314ec08..27c82794 100644 --- a/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidator.java +++ b/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidator.java @@ -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,27 +32,27 @@ import org.xml.sax.SAXParseException; */ public interface XmlValidator { - /** - * Validates the given {@link Source}, and returns an array of {@link SAXParseException}s as result. The array will - * be empty if no validation errors are found. - * - * @param source the input document - * @return an array of {@code SAXParseException}s - * @throws IOException if the {@code source} cannot be read - * @throws XmlValidationException if the {@code source} cannot be validated - */ - SAXParseException[] validate(Source source) throws IOException; + /** + * Validates the given {@link Source}, and returns an array of {@link SAXParseException}s as result. The array will + * be empty if no validation errors are found. + * + * @param source the input document + * @return an array of {@code SAXParseException}s + * @throws IOException if the {@code source} cannot be read + * @throws XmlValidationException if the {@code source} cannot be validated + */ + SAXParseException[] validate(Source source) throws IOException; - /** - * Validates the given {@link Source} and {@link ValidationErrorHandler}, and returns an array of {@link - * SAXParseException}s as result. The array will be empty if no validation errors are found. - * - * @param source the input document - * @param errorHandler the error handler to use. May be {@code null}, in which case a default will be used. - * @return an array of {@code SAXParseException}s - * @throws IOException if the {@code source} cannot be read - * @throws XmlValidationException if the {@code source} cannot be validated - */ - SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException; + /** + * Validates the given {@link Source} and {@link ValidationErrorHandler}, and returns an array of {@link + * SAXParseException}s as result. The array will be empty if no validation errors are found. + * + * @param source the input document + * @param errorHandler the error handler to use. May be {@code null}, in which case a default will be used. + * @return an array of {@code SAXParseException}s + * @throws IOException if the {@code source} cannot be read + * @throws XmlValidationException if the {@code source} cannot be validated + */ + SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException; } \ No newline at end of file diff --git a/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidatorFactory.java b/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidatorFactory.java index 3b4185a9..2cce2c0d 100644 --- a/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidatorFactory.java +++ b/spring-xml/src/main/java/org/springframework/xml/validation/XmlValidatorFactory.java @@ -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,61 +39,61 @@ import org.apache.commons.logging.LogFactory; */ public abstract class XmlValidatorFactory { - private static final Log logger = LogFactory.getLog(XmlValidatorFactory.class); + private static final Log logger = LogFactory.getLog(XmlValidatorFactory.class); - /** Constant that defines a W3C XML Schema. */ - public static final String SCHEMA_W3C_XML = "http://www.w3.org/2001/XMLSchema"; + /** Constant that defines a W3C XML Schema. */ + public static final String SCHEMA_W3C_XML = "http://www.w3.org/2001/XMLSchema"; - /** Constant that defines a RELAX NG Schema. */ - public static final String SCHEMA_RELAX_NG = "http://relaxng.org/ns/structure/1.0"; + /** Constant that defines a RELAX NG Schema. */ + public static final String SCHEMA_RELAX_NG = "http://relaxng.org/ns/structure/1.0"; - /** - * Create a {@link XmlValidator} with the given schema resource and schema language type. The schema language must - * be one of the {@code SCHEMA_XXX} constants. - * - * @param schemaResource a resource that locates the schema to validate against - * @param schemaLanguage the language of the schema - * @return a validator - * @throws IOException if the schema resource cannot be read - * @throws IllegalArgumentException if the schema language is not supported - * @throws IllegalStateException if JAXP 1.0 cannot be located - * @throws XmlValidationException if a {@code XmlValidator} cannot be created - * @see #SCHEMA_RELAX_NG - * @see #SCHEMA_W3C_XML - */ - public static XmlValidator createValidator(Resource schemaResource, String schemaLanguage) throws IOException { - return createValidator(new Resource[]{schemaResource}, schemaLanguage); - } + /** + * Create a {@link XmlValidator} with the given schema resource and schema language type. The schema language must + * be one of the {@code SCHEMA_XXX} constants. + * + * @param schemaResource a resource that locates the schema to validate against + * @param schemaLanguage the language of the schema + * @return a validator + * @throws IOException if the schema resource cannot be read + * @throws IllegalArgumentException if the schema language is not supported + * @throws IllegalStateException if JAXP 1.0 cannot be located + * @throws XmlValidationException if a {@code XmlValidator} cannot be created + * @see #SCHEMA_RELAX_NG + * @see #SCHEMA_W3C_XML + */ + public static XmlValidator createValidator(Resource schemaResource, String schemaLanguage) throws IOException { + return createValidator(new Resource[]{schemaResource}, schemaLanguage); + } - /** - * Create a {@link XmlValidator} with the given schema resources and schema language type. The schema language must - * be one of the {@code SCHEMA_XXX} constants. - * - * @param schemaResources an array of resource that locate the schemas to validate against - * @param schemaLanguage the language of the schemas - * @return a validator - * @throws IOException if the schema resource cannot be read - * @throws IllegalArgumentException if the schema language is not supported - * @throws IllegalStateException if JAXP 1.0 cannot be located - * @throws XmlValidationException if a {@code XmlValidator} cannot be created - * @see #SCHEMA_RELAX_NG - * @see #SCHEMA_W3C_XML - */ - public static XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws IOException { - Assert.notEmpty(schemaResources, "No resources given"); - Assert.hasLength(schemaLanguage, "No schema language provided"); - Assert.isTrue(SCHEMA_W3C_XML.equals(schemaLanguage) || SCHEMA_RELAX_NG.equals(schemaLanguage), - "Invalid schema language: " + schemaLanguage); - for (Resource schemaResource : schemaResources) { - Assert.isTrue(schemaResource.exists(), "schema [" + schemaResource + "] does not exist"); - } - if (JaxpVersion.getJaxpVersion() >= JaxpVersion.JAXP_13) { - logger.trace("Creating JAXP 1.3 XmlValidator"); - return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage); - } - else { - throw new IllegalStateException("Could not locate JAXP 1.3."); - } - } + /** + * Create a {@link XmlValidator} with the given schema resources and schema language type. The schema language must + * be one of the {@code SCHEMA_XXX} constants. + * + * @param schemaResources an array of resource that locate the schemas to validate against + * @param schemaLanguage the language of the schemas + * @return a validator + * @throws IOException if the schema resource cannot be read + * @throws IllegalArgumentException if the schema language is not supported + * @throws IllegalStateException if JAXP 1.0 cannot be located + * @throws XmlValidationException if a {@code XmlValidator} cannot be created + * @see #SCHEMA_RELAX_NG + * @see #SCHEMA_W3C_XML + */ + public static XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws IOException { + Assert.notEmpty(schemaResources, "No resources given"); + Assert.hasLength(schemaLanguage, "No schema language provided"); + Assert.isTrue(SCHEMA_W3C_XML.equals(schemaLanguage) || SCHEMA_RELAX_NG.equals(schemaLanguage), + "Invalid schema language: " + schemaLanguage); + for (Resource schemaResource : schemaResources) { + Assert.isTrue(schemaResource.exists(), "schema [" + schemaResource + "] does not exist"); + } + if (JaxpVersion.getJaxpVersion() >= JaxpVersion.JAXP_13) { + logger.trace("Creating JAXP 1.3 XmlValidator"); + return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage); + } + else { + throw new IllegalStateException("Could not locate JAXP 1.3."); + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/AbstractXPathTemplate.java b/spring-xml/src/main/java/org/springframework/xml/xpath/AbstractXPathTemplate.java index 9fba40b9..0c42f938 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/AbstractXPathTemplate.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/AbstractXPathTemplate.java @@ -36,51 +36,51 @@ import org.springframework.xml.transform.TransformerObjectSupport; */ public abstract class AbstractXPathTemplate extends TransformerObjectSupport implements XPathOperations { - private Map namespaces; + private Map namespaces; - /** Returns namespaces used in the XPath expression. */ - public Map getNamespaces() { - return namespaces; - } + /** Returns namespaces used in the XPath expression. */ + public Map getNamespaces() { + return namespaces; + } - /** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */ - public void setNamespaces(Map namespaces) { - this.namespaces = namespaces; - } + /** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */ + public void setNamespaces(Map namespaces) { + this.namespaces = namespaces; + } - @Override - public final void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler) - throws XPathException { - evaluate(expression, context, new NodeCallbackHandlerNodeMapper(callbackHandler)); - } + @Override + public final void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler) + throws XPathException { + evaluate(expression, context, new NodeCallbackHandlerNodeMapper(callbackHandler)); + } - /** Static inner class that adapts a {@link NodeCallbackHandler} to the interface of {@link NodeMapper}. */ - private static class NodeCallbackHandlerNodeMapper implements NodeMapper { + /** Static inner class that adapts a {@link NodeCallbackHandler} to the interface of {@link NodeMapper}. */ + private static class NodeCallbackHandlerNodeMapper implements NodeMapper { - private final NodeCallbackHandler callbackHandler; + private final NodeCallbackHandler callbackHandler; - public NodeCallbackHandlerNodeMapper(NodeCallbackHandler callbackHandler) { - this.callbackHandler = callbackHandler; - } + public NodeCallbackHandlerNodeMapper(NodeCallbackHandler callbackHandler) { + this.callbackHandler = callbackHandler; + } - @Override - public Object mapNode(Node node, int nodeNum) throws DOMException { - callbackHandler.processNode(node); - return null; - } - } + @Override + public Object mapNode(Node node, int nodeNum) throws DOMException { + callbackHandler.processNode(node); + return null; + } + } - /** - * Returns the root element of the given source. - * - * @param source the source to get the root element from - * @return the root element - */ - protected 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 + */ + protected Element getRootElement(Source source) throws TransformerException { + DOMResult domResult = new DOMResult(); + transform(source, domResult); + Document document = (Document) domResult.getNode(); + return document.getDocumentElement(); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathExpressionFactory.java b/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathExpressionFactory.java index fa54996f..a2aa2fa9 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathExpressionFactory.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathExpressionFactory.java @@ -36,144 +36,144 @@ import org.w3c.dom.Node; */ abstract class JaxenXPathExpressionFactory { - /** - * Creates a Jaxen {@code XPathExpression} from the given string expression. - * - * @param expression the XPath expression - * @return the compiled {@code XPathExpression} - * @throws XPathParseException when the given expression cannot be parsed - */ - static XPathExpression createXPathExpression(String expression) { - try { - XPath xpath = new DOMXPath(expression); - return new JaxenXpathExpression(xpath); - } - catch (JaxenException ex) { - throw new org.springframework.xml.xpath.XPathParseException( - "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); - } - } + /** + * Creates a Jaxen {@code XPathExpression} from the given string expression. + * + * @param expression the XPath expression + * @return the compiled {@code XPathExpression} + * @throws XPathParseException when the given expression cannot be parsed + */ + static XPathExpression createXPathExpression(String expression) { + try { + XPath xpath = new DOMXPath(expression); + return new JaxenXpathExpression(xpath); + } + catch (JaxenException ex) { + throw new org.springframework.xml.xpath.XPathParseException( + "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); + } + } - /** - * Creates a Jaxen {@code XPathExpression} from the given string expression and prefixes. - * - * @param expression the XPath expression - * @param namespaces the namespaces - * @return the compiled {@code XPathExpression} - * @throws XPathParseException when the given expression cannot be parsed - */ - public static XPathExpression createXPathExpression(String expression, Map namespaces) { - try { - XPath xpath = new DOMXPath(expression); - xpath.setNamespaceContext(new SimpleNamespaceContext(namespaces)); - return new JaxenXpathExpression(xpath); - } - catch (JaxenException ex) { - throw new org.springframework.xml.xpath.XPathParseException( - "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); - } - } + /** + * Creates a Jaxen {@code XPathExpression} from the given string expression and prefixes. + * + * @param expression the XPath expression + * @param namespaces the namespaces + * @return the compiled {@code XPathExpression} + * @throws XPathParseException when the given expression cannot be parsed + */ + public static XPathExpression createXPathExpression(String expression, Map namespaces) { + try { + XPath xpath = new DOMXPath(expression); + xpath.setNamespaceContext(new SimpleNamespaceContext(namespaces)); + return new JaxenXpathExpression(xpath); + } + catch (JaxenException ex) { + throw new org.springframework.xml.xpath.XPathParseException( + "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); + } + } - /** Jaxen implementation of the {@code XPathExpression} interface. */ - private static class JaxenXpathExpression implements XPathExpression { + /** Jaxen implementation of the {@code XPathExpression} interface. */ + private static class JaxenXpathExpression implements XPathExpression { - private XPath xpath; + private XPath xpath; - private JaxenXpathExpression(XPath xpath) { - this.xpath = xpath; - } + private JaxenXpathExpression(XPath xpath) { + this.xpath = xpath; + } - @Override - public Node evaluateAsNode(Node node) { - try { - return (Node) xpath.selectSingleNode(node); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } + @Override + public Node evaluateAsNode(Node node) { + try { + return (Node) xpath.selectSingleNode(node); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } - @Override - public boolean evaluateAsBoolean(Node node) { - try { - return xpath.booleanValueOf(node); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } + @Override + public boolean evaluateAsBoolean(Node node) { + try { + return xpath.booleanValueOf(node); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } - @Override - public double evaluateAsNumber(Node node) { - try { - return xpath.numberValueOf(node).doubleValue(); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } + @Override + public double evaluateAsNumber(Node node) { + try { + return xpath.numberValueOf(node).doubleValue(); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } - @Override - public String evaluateAsString(Node node) { - try { - return xpath.stringValueOf(node); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } + @Override + public String evaluateAsString(Node node) { + try { + return xpath.stringValueOf(node); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } - @Override - @SuppressWarnings("unchecked") - public List evaluateAsNodeList(Node node) { - try { - return xpath.selectNodes(node); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } + @Override + @SuppressWarnings("unchecked") + public List evaluateAsNodeList(Node node) { + try { + return xpath.selectNodes(node); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } - @Override - public T evaluateAsObject(Node context, NodeMapper nodeMapper) throws XPathException { - try { - Node result = (Node) xpath.selectSingleNode(context); - if (result != null) { - try { - return nodeMapper.mapNode(result, 0); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - else { - return null; - } - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } + @Override + public T evaluateAsObject(Node context, NodeMapper nodeMapper) throws XPathException { + try { + Node result = (Node) xpath.selectSingleNode(context); + if (result != null) { + try { + return nodeMapper.mapNode(result, 0); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + else { + return null; + } + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } - @Override - public List evaluate(Node context, NodeMapper nodeMapper) throws XPathException { - try { - List nodes = xpath.selectNodes(context); - List results = new ArrayList(nodes.size()); - for (int i = 0; i < nodes.size(); i++) { - Node node = (Node) nodes.get(i); - try { - results.add(nodeMapper.mapNode(node, i)); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - return results; - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); - } - } - } + @Override + public List evaluate(Node context, NodeMapper nodeMapper) throws XPathException { + try { + List nodes = xpath.selectNodes(context); + List results = new ArrayList(nodes.size()); + for (int i = 0; i < nodes.size(); i++) { + Node node = (Node) nodes.get(i); + try { + results.add(nodeMapper.mapNode(node, i)); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + return results; + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + xpath + "] :" + ex.getMessage(), ex); + } + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathTemplate.java b/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathTemplate.java index 880bd9de..166113f1 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathTemplate.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/JaxenXPathTemplate.java @@ -40,140 +40,140 @@ import org.w3c.dom.Node; */ public class JaxenXPathTemplate extends AbstractXPathTemplate { - @Override - public boolean evaluateAsBoolean(String expression, Source context) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - return xpath.booleanValueOf(element); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + @Override + public boolean evaluateAsBoolean(String expression, Source context) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + return xpath.booleanValueOf(element); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - @Override - public Node evaluateAsNode(String expression, Source context) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - return (Node) xpath.selectSingleNode(element); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + @Override + public Node evaluateAsNode(String expression, Source context) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + return (Node) xpath.selectSingleNode(element); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - @Override - @SuppressWarnings("unchecked") - public List evaluateAsNodeList(String expression, Source context) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - return xpath.selectNodes(element); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + @Override + @SuppressWarnings("unchecked") + public List evaluateAsNodeList(String expression, Source context) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + return xpath.selectNodes(element); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - @Override - public double evaluateAsDouble(String expression, Source context) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - return xpath.numberValueOf(element).doubleValue(); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + @Override + public double evaluateAsDouble(String expression, Source context) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + return xpath.numberValueOf(element).doubleValue(); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - @Override - public String evaluateAsString(String expression, Source context) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - return xpath.stringValueOf(element); - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + @Override + public String evaluateAsString(String expression, Source context) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + return xpath.stringValueOf(element); + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - @Override - public T evaluateAsObject(String expression, Source context, NodeMapper nodeMapper) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - Node node = (Node) xpath.selectSingleNode(element); - if (node != null) { - try { - return nodeMapper.mapNode(node, 0); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - else { - return null; - } + @Override + public T evaluateAsObject(String expression, Source context, NodeMapper nodeMapper) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + Node node = (Node) xpath.selectSingleNode(element); + if (node != null) { + try { + return nodeMapper.mapNode(node, 0); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + else { + return null; + } - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - @Override - public List evaluate(String expression, Source context, NodeMapper nodeMapper) throws XPathException { - try { - XPath xpath = createXPath(expression); - Element element = getRootElement(context); - List nodes = xpath.selectNodes(element); - List results = new ArrayList(nodes.size()); - for (int i = 0; i < nodes.size(); i++) { - Node node = (Node) nodes.get(i); - try { - results.add(nodeMapper.mapNode(node, i)); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - return results; - } - catch (JaxenException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - } + @Override + public List evaluate(String expression, Source context, NodeMapper nodeMapper) throws XPathException { + try { + XPath xpath = createXPath(expression); + Element element = getRootElement(context); + List nodes = xpath.selectNodes(element); + List results = new ArrayList(nodes.size()); + for (int i = 0; i < nodes.size(); i++) { + Node node = (Node) nodes.get(i); + try { + results.add(nodeMapper.mapNode(node, i)); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + return results; + } + catch (JaxenException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + } - private XPath createXPath(String expression) throws JaxenException { - XPath xpath = new DOMXPath(expression); - if (getNamespaces() != null && !getNamespaces().isEmpty()) { - xpath.setNamespaceContext(new SimpleNamespaceContext(getNamespaces())); - } - return xpath; - } + private XPath createXPath(String expression) throws JaxenException { + XPath xpath = new DOMXPath(expression); + if (getNamespaces() != null && !getNamespaces().isEmpty()) { + xpath.setNamespaceContext(new SimpleNamespaceContext(getNamespaces())); + } + return xpath; + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactory.java b/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactory.java index 357c2e35..694f51a0 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactory.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactory.java @@ -40,140 +40,140 @@ import org.springframework.xml.namespace.SimpleNamespaceContext; */ abstract class Jaxp13XPathExpressionFactory { - private static XPathFactory xpathFactory = XPathFactory.newInstance(); + private static XPathFactory xpathFactory = XPathFactory.newInstance(); - /** - * Creates a JAXP 1.3 {@code XPathExpression} from the given string expression. - * - * @param expression the XPath expression - * @return the compiled {@code XPathExpression} - * @throws XPathParseException when the given expression cannot be parsed - */ - static XPathExpression createXPathExpression(String expression) { - try { - XPath xpath = createXPath(); - javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression); - return new Jaxp13XPathExpression(xpathExpression); - } - catch (XPathExpressionException ex) { - throw new org.springframework.xml.xpath.XPathParseException( - "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); - } - } + /** + * Creates a JAXP 1.3 {@code XPathExpression} from the given string expression. + * + * @param expression the XPath expression + * @return the compiled {@code XPathExpression} + * @throws XPathParseException when the given expression cannot be parsed + */ + static XPathExpression createXPathExpression(String expression) { + try { + XPath xpath = createXPath(); + javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression); + return new Jaxp13XPathExpression(xpathExpression); + } + catch (XPathExpressionException ex) { + throw new org.springframework.xml.xpath.XPathParseException( + "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); + } + } - /** - * Creates a JAXP 1.3 {@code XPathExpression} from the given string expression and namespaces. - * - * @param expression the XPath expression - * @param namespaces the namespaces - * @return the compiled {@code XPathExpression} - * @throws XPathParseException when the given expression cannot be parsed - */ - public static XPathExpression createXPathExpression(String expression, Map namespaces) { - try { - XPath xpath = createXPath(); - SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); - namespaceContext.setBindings(namespaces); - xpath.setNamespaceContext(namespaceContext); - javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression); - return new Jaxp13XPathExpression(xpathExpression); - } - catch (XPathExpressionException ex) { - throw new org.springframework.xml.xpath.XPathParseException( - "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); - } - } + /** + * Creates a JAXP 1.3 {@code XPathExpression} from the given string expression and namespaces. + * + * @param expression the XPath expression + * @param namespaces the namespaces + * @return the compiled {@code XPathExpression} + * @throws XPathParseException when the given expression cannot be parsed + */ + public static XPathExpression createXPathExpression(String expression, Map namespaces) { + try { + XPath xpath = createXPath(); + SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); + namespaceContext.setBindings(namespaces); + xpath.setNamespaceContext(namespaceContext); + javax.xml.xpath.XPathExpression xpathExpression = xpath.compile(expression); + return new Jaxp13XPathExpression(xpathExpression); + } + catch (XPathExpressionException ex) { + throw new org.springframework.xml.xpath.XPathParseException( + "Could not compile [" + expression + "] to a XPathExpression: " + ex.getMessage(), ex); + } + } - private static synchronized XPath createXPath() { - return xpathFactory.newXPath(); - } - + private static synchronized XPath createXPath() { + return xpathFactory.newXPath(); + } - /** JAXP 1.3 implementation of the {@code XPathExpression} interface. */ - private static class Jaxp13XPathExpression implements XPathExpression { - private final javax.xml.xpath.XPathExpression xpathExpression; + /** JAXP 1.3 implementation of the {@code XPathExpression} interface. */ + private static class Jaxp13XPathExpression implements XPathExpression { - private Jaxp13XPathExpression(javax.xml.xpath.XPathExpression xpathExpression) { - this.xpathExpression = xpathExpression; - } + private final javax.xml.xpath.XPathExpression xpathExpression; - @Override - public String evaluateAsString(Node node) { - return (String) evaluate(node, XPathConstants.STRING); - } + private Jaxp13XPathExpression(javax.xml.xpath.XPathExpression xpathExpression) { + this.xpathExpression = xpathExpression; + } - @Override - public List evaluateAsNodeList(Node node) { - NodeList nodeList = (NodeList) evaluate(node, XPathConstants.NODESET); - return toNodeList(nodeList); - } + @Override + public String evaluateAsString(Node node) { + return (String) evaluate(node, XPathConstants.STRING); + } - private Object evaluate(Node node, QName returnType) { - try { - // XPathExpression is not thread-safe - synchronized (xpathExpression) { - return xpathExpression.evaluate(node, returnType); - } - } - catch (XPathExpressionException ex) { - throw new XPathException("Could not evaluate XPath expression:" + ex.getMessage(), ex); - } - } + @Override + public List evaluateAsNodeList(Node node) { + NodeList nodeList = (NodeList) evaluate(node, XPathConstants.NODESET); + return toNodeList(nodeList); + } - private List toNodeList(NodeList nodeList) { - List result = new ArrayList(nodeList.getLength()); - for (int i = 0; i < nodeList.getLength(); i++) { - result.add(nodeList.item(i)); - } - return result; - } + private Object evaluate(Node node, QName returnType) { + try { + // XPathExpression is not thread-safe + synchronized (xpathExpression) { + return xpathExpression.evaluate(node, returnType); + } + } + catch (XPathExpressionException ex) { + throw new XPathException("Could not evaluate XPath expression:" + ex.getMessage(), ex); + } + } - @Override - public double evaluateAsNumber(Node node) { - return (Double) evaluate(node, XPathConstants.NUMBER); - } + private List toNodeList(NodeList nodeList) { + List result = new ArrayList(nodeList.getLength()); + for (int i = 0; i < nodeList.getLength(); i++) { + result.add(nodeList.item(i)); + } + return result; + } - @Override - public boolean evaluateAsBoolean(Node node) { - return (Boolean) evaluate(node, XPathConstants.BOOLEAN); - } + @Override + public double evaluateAsNumber(Node node) { + return (Double) evaluate(node, XPathConstants.NUMBER); + } - @Override - public Node evaluateAsNode(Node node) { - return (Node) evaluate(node, XPathConstants.NODE); - } + @Override + public boolean evaluateAsBoolean(Node node) { + return (Boolean) evaluate(node, XPathConstants.BOOLEAN); + } - @Override - public T evaluateAsObject(Node node, NodeMapper nodeMapper) throws XPathException { - Node result = (Node) evaluate(node, XPathConstants.NODE); - if (result != null) { - try { - return nodeMapper.mapNode(result, 0); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - else { - return null; - } - } + @Override + public Node evaluateAsNode(Node node) { + return (Node) evaluate(node, XPathConstants.NODE); + } - @Override - public List evaluate(Node node, NodeMapper nodeMapper) throws XPathException { - NodeList nodes = (NodeList) evaluate(node, XPathConstants.NODESET); - List results = new ArrayList(nodes.getLength()); - for (int i = 0; i < nodes.getLength(); i++) { - try { - results.add(nodeMapper.mapNode(nodes.item(i), i)); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - return results; - } - } + @Override + public T evaluateAsObject(Node node, NodeMapper nodeMapper) throws XPathException { + Node result = (Node) evaluate(node, XPathConstants.NODE); + if (result != null) { + try { + return nodeMapper.mapNode(result, 0); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + else { + return null; + } + } + + @Override + public List evaluate(Node node, NodeMapper nodeMapper) throws XPathException { + NodeList nodes = (NodeList) evaluate(node, XPathConstants.NODESET); + List results = new ArrayList(nodes.getLength()); + for (int i = 0; i < nodes.getLength(); i++) { + try { + results.add(nodeMapper.mapNode(nodes.item(i), i)); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + return results; + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathTemplate.java b/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathTemplate.java index 25734840..4b4bcfea 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathTemplate.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/Jaxp13XPathTemplate.java @@ -57,179 +57,179 @@ import org.springframework.xml.transform.TraxUtils; */ public class Jaxp13XPathTemplate extends AbstractXPathTemplate { - private XPathFactory xpathFactory; + private XPathFactory xpathFactory; - public Jaxp13XPathTemplate() { - this(XPathFactory.DEFAULT_OBJECT_MODEL_URI); - } + public Jaxp13XPathTemplate() { + this(XPathFactory.DEFAULT_OBJECT_MODEL_URI); + } - public Jaxp13XPathTemplate(String xpathFactoryUri) { - try { - xpathFactory = XPathFactory.newInstance(xpathFactoryUri); - } - catch (XPathFactoryConfigurationException ex) { - throw new XPathException("Could not create XPathFactory", ex); - } - } + public Jaxp13XPathTemplate(String xpathFactoryUri) { + try { + xpathFactory = XPathFactory.newInstance(xpathFactoryUri); + } + catch (XPathFactoryConfigurationException ex) { + throw new XPathException("Could not create XPathFactory", ex); + } + } - @Override - public boolean evaluateAsBoolean(String expression, Source context) throws XPathException { - Boolean result = (Boolean) evaluate(expression, context, XPathConstants.BOOLEAN); - return result != null && result; - } + @Override + public boolean evaluateAsBoolean(String expression, Source context) throws XPathException { + Boolean result = (Boolean) evaluate(expression, context, XPathConstants.BOOLEAN); + return result != null && result; + } - @Override - public Node evaluateAsNode(String expression, Source context) throws XPathException { - return (Node) evaluate(expression, context, XPathConstants.NODE); - } + @Override + public Node evaluateAsNode(String expression, Source context) throws XPathException { + return (Node) evaluate(expression, context, XPathConstants.NODE); + } - @Override - public List evaluateAsNodeList(String expression, Source context) throws XPathException { - NodeList result = (NodeList) evaluate(expression, context, XPathConstants.NODESET); - List nodes = new ArrayList(result.getLength()); - for (int i = 0; i < result.getLength(); i++) { - nodes.add(result.item(i)); - } - return nodes; - } + @Override + public List evaluateAsNodeList(String expression, Source context) throws XPathException { + NodeList result = (NodeList) evaluate(expression, context, XPathConstants.NODESET); + List nodes = new ArrayList(result.getLength()); + for (int i = 0; i < result.getLength(); i++) { + nodes.add(result.item(i)); + } + return nodes; + } - @Override - public double evaluateAsDouble(String expression, Source context) throws XPathException { - Double result = (Double) evaluate(expression, context, XPathConstants.NUMBER); - return result != null ? result : Double.NaN; - } + @Override + public double evaluateAsDouble(String expression, Source context) throws XPathException { + Double result = (Double) evaluate(expression, context, XPathConstants.NUMBER); + return result != null ? result : Double.NaN; + } - @Override - public String evaluateAsString(String expression, Source context) throws XPathException { - return (String) evaluate(expression, context, XPathConstants.STRING); - } + @Override + public String evaluateAsString(String expression, Source context) throws XPathException { + return (String) evaluate(expression, context, XPathConstants.STRING); + } - @Override - public T evaluateAsObject(String expression, Source context, NodeMapper nodeMapper) throws XPathException { - Node node = evaluateAsNode(expression, context); - if (node != null) { - try { - return nodeMapper.mapNode(node, 0); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - else { - return null; - } - } + @Override + public T evaluateAsObject(String expression, Source context, NodeMapper nodeMapper) throws XPathException { + Node node = evaluateAsNode(expression, context); + if (node != null) { + try { + return nodeMapper.mapNode(node, 0); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + else { + return null; + } + } - @Override - public List evaluate(String expression, Source context, NodeMapper nodeMapper) throws XPathException { - NodeList nodes = (NodeList) evaluate(expression, context, XPathConstants.NODESET); - List results = new ArrayList(nodes.getLength()); - for (int i = 0; i < nodes.getLength(); i++) { - try { - results.add(nodeMapper.mapNode(nodes.item(i), i)); - } - catch (DOMException ex) { - throw new XPathException("Mapping resulted in DOMException", ex); - } - } - return results; - } + @Override + public List evaluate(String expression, Source context, NodeMapper nodeMapper) throws XPathException { + NodeList nodes = (NodeList) evaluate(expression, context, XPathConstants.NODESET); + List results = new ArrayList(nodes.getLength()); + for (int i = 0; i < nodes.getLength(); i++) { + try { + results.add(nodeMapper.mapNode(nodes.item(i), i)); + } + catch (DOMException ex) { + throw new XPathException("Mapping resulted in DOMException", ex); + } + } + return results; + } - private Object evaluate(String expression, Source context, QName returnType) throws XPathException { - XPath xpath = createXPath(); - if (getNamespaces() != null && !getNamespaces().isEmpty()) { - SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); - namespaceContext.setBindings(getNamespaces()); - xpath.setNamespaceContext(namespaceContext); - } - try { - EvaluationCallback callback = new EvaluationCallback(xpath, expression, returnType); - TraxUtils.doWithSource(context, callback); - return callback.result; - } - catch (javax.xml.xpath.XPathException ex) { - throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); - } - catch (TransformerException ex) { - throw new XPathException("Could not transform context to DOM Node", ex); - } - catch (Exception ex) { - throw new XPathException(ex.getMessage(), ex); - } - } + private Object evaluate(String expression, Source context, QName returnType) throws XPathException { + XPath xpath = createXPath(); + if (getNamespaces() != null && !getNamespaces().isEmpty()) { + SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); + namespaceContext.setBindings(getNamespaces()); + xpath.setNamespaceContext(namespaceContext); + } + try { + EvaluationCallback callback = new EvaluationCallback(xpath, expression, returnType); + TraxUtils.doWithSource(context, callback); + return callback.result; + } + catch (javax.xml.xpath.XPathException ex) { + throw new XPathException("Could not evaluate XPath expression [" + expression + "]", ex); + } + catch (TransformerException ex) { + throw new XPathException("Could not transform context to DOM Node", ex); + } + catch (Exception ex) { + throw new XPathException(ex.getMessage(), ex); + } + } - private synchronized XPath createXPath() { - return xpathFactory.newXPath(); - } + private synchronized XPath createXPath() { + return xpathFactory.newXPath(); + } - private static class EvaluationCallback implements TraxUtils.SourceCallback { + private static class EvaluationCallback implements TraxUtils.SourceCallback { - private final XPath xpath; + private final XPath xpath; - private final String expression; + private final String expression; - private final QName returnType; + private final QName returnType; - private final TransformerHelper transformerHelper = new TransformerHelper(); + private final TransformerHelper transformerHelper = new TransformerHelper(); - private Object result; + private Object result; - private EvaluationCallback(XPath xpath, String expression, QName returnType) { - this.xpath = xpath; - this.expression = expression; - this.returnType = returnType; - } + private EvaluationCallback(XPath xpath, String expression, QName returnType) { + this.xpath = xpath; + this.expression = expression; + this.returnType = returnType; + } - @Override - public void domSource(Node node) throws XPathExpressionException { - result = xpath.evaluate(expression, node, returnType); - } + @Override + public void domSource(Node node) throws XPathExpressionException { + result = xpath.evaluate(expression, node, returnType); + } - @Override - public void saxSource(XMLReader reader, InputSource inputSource) throws XPathExpressionException { - inputSource(inputSource); - } + @Override + public void saxSource(XMLReader reader, InputSource inputSource) throws XPathExpressionException { + inputSource(inputSource); + } - @Override - public void staxSource(XMLEventReader eventReader) - throws XPathExpressionException, XMLStreamException, TransformerException { - Element element = getRootElement(StaxUtils.createCustomStaxSource(eventReader)); - domSource(element); - } + @Override + public void staxSource(XMLEventReader eventReader) + throws XPathExpressionException, XMLStreamException, TransformerException { + Element element = getRootElement(StaxUtils.createCustomStaxSource(eventReader)); + domSource(element); + } - @Override - public void staxSource(XMLStreamReader streamReader) throws TransformerException, XPathExpressionException { - Element element = getRootElement(StaxUtils.createCustomStaxSource(streamReader)); - domSource(element); - } + @Override + public void staxSource(XMLStreamReader streamReader) throws TransformerException, XPathExpressionException { + Element element = getRootElement(StaxUtils.createCustomStaxSource(streamReader)); + domSource(element); + } - @Override - public void streamSource(InputStream inputStream) throws XPathExpressionException { - inputSource(new InputSource(inputStream)); - } + @Override + public void streamSource(InputStream inputStream) throws XPathExpressionException { + inputSource(new InputSource(inputStream)); + } - @Override - public void streamSource(Reader reader) throws XPathExpressionException { - inputSource(new InputSource(reader)); - } + @Override + public void streamSource(Reader reader) throws XPathExpressionException { + inputSource(new InputSource(reader)); + } - @Override - public void source(String systemId) throws XPathExpressionException { - inputSource(new InputSource(systemId)); - } + @Override + public void source(String systemId) throws XPathExpressionException { + inputSource(new InputSource(systemId)); + } - private void inputSource(InputSource inputSource) throws XPathExpressionException { - result = xpath.evaluate(expression, inputSource, returnType); - } + private void inputSource(InputSource inputSource) throws XPathExpressionException { + result = xpath.evaluate(expression, inputSource, returnType); + } - 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(); + } - } + } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/NodeCallbackHandler.java b/spring-xml/src/main/java/org/springframework/xml/xpath/NodeCallbackHandler.java index 80984fe6..29b36ff3 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/NodeCallbackHandler.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/NodeCallbackHandler.java @@ -33,12 +33,12 @@ import org.w3c.dom.Node; */ public interface NodeCallbackHandler { - /** - * Processed a single node. - * - * @param node the node to map - * @throws DOMException in case of DOM errors - */ - void processNode(Node node) throws DOMException; + /** + * Processed a single node. + * + * @param node the node to map + * @throws DOMException in case of DOM errors + */ + void processNode(Node node) throws DOMException; } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/NodeMapper.java b/spring-xml/src/main/java/org/springframework/xml/xpath/NodeMapper.java index 8eedd8d2..94087084 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/NodeMapper.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/NodeMapper.java @@ -33,14 +33,14 @@ import org.w3c.dom.Node; */ public interface NodeMapper { - /** - * Maps a single node to an arbitrary object. - * - * @param node the node to map - * @param nodeNum the number of the current node - * @return object for the current node - * @throws DOMException in case of DOM errors - */ - T mapNode(Node node, int nodeNum) throws DOMException; + /** + * Maps a single node to an arbitrary object. + * + * @param node the node to map + * @param nodeNum the number of the current node + * @return object for the current node + * @throws DOMException in case of DOM errors + */ + T mapNode(Node node, int nodeNum) throws DOMException; } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathException.java b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathException.java index 884c9227..634591d4 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathException.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathException.java @@ -27,22 +27,22 @@ import org.springframework.xml.XmlException; @SuppressWarnings("serial") public class XPathException extends XmlException { - /** - * Constructs a new instance of the {@code XPathException} with the specific detail message. - * - * @param message the detail message - */ - public XPathException(String message) { - super(message); - } + /** + * Constructs a new instance of the {@code XPathException} with the specific detail message. + * + * @param message the detail message + */ + public XPathException(String message) { + super(message); + } - /** - * Constructs a new instance of the {@code XPathException} with the specific detail message and exception. - * - * @param message the detail message - * @param throwable the wrapped exception - */ - public XPathException(String message, Throwable throwable) { - super(message, throwable); - } + /** + * Constructs a new instance of the {@code XPathException} with the specific detail message and exception. + * + * @param message the detail message + * @param throwable the wrapped exception + */ + public XPathException(String message, Throwable throwable) { + super(message, throwable); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpression.java b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpression.java index 6d78c8bb..413023a3 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpression.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpression.java @@ -32,93 +32,93 @@ import org.w3c.dom.Node; */ public interface XPathExpression { - /** - * Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or - * {@code false} if it is invalid. - * - *

The return value is determined per the {@code boolean()} function defined in the XPath specification. - * This means that an expression that selects zero nodes will return {@code false}, while an expression that - * selects one or more nodes will return {@code true}. - * An expression that returns a string returns {@code false} for empty strings and {@code true} for all other - * strings. - * An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers. - * - * @param node the starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - boolean() function - */ - boolean evaluateAsBoolean(Node node) throws XPathException; + /** + * Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or + * {@code false} if it is invalid. + * + *

The return value is determined per the {@code boolean()} function defined in the XPath specification. + * This means that an expression that selects zero nodes will return {@code false}, while an expression that + * selects one or more nodes will return {@code true}. + * An expression that returns a string returns {@code false} for empty strings and {@code true} for all other + * strings. + * An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers. + * + * @param node the starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification - boolean() function + */ + boolean evaluateAsBoolean(Node node) throws XPathException; - /** - * Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null} - * if it is invalid. - * - * @param node the starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - Node evaluateAsNode(Node node) throws XPathException; + /** + * Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null} + * if it is invalid. + * + * @param node the starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + Node evaluateAsNode(Node node) throws XPathException; - /** - * Evaluates the given expression, and returns all {@link Node} objects that conform to it. Returns an empty list if - * no result could be found. - * - * @param node the starting point - * @return a list of {@code Node}s that are selected by the expression - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - List evaluateAsNodeList(Node node) throws XPathException; + /** + * Evaluates the given expression, and returns all {@link Node} objects that conform to it. Returns an empty list if + * no result could be found. + * + * @param node the starting point + * @return a list of {@code Node}s that are selected by the expression + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + List evaluateAsNodeList(Node node) throws XPathException; - /** - * Evaluates the given expression as a number ({@code double}). Returns the numeric evaluation of the - * expression, or {@link Double#NaN} if it is invalid. - * - *

The return value is determined per the {@code number()} function as defined in the XPath specification. - * This means that if the expression selects multiple nodes, it will return the number value of the first node. - * - * @param node the starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - number() function - */ - double evaluateAsNumber(Node node) throws XPathException; + /** + * Evaluates the given expression as a number ({@code double}). Returns the numeric evaluation of the + * expression, or {@link Double#NaN} if it is invalid. + * + *

The return value is determined per the {@code number()} function as defined in the XPath specification. + * This means that if the expression selects multiple nodes, it will return the number value of the first node. + * + * @param node the starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification - number() function + */ + double evaluateAsNumber(Node node) throws XPathException; - /** - * Evaluates the given expression as a String. Returns {@code null} if no result could be found. - * - *

The return value is determined per the {@code string()} function as defined in the XPath specification. - * This means that if the expression selects multiple nodes, it will return the string value of the first node. - * - * @param node the starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - string() function - */ - String evaluateAsString(Node node) throws XPathException; + /** + * Evaluates the given expression as a String. Returns {@code null} if no result could be found. + * + *

The return value is determined per the {@code string()} function as defined in the XPath specification. + * This means that if the expression selects multiple nodes, it will return the string value of the first node. + * + * @param node the starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification - string() function + */ + String evaluateAsString(Node node) throws XPathException; - /** - * Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}. - * - * @param node the starting point - * @param nodeMapper object that will map one object per node - * @return the single mapped object - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - T evaluateAsObject(Node node, NodeMapper nodeMapper) throws XPathException; + /** + * Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}. + * + * @param node the starting point + * @param nodeMapper object that will map one object per node + * @return the single mapped object + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + T evaluateAsObject(Node node, NodeMapper nodeMapper) throws XPathException; - /** - * Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link - * NodeMapper}. - * - * @param node the starting point - * @param nodeMapper object that will map one object per node - * @return the result list, containing mapped objects - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - List evaluate(Node node, NodeMapper nodeMapper) throws XPathException; + /** + * Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link + * NodeMapper}. + * + * @param node the starting point + * @param nodeMapper object that will map one object per node + * @return the result list, containing mapped objects + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + List evaluate(Node node, NodeMapper nodeMapper) throws XPathException; } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactory.java b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactory.java index 522b7ecf..364756c4 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactory.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactory.java @@ -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, @@ -37,45 +37,45 @@ import org.apache.commons.logging.LogFactory; */ public abstract class XPathExpressionFactory { - private static final Log logger = LogFactory.getLog(XPathExpressionFactory.class); + private static final Log logger = LogFactory.getLog(XPathExpressionFactory.class); - /** - * Create a compiled XPath expression using the given string. - * - * @param expression the XPath expression - * @return the compiled XPath expression - * @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available - * @throws XPathParseException if the given expression cannot be parsed - */ - public static XPathExpression createXPathExpression(String expression) - throws IllegalStateException, XPathParseException { - return createXPathExpression(expression, Collections.emptyMap()); - } + /** + * Create a compiled XPath expression using the given string. + * + * @param expression the XPath expression + * @return the compiled XPath expression + * @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available + * @throws XPathParseException if the given expression cannot be parsed + */ + public static XPathExpression createXPathExpression(String expression) + throws IllegalStateException, XPathParseException { + return createXPathExpression(expression, Collections.emptyMap()); + } - /** - * Create a compiled XPath expression using the given string and namespaces. The namespace map should consist of - * string prefixes mapped to string namespaces. - * - * @param expression the XPath expression - * @param namespaces a map that binds string prefixes to string namespaces - * @return the compiled XPath expression - * @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available - * @throws XPathParseException if the given expression cannot be parsed - */ - public static XPathExpression createXPathExpression(String expression, Map namespaces) - throws IllegalStateException, XPathParseException { - Assert.hasLength(expression, "expression is empty"); - if (namespaces == null) { - namespaces = Collections.emptyMap(); - } - try { - logger.trace("Creating [javax.xml.xpath.XPathExpression]"); - return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces); - } - catch (XPathException e) { - throw e; - } - } + /** + * Create a compiled XPath expression using the given string and namespaces. The namespace map should consist of + * string prefixes mapped to string namespaces. + * + * @param expression the XPath expression + * @param namespaces a map that binds string prefixes to string namespaces + * @return the compiled XPath expression + * @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available + * @throws XPathParseException if the given expression cannot be parsed + */ + public static XPathExpression createXPathExpression(String expression, Map namespaces) + throws IllegalStateException, XPathParseException { + Assert.hasLength(expression, "expression is empty"); + if (namespaces == null) { + namespaces = Collections.emptyMap(); + } + try { + logger.trace("Creating [javax.xml.xpath.XPathExpression]"); + return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces); + } + catch (XPathException e) { + throw e; + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactoryBean.java b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactoryBean.java index fd7e6632..7b548b28 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactoryBean.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathExpressionFactoryBean.java @@ -35,45 +35,45 @@ import org.springframework.util.CollectionUtils; */ public class XPathExpressionFactoryBean implements FactoryBean, InitializingBean { - private Map namespaces; + private Map namespaces; - private String expressionString; + private String expressionString; - private XPathExpression expression; + private XPathExpression expression; - /** Sets the XPath expression. Setting this property is required. */ - public void setExpression(String expression) { - expressionString = expression; - } + /** Sets the XPath expression. Setting this property is required. */ + public void setExpression(String expression) { + expressionString = expression; + } - /** Sets the namespaces for the expressions. The given properties binds string prefixes to string namespaces. */ - public void setNamespaces(Map namespaces) { - this.namespaces = namespaces; - } + /** Sets the namespaces for the expressions. The given properties binds string prefixes to string namespaces. */ + public void setNamespaces(Map namespaces) { + this.namespaces = namespaces; + } - @Override - public void afterPropertiesSet() throws IllegalStateException, XPathParseException { - Assert.notNull(expressionString, "expression is required"); - if (CollectionUtils.isEmpty(namespaces)) { - expression = XPathExpressionFactory.createXPathExpression(expressionString); - } - else { - expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces); - } - } + @Override + public void afterPropertiesSet() throws IllegalStateException, XPathParseException { + Assert.notNull(expressionString, "expression is required"); + if (CollectionUtils.isEmpty(namespaces)) { + expression = XPathExpressionFactory.createXPathExpression(expressionString); + } + else { + expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces); + } + } - @Override - public XPathExpression getObject() throws Exception { - return expression; - } + @Override + public XPathExpression getObject() throws Exception { + return expression; + } - @Override - public Class getObjectType() { - return XPathExpression.class; - } + @Override + public Class getObjectType() { + return XPathExpression.class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathOperations.java b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathOperations.java index 9618a666..7a1b6e05 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathOperations.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathOperations.java @@ -35,113 +35,113 @@ import org.w3c.dom.Node; */ public interface XPathOperations { - /** - * Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or - * {@code false} if it is invalid. - * - *

The return value is determined per the {@code boolean()} function defined in the XPath specification. - * This means that an expression that selects zero nodes will return {@code false}, while an expression that - * selects one or more nodes will return {@code true}. - * An expression that returns a string returns {@code false} for empty strings and {@code true} for all other - * strings. - * An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers. - * - * @param expression the XPath expression - * @param context the context starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - boolean() function - */ - boolean evaluateAsBoolean(String expression, Source context) throws XPathException; + /** + * Evaluates the given expression as a {@code boolean}. Returns the boolean evaluation of the expression, or + * {@code false} if it is invalid. + * + *

The return value is determined per the {@code boolean()} function defined in the XPath specification. + * This means that an expression that selects zero nodes will return {@code false}, while an expression that + * selects one or more nodes will return {@code true}. + * An expression that returns a string returns {@code false} for empty strings and {@code true} for all other + * strings. + * An expression that returns a number returns {@code false} for zero and {@code true} for non-zero numbers. + * + * @param expression the XPath expression + * @param context the context starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification - boolean() function + */ + boolean evaluateAsBoolean(String expression, Source context) throws XPathException; - /** - * Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null} - * if it is invalid. - * - * @param expression the XPath expression - * @param context the context starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - Node evaluateAsNode(String expression, Source context) throws XPathException; + /** + * Evaluates the given expression as a {@link Node}. Returns the evaluation of the expression, or {@code null} + * if it is invalid. + * + * @param expression the XPath expression + * @param context the context starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + Node evaluateAsNode(String expression, Source context) throws XPathException; - /** - * Evaluates the given expression as a list of {@link Node} objects. Returns the evaluation of the expression, or an - * empty list if no results are found. - * - * @param expression the XPath expression - * @param context the context starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - List evaluateAsNodeList(String expression, Source context) throws XPathException; + /** + * Evaluates the given expression as a list of {@link Node} objects. Returns the evaluation of the expression, or an + * empty list if no results are found. + * + * @param expression the XPath expression + * @param context the context starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + List evaluateAsNodeList(String expression, Source context) throws XPathException; - /** - * Evaluates the given expression as a {@code double}. Returns the evaluation of the expression, or {@link - * Double#NaN} if it is invalid. - * - *

The return value is determined per the {@code number()} function as defined in the XPath specification. - * This means that if the expression selects multiple nodes, it will return the number value of the first node. - * - * @param expression the XPath expression - * @param context the context starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - number() function - */ - double evaluateAsDouble(String expression, Source context) throws XPathException; + /** + * Evaluates the given expression as a {@code double}. Returns the evaluation of the expression, or {@link + * Double#NaN} if it is invalid. + * + *

The return value is determined per the {@code number()} function as defined in the XPath specification. + * This means that if the expression selects multiple nodes, it will return the number value of the first node. + * + * @param expression the XPath expression + * @param context the context starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification - number() function + */ + double evaluateAsDouble(String expression, Source context) throws XPathException; - /** - * Evaluates the given expression as a {@link String}. Returns the evaluation of the expression, or - * {@code null} if it is invalid. - * - *

The return value is determined per the {@code string()} function as defined in the XPath specification. - * This means that if the expression selects multiple nodes, it will return the string value of the first node. - * - * @param expression the XPath expression - * @param context the context starting point - * @return the result of the evaluation - * @throws XPathException in case of XPath errors - * @see XPath specification - string() function - */ - String evaluateAsString(String expression, Source context) throws XPathException; + /** + * Evaluates the given expression as a {@link String}. Returns the evaluation of the expression, or + * {@code null} if it is invalid. + * + *

The return value is determined per the {@code string()} function as defined in the XPath specification. + * This means that if the expression selects multiple nodes, it will return the string value of the first node. + * + * @param expression the XPath expression + * @param context the context starting point + * @return the result of the evaluation + * @throws XPathException in case of XPath errors + * @see XPath specification - string() function + */ + String evaluateAsString(String expression, Source context) throws XPathException; - /** - * Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}. - * - * @param expression the XPath expression - * @param context the context starting point - * @param nodeMapper object that will map one object per node - * @return the single mapped object - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - T evaluateAsObject(String expression, Source context, NodeMapper nodeMapper) throws XPathException; + /** + * Evaluates the given expression, mapping a single {@link Node} result to a Java object via a {@link NodeMapper}. + * + * @param expression the XPath expression + * @param context the context starting point + * @param nodeMapper object that will map one object per node + * @return the single mapped object + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + T evaluateAsObject(String expression, Source context, NodeMapper nodeMapper) throws XPathException; - /** - * Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link - * NodeMapper}. - * - * @param expression the XPath expression - * @param context the context starting point - * @param nodeMapper object that will map one object per node - * @return the result list, containing mapped objects - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - List evaluate(String expression, Source context, NodeMapper nodeMapper) throws XPathException; + /** + * Evaluates the given expression, mapping each result {@link Node} objects to a Java object via a {@link + * NodeMapper}. + * + * @param expression the XPath expression + * @param context the context starting point + * @param nodeMapper object that will map one object per node + * @return the result list, containing mapped objects + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + List evaluate(String expression, Source context, NodeMapper nodeMapper) throws XPathException; - /** - * Evaluates the given expression, handling the result {@link Node} objects on a per-node basis with a {@link - * NodeCallbackHandler}. - * - * @param expression the XPath expression - * @param context the context starting point - * @param callbackHandler object that will extract results, one row at a time - * @throws XPathException in case of XPath errors - * @see XPath specification - */ - void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler) throws XPathException; + /** + * Evaluates the given expression, handling the result {@link Node} objects on a per-node basis with a {@link + * NodeCallbackHandler}. + * + * @param expression the XPath expression + * @param context the context starting point + * @param callbackHandler object that will extract results, one row at a time + * @throws XPathException in case of XPath errors + * @see XPath specification + */ + void evaluate(String expression, Source context, NodeCallbackHandler callbackHandler) throws XPathException; } diff --git a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathParseException.java b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathParseException.java index aca2d81f..f2f04757 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xpath/XPathParseException.java +++ b/spring-xml/src/main/java/org/springframework/xml/xpath/XPathParseException.java @@ -25,23 +25,23 @@ package org.springframework.xml.xpath; @SuppressWarnings("serial") public class XPathParseException extends XPathException { - /** - * Constructs a new instance of the {@code XPathParseException} with the specific detail message. - * - * @param message the detail message - */ - public XPathParseException(String message) { - super(message); - } + /** + * Constructs a new instance of the {@code XPathParseException} with the specific detail message. + * + * @param message the detail message + */ + public XPathParseException(String message) { + super(message); + } - /** - * Constructs a new instance of the {@code XPathParseException} with the specific detail message and - * exception. - * - * @param message the detail message - * @param throwable the wrapped exception - */ - public XPathParseException(String message, Throwable throwable) { - super(message, throwable); - } + /** + * Constructs a new instance of the {@code XPathParseException} with the specific detail message and + * exception. + * + * @param message the detail message + * @param throwable the wrapped exception + */ + public XPathParseException(String message, Throwable throwable) { + super(message, throwable); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/SimpleXsdSchema.java b/spring-xml/src/main/java/org/springframework/xml/xsd/SimpleXsdSchema.java index 93193db8..f2bc09d8 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/SimpleXsdSchema.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/SimpleXsdSchema.java @@ -47,93 +47,93 @@ import org.springframework.xml.validation.XmlValidatorFactory; */ public class SimpleXsdSchema implements XsdSchema, InitializingBean { - private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - private static final String SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"; + private static final String SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"; - private static final QName SCHEMA_NAME = new QName(SCHEMA_NAMESPACE, "schema", "xsd"); + private static final QName SCHEMA_NAME = new QName(SCHEMA_NAMESPACE, "schema", "xsd"); private Resource xsdResource; - private Element schemaElement; + private Element schemaElement; - static { - documentBuilderFactory.setNamespaceAware(true); - } + static { + documentBuilderFactory.setNamespaceAware(true); + } - /** - * Create a new instance of the {@link SimpleXsdSchema} class. - * - *

A subsequent call to the {@link #setXsd(Resource)} method is required. - */ - public SimpleXsdSchema() { - } + /** + * Create a new instance of the {@link SimpleXsdSchema} class. + * + *

A subsequent call to the {@link #setXsd(Resource)} method is required. + */ + public SimpleXsdSchema() { + } - /** - * Create a new instance of the {@link SimpleXsdSchema} class with the specified resource. - * - * @param xsdResource the XSD resource; must not be {@code null} - * @throws IllegalArgumentException if the supplied {@code xsdResource} is {@code null} - */ - public SimpleXsdSchema(Resource xsdResource) { - Assert.notNull(xsdResource, "xsdResource must not be null"); - this.xsdResource = xsdResource; - } + /** + * Create a new instance of the {@link SimpleXsdSchema} class with the specified resource. + * + * @param xsdResource the XSD resource; must not be {@code null} + * @throws IllegalArgumentException if the supplied {@code xsdResource} is {@code null} + */ + public SimpleXsdSchema(Resource xsdResource) { + Assert.notNull(xsdResource, "xsdResource must not be null"); + this.xsdResource = xsdResource; + } - /** - * Set the XSD resource to be exposed by calls to this instances' {@link #getSource()} method. - * - * @param xsdResource the XSD resource - */ - public void setXsd(Resource xsdResource) { - this.xsdResource = xsdResource; - } + /** + * Set the XSD resource to be exposed by calls to this instances' {@link #getSource()} method. + * + * @param xsdResource the XSD resource + */ + public void setXsd(Resource xsdResource) { + this.xsdResource = xsdResource; + } - @Override - public String getTargetNamespace() { - return schemaElement.getAttribute("targetNamespace"); - } + @Override + public String getTargetNamespace() { + return schemaElement.getAttribute("targetNamespace"); + } - @Override - public Source getSource() { - return new DOMSource(schemaElement); - } + @Override + public Source getSource() { + return new DOMSource(schemaElement); + } - @Override - public XmlValidator createValidator() { - try { - return XmlValidatorFactory.createValidator(xsdResource, XmlValidatorFactory.SCHEMA_W3C_XML); - } - catch (IOException ex) { - throw new XsdSchemaException(ex.getMessage(), ex); - } - } + @Override + public XmlValidator createValidator() { + try { + return XmlValidatorFactory.createValidator(xsdResource, XmlValidatorFactory.SCHEMA_W3C_XML); + } + catch (IOException ex) { + throw new XsdSchemaException(ex.getMessage(), ex); + } + } - @Override - public void afterPropertiesSet() throws ParserConfigurationException, IOException, SAXException { - Assert.notNull(xsdResource, "'xsd' is required"); - Assert.isTrue(this.xsdResource.exists(), "xsd '" + this.xsdResource + "' does not exist"); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - loadSchema(documentBuilder); - } + @Override + public void afterPropertiesSet() throws ParserConfigurationException, IOException, SAXException { + Assert.notNull(xsdResource, "'xsd' is required"); + Assert.isTrue(this.xsdResource.exists(), "xsd '" + this.xsdResource + "' does not exist"); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + loadSchema(documentBuilder); + } - private void loadSchema(DocumentBuilder documentBuilder) throws SAXException, IOException { - Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(xsdResource)); - schemaElement = schemaDocument.getDocumentElement(); - Assert.isTrue(SCHEMA_NAME.getLocalPart().equals(schemaElement.getLocalName()), - xsdResource + " has invalid root element : [" + schemaElement.getLocalName() + "] instead of [schema]"); - Assert.isTrue(SCHEMA_NAME.getNamespaceURI().equals(schemaElement.getNamespaceURI()), xsdResource + - " has invalid root element: [" + schemaElement.getNamespaceURI() + "] instead of [" + - SCHEMA_NAME.getNamespaceURI() + "]"); - Assert.hasText(getTargetNamespace(), xsdResource + " has no targetNamespace"); - } + private void loadSchema(DocumentBuilder documentBuilder) throws SAXException, IOException { + Document schemaDocument = documentBuilder.parse(SaxUtils.createInputSource(xsdResource)); + schemaElement = schemaDocument.getDocumentElement(); + Assert.isTrue(SCHEMA_NAME.getLocalPart().equals(schemaElement.getLocalName()), + xsdResource + " has invalid root element : [" + schemaElement.getLocalName() + "] instead of [schema]"); + Assert.isTrue(SCHEMA_NAME.getNamespaceURI().equals(schemaElement.getNamespaceURI()), xsdResource + + " has invalid root element: [" + schemaElement.getNamespaceURI() + "] instead of [" + + SCHEMA_NAME.getNamespaceURI() + "]"); + Assert.hasText(getTargetNamespace(), xsdResource + " has no targetNamespace"); + } - public String toString() { - StringBuilder builder = new StringBuilder("SimpleXsdSchema"); - builder.append('{'); - builder.append(getTargetNamespace()); - builder.append('}'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("SimpleXsdSchema"); + builder.append('{'); + builder.append(getTargetNamespace()); + builder.append('}'); + return builder.toString(); + } } \ No newline at end of file diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchema.java b/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchema.java index fbbf262d..8292c7a9 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchema.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchema.java @@ -29,24 +29,24 @@ import org.springframework.xml.validation.XmlValidator; */ public interface XsdSchema { - /** - * Returns the target namespace of this schema. - * - * @return the target namespace - */ - String getTargetNamespace(); + /** + * Returns the target namespace of this schema. + * + * @return the target namespace + */ + String getTargetNamespace(); - /** - * Returns the {@link Source} of the schema. - * - * @return the source of this XSD schema - */ - Source getSource(); + /** + * Returns the {@link Source} of the schema. + * + * @return the source of this XSD schema + */ + Source getSource(); - /** - * Creates a {@link XmlValidator} based on the schema. - * - * @return a validator for this schema - */ - XmlValidator createValidator(); + /** + * Creates a {@link XmlValidator} based on the schema. + * + * @return a validator for this schema + */ + XmlValidator createValidator(); } diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaCollection.java b/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaCollection.java index da0e49b5..78c3e32a 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaCollection.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaCollection.java @@ -26,18 +26,18 @@ import org.springframework.xml.validation.XmlValidator; */ public interface XsdSchemaCollection { - /** - * Returns all schemas contained in this collection. - * - * @return the schemas contained in this collection - */ - XsdSchema[] getXsdSchemas(); + /** + * Returns all schemas contained in this collection. + * + * @return the schemas contained in this collection + */ + XsdSchema[] getXsdSchemas(); - /** - * Creates a {@link XmlValidator} based on the schemas contained in this collection. - * - * @return a validator for this collection - */ - XmlValidator createValidator(); + /** + * Creates a {@link XmlValidator} based on the schemas contained in this collection. + * + * @return a validator for this collection + */ + XmlValidator createValidator(); } diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaException.java b/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaException.java index d6cd0b63..e475bbf1 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaException.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/XsdSchemaException.java @@ -28,11 +28,11 @@ import org.springframework.xml.XmlException; @SuppressWarnings("serial") public class XsdSchemaException extends XmlException { - public XsdSchemaException(String message) { - super(message); - } + public XsdSchemaException(String message) { + super(message); + } - public XsdSchemaException(String message, Throwable throwable) { - super(message, throwable); - } + public XsdSchemaException(String message, Throwable throwable) { + super(message, throwable); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchema.java b/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchema.java index fa89208c..628d0ac9 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchema.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchema.java @@ -50,95 +50,95 @@ import org.springframework.xml.xsd.XsdSchema; */ public class CommonsXsdSchema implements XsdSchema { - private final XmlSchema schema; + private final XmlSchema schema; - private final XmlSchemaCollection collection; + private final XmlSchemaCollection collection; - /** - * Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} reference. - * - * @param schema the Commons {@code XmlSchema} object; must not be {@code null} - * @throws IllegalArgumentException if the supplied {@code schema} is {@code null} - */ - protected CommonsXsdSchema(XmlSchema schema) { - this(schema, null); - } + /** + * Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} reference. + * + * @param schema the Commons {@code XmlSchema} object; must not be {@code null} + * @throws IllegalArgumentException if the supplied {@code schema} is {@code null} + */ + protected CommonsXsdSchema(XmlSchema schema) { + this(schema, null); + } - /** - * Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} and {@link - * XmlSchemaCollection} reference. - * - * @param schema the Commons {@code XmlSchema} object; must not be {@code null} - * @param collection the Commons {@code XmlSchemaCollection} object; can be {@code null} - * @throws IllegalArgumentException if the supplied {@code schema} is {@code null} - */ - protected CommonsXsdSchema(XmlSchema schema, XmlSchemaCollection collection) { - Assert.notNull(schema, "'schema' must not be null"); - this.schema = schema; - this.collection = collection; - } + /** + * Create a new instance of the {@code CommonsXsdSchema} class with the specified {@link XmlSchema} and {@link + * XmlSchemaCollection} reference. + * + * @param schema the Commons {@code XmlSchema} object; must not be {@code null} + * @param collection the Commons {@code XmlSchemaCollection} object; can be {@code null} + * @throws IllegalArgumentException if the supplied {@code schema} is {@code null} + */ + protected CommonsXsdSchema(XmlSchema schema, XmlSchemaCollection collection) { + Assert.notNull(schema, "'schema' must not be null"); + this.schema = schema; + this.collection = collection; + } - @Override - public String getTargetNamespace() { - return schema.getTargetNamespace(); - } + @Override + public String getTargetNamespace() { + return schema.getTargetNamespace(); + } - public QName[] getElementNames() { - List result = new ArrayList(schema.getElements().keySet()); - return result.toArray(new QName[result.size()]); - } + public QName[] getElementNames() { + List result = new ArrayList(schema.getElements().keySet()); + return result.toArray(new QName[result.size()]); + } - @Override - public Source getSource() { - // try to use the the package-friendly XmlSchemaSerializer first, fall back to slower stream-based version - try { - XmlSchemaSerializer serializer = BeanUtils.instantiateClass(XmlSchemaSerializer.class); - if (collection != null) { - serializer.setExtReg(collection.getExtReg()); - } - Document[] serializedSchemas = serializer.serializeSchema(schema, false); - return new DOMSource(serializedSchemas[0]); - } - catch (BeanInstantiationException ex) { - // ignore - } - catch (XmlSchemaSerializer.XmlSchemaSerializerException ex) { - // ignore - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - schema.write(bos); - } - catch (UnsupportedEncodingException ex) { - throw new CommonsXsdSchemaException(ex.getMessage(), ex); - } - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - return new StreamSource(bis); - } + @Override + public Source getSource() { + // try to use the the package-friendly XmlSchemaSerializer first, fall back to slower stream-based version + try { + XmlSchemaSerializer serializer = BeanUtils.instantiateClass(XmlSchemaSerializer.class); + if (collection != null) { + serializer.setExtReg(collection.getExtReg()); + } + Document[] serializedSchemas = serializer.serializeSchema(schema, false); + return new DOMSource(serializedSchemas[0]); + } + catch (BeanInstantiationException ex) { + // ignore + } + catch (XmlSchemaSerializer.XmlSchemaSerializerException ex) { + // ignore + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + schema.write(bos); + } + catch (UnsupportedEncodingException ex) { + throw new CommonsXsdSchemaException(ex.getMessage(), ex); + } + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + return new StreamSource(bis); + } - @Override - public XmlValidator createValidator() { - try { - Resource resource = new UrlResource(schema.getSourceURI()); - return XmlValidatorFactory - .createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML); - } - catch (IOException ex) { - throw new CommonsXsdSchemaException(ex.getMessage(), ex); - } - } + @Override + public XmlValidator createValidator() { + try { + Resource resource = new UrlResource(schema.getSourceURI()); + return XmlValidatorFactory + .createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML); + } + catch (IOException ex) { + throw new CommonsXsdSchemaException(ex.getMessage(), ex); + } + } - /** Returns the wrapped Commons {@code XmlSchema} object. */ - public XmlSchema getSchema() { - return schema; - } + /** Returns the wrapped Commons {@code XmlSchema} object. */ + public XmlSchema getSchema() { + return schema; + } - public String toString() { - StringBuilder builder = new StringBuilder("CommonsXsdSchema"); - builder.append('{'); - builder.append(getTargetNamespace()); - builder.append('}'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("CommonsXsdSchema"); + builder.append('{'); + builder.append(getTargetNamespace()); + builder.append('}'); + return builder.toString(); + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollection.java b/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollection.java index 2a3335f5..7db35589 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollection.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollection.java @@ -60,225 +60,225 @@ import org.springframework.xml.xsd.XsdSchemaCollection; */ public class CommonsXsdSchemaCollection implements XsdSchemaCollection, InitializingBean, ResourceLoaderAware { - private static final Log logger = LogFactory.getLog(CommonsXsdSchemaCollection.class); + private static final Log logger = LogFactory.getLog(CommonsXsdSchemaCollection.class); - private final XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); + private final XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); - private final List xmlSchemas = new ArrayList(); + private final List xmlSchemas = new ArrayList(); - private Resource[] xsdResources; + private Resource[] xsdResources; - private boolean inline = false; + private boolean inline = false; - private URIResolver uriResolver = new ClasspathUriResolver(); + private URIResolver uriResolver = new ClasspathUriResolver(); - private ResourceLoader resourceLoader; + private ResourceLoader resourceLoader; - /** - * Constructs a new, empty instance of the {@code CommonsXsdSchemaCollection}. - * - *

A subsequent call to the {@link #setXsds(Resource[])} is required. - */ - public CommonsXsdSchemaCollection() { - } + /** + * Constructs a new, empty instance of the {@code CommonsXsdSchemaCollection}. + * + *

A subsequent call to the {@link #setXsds(Resource[])} is required. + */ + public CommonsXsdSchemaCollection() { + } - /** - * Constructs a new instance of the {@code CommonsXsdSchemaCollection} based on the given resources. - * - * @param resources the schema resources to load - */ - public CommonsXsdSchemaCollection(Resource[] resources) { - this.xsdResources = resources; - } + /** + * Constructs a new instance of the {@code CommonsXsdSchemaCollection} based on the given resources. + * + * @param resources the schema resources to load + */ + public CommonsXsdSchemaCollection(Resource[] resources) { + this.xsdResources = resources; + } - /** - * Sets the schema resources to be loaded. - * - * @param xsdResources the schema resources to be loaded - */ - public void setXsds(Resource[] xsdResources) { - this.xsdResources = xsdResources; - } + /** + * Sets the schema resources to be loaded. + * + * @param xsdResources the schema resources to be loaded + */ + public void setXsds(Resource[] xsdResources) { + this.xsdResources = xsdResources; + } - /** - * Defines whether included schemas should be inlined into the including schema. - * - *

Defaults to {@code false}. - */ - public void setInline(boolean inline) { - this.inline = inline; - } + /** + * Defines whether included schemas should be inlined into the including schema. + * + *

Defaults to {@code false}. + */ + public void setInline(boolean inline) { + this.inline = inline; + } - /** - * Sets the WS-Commons uri resolver to use when resolving (relative) schemas. - * - *

Default is an internal subclass of {@link DefaultURIResolver} which correctly handles schemas on the classpath. - */ - public void setUriResolver(URIResolver uriResolver) { - Assert.notNull(uriResolver, "'uriResolver' must not be null"); - this.uriResolver = uriResolver; - } + /** + * Sets the WS-Commons uri resolver to use when resolving (relative) schemas. + * + *

Default is an internal subclass of {@link DefaultURIResolver} which correctly handles schemas on the classpath. + */ + public void setUriResolver(URIResolver uriResolver) { + Assert.notNull(uriResolver, "'uriResolver' must not be null"); + this.uriResolver = uriResolver; + } - @Override - public void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - } + @Override + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } - @Override - public void afterPropertiesSet() throws IOException { - Assert.notEmpty(xsdResources, "'xsds' must not be empty"); + @Override + public void afterPropertiesSet() throws IOException { + Assert.notEmpty(xsdResources, "'xsds' must not be empty"); - schemaCollection.setSchemaResolver(uriResolver); + schemaCollection.setSchemaResolver(uriResolver); - Set processedIncludes = new HashSet(); - Set processedImports = new HashSet(); + Set processedIncludes = new HashSet(); + Set processedImports = new HashSet(); - for (Resource xsdResource : xsdResources) { - Assert.isTrue(xsdResource.exists(), xsdResource + " does not exit"); - try { - XmlSchema xmlSchema = - schemaCollection.read(SaxUtils.createInputSource(xsdResource)); - xmlSchemas.add(xmlSchema); + for (Resource xsdResource : xsdResources) { + Assert.isTrue(xsdResource.exists(), xsdResource + " does not exit"); + try { + XmlSchema xmlSchema = + schemaCollection.read(SaxUtils.createInputSource(xsdResource)); + xmlSchemas.add(xmlSchema); - if (inline) { - inlineIncludes(xmlSchema, processedIncludes, processedImports); - findImports(xmlSchema, processedImports, processedIncludes); - } - } - catch (Exception ex) { - throw new CommonsXsdSchemaException("Schema [" + xsdResource + "] could not be loaded", ex); - } - } - if (logger.isInfoEnabled()) { - logger.info("Loaded " + StringUtils.arrayToCommaDelimitedString(xsdResources)); - } + if (inline) { + inlineIncludes(xmlSchema, processedIncludes, processedImports); + findImports(xmlSchema, processedImports, processedIncludes); + } + } + catch (Exception ex) { + throw new CommonsXsdSchemaException("Schema [" + xsdResource + "] could not be loaded", ex); + } + } + if (logger.isInfoEnabled()) { + logger.info("Loaded " + StringUtils.arrayToCommaDelimitedString(xsdResources)); + } - } + } - @Override - public XsdSchema[] getXsdSchemas() { - XsdSchema[] result = new XsdSchema[xmlSchemas.size()]; - for (int i = 0; i < xmlSchemas.size(); i++) { - XmlSchema xmlSchema = xmlSchemas.get(i); - result[i] = new CommonsXsdSchema(xmlSchema, schemaCollection); - } - return result; - } + @Override + public XsdSchema[] getXsdSchemas() { + XsdSchema[] result = new XsdSchema[xmlSchemas.size()]; + for (int i = 0; i < xmlSchemas.size(); i++) { + XmlSchema xmlSchema = xmlSchemas.get(i); + result[i] = new CommonsXsdSchema(xmlSchema, schemaCollection); + } + return result; + } - @Override - public XmlValidator createValidator() { - try { - Resource[] resources = new Resource[xmlSchemas.size()]; - for (int i = xmlSchemas.size() - 1; i >= 0; i--) { - XmlSchema xmlSchema = xmlSchemas.get(i); - String sourceUri = xmlSchema.getSourceURI(); - if (StringUtils.hasLength(sourceUri)) { - resources[i] = new UrlResource(sourceUri); - } - } - return XmlValidatorFactory - .createValidator(resources, XmlValidatorFactory.SCHEMA_W3C_XML); - } catch (IOException ex) { - throw new CommonsXsdSchemaException(ex.getMessage(), ex); - } - } + @Override + public XmlValidator createValidator() { + try { + Resource[] resources = new Resource[xmlSchemas.size()]; + for (int i = xmlSchemas.size() - 1; i >= 0; i--) { + XmlSchema xmlSchema = xmlSchemas.get(i); + String sourceUri = xmlSchema.getSourceURI(); + if (StringUtils.hasLength(sourceUri)) { + resources[i] = new UrlResource(sourceUri); + } + } + return XmlValidatorFactory + .createValidator(resources, XmlValidatorFactory.SCHEMA_W3C_XML); + } catch (IOException ex) { + throw new CommonsXsdSchemaException(ex.getMessage(), ex); + } + } - private void inlineIncludes(XmlSchema schema, Set processedIncludes, Set processedImports) { - processedIncludes.add(schema); + private void inlineIncludes(XmlSchema schema, Set processedIncludes, Set processedImports) { + processedIncludes.add(schema); - List schemaItems = schema.getItems(); - for (int i = 0; i < schemaItems.size(); i++) { - XmlSchemaObject schemaObject = schemaItems.get(i); - if (schemaObject instanceof XmlSchemaInclude) { - XmlSchema includedSchema = ((XmlSchemaInclude) schemaObject).getSchema(); - if (!processedIncludes.contains(includedSchema)) { - inlineIncludes(includedSchema, processedIncludes, processedImports); - findImports(includedSchema, processedImports, processedIncludes); - List includeItems = includedSchema.getItems(); - for (XmlSchemaObject includedItem : includeItems) { - schemaItems.add(includedItem); - } - } - // remove the - schemaItems.remove(i); - i--; - } - } - } + List schemaItems = schema.getItems(); + for (int i = 0; i < schemaItems.size(); i++) { + XmlSchemaObject schemaObject = schemaItems.get(i); + if (schemaObject instanceof XmlSchemaInclude) { + XmlSchema includedSchema = ((XmlSchemaInclude) schemaObject).getSchema(); + if (!processedIncludes.contains(includedSchema)) { + inlineIncludes(includedSchema, processedIncludes, processedImports); + findImports(includedSchema, processedImports, processedIncludes); + List includeItems = includedSchema.getItems(); + for (XmlSchemaObject includedItem : includeItems) { + schemaItems.add(includedItem); + } + } + // remove the + schemaItems.remove(i); + i--; + } + } + } - private void findImports(XmlSchema schema, Set processedImports, Set processedIncludes) { - processedImports.add(schema); - List externals = schema.getExternals(); - for (XmlSchemaExternal external : externals) { - if (external instanceof XmlSchemaImport) { - XmlSchemaImport schemaImport = (XmlSchemaImport) external; - XmlSchema importedSchema = schemaImport.getSchema(); - if (!"http://www.w3.org/XML/1998/namespace".equals(schemaImport.getNamespace()) && - importedSchema != null && !processedImports.contains(importedSchema)) { - inlineIncludes(importedSchema, processedIncludes, processedImports); - findImports(importedSchema, processedImports, processedIncludes); - xmlSchemas.add(importedSchema); - } - // remove the schemaLocation - external.setSchemaLocation(null); - } - } - } + private void findImports(XmlSchema schema, Set processedImports, Set processedIncludes) { + processedImports.add(schema); + List externals = schema.getExternals(); + for (XmlSchemaExternal external : externals) { + if (external instanceof XmlSchemaImport) { + XmlSchemaImport schemaImport = (XmlSchemaImport) external; + XmlSchema importedSchema = schemaImport.getSchema(); + if (!"http://www.w3.org/XML/1998/namespace".equals(schemaImport.getNamespace()) && + importedSchema != null && !processedImports.contains(importedSchema)) { + inlineIncludes(importedSchema, processedIncludes, processedImports); + findImports(importedSchema, processedImports, processedIncludes); + xmlSchemas.add(importedSchema); + } + // remove the schemaLocation + external.setSchemaLocation(null); + } + } + } - public String toString() { - StringBuilder builder = new StringBuilder("CommonsXsdSchemaCollection"); - builder.append('{'); - for (int i = 0; i < xmlSchemas.size(); i++) { - XmlSchema schema = xmlSchemas.get(i); - builder.append(schema.getTargetNamespace()); - if (i < xmlSchemas.size() - 1) { - builder.append(','); - } - } - builder.append('}'); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder("CommonsXsdSchemaCollection"); + builder.append('{'); + for (int i = 0; i < xmlSchemas.size(); i++) { + XmlSchema schema = xmlSchemas.get(i); + builder.append(schema.getTargetNamespace()); + if (i < xmlSchemas.size() - 1) { + builder.append(','); + } + } + builder.append('}'); + return builder.toString(); + } - private class ClasspathUriResolver extends DefaultURIResolver { + private class ClasspathUriResolver extends DefaultURIResolver { - @Override - public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) { - if (resourceLoader != null) { - Resource resource = resourceLoader.getResource(schemaLocation); - if (resource.exists()) { - return createInputSource(resource); - } - else if (StringUtils.hasLength(baseUri)) { - // let's try and find it relative to the baseUri, see SWS-413 - try { - Resource baseUriResource = new UrlResource(baseUri); - resource = baseUriResource.createRelative(schemaLocation); - if (resource.exists()) { - return createInputSource(resource); - } - } - catch (IOException e) { - // fall through - } - } - // let's try and find it on the classpath, see SWS-362 - String classpathLocation = ResourceLoader.CLASSPATH_URL_PREFIX + "/" + schemaLocation; - resource = resourceLoader.getResource(classpathLocation); - if (resource.exists()) { - return createInputSource(resource); - } - } - return super.resolveEntity(namespace, schemaLocation, baseUri); - } + @Override + public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) { + if (resourceLoader != null) { + Resource resource = resourceLoader.getResource(schemaLocation); + if (resource.exists()) { + return createInputSource(resource); + } + else if (StringUtils.hasLength(baseUri)) { + // let's try and find it relative to the baseUri, see SWS-413 + try { + Resource baseUriResource = new UrlResource(baseUri); + resource = baseUriResource.createRelative(schemaLocation); + if (resource.exists()) { + return createInputSource(resource); + } + } + catch (IOException e) { + // fall through + } + } + // let's try and find it on the classpath, see SWS-362 + String classpathLocation = ResourceLoader.CLASSPATH_URL_PREFIX + "/" + schemaLocation; + resource = resourceLoader.getResource(classpathLocation); + if (resource.exists()) { + return createInputSource(resource); + } + } + return super.resolveEntity(namespace, schemaLocation, baseUri); + } - private InputSource createInputSource(Resource resource) { - try { - return SaxUtils.createInputSource(resource); - } - catch (IOException ex) { - throw new CommonsXsdSchemaException("Could not resolve location", ex); - } - } - } + private InputSource createInputSource(Resource resource) { + try { + return SaxUtils.createInputSource(resource); + } + catch (IOException ex) { + throw new CommonsXsdSchemaException("Could not resolve location", ex); + } + } + } } diff --git a/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaException.java b/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaException.java index 9b09e7ba..b156b07d 100644 --- a/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaException.java +++ b/spring-xml/src/main/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaException.java @@ -27,11 +27,11 @@ import org.springframework.xml.xsd.XsdSchemaException; @SuppressWarnings("serial") public class CommonsXsdSchemaException extends XsdSchemaException { - public CommonsXsdSchemaException(String message) { - super(message); - } + public CommonsXsdSchemaException(String message) { + super(message); + } - public CommonsXsdSchemaException(String message, Throwable exception) { - super(message, exception); - } + public CommonsXsdSchemaException(String message, Throwable exception) { + super(message, exception); + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/dom/DomContentHandlerTest.java b/spring-xml/src/test/java/org/springframework/xml/dom/DomContentHandlerTest.java index c925b3cd..21637277 100644 --- a/spring-xml/src/test/java/org/springframework/xml/dom/DomContentHandlerTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/dom/DomContentHandlerTest.java @@ -32,64 +32,64 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class DomContentHandlerTest { - private static final String XML_1 = "" + "" + - "" + - "content" + - ""; + private static final String XML_1 = "" + "" + + "" + + "content" + + ""; - private static final String XML_2_EXPECTED = "" + "" + - "" + ""; + private static final String XML_2_EXPECTED = "" + "" + + "" + ""; - private static final String XML_2_SNIPPET = - "" + ""; + private static final String XML_2_SNIPPET = + "" + ""; - private Document expected; + private Document expected; - private DomContentHandler handler; + private DomContentHandler handler; - private Document result; + private Document result; - private XMLReader xmlReader; + private XMLReader xmlReader; - private DocumentBuilder documentBuilder; + private DocumentBuilder documentBuilder; - @Before - public void setUp() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - result = documentBuilder.newDocument(); - xmlReader = XMLReaderFactory.createXMLReader(); - } + @Before + public void setUp() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + result = documentBuilder.newDocument(); + xmlReader = XMLReaderFactory.createXMLReader(); + } - @Test - public void testContentHandlerDocumentNamespacePrefixes() throws Exception { - xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); - handler = new DomContentHandler(result); - expected = documentBuilder.parse(new InputSource(new StringReader(XML_1))); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_1))); - assertXMLEqual("Invalid result", expected, result); - } + @Test + public void testContentHandlerDocumentNamespacePrefixes() throws Exception { + xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + handler = new DomContentHandler(result); + expected = documentBuilder.parse(new InputSource(new StringReader(XML_1))); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_1))); + assertXMLEqual("Invalid result", expected, result); + } - @Test - public void testContentHandlerDocumentNoNamespacePrefixes() throws Exception { - handler = new DomContentHandler(result); - expected = documentBuilder.parse(new InputSource(new StringReader(XML_1))); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_1))); - assertXMLEqual("Invalid result", expected, result); - } + @Test + public void testContentHandlerDocumentNoNamespacePrefixes() throws Exception { + handler = new DomContentHandler(result); + expected = documentBuilder.parse(new InputSource(new StringReader(XML_1))); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_1))); + assertXMLEqual("Invalid result", expected, result); + } - @Test - public void testContentHandlerElement() throws Exception { - Element rootElement = result.createElementNS("namespace", "root"); - result.appendChild(rootElement); - handler = new DomContentHandler(rootElement); - expected = documentBuilder.parse(new InputSource(new StringReader(XML_2_EXPECTED))); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); - assertXMLEqual("Invalid result", expected, result); + @Test + public void testContentHandlerElement() throws Exception { + Element rootElement = result.createElementNS("namespace", "root"); + result.appendChild(rootElement); + handler = new DomContentHandler(rootElement); + expected = documentBuilder.parse(new InputSource(new StringReader(XML_2_EXPECTED))); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET))); + assertXMLEqual("Invalid result", expected, result); - } + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/namespace/QNameEditorTest.java b/spring-xml/src/test/java/org/springframework/xml/namespace/QNameEditorTest.java index 2e8cb9e3..82a12239 100644 --- a/spring-xml/src/test/java/org/springframework/xml/namespace/QNameEditorTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/namespace/QNameEditorTest.java @@ -24,41 +24,41 @@ import org.junit.Test; public class QNameEditorTest { - private QNameEditor editor; + private QNameEditor editor; - @Before - public void setUp() throws Exception { - editor = new QNameEditor(); - } + @Before + public void setUp() throws Exception { + editor = new QNameEditor(); + } - @Test - public void testNamespaceLocalPartPrefix() throws Exception { - QName qname = new QName("namespace", "localpart", "prefix"); - doTest(qname); - } + @Test + public void testNamespaceLocalPartPrefix() throws Exception { + QName qname = new QName("namespace", "localpart", "prefix"); + doTest(qname); + } - @Test - public void testNamespaceLocalPart() throws Exception { - QName qname = new QName("namespace", "localpart"); - doTest(qname); - } + @Test + public void testNamespaceLocalPart() throws Exception { + QName qname = new QName("namespace", "localpart"); + doTest(qname); + } - @Test - public void testLocalPart() throws Exception { - QName qname = new QName("localpart"); - doTest(qname); - } + @Test + public void testLocalPart() throws Exception { + QName qname = new QName("localpart"); + doTest(qname); + } - private void doTest(QName qname) { - editor.setValue(qname); - String text = editor.getAsText(); - Assert.assertNotNull("getAsText returns null", text); - editor.setAsText(text); - QName result = (QName) editor.getValue(); - Assert.assertNotNull("getValue returns null", result); - Assert.assertEquals("Parsed QName local part is not equal to original", qname.getLocalPart(), result.getLocalPart()); - Assert.assertEquals("Parsed QName prefix is not equal to original", qname.getPrefix(), result.getPrefix()); - Assert.assertEquals("Parsed QName namespace is not equal to original", qname.getNamespaceURI(), - result.getNamespaceURI()); - } + private void doTest(QName qname) { + editor.setValue(qname); + String text = editor.getAsText(); + Assert.assertNotNull("getAsText returns null", text); + editor.setAsText(text); + QName result = (QName) editor.getValue(); + Assert.assertNotNull("getValue returns null", result); + Assert.assertEquals("Parsed QName local part is not equal to original", qname.getLocalPart(), result.getLocalPart()); + Assert.assertEquals("Parsed QName prefix is not equal to original", qname.getPrefix(), result.getPrefix()); + Assert.assertEquals("Parsed QName namespace is not equal to original", qname.getNamespaceURI(), + result.getNamespaceURI()); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/namespace/QNameUtilsTest.java b/spring-xml/src/test/java/org/springframework/xml/namespace/QNameUtilsTest.java index dade17fa..4535ffd3 100644 --- a/spring-xml/src/test/java/org/springframework/xml/namespace/QNameUtilsTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/namespace/QNameUtilsTest.java @@ -29,89 +29,89 @@ import org.w3c.dom.Element; public class QNameUtilsTest { - @Test - public void testValidQNames() { - Assert.assertTrue("Namespace QName not validated", QNameUtils.validateQName("{namespace}local")); - Assert.assertTrue("No Namespace QName not validated", QNameUtils.validateQName("local")); - } + @Test + public void testValidQNames() { + Assert.assertTrue("Namespace QName not validated", QNameUtils.validateQName("{namespace}local")); + Assert.assertTrue("No Namespace QName not validated", QNameUtils.validateQName("local")); + } - @Test - public void testInvalidQNames() { - Assert.assertFalse("Null QName validated", QNameUtils.validateQName(null)); - Assert.assertFalse("Empty QName validated", QNameUtils.validateQName("")); - Assert.assertFalse("Invalid QName validated", QNameUtils.validateQName("{namespace}")); - Assert.assertFalse("Invalid QName validated", QNameUtils.validateQName("{namespace")); - } + @Test + public void testInvalidQNames() { + Assert.assertFalse("Null QName validated", QNameUtils.validateQName(null)); + Assert.assertFalse("Empty QName validated", QNameUtils.validateQName("")); + Assert.assertFalse("Invalid QName validated", QNameUtils.validateQName("{namespace}")); + Assert.assertFalse("Invalid QName validated", QNameUtils.validateQName("{namespace")); + } - @Test - public void testGetQNameForNodeNoNamespace() throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Element element = document.createElement("localname"); - QName qName = QNameUtils.getQNameForNode(element); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertFalse("Qname has invalid namespace", StringUtils.hasLength(qName.getNamespaceURI())); - Assert.assertFalse("Qname has invalid prefix", StringUtils.hasLength(qName.getPrefix())); + @Test + public void testGetQNameForNodeNoNamespace() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Element element = document.createElement("localname"); + QName qName = QNameUtils.getQNameForNode(element); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertFalse("Qname has invalid namespace", StringUtils.hasLength(qName.getNamespaceURI())); + Assert.assertFalse("Qname has invalid prefix", StringUtils.hasLength(qName.getPrefix())); - } + } - @Test - public void testGetQNameForNodeNoPrefix() throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Element element = document.createElementNS("namespace", "localname"); - QName qName = QNameUtils.getQNameForNode(element); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertFalse("Qname has invalid prefix", StringUtils.hasLength(qName.getPrefix())); - } + @Test + public void testGetQNameForNodeNoPrefix() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Element element = document.createElementNS("namespace", "localname"); + QName qName = QNameUtils.getQNameForNode(element); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertFalse("Qname has invalid prefix", StringUtils.hasLength(qName.getPrefix())); + } - @Test - public void testGetQNameForNode() throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Element element = document.createElementNS("namespace", "prefix:localname"); - QName qName = QNameUtils.getQNameForNode(element); - Assert.assertNotNull("getQNameForNode returns null", qName); - Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); - Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); - Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); - } + @Test + public void testGetQNameForNode() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Element element = document.createElementNS("namespace", "prefix:localname"); + QName qName = QNameUtils.getQNameForNode(element); + Assert.assertNotNull("getQNameForNode returns null", qName); + Assert.assertEquals("QName has invalid localname", "localname", qName.getLocalPart()); + Assert.assertEquals("Qname has invalid namespace", "namespace", qName.getNamespaceURI()); + Assert.assertEquals("Qname has invalid prefix", "prefix", qName.getPrefix()); + } - @Test - public void testToQualifiedNamePrefix() throws Exception { - QName qName = new QName("namespace", "localName", "prefix"); - String result = QNameUtils.toQualifiedName(qName); - Assert.assertEquals("Invalid result", "prefix:localName", result); - } + @Test + public void testToQualifiedNamePrefix() throws Exception { + QName qName = new QName("namespace", "localName", "prefix"); + String result = QNameUtils.toQualifiedName(qName); + Assert.assertEquals("Invalid result", "prefix:localName", result); + } - @Test - public void testToQualifiedNameNoPrefix() throws Exception { - QName qName = new QName("localName"); - String result = QNameUtils.toQualifiedName(qName); - Assert.assertEquals("Invalid result", "localName", result); - } + @Test + public void testToQualifiedNameNoPrefix() throws Exception { + QName qName = new QName("localName"); + String result = QNameUtils.toQualifiedName(qName); + Assert.assertEquals("Invalid result", "localName", result); + } - @Test - public void testToQNamePrefix() throws Exception { - QName result = QNameUtils.toQName("namespace", "prefix:localName"); - Assert.assertEquals("invalid namespace", "namespace", result.getNamespaceURI()); - Assert.assertEquals("invalid prefix", "prefix", result.getPrefix()); - Assert.assertEquals("invalid localname", "localName", result.getLocalPart()); - } + @Test + public void testToQNamePrefix() throws Exception { + QName result = QNameUtils.toQName("namespace", "prefix:localName"); + Assert.assertEquals("invalid namespace", "namespace", result.getNamespaceURI()); + Assert.assertEquals("invalid prefix", "prefix", result.getPrefix()); + Assert.assertEquals("invalid localname", "localName", result.getLocalPart()); + } - @Test - public void testToQNameNoPrefix() throws Exception { - QName result = QNameUtils.toQName("namespace", "localName"); - Assert.assertEquals("invalid namespace", "namespace", result.getNamespaceURI()); - Assert.assertEquals("invalid prefix", "", result.getPrefix()); - Assert.assertEquals("invalid localname", "localName", result.getLocalPart()); - } + @Test + public void testToQNameNoPrefix() throws Exception { + QName result = QNameUtils.toQName("namespace", "localName"); + Assert.assertEquals("invalid namespace", "namespace", result.getNamespaceURI()); + Assert.assertEquals("invalid prefix", "", result.getPrefix()); + Assert.assertEquals("invalid localname", "localName", result.getLocalPart()); + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/namespace/SimpleNamespaceContextTest.java b/spring-xml/src/test/java/org/springframework/xml/namespace/SimpleNamespaceContextTest.java index 2d19d34b..f0c42a5e 100644 --- a/spring-xml/src/test/java/org/springframework/xml/namespace/SimpleNamespaceContextTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/namespace/SimpleNamespaceContextTest.java @@ -26,157 +26,157 @@ import org.junit.Test; public class SimpleNamespaceContextTest { - private SimpleNamespaceContext context; + private SimpleNamespaceContext context; - @Before - public void setUp() throws Exception { - context = new SimpleNamespaceContext(); - context.bindNamespaceUri("prefix", "namespaceURI"); - } + @Before + public void setUp() throws Exception { + context = new SimpleNamespaceContext(); + context.bindNamespaceUri("prefix", "namespaceURI"); + } - @Test - public void testGetNamespaceURI() { - Assert.assertEquals("Invalid namespaceURI for default namespace", "", context - .getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); - String defaultNamespaceUri = "defaultNamespace"; - context.bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, defaultNamespaceUri); - Assert.assertEquals("Invalid namespaceURI for default namespace", defaultNamespaceUri, context - .getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); - Assert.assertEquals("Invalid namespaceURI for bound prefix", "namespaceURI", context.getNamespaceURI("prefix")); - Assert.assertEquals("Invalid namespaceURI for unbound prefix", "", context.getNamespaceURI("unbound")); - Assert.assertEquals("Invalid namespaceURI for namespace prefix", XMLConstants.XML_NS_URI, context - .getNamespaceURI(XMLConstants.XML_NS_PREFIX)); - Assert.assertEquals("Invalid namespaceURI for attribute prefix", XMLConstants.XMLNS_ATTRIBUTE_NS_URI, context - .getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE)); + @Test + public void testGetNamespaceURI() { + Assert.assertEquals("Invalid namespaceURI for default namespace", "", context + .getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); + String defaultNamespaceUri = "defaultNamespace"; + context.bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, defaultNamespaceUri); + Assert.assertEquals("Invalid namespaceURI for default namespace", defaultNamespaceUri, context + .getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)); + Assert.assertEquals("Invalid namespaceURI for bound prefix", "namespaceURI", context.getNamespaceURI("prefix")); + Assert.assertEquals("Invalid namespaceURI for unbound prefix", "", context.getNamespaceURI("unbound")); + Assert.assertEquals("Invalid namespaceURI for namespace prefix", XMLConstants.XML_NS_URI, context + .getNamespaceURI(XMLConstants.XML_NS_PREFIX)); + Assert.assertEquals("Invalid namespaceURI for attribute prefix", XMLConstants.XMLNS_ATTRIBUTE_NS_URI, context + .getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE)); - } + } - @Test - public void testGetPrefix() { - context.bindDefaultNamespaceUri("defaultNamespaceURI"); - Assert.assertEquals("Invalid prefix for default namespace", XMLConstants.DEFAULT_NS_PREFIX, context.getPrefix("defaultNamespaceURI")); - Assert.assertEquals("Invalid prefix for bound namespace", "prefix", context.getPrefix("namespaceURI")); - Assert.assertNull("Invalid prefix for unbound namespace", context.getPrefix("unbound")); - Assert.assertEquals("Invalid prefix for namespace", XMLConstants.XML_NS_PREFIX, context - .getPrefix(XMLConstants.XML_NS_URI)); - Assert.assertEquals("Invalid prefix for attribute namespace", XMLConstants.XMLNS_ATTRIBUTE, context - .getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)); - } + @Test + public void testGetPrefix() { + context.bindDefaultNamespaceUri("defaultNamespaceURI"); + Assert.assertEquals("Invalid prefix for default namespace", XMLConstants.DEFAULT_NS_PREFIX, context.getPrefix("defaultNamespaceURI")); + Assert.assertEquals("Invalid prefix for bound namespace", "prefix", context.getPrefix("namespaceURI")); + Assert.assertNull("Invalid prefix for unbound namespace", context.getPrefix("unbound")); + Assert.assertEquals("Invalid prefix for namespace", XMLConstants.XML_NS_PREFIX, context + .getPrefix(XMLConstants.XML_NS_URI)); + Assert.assertEquals("Invalid prefix for attribute namespace", XMLConstants.XMLNS_ATTRIBUTE, context + .getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)); + } - @Test - public void testGetPrefixes() { - context.bindDefaultNamespaceUri("defaultNamespaceURI"); - assertPrefixes("defaultNamespaceURI", XMLConstants.DEFAULT_NS_PREFIX); - assertPrefixes("namespaceURI", "prefix"); - Assert.assertFalse("Invalid prefix for unbound namespace", context.getPrefixes("unbound").hasNext()); - assertPrefixes(XMLConstants.XML_NS_URI, XMLConstants.XML_NS_PREFIX); - assertPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE); - } - - @Test(expected = UnsupportedOperationException.class) - public void unmodifiableGetPrefixes() { - String namespaceUri = "namespaceUri"; - context.bindNamespaceUri("prefix1", namespaceUri); - context.bindNamespaceUri("prefix2", namespaceUri); + @Test + public void testGetPrefixes() { + context.bindDefaultNamespaceUri("defaultNamespaceURI"); + assertPrefixes("defaultNamespaceURI", XMLConstants.DEFAULT_NS_PREFIX); + assertPrefixes("namespaceURI", "prefix"); + Assert.assertFalse("Invalid prefix for unbound namespace", context.getPrefixes("unbound").hasNext()); + assertPrefixes(XMLConstants.XML_NS_URI, XMLConstants.XML_NS_PREFIX); + assertPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE); + } - Iterator prefixes = context.getPrefixes(namespaceUri); - prefixes.next(); - prefixes.remove(); - } + @Test(expected = UnsupportedOperationException.class) + public void unmodifiableGetPrefixes() { + String namespaceUri = "namespaceUri"; + context.bindNamespaceUri("prefix1", namespaceUri); + context.bindNamespaceUri("prefix2", namespaceUri); - @Test - public void testMultiplePrefixes() { - context.bindNamespaceUri("prefix1", "namespace"); - context.bindNamespaceUri("prefix2", "namespace"); - Iterator iterator = context.getPrefixes("namespace"); - Assert.assertNotNull("getPrefixes returns null", iterator); - Assert.assertTrue("iterator is empty", iterator.hasNext()); - String result = iterator.next(); - Assert.assertTrue("Invalid prefix", result.equals("prefix1") || result.equals("prefix2")); - Assert.assertTrue("iterator is empty", iterator.hasNext()); - result = iterator.next(); - Assert.assertTrue("Invalid prefix", result.equals("prefix1") || result.equals("prefix2")); - Assert.assertFalse("iterator contains more than two values", iterator.hasNext()); - } + Iterator prefixes = context.getPrefixes(namespaceUri); + prefixes.next(); + prefixes.remove(); + } - private void assertPrefixes(String namespaceUri, String prefix) { - Iterator iterator = context.getPrefixes(namespaceUri); - Assert.assertNotNull("getPrefixes returns null", iterator); - Assert.assertTrue("iterator is empty", iterator.hasNext()); - String result = iterator.next(); - Assert.assertEquals("Invalid prefix", prefix, result); - Assert.assertFalse("iterator contains multiple values", iterator.hasNext()); - } + @Test + public void testMultiplePrefixes() { + context.bindNamespaceUri("prefix1", "namespace"); + context.bindNamespaceUri("prefix2", "namespace"); + Iterator iterator = context.getPrefixes("namespace"); + Assert.assertNotNull("getPrefixes returns null", iterator); + Assert.assertTrue("iterator is empty", iterator.hasNext()); + String result = iterator.next(); + Assert.assertTrue("Invalid prefix", result.equals("prefix1") || result.equals("prefix2")); + Assert.assertTrue("iterator is empty", iterator.hasNext()); + result = iterator.next(); + Assert.assertTrue("Invalid prefix", result.equals("prefix1") || result.equals("prefix2")); + Assert.assertFalse("iterator contains more than two values", iterator.hasNext()); + } - @Test - public void testGetBoundPrefixes() throws Exception { - Iterator iterator = context.getBoundPrefixes(); - Assert.assertNotNull("getPrefixes returns null", iterator); - Assert.assertTrue("iterator is empty", iterator.hasNext()); - String result = iterator.next(); - Assert.assertEquals("Invalid prefix", "prefix", result); - Assert.assertFalse("iterator contains multiple values", iterator.hasNext()); - } + private void assertPrefixes(String namespaceUri, String prefix) { + Iterator iterator = context.getPrefixes(namespaceUri); + Assert.assertNotNull("getPrefixes returns null", iterator); + Assert.assertTrue("iterator is empty", iterator.hasNext()); + String result = iterator.next(); + Assert.assertEquals("Invalid prefix", prefix, result); + Assert.assertFalse("iterator contains multiple values", iterator.hasNext()); + } - @Test - public void testSetBindings() throws Exception { - context.setBindings(Collections.singletonMap("prefix", "namespace")); - Assert.assertEquals("Invalid namespace uri", "namespace", context.getNamespaceURI("prefix")); - } + @Test + public void testGetBoundPrefixes() throws Exception { + Iterator iterator = context.getBoundPrefixes(); + Assert.assertNotNull("getPrefixes returns null", iterator); + Assert.assertTrue("iterator is empty", iterator.hasNext()); + String result = iterator.next(); + Assert.assertEquals("Invalid prefix", "prefix", result); + Assert.assertFalse("iterator contains multiple values", iterator.hasNext()); + } - @Test - public void testRemoveBinding() { - context.clear(); - String prefix1 = "prefix1"; - String prefix2 = "prefix2"; - String namespaceUri = "namespaceUri"; - context.bindNamespaceUri(prefix1, namespaceUri); - context.bindNamespaceUri(prefix2, namespaceUri); - Iterator iter = context.getPrefixes(namespaceUri); - Assert.assertTrue("iterator is empty", iter.hasNext()); - Assert.assertEquals(prefix1, iter.next()); - Assert.assertTrue("iterator is empty", iter.hasNext()); - Assert.assertEquals(prefix2, iter.next()); - Assert.assertFalse("iterator not empty", iter.hasNext()); + @Test + public void testSetBindings() throws Exception { + context.setBindings(Collections.singletonMap("prefix", "namespace")); + Assert.assertEquals("Invalid namespace uri", "namespace", context.getNamespaceURI("prefix")); + } - context.removeBinding(prefix1); + @Test + public void testRemoveBinding() { + context.clear(); + String prefix1 = "prefix1"; + String prefix2 = "prefix2"; + String namespaceUri = "namespaceUri"; + context.bindNamespaceUri(prefix1, namespaceUri); + context.bindNamespaceUri(prefix2, namespaceUri); + Iterator iter = context.getPrefixes(namespaceUri); + Assert.assertTrue("iterator is empty", iter.hasNext()); + Assert.assertEquals(prefix1, iter.next()); + Assert.assertTrue("iterator is empty", iter.hasNext()); + Assert.assertEquals(prefix2, iter.next()); + Assert.assertFalse("iterator not empty", iter.hasNext()); - iter = context.getPrefixes(namespaceUri); - Assert.assertTrue("iterator is empty", iter.hasNext()); - Assert.assertEquals(prefix2, iter.next()); - Assert.assertFalse("iterator not empty", iter.hasNext()); + context.removeBinding(prefix1); - context.removeBinding(prefix2); + iter = context.getPrefixes(namespaceUri); + Assert.assertTrue("iterator is empty", iter.hasNext()); + Assert.assertEquals(prefix2, iter.next()); + Assert.assertFalse("iterator not empty", iter.hasNext()); - iter = context.getPrefixes(namespaceUri); - Assert.assertFalse("iterator not empty", iter.hasNext()); - } + context.removeBinding(prefix2); - @Test - public void testHasBinding() { - context.clear(); - String prefix = "prefix"; - Assert.assertFalse("Context has binding", context.hasBinding(prefix)); - String namespaceUri = "namespaceUri"; - context.bindNamespaceUri(prefix, namespaceUri); - Assert.assertTrue("Context has no binding", context.hasBinding(prefix)); - } + iter = context.getPrefixes(namespaceUri); + Assert.assertFalse("iterator not empty", iter.hasNext()); + } - @Test - public void testDefaultNamespaceMultiplePrefixes() { - String defaultNamespace = "http://springframework.org/spring-ws"; - context.bindDefaultNamespaceUri(defaultNamespace); - context.bindNamespaceUri("prefix", defaultNamespace); - Assert.assertEquals("Invalid prefix", XMLConstants.DEFAULT_NS_PREFIX, context.getPrefix(defaultNamespace)); - Iterator iterator = context.getPrefixes(defaultNamespace); - Assert.assertNotNull("getPrefixes returns null", iterator); - Assert.assertTrue("iterator is empty", iterator.hasNext()); - String result = iterator.next(); - Assert.assertTrue("Invalid prefix", result.equals(XMLConstants.DEFAULT_NS_PREFIX) || result.equals("prefix")); - Assert.assertTrue("iterator is empty", iterator.hasNext()); - result = iterator.next(); - Assert.assertTrue("Invalid prefix", result.equals(XMLConstants.DEFAULT_NS_PREFIX) || result.equals("prefix")); - Assert.assertFalse("iterator contains more than two values", iterator.hasNext()); - } + @Test + public void testHasBinding() { + context.clear(); + String prefix = "prefix"; + Assert.assertFalse("Context has binding", context.hasBinding(prefix)); + String namespaceUri = "namespaceUri"; + context.bindNamespaceUri(prefix, namespaceUri); + Assert.assertTrue("Context has no binding", context.hasBinding(prefix)); + } + + @Test + public void testDefaultNamespaceMultiplePrefixes() { + String defaultNamespace = "http://springframework.org/spring-ws"; + context.bindDefaultNamespaceUri(defaultNamespace); + context.bindNamespaceUri("prefix", defaultNamespace); + Assert.assertEquals("Invalid prefix", XMLConstants.DEFAULT_NS_PREFIX, context.getPrefix(defaultNamespace)); + Iterator iterator = context.getPrefixes(defaultNamespace); + Assert.assertNotNull("getPrefixes returns null", iterator); + Assert.assertTrue("iterator is empty", iterator.hasNext()); + String result = iterator.next(); + Assert.assertTrue("Invalid prefix", result.equals(XMLConstants.DEFAULT_NS_PREFIX) || result.equals("prefix")); + Assert.assertTrue("iterator is empty", iterator.hasNext()); + result = iterator.next(); + Assert.assertTrue("Invalid prefix", result.equals(XMLConstants.DEFAULT_NS_PREFIX) || result.equals("prefix")); + Assert.assertFalse("iterator contains more than two values", iterator.hasNext()); + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/sax/SaxUtilsTest.java b/spring-xml/src/test/java/org/springframework/xml/sax/SaxUtilsTest.java index 96285163..5f6d9320 100644 --- a/spring-xml/src/test/java/org/springframework/xml/sax/SaxUtilsTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/sax/SaxUtilsTest.java @@ -24,11 +24,11 @@ import org.junit.Test; public class SaxUtilsTest { - @Test - public void testGetSystemId() throws Exception { - Resource resource = new FileSystemResource("/path with spaces/file with spaces.txt"); - String systemId = SaxUtils.getSystemId(resource); - Assert.assertNotNull("No systemId returned", systemId); - Assert.assertTrue("Invalid system id", systemId.endsWith("path%20with%20spaces/file%20with%20spaces.txt")); - } + @Test + public void testGetSystemId() throws Exception { + Resource resource = new FileSystemResource("/path with spaces/file with spaces.txt"); + String systemId = SaxUtils.getSystemId(resource); + Assert.assertNotNull("No systemId returned", systemId); + Assert.assertTrue("Invalid system id", systemId.endsWith("path%20with%20spaces/file%20with%20spaces.txt")); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/transform/ResourceSourceTest.java b/spring-xml/src/test/java/org/springframework/xml/transform/ResourceSourceTest.java index 086a474f..da184d77 100644 --- a/spring-xml/src/test/java/org/springframework/xml/transform/ResourceSourceTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/transform/ResourceSourceTest.java @@ -28,16 +28,16 @@ import org.w3c.dom.Element; public class ResourceSourceTest { - @Test - public void testStringSource() throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - DOMResult result = new DOMResult(); - ResourceSource source = new ResourceSource(new ClassPathResource("resourceSource.xml", getClass())); - transformer.transform(source, result); - Element rootElement = (Element) result.getNode().getFirstChild(); - Assert.assertEquals("Invalid local name", "content", rootElement.getLocalName()); - Assert.assertEquals("Invalid prefix", "prefix", rootElement.getPrefix()); - Assert.assertEquals("Invalid namespace", "namespace", rootElement.getNamespaceURI()); - } + @Test + public void testStringSource() throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + DOMResult result = new DOMResult(); + ResourceSource source = new ResourceSource(new ClassPathResource("resourceSource.xml", getClass())); + transformer.transform(source, result); + Element rootElement = (Element) result.getNode().getFirstChild(); + Assert.assertEquals("Invalid local name", "content", rootElement.getLocalName()); + Assert.assertEquals("Invalid prefix", "prefix", rootElement.getPrefix()); + Assert.assertEquals("Invalid namespace", "namespace", rootElement.getNamespaceURI()); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/transform/StringResultTest.java b/spring-xml/src/test/java/org/springframework/xml/transform/StringResultTest.java index f76b0217..cdc30532 100644 --- a/spring-xml/src/test/java/org/springframework/xml/transform/StringResultTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/transform/StringResultTest.java @@ -29,15 +29,15 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class StringResultTest { - @Test - public void testStringResult() throws Exception { - Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - Element element = document.createElementNS("namespace", "prefix:localName"); - document.appendChild(element); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - StringResult result = new StringResult(); - transformer.transform(new DOMSource(document), result); - assertXMLEqual("Invalid result", "", result.toString()); - } + @Test + public void testStringResult() throws Exception { + Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + Element element = document.createElementNS("namespace", "prefix:localName"); + document.appendChild(element); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + StringResult result = new StringResult(); + transformer.transform(new DOMSource(document), result); + assertXMLEqual("Invalid result", "", result.toString()); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/transform/StringSourceTest.java b/spring-xml/src/test/java/org/springframework/xml/transform/StringSourceTest.java index 6f0648f8..2f775e70 100644 --- a/spring-xml/src/test/java/org/springframework/xml/transform/StringSourceTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/transform/StringSourceTest.java @@ -27,15 +27,15 @@ import org.w3c.dom.Element; public class StringSourceTest { - @Test - public void testStringSource() throws TransformerException { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - String content = ""; - DOMResult result = new DOMResult(); - transformer.transform(new StringSource(content), result); - Element rootElement = (Element) result.getNode().getFirstChild(); - Assert.assertEquals("Invalid local name", "content", rootElement.getLocalName()); - Assert.assertEquals("Invalid prefix", "prefix", rootElement.getPrefix()); - Assert.assertEquals("Invalid namespace", "namespace", rootElement.getNamespaceURI()); - } + @Test + public void testStringSource() throws TransformerException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + String content = ""; + DOMResult result = new DOMResult(); + transformer.transform(new StringSource(content), result); + Element rootElement = (Element) result.getNode().getFirstChild(); + Assert.assertEquals("Invalid local name", "content", rootElement.getLocalName()); + Assert.assertEquals("Invalid prefix", "prefix", rootElement.getPrefix()); + Assert.assertEquals("Invalid namespace", "namespace", rootElement.getNamespaceURI()); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/transform/TransformerHelperTest.java b/spring-xml/src/test/java/org/springframework/xml/transform/TransformerHelperTest.java index 273622cf..78b0dd82 100644 --- a/spring-xml/src/test/java/org/springframework/xml/transform/TransformerHelperTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/transform/TransformerHelperTest.java @@ -30,31 +30,31 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class TransformerHelperTest { - private TransformerHelper helper; + private TransformerHelper helper; - @Before - public void setUp() throws Exception { - helper = new TransformerHelper(); - } + @Before + public void setUp() throws Exception { + helper = new TransformerHelper(); + } - @Test - public void defaultTransformerFactory() throws TransformerException, IOException, SAXException { - doTest(); - } + @Test + public void defaultTransformerFactory() throws TransformerException, IOException, SAXException { + doTest(); + } - @Test - public void customTransformerFactory() throws TransformerException, IOException, SAXException { - helper.setTransformerFactoryClass(TransformerFactoryImpl.class); - doTest(); - } + @Test + public void customTransformerFactory() throws TransformerException, IOException, SAXException { + helper.setTransformerFactoryClass(TransformerFactoryImpl.class); + doTest(); + } - private void doTest() throws TransformerException, SAXException, IOException { - String xml = "text"; - Source source = new StringSource(xml); - Result result = new StringResult(); + private void doTest() throws TransformerException, SAXException, IOException { + String xml = "text"; + Source source = new StringSource(xml); + Result result = new StringResult(); - helper.transform(source, result); + helper.transform(source, result); - assertXMLEqual(xml, result.toString()); - } + assertXMLEqual(xml, result.toString()); + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/transform/TraxUtilsTest.java b/spring-xml/src/test/java/org/springframework/xml/transform/TraxUtilsTest.java index 0a024d1c..a4e92914 100644 --- a/spring-xml/src/test/java/org/springframework/xml/transform/TraxUtilsTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/transform/TraxUtilsTest.java @@ -59,268 +59,268 @@ import static org.easymock.EasyMock.*; public class TraxUtilsTest { - @Test - public void testGetDocument() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - Assert.assertSame("Invalid document", document, TraxUtils.getDocument(new DOMSource(document))); - Element element = document.createElement("element"); - document.appendChild(element); - Assert.assertSame("Invalid document", document, TraxUtils.getDocument(new DOMSource(element))); - } + @Test + public void testGetDocument() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + Assert.assertSame("Invalid document", document, TraxUtils.getDocument(new DOMSource(document))); + Element element = document.createElement("element"); + document.appendChild(element); + Assert.assertSame("Invalid document", document, TraxUtils.getDocument(new DOMSource(element))); + } - @Test - public void testDoWithDomSource() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); + @Test + public void testDoWithDomSource() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.domSource(document); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.domSource(document); - replay(mock); + replay(mock); - TraxUtils.doWithSource(new DOMSource(document), mock); + TraxUtils.doWithSource(new DOMSource(document), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithDomResult() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); + @Test + public void testDoWithDomResult() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.domResult(document); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.domResult(document); - replay(mock); + replay(mock); - TraxUtils.doWithResult(new DOMResult(document), mock); + TraxUtils.doWithResult(new DOMResult(document), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithSaxSource() throws Exception { - XMLReader reader = XMLReaderFactory.createXMLReader(); - InputSource inputSource = new InputSource(); + @Test + public void testDoWithSaxSource() throws Exception { + XMLReader reader = XMLReaderFactory.createXMLReader(); + InputSource inputSource = new InputSource(); - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.saxSource(reader, inputSource); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.saxSource(reader, inputSource); - replay(mock); + replay(mock); - TraxUtils.doWithSource(new SAXSource(reader, inputSource), mock); + TraxUtils.doWithSource(new SAXSource(reader, inputSource), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithSaxResult() throws Exception { - ContentHandler contentHandler = new DefaultHandler(); - LexicalHandler lexicalHandler = new DefaultHandler2(); + @Test + public void testDoWithSaxResult() throws Exception { + ContentHandler contentHandler = new DefaultHandler(); + LexicalHandler lexicalHandler = new DefaultHandler2(); - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.saxResult(contentHandler, lexicalHandler); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.saxResult(contentHandler, lexicalHandler); - replay(mock); + replay(mock); - SAXResult result = new SAXResult(contentHandler); - result.setLexicalHandler(lexicalHandler); - TraxUtils.doWithResult(result, mock); + SAXResult result = new SAXResult(contentHandler); + result.setLexicalHandler(lexicalHandler); + TraxUtils.doWithResult(result, mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStaxSourceEventReader() throws Exception { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader("")); + @Test + public void testDoWithStaxSourceEventReader() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader("")); - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.staxSource(eventReader); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.staxSource(eventReader); - replay(mock); + replay(mock); - TraxUtils.doWithSource(StaxUtils.createStaxSource(eventReader), mock); + TraxUtils.doWithSource(StaxUtils.createStaxSource(eventReader), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStaxResultEventWriter() throws Exception { - XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); - XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new StringWriter()); + @Test + public void testDoWithStaxResultEventWriter() throws Exception { + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new StringWriter()); - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.staxResult(eventWriter); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.staxResult(eventWriter); - replay(mock); + replay(mock); - TraxUtils.doWithResult(StaxUtils.createStaxResult(eventWriter), mock); + TraxUtils.doWithResult(StaxUtils.createStaxResult(eventWriter), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStaxSourceStreamReader() throws Exception { - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader("")); + @Test + public void testDoWithStaxSourceStreamReader() throws Exception { + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader("")); - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.staxSource(streamReader); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.staxSource(streamReader); - replay(mock); + replay(mock); - TraxUtils.doWithSource(StaxUtils.createStaxSource(streamReader), mock); + TraxUtils.doWithSource(StaxUtils.createStaxSource(streamReader), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStaxResultStreamWriter() throws Exception { - XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); - XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(new StringWriter()); + @Test + public void testDoWithStaxResultStreamWriter() throws Exception { + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(new StringWriter()); - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.staxResult(streamWriter); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.staxResult(streamWriter); - replay(mock); + replay(mock); - TraxUtils.doWithResult(StaxUtils.createStaxResult(streamWriter), mock); + TraxUtils.doWithResult(StaxUtils.createStaxResult(streamWriter), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStreamSourceInputStream() throws Exception { - byte[] xml = "".getBytes("UTF-8"); - InputStream inputStream = new ByteArrayInputStream(xml); + @Test + public void testDoWithStreamSourceInputStream() throws Exception { + byte[] xml = "".getBytes("UTF-8"); + InputStream inputStream = new ByteArrayInputStream(xml); - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.streamSource(inputStream); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.streamSource(inputStream); - replay(mock); + replay(mock); - TraxUtils.doWithSource(new StreamSource(inputStream), mock); + TraxUtils.doWithSource(new StreamSource(inputStream), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStreamResultOutputStream() throws Exception { - OutputStream outputStream = new ByteArrayOutputStream(); + @Test + public void testDoWithStreamResultOutputStream() throws Exception { + OutputStream outputStream = new ByteArrayOutputStream(); - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.streamResult(outputStream); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.streamResult(outputStream); - replay(mock); + replay(mock); - TraxUtils.doWithResult(new StreamResult(outputStream), mock); + TraxUtils.doWithResult(new StreamResult(outputStream), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStreamSourceReader() throws Exception { - String xml = ""; - Reader reader = new StringReader(xml); + @Test + public void testDoWithStreamSourceReader() throws Exception { + String xml = ""; + Reader reader = new StringReader(xml); - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.streamSource(reader); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.streamSource(reader); - replay(mock); + replay(mock); - TraxUtils.doWithSource(new StreamSource(reader), mock); + TraxUtils.doWithSource(new StreamSource(reader), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithStreamResultWriter() throws Exception { - Writer writer = new StringWriter(); + @Test + public void testDoWithStreamResultWriter() throws Exception { + Writer writer = new StringWriter(); - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.streamResult(writer); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.streamResult(writer); - replay(mock); + replay(mock); - TraxUtils.doWithResult(new StreamResult(writer), mock); + TraxUtils.doWithResult(new StreamResult(writer), mock); - verify(mock); - } + verify(mock); + } - @Test - public void testDoWithSystemIdSource() throws Exception { - String systemId = "http://www.springframework.org/dtd/spring-beans.dtd"; + @Test + public void testDoWithSystemIdSource() throws Exception { + String systemId = "http://www.springframework.org/dtd/spring-beans.dtd"; - TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); - mock.source(systemId); + TraxUtils.SourceCallback mock = createMock(TraxUtils.SourceCallback.class); + mock.source(systemId); - replay(mock); + replay(mock); - TraxUtils.doWithSource(new StreamSource(systemId), mock); + TraxUtils.doWithSource(new StreamSource(systemId), mock); - verify(mock); - } - - @Test - public void testDoWithSystemIdResult() throws Exception { - String systemId = "http://www.springframework.org/dtd/spring-beans.dtd"; + verify(mock); + } - TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); - mock.result(systemId); + @Test + public void testDoWithSystemIdResult() throws Exception { + String systemId = "http://www.springframework.org/dtd/spring-beans.dtd"; - replay(mock); + TraxUtils.ResultCallback mock = createMock(TraxUtils.ResultCallback.class); + mock.result(systemId); - TraxUtils.doWithResult(new StreamResult(systemId), mock); + replay(mock); - verify(mock); - } + TraxUtils.doWithResult(new StreamResult(systemId), mock); + verify(mock); + } - @Test - public void testDoWithInvalidSource() throws Exception { - Source source = new Source() { - public void setSystemId(String systemId) { - } + @Test + public void testDoWithInvalidSource() throws Exception { + Source source = new Source() { - public String getSystemId() { - return null; - } - }; + public void setSystemId(String systemId) { + } - try { - TraxUtils.doWithSource(source, null); - Assert.fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + public String getSystemId() { + return null; + } + }; - @Test - public void testDoWithInvalidResult() throws Exception { - Result result = new Result() { + try { + TraxUtils.doWithSource(source, null); + Assert.fail("IllegalArgumentException expected"); + } + catch (IllegalArgumentException ex) { + // expected + } + } - public void setSystemId(String systemId) { - } + @Test + public void testDoWithInvalidResult() throws Exception { + Result result = new Result() { - public String getSystemId() { - return null; - } - }; + public void setSystemId(String systemId) { + } - try { - TraxUtils.doWithResult(result, null); - Assert.fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + public String getSystemId() { + return null; + } + }; + + try { + TraxUtils.doWithResult(result, null); + Assert.fail("IllegalArgumentException expected"); + } + catch (IllegalArgumentException ex) { + // expected + } + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/validation/AbstractValidatorFactoryTestCase.java b/spring-xml/src/test/java/org/springframework/xml/validation/AbstractValidatorFactoryTestCase.java index 8c96c612..79e8720d 100644 --- a/spring-xml/src/test/java/org/springframework/xml/validation/AbstractValidatorFactoryTestCase.java +++ b/spring-xml/src/test/java/org/springframework/xml/validation/AbstractValidatorFactoryTestCase.java @@ -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, @@ -38,123 +38,123 @@ import org.xml.sax.SAXParseException; public abstract class AbstractValidatorFactoryTestCase { - private XmlValidator validator; + private XmlValidator validator; - private InputStream validInputStream; + private InputStream validInputStream; - private InputStream invalidInputStream; + private InputStream invalidInputStream; - @Before - public void setUp() throws Exception { - Resource[] schemaResource = - new Resource[]{new ClassPathResource("schema.xsd", AbstractValidatorFactoryTestCase.class)}; - validator = createValidator(schemaResource, XmlValidatorFactory.SCHEMA_W3C_XML); - validInputStream = AbstractValidatorFactoryTestCase.class.getResourceAsStream("validDocument.xml"); - invalidInputStream = AbstractValidatorFactoryTestCase.class.getResourceAsStream("invalidDocument.xml"); - } + @Before + public void setUp() throws Exception { + Resource[] schemaResource = + new Resource[]{new ClassPathResource("schema.xsd", AbstractValidatorFactoryTestCase.class)}; + validator = createValidator(schemaResource, XmlValidatorFactory.SCHEMA_W3C_XML); + validInputStream = AbstractValidatorFactoryTestCase.class.getResourceAsStream("validDocument.xml"); + invalidInputStream = AbstractValidatorFactoryTestCase.class.getResourceAsStream("invalidDocument.xml"); + } - @After - public void tearDown() throws Exception { - validInputStream.close(); - invalidInputStream.close(); - } + @After + public void tearDown() throws Exception { + validInputStream.close(); + invalidInputStream.close(); + } - protected abstract XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws Exception; + protected abstract XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws Exception; - @Test - public void testHandleValidMessageStream() throws Exception { - SAXParseException[] errors = validator.validate(new StreamSource(validInputStream)); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 0, errors.length); - } + @Test + public void testHandleValidMessageStream() throws Exception { + SAXParseException[] errors = validator.validate(new StreamSource(validInputStream)); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 0, errors.length); + } - @Test - public void testValidateTwice() throws Exception { - validator.validate(new StreamSource(validInputStream)); - validInputStream = AbstractValidatorFactoryTestCase.class.getResourceAsStream("validDocument.xml"); - validator.validate(new StreamSource(validInputStream)); - } + @Test + public void testValidateTwice() throws Exception { + validator.validate(new StreamSource(validInputStream)); + validInputStream = AbstractValidatorFactoryTestCase.class.getResourceAsStream("validDocument.xml"); + validator.validate(new StreamSource(validInputStream)); + } - @Test - public void testHandleInvalidMessageStream() throws Exception { - SAXParseException[] errors = validator.validate(new StreamSource(invalidInputStream)); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 3, errors.length); - } + @Test + public void testHandleInvalidMessageStream() throws Exception { + SAXParseException[] errors = validator.validate(new StreamSource(invalidInputStream)); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 3, errors.length); + } - @Test - public void testHandleValidMessageSax() throws Exception { - SAXParseException[] errors = validator.validate(new SAXSource(new InputSource(validInputStream))); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 0, errors.length); - } + @Test + public void testHandleValidMessageSax() throws Exception { + SAXParseException[] errors = validator.validate(new SAXSource(new InputSource(validInputStream))); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 0, errors.length); + } - @Test - public void testHandleInvalidMessageSax() throws Exception { - SAXParseException[] errors = validator.validate(new SAXSource(new InputSource(invalidInputStream))); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 3, errors.length); - } + @Test + public void testHandleInvalidMessageSax() throws Exception { + SAXParseException[] errors = validator.validate(new SAXSource(new InputSource(invalidInputStream))); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 3, errors.length); + } - @Test - public void testHandleValidMessageDom() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - Document document = documentBuilderFactory.newDocumentBuilder() - .parse(new InputSource(validInputStream)); - SAXParseException[] errors = validator.validate(new DOMSource(document)); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 0, errors.length); - } + @Test + public void testHandleValidMessageDom() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + Document document = documentBuilderFactory.newDocumentBuilder() + .parse(new InputSource(validInputStream)); + SAXParseException[] errors = validator.validate(new DOMSource(document)); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 0, errors.length); + } - @Test - public void testHandleInvalidMessageDom() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - Document document = documentBuilderFactory.newDocumentBuilder() - .parse(new InputSource(invalidInputStream)); - SAXParseException[] errors = validator.validate(new DOMSource(document)); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 3, errors.length); - } + @Test + public void testHandleInvalidMessageDom() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + Document document = documentBuilderFactory.newDocumentBuilder() + .parse(new InputSource(invalidInputStream)); + SAXParseException[] errors = validator.validate(new DOMSource(document)); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 3, errors.length); + } - @Test - public void testMultipleSchemasValidMessage() throws Exception { - Resource[] schemaResources = new Resource[]{ - new ClassPathResource("multipleSchemas1.xsd", AbstractValidatorFactoryTestCase.class), - new ClassPathResource("multipleSchemas2.xsd", AbstractValidatorFactoryTestCase.class)}; - validator = createValidator(schemaResources, XmlValidatorFactory.SCHEMA_W3C_XML); + @Test + public void testMultipleSchemasValidMessage() throws Exception { + Resource[] schemaResources = new Resource[]{ + new ClassPathResource("multipleSchemas1.xsd", AbstractValidatorFactoryTestCase.class), + new ClassPathResource("multipleSchemas2.xsd", AbstractValidatorFactoryTestCase.class)}; + validator = createValidator(schemaResources, XmlValidatorFactory.SCHEMA_W3C_XML); - Source document = new ResourceSource( - new ClassPathResource("multipleSchemas1.xml", AbstractValidatorFactoryTestCase.class)); - SAXParseException[] errors = validator.validate(document); - Assert.assertEquals("ValidationErrors returned", 0, errors.length); - validator = createValidator(schemaResources, XmlValidatorFactory.SCHEMA_W3C_XML); - document = new ResourceSource( - new ClassPathResource("multipleSchemas2.xml", AbstractValidatorFactoryTestCase.class)); - errors = validator.validate(document); - Assert.assertEquals("ValidationErrors returned", 0, errors.length); - } + Source document = new ResourceSource( + new ClassPathResource("multipleSchemas1.xml", AbstractValidatorFactoryTestCase.class)); + SAXParseException[] errors = validator.validate(document); + Assert.assertEquals("ValidationErrors returned", 0, errors.length); + validator = createValidator(schemaResources, XmlValidatorFactory.SCHEMA_W3C_XML); + document = new ResourceSource( + new ClassPathResource("multipleSchemas2.xml", AbstractValidatorFactoryTestCase.class)); + errors = validator.validate(document); + Assert.assertEquals("ValidationErrors returned", 0, errors.length); + } - @Test - public void customErrorHandler() throws Exception { - ValidationErrorHandler myHandler = new ValidationErrorHandler() { - public SAXParseException[] getErrors() { - return new SAXParseException[0]; - } + @Test + public void customErrorHandler() throws Exception { + ValidationErrorHandler myHandler = new ValidationErrorHandler() { + public SAXParseException[] getErrors() { + return new SAXParseException[0]; + } - public void warning(SAXParseException exception) throws SAXException { - } + public void warning(SAXParseException exception) throws SAXException { + } - public void error(SAXParseException exception) throws SAXException { - } + public void error(SAXParseException exception) throws SAXException { + } - public void fatalError(SAXParseException exception) throws SAXException { - } - }; - SAXParseException[] errors = validator.validate(new StreamSource(invalidInputStream), myHandler); - Assert.assertNotNull("Null returned for errors", errors); - Assert.assertEquals("ValidationErrors returned", 0, errors.length); - } + public void fatalError(SAXParseException exception) throws SAXException { + } + }; + SAXParseException[] errors = validator.validate(new StreamSource(invalidInputStream), myHandler); + Assert.assertNotNull("Null returned for errors", errors); + Assert.assertEquals("ValidationErrors returned", 0, errors.length); + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/validation/Jaxp13ValidatorFactoryTest.java b/spring-xml/src/test/java/org/springframework/xml/validation/Jaxp13ValidatorFactoryTest.java index e46b85d2..58b1dc41 100644 --- a/spring-xml/src/test/java/org/springframework/xml/validation/Jaxp13ValidatorFactoryTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/validation/Jaxp13ValidatorFactoryTest.java @@ -22,8 +22,8 @@ import org.springframework.core.io.Resource; public class Jaxp13ValidatorFactoryTest extends AbstractValidatorFactoryTestCase { - @Override - protected XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws IOException { - return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage); - } + @Override + protected XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage) throws IOException { + return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/validation/SchemaLoaderUtilsTest.java b/spring-xml/src/test/java/org/springframework/xml/validation/SchemaLoaderUtilsTest.java index a964cab3..e032e246 100644 --- a/spring-xml/src/test/java/org/springframework/xml/validation/SchemaLoaderUtilsTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/validation/SchemaLoaderUtilsTest.java @@ -27,45 +27,45 @@ import org.junit.Test; public class SchemaLoaderUtilsTest { - @Test - public void testLoadSchema() throws Exception { - Resource resource = new ClassPathResource("schema.xsd", getClass()); - Schema schema = SchemaLoaderUtils.loadSchema(resource, XMLConstants.W3C_XML_SCHEMA_NS_URI); - Assert.assertNotNull("No schema returned", schema); - Assert.assertFalse("Resource not closed", resource.isOpen()); - } + @Test + public void testLoadSchema() throws Exception { + Resource resource = new ClassPathResource("schema.xsd", getClass()); + Schema schema = SchemaLoaderUtils.loadSchema(resource, XMLConstants.W3C_XML_SCHEMA_NS_URI); + Assert.assertNotNull("No schema returned", schema); + Assert.assertFalse("Resource not closed", resource.isOpen()); + } - @Test - public void testLoadNonExistantSchema() throws Exception { - try { - Resource nonExistant = new ClassPathResource("bla"); - SchemaLoaderUtils.loadSchema(nonExistant, XMLConstants.W3C_XML_SCHEMA_NS_URI); - Assert.fail("Should have thrown an IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - } - } + @Test + public void testLoadNonExistantSchema() throws Exception { + try { + Resource nonExistant = new ClassPathResource("bla"); + SchemaLoaderUtils.loadSchema(nonExistant, XMLConstants.W3C_XML_SCHEMA_NS_URI); + Assert.fail("Should have thrown an IllegalArgumentException"); + } + catch (IllegalArgumentException e) { + // expected + } + } - @Test - public void testLoadNullSchema() throws Exception { - try { - SchemaLoaderUtils.loadSchema((Resource) null, XMLConstants.W3C_XML_SCHEMA_NS_URI); - Assert.fail("Should have thrown an IllegalArgumentException"); - } - catch (IllegalArgumentException e) { - // expected - } - } + @Test + public void testLoadNullSchema() throws Exception { + try { + SchemaLoaderUtils.loadSchema((Resource) null, XMLConstants.W3C_XML_SCHEMA_NS_URI); + Assert.fail("Should have thrown an IllegalArgumentException"); + } + catch (IllegalArgumentException e) { + // expected + } + } - @Test - public void testLoadMultipleSchemas() throws Exception { - Resource envelope = new ClassPathResource("envelope.xsd", getClass()); - Resource encoding = new ClassPathResource("encoding.xsd", getClass()); - Schema schema = - SchemaLoaderUtils.loadSchema(new Resource[]{envelope, encoding}, XMLConstants.W3C_XML_SCHEMA_NS_URI); - Assert.assertNotNull("No schema returned", schema); - Assert.assertFalse("Resource not closed", envelope.isOpen()); - Assert.assertFalse("Resource not closed", encoding.isOpen()); - } + @Test + public void testLoadMultipleSchemas() throws Exception { + Resource envelope = new ClassPathResource("envelope.xsd", getClass()); + Resource encoding = new ClassPathResource("encoding.xsd", getClass()); + Schema schema = + SchemaLoaderUtils.loadSchema(new Resource[]{envelope, encoding}, XMLConstants.W3C_XML_SCHEMA_NS_URI); + Assert.assertNotNull("No schema returned", schema); + Assert.assertFalse("Resource not closed", envelope.isOpen()); + Assert.assertFalse("Resource not closed", encoding.isOpen()); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/validation/XmlValidatorFactoryTest.java b/spring-xml/src/test/java/org/springframework/xml/validation/XmlValidatorFactoryTest.java index 34c3b0d9..67f97a17 100644 --- a/spring-xml/src/test/java/org/springframework/xml/validation/XmlValidatorFactoryTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/validation/XmlValidatorFactoryTest.java @@ -31,87 +31,87 @@ import org.springframework.core.io.Resource; public class XmlValidatorFactoryTest { - @Test - public void testCreateValidator() throws Exception { - Resource resource = new ClassPathResource("schema.xsd", AbstractValidatorFactoryTestCase.class); - XmlValidator validator = XmlValidatorFactory.createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML); - Assert.assertNotNull("No validator returned", validator); - } + @Test + public void testCreateValidator() throws Exception { + Resource resource = new ClassPathResource("schema.xsd", AbstractValidatorFactoryTestCase.class); + XmlValidator validator = XmlValidatorFactory.createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML); + Assert.assertNotNull("No validator returned", validator); + } - @Test - public void testNonExistentResource() throws Exception { - Resource resource = new NonExistentResource(); - try { - XmlValidatorFactory.createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML); - Assert.fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + @Test + public void testNonExistentResource() throws Exception { + Resource resource = new NonExistentResource(); + try { + XmlValidatorFactory.createValidator(resource, XmlValidatorFactory.SCHEMA_W3C_XML); + Assert.fail("IllegalArgumentException expected"); + } + catch (IllegalArgumentException ex) { + // expected + } + } - @Test - public void testInvalidSchemaLanguage() throws Exception { - Resource resource = new ClassPathResource("schema.xsd", AbstractValidatorFactoryTestCase.class); - try { - XmlValidatorFactory.createValidator(resource, "bla"); - Assert.fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + @Test + public void testInvalidSchemaLanguage() throws Exception { + Resource resource = new ClassPathResource("schema.xsd", AbstractValidatorFactoryTestCase.class); + try { + XmlValidatorFactory.createValidator(resource, "bla"); + Assert.fail("IllegalArgumentException expected"); + } + catch (IllegalArgumentException ex) { + // expected + } + } - private static class NonExistentResource extends AbstractResource { + private static class NonExistentResource extends AbstractResource { - @Override - public Resource createRelative(String relativePath) throws IOException { - throw new IOException(); - } + @Override + public Resource createRelative(String relativePath) throws IOException { + throw new IOException(); + } - @Override - public boolean exists() { - return false; - } + @Override + public boolean exists() { + return false; + } - @Override - public String getDescription() { - return null; - } + @Override + public String getDescription() { + return null; + } - @Override - public File getFile() throws IOException { - throw new IOException(); - } + @Override + public File getFile() throws IOException { + throw new IOException(); + } - @Override - public String getFilename() { - return null; - } + @Override + public String getFilename() { + return null; + } - @Override - public URL getURL() throws IOException { - throw new IOException(); - } + @Override + public URL getURL() throws IOException { + throw new IOException(); + } - @Override - public URI getURI() throws IOException { - throw new IOException(); - } + @Override + public URI getURI() throws IOException { + throw new IOException(); + } - @Override - public boolean isOpen() { - return false; - } + @Override + public boolean isOpen() { + return false; + } - @Override - public InputStream getInputStream() throws IOException { - throw new IOException(); - } + @Override + public InputStream getInputStream() throws IOException { + throw new IOException(); + } - @Override - public boolean isReadable() { - return false; - } - } + @Override + public boolean isReadable() { + return false; + } + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathExpressionFactoryTestCase.java b/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathExpressionFactoryTestCase.java index e1de09ae..c9e075ba 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathExpressionFactoryTestCase.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathExpressionFactoryTestCase.java @@ -36,207 +36,207 @@ import org.xml.sax.SAXException; public abstract class AbstractXPathExpressionFactoryTestCase { - private Document noNamespacesDocument; + private Document noNamespacesDocument; - private Document namespacesDocument; + private Document namespacesDocument; - private Map namespaces = new HashMap(); + private Map namespaces = new HashMap(); - @Before - public void setUp() throws Exception { - namespaces.put("prefix1", "namespace1"); - namespaces.put("prefix2", "namespace2"); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - InputStream inputStream = getClass().getResourceAsStream("nonamespaces.xml"); - try { - noNamespacesDocument = documentBuilder.parse(inputStream); - } - finally { - inputStream.close(); - } - inputStream = getClass().getResourceAsStream("namespaces.xml"); - try { - namespacesDocument = documentBuilder.parse(inputStream); - } - finally { - inputStream.close(); - } - } + @Before + public void setUp() throws Exception { + namespaces.put("prefix1", "namespace1"); + namespaces.put("prefix2", "namespace2"); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + InputStream inputStream = getClass().getResourceAsStream("nonamespaces.xml"); + try { + noNamespacesDocument = documentBuilder.parse(inputStream); + } + finally { + inputStream.close(); + } + inputStream = getClass().getResourceAsStream("namespaces.xml"); + try { + namespacesDocument = documentBuilder.parse(inputStream); + } + finally { + inputStream.close(); + } + } - @Test - public void testEvaluateAsBooleanInvalidNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); - boolean result = expression.evaluateAsBoolean(namespacesDocument); - Assert.assertFalse("Invalid result [" + result + "]", result); - } + @Test + public void testEvaluateAsBooleanInvalidNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); + boolean result = expression.evaluateAsBoolean(namespacesDocument); + Assert.assertFalse("Invalid result [" + result + "]", result); + } - @Test - public void testEvaluateAsBooleanInvalidNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/otherchild"); - boolean result = expression.evaluateAsBoolean(noNamespacesDocument); - Assert.assertFalse("Invalid result [" + result + "]", result); - } + @Test + public void testEvaluateAsBooleanInvalidNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/otherchild"); + boolean result = expression.evaluateAsBoolean(noNamespacesDocument); + Assert.assertFalse("Invalid result [" + result + "]", result); + } - @Test - public void testEvaluateAsBooleanNamespaces() throws IOException, SAXException { - XPathExpression expression = - createXPathExpression("/prefix1:root/prefix2:child/prefix2:boolean/text()", namespaces); - boolean result = expression.evaluateAsBoolean(namespacesDocument); - Assert.assertTrue("Invalid result", result); - } + @Test + public void testEvaluateAsBooleanNamespaces() throws IOException, SAXException { + XPathExpression expression = + createXPathExpression("/prefix1:root/prefix2:child/prefix2:boolean/text()", namespaces); + boolean result = expression.evaluateAsBoolean(namespacesDocument); + Assert.assertTrue("Invalid result", result); + } - @Test - public void testEvaluateAsBooleanNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/child/boolean/text()"); - boolean result = expression.evaluateAsBoolean(noNamespacesDocument); - Assert.assertTrue("Invalid result", result); - } + @Test + public void testEvaluateAsBooleanNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/child/boolean/text()"); + boolean result = expression.evaluateAsBoolean(noNamespacesDocument); + Assert.assertTrue("Invalid result", result); + } - @Test - public void testEvaluateAsDoubleInvalidNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); - double result = expression.evaluateAsNumber(noNamespacesDocument); - Assert.assertTrue("Invalid result [" + result + "]", Double.isNaN(result)); - } + @Test + public void testEvaluateAsDoubleInvalidNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); + double result = expression.evaluateAsNumber(noNamespacesDocument); + Assert.assertTrue("Invalid result [" + result + "]", Double.isNaN(result)); + } - @Test - public void testEvaluateAsDoubleInvalidNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/otherchild"); - double result = expression.evaluateAsNumber(noNamespacesDocument); - Assert.assertTrue("Invalid result [" + result + "]", Double.isNaN(result)); - } + @Test + public void testEvaluateAsDoubleInvalidNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/otherchild"); + double result = expression.evaluateAsNumber(noNamespacesDocument); + Assert.assertTrue("Invalid result [" + result + "]", Double.isNaN(result)); + } - @Test - public void testEvaluateAsDoubleNamespaces() throws IOException, SAXException { - XPathExpression expression = - createXPathExpression("/prefix1:root/prefix2:child/prefix2:number/text()", namespaces); - double result = expression.evaluateAsNumber(namespacesDocument); - Assert.assertEquals("Invalid result", 42D, result, 0D); - } + @Test + public void testEvaluateAsDoubleNamespaces() throws IOException, SAXException { + XPathExpression expression = + createXPathExpression("/prefix1:root/prefix2:child/prefix2:number/text()", namespaces); + double result = expression.evaluateAsNumber(namespacesDocument); + Assert.assertEquals("Invalid result", 42D, result, 0D); + } - @Test - public void testEvaluateAsDoubleNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/child/number/text()"); - double result = expression.evaluateAsNumber(noNamespacesDocument); - Assert.assertEquals("Invalid result", 42D, result, 0D); - } + @Test + public void testEvaluateAsDoubleNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/child/number/text()"); + double result = expression.evaluateAsNumber(noNamespacesDocument); + Assert.assertEquals("Invalid result", 42D, result, 0D); + } - @Test - public void testEvaluateAsNodeInvalidNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); - Node result = expression.evaluateAsNode(namespacesDocument); - Assert.assertNull("Invalid result [" + result + "]", result); - } + @Test + public void testEvaluateAsNodeInvalidNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); + Node result = expression.evaluateAsNode(namespacesDocument); + Assert.assertNull("Invalid result [" + result + "]", result); + } - @Test - public void testEvaluateAsNodeInvalidNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/otherchild"); - Node result = expression.evaluateAsNode(noNamespacesDocument); - Assert.assertNull("Invalid result [" + result + "]", result); - } + @Test + public void testEvaluateAsNodeInvalidNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/otherchild"); + Node result = expression.evaluateAsNode(noNamespacesDocument); + Assert.assertNull("Invalid result [" + result + "]", result); + } - @Test - public void testEvaluateAsNodeNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:child", namespaces); - Node result = expression.evaluateAsNode(namespacesDocument); - Assert.assertNotNull("Invalid result", result); - Assert.assertEquals("Invalid localname", "child", result.getLocalName()); - } + @Test + public void testEvaluateAsNodeNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:child", namespaces); + Node result = expression.evaluateAsNode(namespacesDocument); + Assert.assertNotNull("Invalid result", result); + Assert.assertEquals("Invalid localname", "child", result.getLocalName()); + } - @Test - public void testEvaluateAsNodeNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/child"); - Node result = expression.evaluateAsNode(noNamespacesDocument); - Assert.assertNotNull("Invalid result", result); - Assert.assertEquals("Invalid localname", "child", result.getLocalName()); - } + @Test + public void testEvaluateAsNodeNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/child"); + Node result = expression.evaluateAsNode(noNamespacesDocument); + Assert.assertNotNull("Invalid result", result); + Assert.assertEquals("Invalid localname", "child", result.getLocalName()); + } - @Test - public void testEvaluateAsNodeListNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:child/*", namespaces); - List results = expression.evaluateAsNodeList(namespacesDocument); - Assert.assertNotNull("Invalid result", results); - Assert.assertEquals("Invalid amount of results", 3, results.size()); - } + @Test + public void testEvaluateAsNodeListNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:child/*", namespaces); + List results = expression.evaluateAsNodeList(namespacesDocument); + Assert.assertNotNull("Invalid result", results); + Assert.assertEquals("Invalid amount of results", 3, results.size()); + } - @Test - public void testEvaluateAsNodeListNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/child/*"); - List results = expression.evaluateAsNodeList(noNamespacesDocument); - Assert.assertNotNull("Invalid result", results); - Assert.assertEquals("Invalid amount of results", 3, results.size()); - } + @Test + public void testEvaluateAsNodeListNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/child/*"); + List results = expression.evaluateAsNodeList(noNamespacesDocument); + Assert.assertNotNull("Invalid result", results); + Assert.assertEquals("Invalid amount of results", 3, results.size()); + } - @Test - public void testEvaluateAsStringInvalidNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); - String result = expression.evaluateAsString(namespacesDocument); - Assert.assertFalse("Invalid result [" + result + "]", StringUtils.hasText(result)); - } + @Test + public void testEvaluateAsStringInvalidNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/prefix1:root/prefix2:otherchild", namespaces); + String result = expression.evaluateAsString(namespacesDocument); + Assert.assertFalse("Invalid result [" + result + "]", StringUtils.hasText(result)); + } - @Test - public void testEvaluateAsStringInvalidNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/otherchild"); - String result = expression.evaluateAsString(noNamespacesDocument); - Assert.assertFalse("Invalid result [" + result + "]", StringUtils.hasText(result)); - } + @Test + public void testEvaluateAsStringInvalidNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/otherchild"); + String result = expression.evaluateAsString(noNamespacesDocument); + Assert.assertFalse("Invalid result [" + result + "]", StringUtils.hasText(result)); + } - @Test - public void testEvaluateAsStringNamespaces() throws IOException, SAXException { - XPathExpression expression = - createXPathExpression("/prefix1:root/prefix2:child/prefix2:text/text()", namespaces); - String result = expression.evaluateAsString(namespacesDocument); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateAsStringNamespaces() throws IOException, SAXException { + XPathExpression expression = + createXPathExpression("/prefix1:root/prefix2:child/prefix2:text/text()", namespaces); + String result = expression.evaluateAsString(namespacesDocument); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateAsStringNoNamespaces() throws IOException, SAXException { - XPathExpression expression = createXPathExpression("/root/child/text/text()"); - String result = expression.evaluateAsString(noNamespacesDocument); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateAsStringNoNamespaces() throws IOException, SAXException { + XPathExpression expression = createXPathExpression("/root/child/text/text()"); + String result = expression.evaluateAsString(noNamespacesDocument); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateAsObject() throws Exception { - XPathExpression expression = createXPathExpression("/root/child"); - String result = expression.evaluateAsObject(noNamespacesDocument, new NodeMapper() { - public String mapNode(Node node, int nodeNum) throws DOMException { - return node.getLocalName(); - } - }); - Assert.assertNotNull("Invalid result", result); - Assert.assertEquals("Invalid localname", "child", result); - } + @Test + public void testEvaluateAsObject() throws Exception { + XPathExpression expression = createXPathExpression("/root/child"); + String result = expression.evaluateAsObject(noNamespacesDocument, new NodeMapper() { + public String mapNode(Node node, int nodeNum) throws DOMException { + return node.getLocalName(); + } + }); + Assert.assertNotNull("Invalid result", result); + Assert.assertEquals("Invalid localname", "child", result); + } - @Test - public void testEvaluate() throws Exception { - XPathExpression expression = createXPathExpression("/root/child/*"); - List results = expression.evaluate(noNamespacesDocument, new NodeMapper() { - public String mapNode(Node node, int nodeNum) throws DOMException { - return node.getLocalName(); - } - }); - Assert.assertNotNull("Invalid result", results); - Assert.assertEquals("Invalid amount of results", 3, results.size()); - Assert.assertEquals("Invalid first result", "text", results.get(0)); - Assert.assertEquals("Invalid first result", "number", results.get(1)); - Assert.assertEquals("Invalid first result", "boolean", results.get(2)); - } + @Test + public void testEvaluate() throws Exception { + XPathExpression expression = createXPathExpression("/root/child/*"); + List results = expression.evaluate(noNamespacesDocument, new NodeMapper() { + public String mapNode(Node node, int nodeNum) throws DOMException { + return node.getLocalName(); + } + }); + Assert.assertNotNull("Invalid result", results); + Assert.assertEquals("Invalid amount of results", 3, results.size()); + Assert.assertEquals("Invalid first result", "text", results.get(0)); + Assert.assertEquals("Invalid first result", "number", results.get(1)); + Assert.assertEquals("Invalid first result", "boolean", results.get(2)); + } - @Test - public void testInvalidExpression() { - try { - createXPathExpression("\\"); - Assert.fail("No XPathParseException thrown"); - } - catch (XPathParseException ex) { - // Expected behaviour - } - } + @Test + public void testInvalidExpression() { + try { + createXPathExpression("\\"); + Assert.fail("No XPathParseException thrown"); + } + catch (XPathParseException ex) { + // Expected behaviour + } + } - protected abstract XPathExpression createXPathExpression(String expression); + protected abstract XPathExpression createXPathExpression(String expression); - protected abstract XPathExpression createXPathExpression(String expression, Map namespaces); + protected abstract XPathExpression createXPathExpression(String expression, Map namespaces); } diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathTemplateTestCase.java b/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathTemplateTestCase.java index b6f02e78..61f4080c 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathTemplateTestCase.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/AbstractXPathTemplateTestCase.java @@ -46,163 +46,163 @@ import org.xml.sax.SAXException; public abstract class AbstractXPathTemplateTestCase { - XPathOperations template; + XPathOperations template; - private Source namespaces; + private Source namespaces; - private Source nonamespaces; + private Source nonamespaces; - @Before - public final void setUp() throws Exception { - template = createTemplate(); - namespaces = new ResourceSource(new ClassPathResource("namespaces.xml", AbstractXPathTemplateTestCase.class)); - nonamespaces = - new ResourceSource(new ClassPathResource("nonamespaces.xml", AbstractXPathTemplateTestCase.class)); - } + @Before + public final void setUp() throws Exception { + template = createTemplate(); + namespaces = new ResourceSource(new ClassPathResource("namespaces.xml", AbstractXPathTemplateTestCase.class)); + nonamespaces = + new ResourceSource(new ClassPathResource("nonamespaces.xml", AbstractXPathTemplateTestCase.class)); + } - protected abstract XPathOperations createTemplate() throws Exception; + protected abstract XPathOperations createTemplate() throws Exception; - @Test - public void testEvaluateAsBoolean() { - boolean result = template.evaluateAsBoolean("/root/child/boolean", nonamespaces); - Assert.assertTrue("Invalid result", result); - } + @Test + public void testEvaluateAsBoolean() { + boolean result = template.evaluateAsBoolean("/root/child/boolean", nonamespaces); + Assert.assertTrue("Invalid result", result); + } - @Test - public void testEvaluateAsBooleanNamespaces() { - boolean result = template.evaluateAsBoolean("/prefix1:root/prefix2:child/prefix2:boolean", namespaces); - Assert.assertTrue("Invalid result", result); - } + @Test + public void testEvaluateAsBooleanNamespaces() { + boolean result = template.evaluateAsBoolean("/prefix1:root/prefix2:child/prefix2:boolean", namespaces); + Assert.assertTrue("Invalid result", result); + } - @Test - public void testEvaluateAsDouble() { - double result = template.evaluateAsDouble("/root/child/number", nonamespaces); - Assert.assertEquals("Invalid result", 42D, result, 0D); - } + @Test + public void testEvaluateAsDouble() { + double result = template.evaluateAsDouble("/root/child/number", nonamespaces); + Assert.assertEquals("Invalid result", 42D, result, 0D); + } - @Test - public void testEvaluateAsDoubleNamespaces() { - double result = template.evaluateAsDouble("/prefix1:root/prefix2:child/prefix2:number", namespaces); - Assert.assertEquals("Invalid result", 42D, result, 0D); - } + @Test + public void testEvaluateAsDoubleNamespaces() { + double result = template.evaluateAsDouble("/prefix1:root/prefix2:child/prefix2:number", namespaces); + Assert.assertEquals("Invalid result", 42D, result, 0D); + } - @Test - public void testEvaluateAsNode() { - Node result = template.evaluateAsNode("/root/child", nonamespaces); - Assert.assertNotNull("Invalid result", result); - Assert.assertEquals("Invalid localname", "child", result.getLocalName()); - } + @Test + public void testEvaluateAsNode() { + Node result = template.evaluateAsNode("/root/child", nonamespaces); + Assert.assertNotNull("Invalid result", result); + Assert.assertEquals("Invalid localname", "child", result.getLocalName()); + } - @Test - public void testEvaluateAsNodeNamespaces() { - Node result = template.evaluateAsNode("/prefix1:root/prefix2:child", namespaces); - Assert.assertNotNull("Invalid result", result); - Assert.assertEquals("Invalid localname", "child", result.getLocalName()); - } + @Test + public void testEvaluateAsNodeNamespaces() { + Node result = template.evaluateAsNode("/prefix1:root/prefix2:child", namespaces); + Assert.assertNotNull("Invalid result", result); + Assert.assertEquals("Invalid localname", "child", result.getLocalName()); + } - @Test - public void testEvaluateAsNodes() { - List results = template.evaluateAsNodeList("/root/child/*", nonamespaces); - Assert.assertNotNull("Invalid result", results); - Assert.assertEquals("Invalid amount of results", 3, results.size()); - } + @Test + public void testEvaluateAsNodes() { + List results = template.evaluateAsNodeList("/root/child/*", nonamespaces); + Assert.assertNotNull("Invalid result", results); + Assert.assertEquals("Invalid amount of results", 3, results.size()); + } - @Test - public void testEvaluateAsNodesNamespaces() { - List results = template.evaluateAsNodeList("/prefix1:root/prefix2:child/*", namespaces); - Assert.assertNotNull("Invalid result", results); - Assert.assertEquals("Invalid amount of results", 3, results.size()); - } + @Test + public void testEvaluateAsNodesNamespaces() { + List results = template.evaluateAsNodeList("/prefix1:root/prefix2:child/*", namespaces); + Assert.assertNotNull("Invalid result", results); + Assert.assertEquals("Invalid amount of results", 3, results.size()); + } - @Test - public void testEvaluateAsStringNamespaces() throws IOException, SAXException { - String result = template.evaluateAsString("/prefix1:root/prefix2:child/prefix2:text", namespaces); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateAsStringNamespaces() throws IOException, SAXException { + String result = template.evaluateAsString("/prefix1:root/prefix2:child/prefix2:text", namespaces); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateAsString() throws IOException, SAXException { - String result = template.evaluateAsString("/root/child/text", nonamespaces); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateAsString() throws IOException, SAXException { + String result = template.evaluateAsString("/root/child/text", nonamespaces); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateDomSource() throws IOException, SAXException, ParserConfigurationException { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.parse(SaxUtils.createInputSource( - new ClassPathResource("nonamespaces.xml", AbstractXPathTemplateTestCase.class))); + @Test + public void testEvaluateDomSource() throws IOException, SAXException, ParserConfigurationException { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.parse(SaxUtils.createInputSource( + new ClassPathResource("nonamespaces.xml", AbstractXPathTemplateTestCase.class))); - String result = template.evaluateAsString("/root/child/text", new DOMSource(document)); - Assert.assertEquals("Invalid result", "text", result); - } + String result = template.evaluateAsString("/root/child/text", new DOMSource(document)); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateSAXSource() throws Exception { - InputStream in = AbstractXPathTemplateTestCase.class.getResourceAsStream("nonamespaces.xml"); - SAXSource source = new SAXSource(new InputSource(in)); - String result = template.evaluateAsString("/root/child/text", source); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateSAXSource() throws Exception { + InputStream in = AbstractXPathTemplateTestCase.class.getResourceAsStream("nonamespaces.xml"); + SAXSource source = new SAXSource(new InputSource(in)); + String result = template.evaluateAsString("/root/child/text", source); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateStaxSource() throws Exception { - InputStream in = AbstractXPathTemplateTestCase.class.getResourceAsStream("nonamespaces.xml"); - XMLStreamReader streamReader = XMLInputFactory.newFactory().createXMLStreamReader(in); - StAXSource source = new StAXSource(streamReader); - String result = template.evaluateAsString("/root/child/text", source); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateStaxSource() throws Exception { + InputStream in = AbstractXPathTemplateTestCase.class.getResourceAsStream("nonamespaces.xml"); + XMLStreamReader streamReader = XMLInputFactory.newFactory().createXMLStreamReader(in); + StAXSource source = new StAXSource(streamReader); + String result = template.evaluateAsString("/root/child/text", source); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateStreamSourceInputStream() throws IOException, SAXException, ParserConfigurationException { - InputStream in = AbstractXPathTemplateTestCase.class.getResourceAsStream("nonamespaces.xml"); - StreamSource source = new StreamSource(in); - String result = template.evaluateAsString("/root/child/text", source); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateStreamSourceInputStream() throws IOException, SAXException, ParserConfigurationException { + InputStream in = AbstractXPathTemplateTestCase.class.getResourceAsStream("nonamespaces.xml"); + StreamSource source = new StreamSource(in); + String result = template.evaluateAsString("/root/child/text", source); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testEvaluateStreamSourceSystemId() throws IOException, SAXException, ParserConfigurationException { - URL url = AbstractXPathTemplateTestCase.class.getResource("nonamespaces.xml"); - String result = template.evaluateAsString("/root/child/text", new StreamSource(url.toString())); - Assert.assertEquals("Invalid result", "text", result); - } + @Test + public void testEvaluateStreamSourceSystemId() throws IOException, SAXException, ParserConfigurationException { + URL url = AbstractXPathTemplateTestCase.class.getResource("nonamespaces.xml"); + String result = template.evaluateAsString("/root/child/text", new StreamSource(url.toString())); + Assert.assertEquals("Invalid result", "text", result); + } - @Test - public void testInvalidExpression() { - try { - template.evaluateAsBoolean("\\", namespaces); - Assert.fail("No XPathException thrown"); - } - catch (XPathException ex) { - // Expected behaviour - } - } + @Test + public void testInvalidExpression() { + try { + template.evaluateAsBoolean("\\", namespaces); + Assert.fail("No XPathException thrown"); + } + catch (XPathException ex) { + // Expected behaviour + } + } - @Test - public void testEvaluateAsObject() throws Exception { - String result = template.evaluateAsObject("/root/child", nonamespaces, new NodeMapper() { - public String mapNode(Node node, int nodeNum) throws DOMException { - return node.getLocalName(); - } - }); - Assert.assertNotNull("Invalid result", result); - Assert.assertEquals("Invalid localname", "child", result); - } + @Test + public void testEvaluateAsObject() throws Exception { + String result = template.evaluateAsObject("/root/child", nonamespaces, new NodeMapper() { + public String mapNode(Node node, int nodeNum) throws DOMException { + return node.getLocalName(); + } + }); + Assert.assertNotNull("Invalid result", result); + Assert.assertEquals("Invalid localname", "child", result); + } - @Test - public void testEvaluate() throws Exception { - List results = template.evaluate("/root/child/*", nonamespaces, new NodeMapper() { - public String mapNode(Node node, int nodeNum) throws DOMException { - return node.getLocalName(); - } - }); - Assert.assertNotNull("Invalid result", results); - Assert.assertEquals("Invalid amount of results", 3, results.size()); - Assert.assertEquals("Invalid first result", "text", results.get(0)); - Assert.assertEquals("Invalid first result", "number", results.get(1)); - Assert.assertEquals("Invalid first result", "boolean", results.get(2)); - } + @Test + public void testEvaluate() throws Exception { + List results = template.evaluate("/root/child/*", nonamespaces, new NodeMapper() { + public String mapNode(Node node, int nodeNum) throws DOMException { + return node.getLocalName(); + } + }); + Assert.assertNotNull("Invalid result", results); + Assert.assertEquals("Invalid amount of results", 3, results.size()); + Assert.assertEquals("Invalid first result", "text", results.get(0)); + Assert.assertEquals("Invalid first result", "number", results.get(1)); + Assert.assertEquals("Invalid first result", "boolean", results.get(2)); + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathExpressionFactoryTest.java b/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathExpressionFactoryTest.java index 3055633e..d47f0fc7 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathExpressionFactoryTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathExpressionFactoryTest.java @@ -23,24 +23,24 @@ import org.xml.sax.SAXException; public class JaxenXPathExpressionFactoryTest extends AbstractXPathExpressionFactoryTestCase { - @Override - protected XPathExpression createXPathExpression(String expression) { - return JaxenXPathExpressionFactory.createXPathExpression(expression); - } + @Override + protected XPathExpression createXPathExpression(String expression) { + return JaxenXPathExpressionFactory.createXPathExpression(expression); + } - @Override - protected XPathExpression createXPathExpression(String expression, Map namespaces) { - return JaxenXPathExpressionFactory.createXPathExpression(expression, namespaces); - } + @Override + protected XPathExpression createXPathExpression(String expression, Map namespaces) { + return JaxenXPathExpressionFactory.createXPathExpression(expression, namespaces); + } - @Override - public void testEvaluateAsDoubleNoNamespaces() throws IOException, SAXException { - // Currently not working on Jaxen 1.1 beta 8, hence the override here - } + @Override + public void testEvaluateAsDoubleNoNamespaces() throws IOException, SAXException { + // Currently not working on Jaxen 1.1 beta 8, hence the override here + } - @Override - public void testEvaluateAsDoubleNamespaces() throws IOException, SAXException { - // Currently not working on Jaxen 1.1 beta 8, hence the override here - } + @Override + public void testEvaluateAsDoubleNamespaces() throws IOException, SAXException { + // Currently not working on Jaxen 1.1 beta 8, hence the override here + } } diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathTemplateTest.java b/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathTemplateTest.java index 6e419b02..78f3f0fc 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathTemplateTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/JaxenXPathTemplateTest.java @@ -21,14 +21,14 @@ import java.util.Map; public class JaxenXPathTemplateTest extends AbstractXPathTemplateTestCase { - @Override - protected XPathOperations createTemplate() throws Exception { - JaxenXPathTemplate template = new JaxenXPathTemplate(); - Map namespaces = new HashMap(); - namespaces.put("prefix1", "namespace1"); - namespaces.put("prefix2", "namespace2"); - template.setNamespaces(namespaces); - return template; - } + @Override + protected XPathOperations createTemplate() throws Exception { + JaxenXPathTemplate template = new JaxenXPathTemplate(); + Map namespaces = new HashMap(); + namespaces.put("prefix1", "namespace1"); + namespaces.put("prefix2", "namespace2"); + template.setNamespaces(namespaces); + return template; + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactoryTest.java b/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactoryTest.java index b851448a..61b0db32 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactoryTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathExpressionFactoryTest.java @@ -20,13 +20,13 @@ import java.util.Map; public class Jaxp13XPathExpressionFactoryTest extends AbstractXPathExpressionFactoryTestCase { - @Override - protected XPathExpression createXPathExpression(String expression) { - return Jaxp13XPathExpressionFactory.createXPathExpression(expression); - } + @Override + protected XPathExpression createXPathExpression(String expression) { + return Jaxp13XPathExpressionFactory.createXPathExpression(expression); + } - @Override - protected XPathExpression createXPathExpression(String expression, Map namespaces) { - return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces); - } + @Override + protected XPathExpression createXPathExpression(String expression, Map namespaces) { + return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathTemplateTest.java b/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathTemplateTest.java index 4ecfd8a9..a3050856 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathTemplateTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/Jaxp13XPathTemplateTest.java @@ -21,14 +21,14 @@ import java.util.Map; public class Jaxp13XPathTemplateTest extends AbstractXPathTemplateTestCase { - @Override - protected XPathOperations createTemplate() throws Exception { - Jaxp13XPathTemplate template = new Jaxp13XPathTemplate(); - Map namespaces = new HashMap(); - namespaces.put("prefix1", "namespace1"); - namespaces.put("prefix2", "namespace2"); - template.setNamespaces(namespaces); - return template; - } + @Override + protected XPathOperations createTemplate() throws Exception { + Jaxp13XPathTemplate template = new Jaxp13XPathTemplate(); + Map namespaces = new HashMap(); + namespaces.put("prefix1", "namespace1"); + namespaces.put("prefix2", "namespace2"); + template.setNamespaces(namespaces); + return template; + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryBeanTest.java b/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryBeanTest.java index 44caa043..39ac5e2b 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryBeanTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryBeanTest.java @@ -22,21 +22,21 @@ import org.junit.Test; public class XPathExpressionFactoryBeanTest { - private XPathExpressionFactoryBean factoryBean; + private XPathExpressionFactoryBean factoryBean; - @Before - public void setUp() throws Exception { - factoryBean = new XPathExpressionFactoryBean(); - } + @Before + public void setUp() throws Exception { + factoryBean = new XPathExpressionFactoryBean(); + } - @Test - public void testFactoryBean() throws Exception { - factoryBean.setExpression("/root"); - factoryBean.afterPropertiesSet(); - Object result = factoryBean.getObject(); - Assert.assertNotNull("No result obtained", result); - Assert.assertTrue("No XPathExpression returned", result instanceof XPathExpression); - Assert.assertTrue("Not a singleton", factoryBean.isSingleton()); - Assert.assertEquals("Not a XPathExpresison", XPathExpression.class, factoryBean.getObjectType()); - } + @Test + public void testFactoryBean() throws Exception { + factoryBean.setExpression("/root"); + factoryBean.afterPropertiesSet(); + Object result = factoryBean.getObject(); + Assert.assertNotNull("No result obtained", result); + Assert.assertTrue("No XPathExpression returned", result instanceof XPathExpression); + Assert.assertTrue("Not a singleton", factoryBean.isSingleton()); + Assert.assertEquals("Not a XPathExpresison", XPathExpression.class, factoryBean.getObjectType()); + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryTest.java b/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryTest.java index eb6333de..70452fba 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xpath/XPathExpressionFactoryTest.java @@ -21,20 +21,20 @@ import org.junit.Test; public class XPathExpressionFactoryTest { - @Test - public void testCreateXPathExpression() throws Exception { - XPathExpression expression = XPathExpressionFactory.createXPathExpression("/root"); - Assert.assertNotNull("No expression returned", expression); - } + @Test + public void testCreateXPathExpression() throws Exception { + XPathExpression expression = XPathExpressionFactory.createXPathExpression("/root"); + Assert.assertNotNull("No expression returned", expression); + } - @Test - public void testCreateEmptyXPathExpression() throws Exception { - try { - XPathExpressionFactory.createXPathExpression(""); - Assert.fail("Should have thrown an Exception"); - } - catch (IllegalArgumentException ex) { - // expected - } - } + @Test + public void testCreateEmptyXPathExpression() throws Exception { + try { + XPathExpressionFactory.createXPathExpression(""); + Assert.fail("Should have thrown an Exception"); + } + catch (IllegalArgumentException ex) { + // expected + } + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xsd/AbstractXsdSchemaTestCase.java b/spring-xml/src/test/java/org/springframework/xml/xsd/AbstractXsdSchemaTestCase.java index 251b8137..e8aaefdd 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xsd/AbstractXsdSchemaTestCase.java +++ b/spring-xml/src/test/java/org/springframework/xml/xsd/AbstractXsdSchemaTestCase.java @@ -37,83 +37,83 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public abstract class AbstractXsdSchemaTestCase { - private DocumentBuilder documentBuilder; + private DocumentBuilder documentBuilder; - protected Transformer transformer; + protected Transformer transformer; - @Before - public final void setUp() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public final void setUp() throws Exception { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + XMLUnit.setIgnoreWhitespace(true); + } - @Test - public void testSingle() throws Exception { - Resource resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); - XsdSchema single = createSchema(resource); - String namespace = "http://www.springframework.org/spring-ws/single/schema"; - Assert.assertEquals("Invalid target namespace", namespace, single.getTargetNamespace()); - resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); - DOMResult domResult = new DOMResult(); - transformer.transform(single.getSource(), domResult); - Document result = (Document) domResult.getNode(); - assertXMLEqual("Invalid Source returned", expected, result); - } + @Test + public void testSingle() throws Exception { + Resource resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); + XsdSchema single = createSchema(resource); + String namespace = "http://www.springframework.org/spring-ws/single/schema"; + Assert.assertEquals("Invalid target namespace", namespace, single.getTargetNamespace()); + resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); + DOMResult domResult = new DOMResult(); + transformer.transform(single.getSource(), domResult); + Document result = (Document) domResult.getNode(); + assertXMLEqual("Invalid Source returned", expected, result); + } - @Test - public void testIncludes() throws Exception { - Resource resource = new ClassPathResource("including.xsd", AbstractXsdSchemaTestCase.class); - XsdSchema including = createSchema(resource); - String namespace = "http://www.springframework.org/spring-ws/include/schema"; - Assert.assertEquals("Invalid target namespace", namespace, including.getTargetNamespace()); - resource = new ClassPathResource("including.xsd", AbstractXsdSchemaTestCase.class); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); - DOMResult domResult = new DOMResult(); - transformer.transform(including.getSource(), domResult); - Document result = (Document) domResult.getNode(); - assertXMLEqual("Invalid Source returned", expected, result); - } + @Test + public void testIncludes() throws Exception { + Resource resource = new ClassPathResource("including.xsd", AbstractXsdSchemaTestCase.class); + XsdSchema including = createSchema(resource); + String namespace = "http://www.springframework.org/spring-ws/include/schema"; + Assert.assertEquals("Invalid target namespace", namespace, including.getTargetNamespace()); + resource = new ClassPathResource("including.xsd", AbstractXsdSchemaTestCase.class); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); + DOMResult domResult = new DOMResult(); + transformer.transform(including.getSource(), domResult); + Document result = (Document) domResult.getNode(); + assertXMLEqual("Invalid Source returned", expected, result); + } - @Test - public void testImports() throws Exception { - Resource resource = new ClassPathResource("importing.xsd", AbstractXsdSchemaTestCase.class); - XsdSchema importing = createSchema(resource); - String namespace = "http://www.springframework.org/spring-ws/importing/schema"; - Assert.assertEquals("Invalid target namespace", namespace, importing.getTargetNamespace()); - resource = new ClassPathResource("importing.xsd", AbstractXsdSchemaTestCase.class); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); - DOMResult domResult = new DOMResult(); - transformer.transform(importing.getSource(), domResult); - Document result = (Document) domResult.getNode(); - assertXMLEqual("Invalid Source returned", expected, result); - } + @Test + public void testImports() throws Exception { + Resource resource = new ClassPathResource("importing.xsd", AbstractXsdSchemaTestCase.class); + XsdSchema importing = createSchema(resource); + String namespace = "http://www.springframework.org/spring-ws/importing/schema"; + Assert.assertEquals("Invalid target namespace", namespace, importing.getTargetNamespace()); + resource = new ClassPathResource("importing.xsd", AbstractXsdSchemaTestCase.class); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); + DOMResult domResult = new DOMResult(); + transformer.transform(importing.getSource(), domResult); + Document result = (Document) domResult.getNode(); + assertXMLEqual("Invalid Source returned", expected, result); + } - @Test - public void testXmlNamespace() throws Exception { - Resource resource = new ClassPathResource("xmlNamespace.xsd", AbstractXsdSchemaTestCase.class); - XsdSchema importing = createSchema(resource); - String namespace = "http://www.springframework.org/spring-ws/xmlNamespace"; - Assert.assertEquals("Invalid target namespace", namespace, importing.getTargetNamespace()); - resource = new ClassPathResource("xmlNamespace.xsd", AbstractXsdSchemaTestCase.class); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); - DOMResult domResult = new DOMResult(); - transformer.transform(importing.getSource(), domResult); - Document result = (Document) domResult.getNode(); - assertXMLEqual("Invalid Source returned", expected, result); - } + @Test + public void testXmlNamespace() throws Exception { + Resource resource = new ClassPathResource("xmlNamespace.xsd", AbstractXsdSchemaTestCase.class); + XsdSchema importing = createSchema(resource); + String namespace = "http://www.springframework.org/spring-ws/xmlNamespace"; + Assert.assertEquals("Invalid target namespace", namespace, importing.getTargetNamespace()); + resource = new ClassPathResource("xmlNamespace.xsd", AbstractXsdSchemaTestCase.class); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(resource)); + DOMResult domResult = new DOMResult(); + transformer.transform(importing.getSource(), domResult); + Document result = (Document) domResult.getNode(); + assertXMLEqual("Invalid Source returned", expected, result); + } - @Test - public void testCreateValidator() throws Exception { - Resource resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); - XsdSchema single = createSchema(resource); - XmlValidator validator = single.createValidator(); - Assert.assertNotNull("No XmlValidator returned", validator); - } + @Test + public void testCreateValidator() throws Exception { + Resource resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); + XsdSchema single = createSchema(resource); + XmlValidator validator = single.createValidator(); + Assert.assertNotNull("No XmlValidator returned", validator); + } - protected abstract XsdSchema createSchema(Resource resource) throws Exception; + protected abstract XsdSchema createSchema(Resource resource) throws Exception; } diff --git a/spring-xml/src/test/java/org/springframework/xml/xsd/SimpleXsdSchemaTest.java b/spring-xml/src/test/java/org/springframework/xml/xsd/SimpleXsdSchemaTest.java index 7bd681d6..1fc7afa0 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xsd/SimpleXsdSchemaTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xsd/SimpleXsdSchemaTest.java @@ -20,11 +20,11 @@ import org.springframework.core.io.Resource; public class SimpleXsdSchemaTest extends AbstractXsdSchemaTestCase { - @Override - protected XsdSchema createSchema(Resource resource) throws Exception { - SimpleXsdSchema schema = new SimpleXsdSchema(resource); - schema.afterPropertiesSet(); - return schema; - } + @Override + protected XsdSchema createSchema(Resource resource) throws Exception { + SimpleXsdSchema schema = new SimpleXsdSchema(resource); + schema.afterPropertiesSet(); + return schema; + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollectionTest.java b/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollectionTest.java index 028300fb..fae18786 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollectionTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaCollectionTest.java @@ -39,122 +39,122 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class CommonsXsdSchemaCollectionTest { - private CommonsXsdSchemaCollection collection; + private CommonsXsdSchemaCollection collection; - private Transformer transformer; + private Transformer transformer; - private DocumentBuilder documentBuilder; + private DocumentBuilder documentBuilder; - @Before - public void setUp() throws Exception { - collection = new CommonsXsdSchemaCollection(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - transformer = transformerFactory.newTransformer(); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - XMLUnit.setIgnoreWhitespace(true); - } + @Before + public void setUp() throws Exception { + collection = new CommonsXsdSchemaCollection(); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformer = transformerFactory.newTransformer(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + XMLUnit.setIgnoreWhitespace(true); + } - @Test - public void testSingle() throws Exception { - Resource resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); - collection.setXsds(new Resource[]{resource}); - collection.afterPropertiesSet(); - Assert.assertEquals("Invalid amount of XSDs loaded", 1, collection.getXsdSchemas().length); - } + @Test + public void testSingle() throws Exception { + Resource resource = new ClassPathResource("single.xsd", AbstractXsdSchemaTestCase.class); + collection.setXsds(new Resource[]{resource}); + collection.afterPropertiesSet(); + Assert.assertEquals("Invalid amount of XSDs loaded", 1, collection.getXsdSchemas().length); + } - @Test - public void testInlineComplex() throws Exception { - Resource a = new ClassPathResource("A.xsd", AbstractXsdSchemaTestCase.class); - collection.setXsds(new Resource[]{a}); - collection.setInline(true); - collection.afterPropertiesSet(); - XsdSchema[] schemas = collection.getXsdSchemas(); - Assert.assertEquals("Invalid amount of XSDs loaded", 2, schemas.length); + @Test + public void testInlineComplex() throws Exception { + Resource a = new ClassPathResource("A.xsd", AbstractXsdSchemaTestCase.class); + collection.setXsds(new Resource[]{a}); + collection.setInline(true); + collection.afterPropertiesSet(); + XsdSchema[] schemas = collection.getXsdSchemas(); + Assert.assertEquals("Invalid amount of XSDs loaded", 2, schemas.length); - Assert.assertEquals("Invalid target namespace", "urn:1", schemas[0].getTargetNamespace()); - Resource abc = new ClassPathResource("ABC.xsd", AbstractXsdSchemaTestCase.class); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(abc)); - DOMResult domResult = new DOMResult(); - transformer.transform(schemas[0].getSource(), domResult); - assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); + Assert.assertEquals("Invalid target namespace", "urn:1", schemas[0].getTargetNamespace()); + Resource abc = new ClassPathResource("ABC.xsd", AbstractXsdSchemaTestCase.class); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(abc)); + DOMResult domResult = new DOMResult(); + transformer.transform(schemas[0].getSource(), domResult); + assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); - Assert.assertEquals("Invalid target namespace", "urn:2", schemas[1].getTargetNamespace()); - Resource cd = new ClassPathResource("CD.xsd", AbstractXsdSchemaTestCase.class); - expected = documentBuilder.parse(SaxUtils.createInputSource(cd)); - domResult = new DOMResult(); - transformer.transform(schemas[1].getSource(), domResult); - assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); - } + Assert.assertEquals("Invalid target namespace", "urn:2", schemas[1].getTargetNamespace()); + Resource cd = new ClassPathResource("CD.xsd", AbstractXsdSchemaTestCase.class); + expected = documentBuilder.parse(SaxUtils.createInputSource(cd)); + domResult = new DOMResult(); + transformer.transform(schemas[1].getSource(), domResult); + assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); + } - @Test - public void testCircular() throws Exception { - Resource resource = new ClassPathResource("circular-1.xsd", AbstractXsdSchemaTestCase.class); - collection.setXsds(new Resource[]{resource}); - collection.setInline(true); - collection.afterPropertiesSet(); - XsdSchema[] schemas = collection.getXsdSchemas(); - Assert.assertEquals("Invalid amount of XSDs loaded", 1, schemas.length); - } + @Test + public void testCircular() throws Exception { + Resource resource = new ClassPathResource("circular-1.xsd", AbstractXsdSchemaTestCase.class); + collection.setXsds(new Resource[]{resource}); + collection.setInline(true); + collection.afterPropertiesSet(); + XsdSchema[] schemas = collection.getXsdSchemas(); + Assert.assertEquals("Invalid amount of XSDs loaded", 1, schemas.length); + } - @Test - public void testXmlNamespace() throws Exception { - Resource resource = new ClassPathResource("xmlNamespace.xsd", AbstractXsdSchemaTestCase.class); - collection.setXsds(new Resource[]{resource}); - collection.setInline(true); - collection.afterPropertiesSet(); - XsdSchema[] schemas = collection.getXsdSchemas(); - Assert.assertEquals("Invalid amount of XSDs loaded", 1, schemas.length); - } + @Test + public void testXmlNamespace() throws Exception { + Resource resource = new ClassPathResource("xmlNamespace.xsd", AbstractXsdSchemaTestCase.class); + collection.setXsds(new Resource[]{resource}); + collection.setInline(true); + collection.afterPropertiesSet(); + XsdSchema[] schemas = collection.getXsdSchemas(); + Assert.assertEquals("Invalid amount of XSDs loaded", 1, schemas.length); + } - @Test - public void testCreateValidator() throws Exception { - Resource a = new ClassPathResource("A.xsd", AbstractXsdSchemaTestCase.class); - collection.setXsds(new Resource[]{a}); - collection.setInline(true); - collection.afterPropertiesSet(); + @Test + public void testCreateValidator() throws Exception { + Resource a = new ClassPathResource("A.xsd", AbstractXsdSchemaTestCase.class); + collection.setXsds(new Resource[]{a}); + collection.setInline(true); + collection.afterPropertiesSet(); - XmlValidator validator = collection.createValidator(); - Assert.assertNotNull("No XmlValidator returned", validator); - } + XmlValidator validator = collection.createValidator(); + Assert.assertNotNull("No XmlValidator returned", validator); + } - @Test - public void testInvalidSchema() throws Exception { - Resource invalid = new ClassPathResource("invalid.xsd", AbstractXsdSchemaTestCase.class); - collection.setXsds(new Resource[]{invalid}); - try { - collection.afterPropertiesSet(); - Assert.fail("CommonsXsdSchemaException expected"); - } - catch (CommonsXsdSchemaException ex) { - // expected - } - } + @Test + public void testInvalidSchema() throws Exception { + Resource invalid = new ClassPathResource("invalid.xsd", AbstractXsdSchemaTestCase.class); + collection.setXsds(new Resource[]{invalid}); + try { + collection.afterPropertiesSet(); + Assert.fail("CommonsXsdSchemaException expected"); + } + catch (CommonsXsdSchemaException ex) { + // expected + } + } - @Test - public void testIncludesAndImports() throws Exception { - Resource hr = new ClassPathResource("hr.xsd", getClass()); - collection.setXsds(new Resource[]{hr}); - collection.setInline(true); - collection.afterPropertiesSet(); + @Test + public void testIncludesAndImports() throws Exception { + Resource hr = new ClassPathResource("hr.xsd", getClass()); + collection.setXsds(new Resource[]{hr}); + collection.setInline(true); + collection.afterPropertiesSet(); - XsdSchema[] schemas = collection.getXsdSchemas(); - Assert.assertEquals("Invalid amount of XSDs loaded", 2, schemas.length); + XsdSchema[] schemas = collection.getXsdSchemas(); + Assert.assertEquals("Invalid amount of XSDs loaded", 2, schemas.length); - Assert.assertEquals("Invalid target namespace", "http://mycompany.com/hr/schemas", schemas[0].getTargetNamespace()); - Resource hr_employee = new ClassPathResource("hr_employee.xsd", getClass()); - Document expected = documentBuilder.parse(SaxUtils.createInputSource(hr_employee)); - DOMResult domResult = new DOMResult(); - transformer.transform(schemas[0].getSource(), domResult); - assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); + Assert.assertEquals("Invalid target namespace", "http://mycompany.com/hr/schemas", schemas[0].getTargetNamespace()); + Resource hr_employee = new ClassPathResource("hr_employee.xsd", getClass()); + Document expected = documentBuilder.parse(SaxUtils.createInputSource(hr_employee)); + DOMResult domResult = new DOMResult(); + transformer.transform(schemas[0].getSource(), domResult); + assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); - Assert.assertEquals("Invalid target namespace", "http://mycompany.com/hr/schemas/holiday", schemas[1].getTargetNamespace()); - Resource holiday = new ClassPathResource("holiday.xsd", getClass()); - expected = documentBuilder.parse(SaxUtils.createInputSource(holiday)); - domResult = new DOMResult(); - transformer.transform(schemas[1].getSource(), domResult); - assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); + Assert.assertEquals("Invalid target namespace", "http://mycompany.com/hr/schemas/holiday", schemas[1].getTargetNamespace()); + Resource holiday = new ClassPathResource("holiday.xsd", getClass()); + expected = documentBuilder.parse(SaxUtils.createInputSource(holiday)); + domResult = new DOMResult(); + transformer.transform(schemas[1].getSource(), domResult); + assertXMLEqual("Invalid XSD generated", expected, (Document) domResult.getNode()); - } + } } \ No newline at end of file diff --git a/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaTest.java b/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaTest.java index eb65969b..5d4fc567 100644 --- a/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaTest.java +++ b/spring-xml/src/test/java/org/springframework/xml/xsd/commons/CommonsXsdSchemaTest.java @@ -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, @@ -35,25 +35,25 @@ import static org.junit.Assert.assertNotNull; public class CommonsXsdSchemaTest extends AbstractXsdSchemaTestCase { - @Override - protected XsdSchema createSchema(Resource resource) throws Exception { - XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); - XmlSchema schema = schemaCollection.read(SaxUtils.createInputSource(resource)); - return new CommonsXsdSchema(schema); - } + @Override + protected XsdSchema createSchema(Resource resource) throws Exception { + XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); + XmlSchema schema = schemaCollection.read(SaxUtils.createInputSource(resource)); + return new CommonsXsdSchema(schema); + } - @Test - public void testXmime() throws Exception { - Resource resource = new ClassPathResource("xmime.xsd", AbstractXsdSchemaTestCase.class); - XsdSchema schema = createSchema(resource); - String namespace = "urn:test"; - assertEquals("Invalid target namespace", namespace, schema.getTargetNamespace()); - Document result = (Document) ((DOMSource) schema.getSource()).getNode(); - Element schemaElement = result.getDocumentElement(); - Element elementElement = (Element) schemaElement.getFirstChild(); - assertNotNull("No expectedContentTypes found", - elementElement.getAttributeNS("http://www.w3.org/2005/05/xmlmime", "expectedContentTypes")); - } + @Test + public void testXmime() throws Exception { + Resource resource = new ClassPathResource("xmime.xsd", AbstractXsdSchemaTestCase.class); + XsdSchema schema = createSchema(resource); + String namespace = "urn:test"; + assertEquals("Invalid target namespace", namespace, schema.getTargetNamespace()); + Document result = (Document) ((DOMSource) schema.getSource()).getNode(); + Element schemaElement = result.getDocumentElement(); + Element elementElement = (Element) schemaElement.getFirstChild(); + assertNotNull("No expectedContentTypes found", + elementElement.getAttributeNS("http://www.w3.org/2005/05/xmlmime", "expectedContentTypes")); + } } \ No newline at end of file