title: How can I parse an inbound message with MTOM attachments under Metro without pulling in all the attachment data?
body: <p>Using JAX-WS-RI or Metro I can write a WebService using the com.sun.xml.ws.api.server.AsyncProvider interface.</p>
  
  <p>I can choose to get the whole message including the SOAP headers</p>
  
  <pre><code>import javax.xml.transform.Source;
  import com.sun.xml.ws.api.server.AsyncProvider;
  import com.sun.xml.ws.api.server.AsyncProviderCallback;
  
  import javax.xml.ws.ServiceMode;
  import javax.xml.ws.WebServiceContext;
  import javax.xml.ws.WebServiceProvider;
  
  
  @ServiceMode(value=Service.Mode.MESSAGE)
  @WebServiceProvider()
  public class AddNumbersAsynchImpl implements AsyncProvider&lt;Source&gt; {
  ...
  </code></pre>
  
  <p>I can then write something which parses the message and processes accordingly</p>
  
  <pre><code>public void invoke(Source source, AsyncProviderCallback&lt;Source&gt; cbak, WebServiceContext ctxt) {
          DOMResult dom = new DOMResult();
          Transformer trans = TransformerFactory.newInstance().newTransformer();
          trans.transform(source, dom);
  
          XPath xpath = XPathFactory.newInstance().newXPath();
          xpath.setNamespaceContext(new MyNamespaceContext());
  
          String opName = (String) xpath.evaluate("name(/S:Envelope/S:Body/X:*[1])", dom.getNode(), XPathConstants.STRING);
  
          if(knownOp(opName)) {
              doOp(opName, dom.getNode(), cbak);
          }
          else {
              doFault("Unknown operation " + opName, cbak);
          }
  
  }
  </code></pre>
  
  <p>However part of the reason for doing this is to adapt an existing XML based application into the SOAP stack. 
  The application defines a complete set of schemas for the messages that it takes and it easy to generate a WSDL to define the service.</p>
  
  <p>For small XML messages this all works fine. </p>
  
  <p>However if I wish to process the XML in a more stream orientated fashion in some operations where the messages are bulky I come across two problems using MTOM attachments.
  I change the set up of my Provider as follows;</p>
  
  <pre><code>import com.sun.xml.ws.api.message.Message;
  import javax.xml.ws.soap.MTOM;
  import com.sun.xml.ws.developer.StreamingAttachment;
  import com.sun.xml.ws.developer.StreamingDataHandler;
  
  ServiceMode(value=Service.Mode.MESSAGE)
  @WebServiceProvider()
  @StreamingAttachment(parseEagerly=true, memoryThreshold=1000L)
  @MTOM(enabled=true, threshold=1000) 
  public class AddNumbersAsynchImplMessage implements AsyncProvider&lt;Message&gt; {
  ...
  </code></pre>
  
  <p>I Add the appropriate MTOM policy to my WSDL;</p>
  
  <pre><code>&lt;definitions
          name="AddNumbersAsynch"
          targetNamespace="http://asynch.duke.example.org"
          xmlns:tns="http://asynch.duke.example.org"
          xmlns="http://schemas.xmlsoap.org/wsdl/"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
          xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
          xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrmp/200702"
          xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
          xmlns:wsoma="http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization"
          xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"&gt;
          &lt;wsp:Policy wsu:Id="AddNumbersAsynch_policy"&gt;
              &lt;wsam:Addressing wsp:Optional="false" /&gt;
              &lt;wsoma:OptimizedMimeSerialization/&gt;
          &lt;/wsp:Policy&gt;
  </code></pre>
  
  <p>And declare my message schemas for this operation as appropriate</p>
  
  <pre><code>        &lt;complexType name="sendBulk"&gt;
              &lt;sequence&gt;
                  &lt;element name="data" type="base64Binary"
                      xmime:expectedContentTypes="application/xml"
                      xmlns:xmime="http://www.w3.org/2005/05/xmlmime"/&gt;
              &lt;/sequence&gt;
          &lt;/complexType&gt;
          &lt;element name="sendBulk" type="tns:sendBulk"/&gt;
  
          &lt;complexType name="sendBulkResponse"&gt;
              &lt;sequence&gt;
                  &lt;element name="return" type="xsd:string" /&gt;
              &lt;/sequence&gt;
          &lt;/complexType&gt;
          &lt;element name="sendBulkResponse" type="tns:sendBulkResponse"/&gt;
  </code></pre>
  
  <p>Setting up the binding as appropriate;</p>
  
  <pre><code>&lt;binding name="AddNumbersBinding" type="tns:AddNumbersPortType"&gt;
  &lt;wsp:PolicyReference URI="#AddNumbersAsynch_policy"/&gt;
      &lt;soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" /&gt;
      &lt;operation name="sendBulk"&gt;
          &lt;soap:operation soapAction="" /&gt;
          &lt;input&gt;
              &lt;soap:body use="literal" /&gt;
          &lt;/input&gt;
          &lt;output&gt;
              &lt;soap:body use="literal" /&gt;
          &lt;/output&gt;
      &lt;/operation&gt;
  &lt;/binding&gt;
  </code></pre>
  
  <p>I generate the client and amend the code</p>
  
  <pre><code>port = new AddNumbersService().getAddNumbersPort(new SyncStartForAsyncFeature(), new MTOMFeature(1000));
    Source data = new StreamSource(new FileInputStream(file));
    String result = port.sendBulk(data);
  </code></pre>
  
  <p>and the http dump shows that the data is being sent as a multipart mime with the appropriate xop:include element in the 'message body'</p>
  
  <pre><code>---[HTTP request - http://localhost:8080/ProviderTest2/addnumbersAsynchMessage]---
  Accept: text/xml, multipart/related
  Content-Type: multipart/related;start="&lt;rootpart*daff762b-9651-40aa-ae2f-30d30a3c5e2e@example.jaxws.sun.com&gt;";type="application/xop+xml";boundary="uuid:daff762b-9651-40aa-ae2f-30d30a3c5e2e";start-info="text/xml"
  SOAPAction: "http://message.asynch.duke.example.org/AddNumbersPortType/sendBulkRequest"
  User-Agent: Metro/2.2 (branches/2.2-7015; 2012-02-20T20:31:25+0000) JAXWS-RI/2.2.6 JAXWS/2.2 svn-revision#unknown
  --uuid:daff762b-9651-40aa-ae2f-30d30a3c5e2e
  Content-Id: &lt;rootpart*daff762b-9651-40aa-ae2f-30d30a3c5e2e@example.jaxws.sun.com&gt;
  Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
  Content-Transfer-Encoding: binary
  
  &lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;S:Header&gt;&lt;To xmlns="http://www.w3.org/2005/08/addressing"&gt;http://localhost:8080/ProviderTest2/addnumbersAsynchMessage&lt;/To&gt;&lt;Action xmlns="http://www.w3.org/2005/08/addressing" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" S:mustUnderstand="1"&gt;http://message.asynch.duke.example.org/AddNumbersPortType/sendBulkRequest&lt;/Action&gt;&lt;ReplyTo xmlns="http://www.w3.org/2005/08/addressing"&gt;
      &lt;Address&gt;http://www.w3.org/2005/08/addressing/anonymous&lt;/Address&gt;
  &lt;/ReplyTo&gt;&lt;FaultTo xmlns="http://www.w3.org/2005/08/addressing"&gt;
      &lt;Address&gt;http://www.w3.org/2005/08/addressing/anonymous&lt;/Address&gt;
  &lt;/FaultTo&gt;&lt;MessageID xmlns="http://www.w3.org/2005/08/addressing"&gt;uuid:406ce4bc-7332-4849-b16b-69cec6ca21ea&lt;/MessageID&gt;&lt;/S:Header&gt;&lt;S:Body&gt;&lt;sendBulk xmlns="http://message.asynch.duke.example.org"&gt;&lt;data&gt;&lt;xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:5f88ee1b-0aa1-46ef-bad3-93df9b2aaa02@example.jaxws.sun.com"/&gt;&lt;/data&gt;&lt;/sendBulk&gt;&lt;/S:Body&gt;&lt;/S:Envelope&gt;
  --uuid:daff762b-9651-40aa-ae2f-30d30a3c5e2e
  Content-Id: &lt;5f88ee1b-0aa1-46ef-bad3-93df9b2aaa02@example.jaxws.sun.com&gt;
  Content-Type: application/xml; charset=UTF-8
  Content-Transfer-Encoding: binary
  
  ....snip!
  </code></pre>
  
  <p>Inside the server I get an attachment;</p>
  
  <pre><code>public void invoke(Message source, AsyncProviderCallback&lt;Message&gt; cbak, WebServiceContext ctxt) {
  
          Map&lt;String, DataHandler&gt; attachments = (Map&lt;String, DataHandler&gt;) ctxt.getMessageContext().get(javax.xml.ws.handler.MessageContext.INBOUND_MESSAGE_ATTACHMENTS); 
          for(String attachmentKey: attachments.keySet()) {
              StreamingDataHandler handler = (StreamingDataHandler) attachments.get(attachmentKey);
              System.out.println("Got attachment " + attachmentKey + " of type " + attachments.get(attachmentKey));
          }
          if(attachments.isEmpty()) {
              System.out.println("Got No attachments");
          }
  </code></pre>
  
  <p>I then wish top parse the incoming message and get the context for the bulk attachment - for example the name of the element that encloses it - but not the bulk attachment itself, YET;</p>
  
  <pre><code>XMLStreamWriter sw = new MyXMLStreamWriter();
  source.writeTo(sw);
  </code></pre>
  
  <p>Hopefully the attachment parser has not read all that part of the incoimuing HTTP stream yet, or if it has it has chunked it off into a file, where I can then read it chunk by chunk. 
  The trouble is that I cannot find a way of parsing Message that does not convert the incoming  into the base64 encoded data in the attachment.
  After I get the SAX/StaX event indicating the start of the  element, it is followed by a characters event which is the base64 encoded data.
  Looking at the code for StreamMessage there is no way to "insert" any XMLReader or XMLStreamReader etc. 'in front of' the existing XMLStreamReader that the Message is already bound to ( not suprising as we are part way through message processing). 
  But that XMLStreamReader implementation is a com.sun.xml.ws.encoding.MtomCodec$MtomXMLStreamReaderEx which always 'unpacks' attachments in line into memory.
  There is no way to paramterize the com.sun.xml.ws.encoding.MtomCodec class so that it does not first pass events to its inner MtomXMLStreamReaderEx class which unpacks the attachment inline.</p>
  
  <p>I tried to read the attachment into a temporary file and then substitute the Message context  attachments for a FileDataSource, but since Metro ignores these, that only had the effect of making the original DataSource throw a ReadOnce type error.</p>
  
  <pre><code>Map&lt;String, DataHandler&gt; attachments = (Map&lt;String, DataHandler&gt;) ctxt.getMessageContext().get(javax.xml.ws.handler.MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
              HashMap&lt;String, DataHandler&gt; clonedAttachments = new HashMap&lt;String, DataHandler&gt;(attachments);
              for(String attachmentKey: attachments.keySet()) {
                  StreamingDataHandler handler = (StreamingDataHandler) attachments.get(attachmentKey);
                  File tempFile = File.createTempFile("Attachment" + attachmentKey, ".xmlb64", new File("C:\\Users\\Administrator\\workspaceTool1\\TomcatWorkingDir"));
                  handler.moveTo(tempFile);
                  FileDataSource newSource = new FileDataSource(tempFile);
                  clonedAttachments.put(attachmentKey, new DataHandler(newSource));
                  System.out.println("Got attachment " + attachmentKey + " of type " + attachments.get(attachmentKey));
              }
              if(attachments.isEmpty()) {
                  System.out.println("Got No attachments");
              }
              else {
                  ctxt.getMessageContext().put(javax.xml.ws.handler.MessageContext.INBOUND_MESSAGE_ATTACHMENTS, clonedAttachments);
              }
  </code></pre>
  
  <p>I tried also turning off MTOM in the provider by setting the annotation to disabled;</p>
  
  <pre><code>@MTOM(enabled=false) 
  </code></pre>
  
  <p>and then removing it and then the StreamingAttachment annotation to no avail. I also set the  enable-mtom="false" attribute in the endpoint element for it in the sun-jaxws.xml file, again to no avail; it seems that xop:Include parsing is hardwired. I do not want to change the wsdl because that I do want clients to use MTOM if possible. ( but see my swaRef answer below ) </p>
  
  <p>I can make Metro do what I want if I use swaRef, but my understanding was that MTOM is the protocol that has gained support? With the swaRef I have to edit the WSDL ;</p>
  
  <pre><code>&lt;types&gt;
  
  
          &lt;xsd:schema
              xmlns="http://www.w3.org/2001/XMLSchema"
              targetNamespace="http://swaRef.asynch.duke.example.org"
              elementFormDefault="qualified"&gt;
  
          &lt;xsd:import namespace="http://ws-i.org/profiles/basic/1.1/xsd"  
                          schemaLocation="http://www.ws-i.org/profiles/basic/1.1/swaref.xsd"/&gt;
  
  
  
              &lt;complexType name="sendBulk"&gt;
                  &lt;sequence&gt;
                      &lt;element name="data" type="wsi:swaRef"
                          xmlns:wsi="http://ws-i.org/profiles/basic/1.1/xsd"/&gt;
                  &lt;/sequence&gt;
              &lt;/complexType&gt;
              &lt;element name="sendBulk" type="tns:sendBulk"/&gt;
  </code></pre>
  
  <p>I also have to generate a new client and call the sendBulk method differently;</p>
  
  <pre><code>FileDataSource newSource = new FileDataSource(file);
  DataHandler data = new DataHandler(newSource);
  String result = port.sendBulk(data);
  </code></pre>
  
  <p>But now when I parse the data element I get the corresponding cid which I can then use to retrieve the attachment as I wish;</p>
  
  <pre><code>DataHandler handler = attachments.get(dataText.substring("cid:".length()));
  InputStream input = handler.getInputStream();
  </code></pre>
  
  <p>So, with MTOM and Metro though the attachments may have not been read up to the point where I parse the data element, or indeed streamed efficiently in chunks to a temporary file, I have no way to read the "rest" of the input message without reading the whole of the attachment into memory which seems self defeating?
  Apart from dumping Metro - suggestions re: Axis, CXF welcomed - is there any way around this anyone has discovered? </p>
  
  <p>Logged <a href="http://java.net/jira/browse/JAX_WS-1070" rel="nofollow">a feature request</a>.</p>