Search in sources :

Example 41 with Message

use of org.apache.axis2.transport.msmq.util.Message in project wso2-axis2-transports by wso2.

the class XMPPPacketListener method buildSOAPEnvelope.

/**
 * builds SOAP envelop using message contained in packet
 * @param packet
 * @param msgContext
 * @throws AxisFault
 */
private void buildSOAPEnvelope(Packet packet, MessageContext msgContext) throws AxisFault {
    Message message = (Message) packet;
    String logMsg = "Trying to create " + "message content using XMPP message received :" + packet.toXML();
    String messageBody = StringEscapeUtils.unescapeXml(message.getBody());
    if (msgContext.isServerSide()) {
        log.debug("Received Envelope : " + messageBody);
    }
    InputStream inputStream = new ByteArrayInputStream(messageBody.getBytes());
    SOAPEnvelope envelope = null;
    try {
        Object obj = message.getProperty(XMPPConstants.CONTAINS_SOAP_ENVELOPE);
        if (obj != null && ((Boolean) obj).booleanValue()) {
            String contentType = (String) message.getProperty(XMPPConstants.CONTENT_TYPE);
            if (contentType == null) {
                throw new AxisFault("Can not Find Content type Property in the XMPP Message");
            }
            envelope = TransportUtils.createSOAPMessage(msgContext, inputStream, contentType);
            msgContext.setProperty(XMPPConstants.CONTAINS_SOAP_ENVELOPE, new Boolean(true));
        } else {
            // This message could either be a service call or a help command
            if (!(messageContainsCommandsFromChat(messageBody, msgContext))) {
                envelope = createSOAPEnvelopeForRawMessage(msgContext, messageBody);
            }
        }
        if (envelope != null) {
            msgContext.setEnvelope(envelope);
        }
    } catch (OMException e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    } catch (XMLStreamException e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    } catch (FactoryConfigurationError e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    } catch (AxisFault e) {
        log.error(logMsg, e);
        throw new AxisFault(logMsg);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Message(org.jivesoftware.smack.packet.Message) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) OMException(org.apache.axiom.om.OMException) FactoryConfigurationError(javax.xml.parsers.FactoryConfigurationError)

Example 42 with Message

use of org.apache.axis2.transport.msmq.util.Message in project wso2-axis2-transports by wso2.

the class JMSSender method createJMSMessage.

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session
 *
 * @param msgContext the MessageContext
 * @param session    the JMS session
 * @param contentTypeProperty the message property to be used to store the
 *                            content type
 * @return a JMS message from the context and session
 * @throws JMSException on exception
 * @throws AxisFault on exception
 */
private Message createJMSMessage(MessageContext msgContext, Session session, String contentTypeProperty) throws JMSException, AxisFault {
    Message message = null;
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);
    // check the first element of the SOAP body, do we have content wrapped using the
    // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages
    // for JMS but just get the payload in its native format
    String jmsPayloadType = guessMessageType(msgContext);
    if (jmsPayloadType == null) {
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new JMSException("Unable to get the message formatter to use");
        }
        String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());
        boolean useBytesMessage = msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1;
        OutputStream out;
        StringWriter sw;
        if (useBytesMessage) {
            BytesMessage bytesMsg = session.createBytesMessage();
            sw = null;
            out = new BytesMessageOutputStream(bytesMsg);
            message = bytesMsg;
        } else {
            sw = new StringWriter();
            try {
                out = new WriterOutputStream(sw, format.getCharSetEncoding());
            } catch (UnsupportedCharsetException ex) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
                return null;
            }
        }
        try {
            messageFormatter.writeTo(msgContext, format, out, true);
            out.close();
        } catch (IOException e) {
            Transaction transaction = null;
            try {
                transaction = ((TransactionManager) msgContext.getProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER)).getTransaction();
                rollbackXATransaction(transaction);
            } catch (SystemException e1) {
                handleException("Error occurred during obtaining  transaction", e1);
            }
            handleException("IO Error while creating BytesMessage", e);
        }
        if (!useBytesMessage) {
            TextMessage txtMsg = session.createTextMessage();
            txtMsg.setText(sw.toString());
            message = txtMsg;
        }
        if (contentTypeProperty != null) {
            message.setStringProperty(contentTypeProperty, contentType);
        }
    } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) {
        message = session.createBytesMessage();
        BytesMessage bytesMsg = (BytesMessage) message;
        OMElement wrapper = msgContext.getEnvelope().getBody().getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER);
        OMNode omNode = wrapper.getFirstOMChild();
        if (omNode != null && omNode instanceof OMText) {
            Object dh = ((OMText) omNode).getDataHandler();
            if (dh != null && dh instanceof DataHandler) {
                try {
                    ((DataHandler) dh).writeTo(new BytesMessageOutputStream(bytesMsg));
                } catch (IOException e) {
                    Transaction transaction = null;
                    try {
                        transaction = ((TransactionManager) msgContext.getProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER)).getTransaction();
                        rollbackXATransaction(transaction);
                    } catch (SystemException e1) {
                        handleException("Error occurred during obtaining  transaction", e1);
                    }
                    handleException("Error serializing binary content of element : " + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                }
            }
        }
    } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) {
        message = session.createTextMessage();
        TextMessage txtMsg = (TextMessage) message;
        txtMsg.setText(msgContext.getEnvelope().getBody().getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText());
    } else if (JMSConstants.JMS_MAP_MESSAGE.equalsIgnoreCase(jmsPayloadType)) {
        message = session.createMapMessage();
        JMSUtils.convertXMLtoJMSMap(msgContext.getEnvelope().getBody().getFirstChildWithName(JMSConstants.JMS_MAP_QNAME), (MapMessage) message);
    }
    // set the JMS correlation ID if specified
    String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID);
    if (correlationId == null && msgContext.getRelatesTo() != null) {
        correlationId = msgContext.getRelatesTo().getValue();
    }
    if (correlationId != null) {
        message.setJMSCorrelationID(correlationId);
    }
    if (msgContext.isServerSide()) {
        // set SOAP Action as a property on the JMS message
        setProperty(message, msgContext, BaseConstants.SOAPACTION);
    } else {
        String action = msgContext.getOptions().getAction();
        if (action != null) {
            message.setStringProperty(BaseConstants.SOAPACTION, action);
        }
    }
    JMSUtils.setTransportHeaders(msgContext, message);
    return message;
}
Also used : AxisFault(org.apache.axis2.AxisFault) BytesMessageOutputStream(org.apache.axis2.transport.jms.iowrappers.BytesMessageOutputStream) OutputStream(java.io.OutputStream) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) BytesMessageOutputStream(org.apache.axis2.transport.jms.iowrappers.BytesMessageOutputStream) OMElement(org.apache.axiom.om.OMElement) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) OMNode(org.apache.axiom.om.OMNode) StringWriter(java.io.StringWriter) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) TransactionManager(javax.transaction.TransactionManager) OMText(org.apache.axiom.om.OMText) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 43 with Message

