Search in sources :

Example 6 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter in project wso2-axis2-transports by wso2.

the class SMSManager method init.

/**
 * Initialize the SMS Maneger with TransportOutDiscription
 * if the Maneger is already inited  it will set the Transport Outdetails
 * in the Current Implimentation Manage
 * @param transportOutDescription
 * @param configurationContext
 */
public void init(TransportOutDescription transportOutDescription, ConfigurationContext configurationContext) throws AxisFault {
    if (!inited) {
        basicInit(transportOutDescription, configurationContext);
    }
    Parameter formatterClass = transportOutDescription.getParameter(SMSTransportConstents.FORMATTER_CLASS);
    if (formatterClass == null) {
        messageFormatter = new DefaultSMSMessageFormatterImpl();
    } else {
        try {
            messageFormatter = (SMSMessageFormatter) Class.forName((String) formatterClass.getValue()).newInstance();
        } catch (Exception e) {
            throw new AxisFault("Error while instentiating the Class: " + formatterClass.getValue(), e);
        }
    }
    currentImplimentation.setTransportOutDetails(transportOutDescription);
    Parameter invertS_n_D = transportOutDescription.getParameter(SMSTransportConstents.INVERT_SOURCE_AND_DESTINATION);
    if (invertS_n_D != null) {
        String val = (String) invertS_n_D.getValue();
        if ("false".equals(val)) {
            invertSourceAndDestination = false;
        } else if ("true".equals(val)) {
            invertSourceAndDestination = true;
        } else {
            log.warn("Invalid parameter value set to the parameter invert_source_and_destination," + "setting the default value :true ");
            invertSourceAndDestination = true;
        }
    }
    inited = true;
}
Also used : AxisFault(org.apache.axis2.AxisFault) Parameter(org.apache.axis2.description.Parameter)

Example 7 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter in project wso2-axis2-transports by wso2.

the class TCPTransportSender method writeMessageOut.

/**
 * Writing the message to the output stream of the TCP socket after applying correct message formatter
 * This method is synchronized because there will be issue when formatter write to same output stream which causes
 * to mixed messages
 *
 * @param msgContext the message context
 * @param outputStream the socket output stream
 * @throws AxisFault if error occurred
 * @throws IOException if IO exception occurred
 */
private synchronized void writeMessageOut(MessageContext msgContext, OutputStream outputStream, String delimiter, String delimiterType) throws AxisFault, IOException {
    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    messageFormatter.writeTo(msgContext, format, outputStream, true);
    if (delimiter != null && !delimiter.isEmpty()) {
        if (TCPConstants.BYTE_DELIMITER_TYPE.equalsIgnoreCase(delimiterType)) {
            outputStream.write((char) Integer.parseInt(delimiter.split("0x")[1], 16));
        } else {
            outputStream.write(delimiter.getBytes());
        }
    }
    outputStream.flush();
}
Also used : MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 8 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter 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 9 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter 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

OMOutputFormat (org.apache.axiom.om.OMOutputFormat)8 MessageFormatter (org.apache.axis2.transport.MessageFormatter)8 AxisFault (org.apache.axis2.AxisFault)7 IOException (java.io.IOException)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)5 OutputStream (java.io.OutputStream)3 StringWriter (java.io.StringWriter)3 WriterOutputStream (org.apache.commons.io.output.WriterOutputStream)3 AMQP (com.rabbitmq.client.AMQP)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 DataHandler (javax.activation.DataHandler)2 AxisRabbitMQException (org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 DatagramPacket (java.net.DatagramPacket)1 DatagramSocket (java.net.DatagramSocket)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 SystemException (javax.transaction.SystemException)1 Transaction (javax.transaction.Transaction)1 TransactionManager (javax.transaction.TransactionManager)1 OMElement (org.apache.axiom.om.OMElement)1