How do I convert MTOM Attachment to binary data

prabhup1
Participant II

Here's what I am looking to do:

a. Create an API Proxy that receives MTOM attachment along with XML data.

b. Convert MTOM attachment to binary data and store it in a variable.

c. Create a new XML message (Assign Message) and insert the binary data from the variable into the new XML.

d. Make a ServiceCallout using the new XML.

e. If successful, pass the original XML message with MTOM attachment as-is to the backend service.

The goal is to virus scan all MTOM attachments before forwarding them to the back end service. The reason that the MTOM attachment needs to be converted to binary data is that the Virus Scan software interface does not accept MTOM attachments. Handles inline binary data only.

2 2 1,656
2 REPLIES 2

I understand what you wish to do. In order to do what you want, you will need to process the inbound message, with the MTOM attachment, to separate the binary content from the XML/SOAP.

I do not know of a way to do what you want, other than via writing a custom extension. Fortunately, these are easy to write, using Java. Apigee calls these extensions "Java callouts". They are really just custom policies that you define, by writing Java code.

The way I believe it would work:

  • The Java callout receives the entire message
  • The Java callout parses the message , probably using something like the javax.mail.internet.MimeMultipart class. It will give you a BodyPart.
  • use the getInputStream() on that MimeBodyPart to read the binary data
  • place this data into a context variable (unencoded)
  • the Java callout ends

At that point you can access the context variable, from within your service Callout, to transmit the attachment data.

I haven't tried this, but it should be straightforward to do so.

MTOM is actually binary - the attachment is sent in binary form, and not in an encoded (eg base64) form. This is done for performance reasons. Therefore there is no need to "convert the attachment to binary form". It's already binary. All you would need to do is extract the binary attachment data from the rest of the inbound message, which is mixed XML + binary.

There's a second way to do this, which is to simply send the outbound call to the Virus scanner, from within the Java callout itself. This means there'd be no need for an additional ServiceCallout policy. The Java callout would do three things: (a) extract the data, and (b) send just that data to the virus scanner, (c) interpret the result from the scan. Only if all three succeed should you pass the inbound message to the backend service.

There are lots of example Java callouts on github to get you started. Try here and here.

prabhup1
Participant II

Thanks Dino. I will give that a try.