use of org.apache.axis2.transport.msmq.util.Message in project wso2-axis2-transports by wso2.

the class JMSSenderTestCase method testTransactionCommandParameter.

/**
 * Test case for EI-1244.
 * test transport.jms.TransactionCommand parameter in transport url when sending the message.
 * This will verify the fixes which prevent possible OOM issue when publishing messages to a broker using jms.
 *
 * @throws Exception
 */
public void testTransactionCommandParameter() throws Exception {
    JMSSender jmsSender = PowerMockito.spy(new JMSSender());
    JMSOutTransportInfo jmsOutTransportInfo = Mockito.mock(JMSOutTransportInfo.class);
    JMSMessageSender jmsMessageSender = Mockito.mock(JMSMessageSender.class);
    Session session = Mockito.mock(Session.class);
    Mockito.doReturn(session).when(jmsMessageSender).getSession();
    PowerMockito.whenNew(JMSOutTransportInfo.class).withArguments(any(String.class)).thenReturn(jmsOutTransportInfo);
    Mockito.doReturn(jmsMessageSender).when(jmsOutTransportInfo).createJMSSender(any(MessageContext.class));
    PowerMockito.doNothing().when(jmsSender, "sendOverJMS", ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any());
    jmsSender.init(new ConfigurationContext(new AxisConfiguration()), new TransportOutDescription("jms"));
    MessageContext messageContext = new MessageContext();
    // append the transport.jms.TransactionCommand
    String targetAddress = "jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=" + "QueueConnectionFactory&transport.jms.TransactionCommand=begin" + "&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory";
    Transaction transaction = new TestJMSTransaction();
    messageContext.setProperty(JMSConstants.JMS_XA_TRANSACTION, transaction);
    jmsSender.sendMessage(messageContext, targetAddress, null);
    Map<Transaction, ArrayList<JMSMessageSender>> jmsMessageSenderMap = Whitebox.getInternalState(JMSSender.class, "jmsMessageSenderMap");
    Assert.assertEquals("Transaction not added to map", 1, jmsMessageSenderMap.size());
    List senderList = jmsMessageSenderMap.get(transaction);
    Assert.assertNotNull("List is null", senderList);
    Assert.assertEquals("List is empty", 1, senderList.size());
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ArrayList(java.util.ArrayList) Transaction(javax.transaction.Transaction) ArrayList(java.util.ArrayList) List(java.util.List) MessageContext(org.apache.axis2.context.MessageContext) Session(javax.jms.Session) TransportOutDescription(org.apache.axis2.description.TransportOutDescription)

Example 44 with Message

use of org.apache.axis2.transport.msmq.util.Message in project wso2-axis2-transports by wso2.

the class XMPPSender method sendMessage.

/**
 * Send the given message over XMPP transport
 *
 * @param msgCtx the axis2 message context
 * @throws AxisFault on error
 */
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo) throws AxisFault {
    XMPPConnection xmppConnection = null;
    XMPPOutTransportInfo xmppOutTransportInfo = null;
    XMPPConnectionFactory connectionFactory;
    // if on client side,create connection to xmpp server
    if (msgCtx.isServerSide()) {
        xmppOutTransportInfo = (XMPPOutTransportInfo) msgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO);
        connectionFactory = xmppOutTransportInfo.getConnectionFactory();
    } else {
        getConnectionDetailsFromClientOptions(msgCtx);
        connectionFactory = defaultConnectionFactory;
    }
    synchronized (this) {
        xmppConnection = connectionFactory.getXmppConnection();
        if (xmppConnection == null) {
            connectionFactory.connect(serverCredentials);
            xmppConnection = connectionFactory.getXmppConnection();
        }
    }
    Message message = new Message();
    Options options = msgCtx.getOptions();
    String serviceName = XMPPUtils.getServiceName(targetAddress);
    SOAPVersion version = msgCtx.getEnvelope().getVersion();
    if (version instanceof SOAP12Version) {
        message.setProperty(XMPPConstants.CONTENT_TYPE, HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML + "; action=" + msgCtx.getSoapAction());
    } else {
        message.setProperty(XMPPConstants.CONTENT_TYPE, HTTPConstants.MEDIA_TYPE_TEXT_XML);
    }
    if (targetAddress != null) {
        xmppOutTransportInfo = new XMPPOutTransportInfo(targetAddress);
        xmppOutTransportInfo.setConnectionFactory(defaultConnectionFactory);
    } else if (msgCtx.getTo() != null && !msgCtx.getTo().hasAnonymousAddress()) {
    // TODO
    } else if (msgCtx.isServerSide()) {
        xmppOutTransportInfo = (XMPPOutTransportInfo) msgCtx.getProperty(Constants.OUT_TRANSPORT_INFO);
    }
    try {
        if (msgCtx.isServerSide()) {
            message.setProperty(XMPPConstants.IS_SERVER_SIDE, new Boolean(false));
            message.setProperty(XMPPConstants.IN_REPLY_TO, xmppOutTransportInfo.getInReplyTo());
            message.setProperty(XMPPConstants.SEQUENCE_ID, xmppOutTransportInfo.getSequenceID());
        } else {
            // message is going to be processed on server side
            message.setProperty(XMPPConstants.IS_SERVER_SIDE, new Boolean(true));
            // we are sending a soap envelope as a message
            message.setProperty(XMPPConstants.CONTAINS_SOAP_ENVELOPE, new Boolean(true));
            message.setProperty(XMPPConstants.SERVICE_NAME, serviceName);
            String action = options.getAction();
            if (action == null) {
                AxisOperation axisOperation = msgCtx.getAxisOperation();
                if (axisOperation != null) {
                    action = axisOperation.getSoapAction();
                }
            }
            if (action != null) {
                message.setProperty(XMPPConstants.ACTION, action);
            }
        }
        if (xmppConnection == null) {
            handleException("Connection to XMPP Server is not established.");
        }
        // initialize the chat manager using connection
        ChatManager chatManager = xmppConnection.getChatManager();
        Chat chat = chatManager.createChat(xmppOutTransportInfo.getDestinationAccount(), null);
        boolean waitForResponse = msgCtx.getOperationContext() != null && WSDL2Constants.MEP_URI_OUT_IN.equals(msgCtx.getOperationContext().getAxisOperation().getMessageExchangePattern());
        OMElement msgElement;
        String messageToBeSent = "";
        if (XMPPConstants.XMPP_CONTENT_TYPE_STRING.equals(xmppOutTransportInfo.getContentType())) {
            // if request is received from a chat client, whole soap envelope
            // should not be sent.
            OMElement soapBodyEle = msgCtx.getEnvelope().getBody();
            OMElement responseEle = soapBodyEle.getFirstElement();
            if (responseEle != null) {
                msgElement = responseEle.getFirstElement();
            } else {
                msgElement = responseEle;
            }
        } else {
            // if request received from a ws client whole soap envelope
            // must be sent.
            msgElement = msgCtx.getEnvelope();
        }
        messageToBeSent = msgElement.toString();
        message.setBody(messageToBeSent);
        String key = null;
        if (waitForResponse && !msgCtx.isServerSide()) {
            PacketFilter filter = new PacketTypeFilter(message.getClass());
            xmppConnection.addPacketListener(xmppClientSidePacketListener, filter);
            key = UUID.randomUUID().toString();
            xmppClientSidePacketListener.listenForResponse(key, msgCtx);
            message.setProperty(XMPPConstants.SEQUENCE_ID, key);
        }
        chat.sendMessage(message);
        log.debug("Sent message :" + message.toXML());
        // Is this the best way to do this?
        if (waitForResponse && !msgCtx.isServerSide()) {
            xmppClientSidePacketListener.waitFor(key);
            // xmppConnection.disconnect();
            log.debug("Received response sucessfully");
        }
    } catch (XMPPException e) {
        log.error("Error occurred while sending the message : " + message.toXML(), e);
        handleException("Error occurred while sending the message : " + message.toXML(), e);
    } catch (InterruptedException e) {
        log.error("Error occurred while sending the message : " + message.toXML(), e);
        handleException("Error occurred while sending the message : " + message.toXML(), e);
    } finally {
    // if(xmppConnection != null && !msgCtx.isServerSide()){
    // xmppConnection.disconnect();
    // }
    }
}
Also used : Options(org.apache.axis2.client.Options) XMPPConnectionFactory(org.apache.axis2.transport.xmpp.util.XMPPConnectionFactory) PacketFilter(org.jivesoftware.smack.filter.PacketFilter) AxisMessage(org.apache.axis2.description.AxisMessage) Message(org.jivesoftware.smack.packet.Message) AxisOperation(org.apache.axis2.description.AxisOperation) OMElement(org.apache.axiom.om.OMElement) PacketTypeFilter(org.jivesoftware.smack.filter.PacketTypeFilter) XMPPConnection(org.jivesoftware.smack.XMPPConnection) XMPPOutTransportInfo(org.apache.axis2.transport.xmpp.util.XMPPOutTransportInfo) SOAPVersion(org.apache.axiom.soap.SOAPVersion) Chat(org.jivesoftware.smack.Chat) XMPPException(org.jivesoftware.smack.XMPPException) ChatManager(org.jivesoftware.smack.ChatManager) SOAP12Version(org.apache.axiom.soap.SOAP12Version)

