1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 package org.apache.synapse.format; 20 21 import java.io.IOException; 22 import java.io.InputStream; 23 24 import javax.activation.DataHandler; 25 import javax.xml.namespace.QName; 26 27 import org.apache.axiom.attachments.ByteArrayDataSource; 28 import org.apache.axiom.om.OMAbstractFactory; 29 import org.apache.axiom.om.OMElement; 30 import org.apache.axiom.om.OMFactory; 31 import org.apache.axis2.AxisFault; 32 import org.apache.axis2.builder.Builder; 33 import org.apache.axis2.context.MessageContext; 34 import org.apache.axis2.description.Parameter; 35 import org.apache.commons.io.IOUtils; 36 import org.apache.synapse.transport.base.BaseConstants; 37 import org.apache.synapse.transport.base.BaseUtils; 38 39 /** 40 * Message builder for binary payloads. 41 * <p> 42 * This builder processes the input message as binary and wraps 43 * the data in a wrapper element. The name of the wrapper element can 44 * be configured as a service parameter (see {@link BaseConstants#WRAPPER_PARAM}). 45 * It defaults to {@link BaseConstants#DEFAULT_BINARY_WRAPPER}. 46 */ 47 public class BinaryBuilder implements Builder { 48 public OMElement processDocument(InputStream inputStream, 49 String contentType, 50 MessageContext msgContext) throws AxisFault { 51 Parameter wrapperParam = msgContext.getAxisService().getParameter(BaseConstants.WRAPPER_PARAM); 52 QName wrapperQName; 53 if (wrapperParam != null) { 54 wrapperQName = BaseUtils.getQNameFromString(wrapperParam.getValue()); 55 } else { 56 wrapperQName = BaseConstants.DEFAULT_BINARY_WRAPPER; 57 } 58 OMFactory factory = OMAbstractFactory.getOMFactory(); 59 OMElement wrapper = factory.createOMElement(wrapperQName, null); 60 byte[] msgBytes; 61 try { 62 msgBytes = IOUtils.toByteArray(inputStream); 63 } catch (IOException ex) { 64 throw new AxisFault("Unable to read message payload", ex); 65 } 66 DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(msgBytes)); 67 wrapper.addChild(factory.createOMText(dataHandler, true)); 68 msgContext.setDoingMTOM(true); 69 return wrapper; 70 } 71 }