Example 45 with Message

use of org.apache.axis2.transport.msmq.util.Message in project wso2-axis2-transports by wso2.

the class MailTransportSender method sendMail.

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error
 * @return id of the send mail message
 */
private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException {
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    // Make sure that non textual attachements are sent with base64 transfer encoding
    // instead of binary.
    format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true);
    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);
    if (log.isDebugEnabled()) {
        log.debug("Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName());
    }
    WSMimeMessage message = null;
    if (outInfo.getFromAddress() != null) {
        message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress());
    } else {
        message = new WSMimeMessage(session, "");
    }
    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (log.isDebugEnabled() && trpHeaders != null) {
        log.debug("Using transport headers: " + trpHeaders);
    }
    // to the transport senders default From address
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + outInfo.getFromAddress().getAddress() + " from OutTransportInfo");
        }
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM));
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + from.getAddress() + " from transport headers");
        }
        message.setFrom(from);
        message.setReplyTo(new Address[] { from });
    } else {
        if (smtpFromAddress != null) {
            if (log.isDebugEnabled()) {
                log.debug("Setting From header to " + smtpFromAddress.getAddress() + " from transport configuration");
            }
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO));
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.TO, to);
    } else if (outInfo.getTargetAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses()) + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC));
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.CC, cc);
    } else if (outInfo.getCcAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses()) + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }
    // custom transport header
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers");
        }
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }
    if (smtpBccAddresses != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses) + " from transport configuration");
        }
        message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses);
    }
    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT) + "' from transport headers");
        }
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers");
        }
        message.setSubject(outInfo.getSubject());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Generating default Subject header from SOAP action");
        }
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }
    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());
    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }
    // set Date
    message.setSentDate(new Date());
    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
    // write body
    MessageFormatterEx messageFormatterEx;
    if (messageFormatter instanceof MessageFormatterEx) {
        messageFormatterEx = (MessageFormatterEx) messageFormatter;
    } else {
        messageFormatterEx = new MessageFormatterExAdapter(messageFormatter);
    }
    DataHandler dataHandler = new DataHandler(messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction()));
    MimeMultipart mimeMultiPart = null;
    String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
    if (mFormat == null) {
        mFormat = defaultMailFormat;
    }
    if (log.isDebugEnabled()) {
        log.debug("Using mail format '" + mFormat + "'");
    }
    MimePart mainPart;
    boolean isMultiPart = MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat);
    boolean isAttachFile = MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat);
    if (isMultiPart || isAttachFile) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        String body = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_BODY_WHEN_ATTACHED);
        if (body == null) {
            body = "Web Service Message Attached";
        }
        String bodyMime = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_BODY_MIME_WHEN_ATTACHED);
        if (bodyMime == null) {
            bodyMime = "text/plain";
        }
        mimeBodyPart1.setContent(body, bodyMime);
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);
        if (isAttachFile) {
            String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE);
            if (fileName != null) {
                mimeBodyPart2.setFileName(fileName);
            } else {
                mimeBodyPart2.setFileName("attachment");
            }
        }
        mainPart = mimeBodyPart2;
    } else {
        mainPart = message;
    }
    try {
        mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
        mainPart.setDataHandler(dataHandler);
        // needs to scan the entire content to determine this.
        if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) {
            mainPart.setHeader("Content-Transfer-Encoding", (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding"));
        } else {
            String contentType = dataHandler.getContentType().toLowerCase();
            if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) {
                mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            }
        }
        // setting any custom headers defined by the user
        if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) {
            Map customTransportHeaders = (Map) msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS);
            for (Object header : customTransportHeaders.keySet()) {
                mainPart.setHeader((String) header, (String) customTransportHeaders.get(header));
            }
        }
        log.debug("Sending message");
        Transport.send(message);
        // update metrics
        metrics.incrementMessagesSent(msgContext);
        long bytesSent = message.getBytesSent();
        if (bytesSent != -1) {
            metrics.incrementBytesSent(msgContext, bytesSent);
        }
    } catch (MessagingException e) {
        metrics.incrementFaultsSending();
        handleException("Error creating mail message or sending it to the configured server", e);
    }
    return message.getMessageID();
}
Also used : MessageFormatterExAdapter(org.apache.axis2.format.MessageFormatterExAdapter) MessageFormatter(org.apache.axis2.transport.MessageFormatter) DataHandler(javax.activation.DataHandler) MessageFormatterEx(org.apache.axis2.format.MessageFormatterEx) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

AxisFault (org.apache.axis2.AxisFault)25 MessageContext (org.apache.axis2.context.MessageContext)20 IOException (java.io.IOException)9 OMOutputFormat (org.apache.axiom.om.OMOutputFormat)8 MessageFormatter (org.apache.axis2.transport.MessageFormatter)8 ContentType (javax.mail.internet.ContentType)7 OMElement (org.apache.axiom.om.OMElement)7 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)6 IncomingMessage (org.apache.axis2.transport.testkit.message.IncomingMessage)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)5 AxisOperation (org.apache.axis2.description.AxisOperation)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 OutputStream (java.io.OutputStream)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 XMPPConnection (org.jivesoftware.smack.XMPPConnection)4 XMPPException (org.jivesoftware.smack.XMPPException)4 Message (org.jivesoftware.smack.packet.Message)4 AMQP (com.rabbitmq.client.AMQP)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3