Skip to main content

Send e-mail with attachment through OSB

Oracle Service Bus (OSB) contains a good collection of adapter to integrate with any legacy application, including ftp, email, MQ, tuxedo. However e-mail still recognize as a stable protocol to integrate with any application asynchronously. Send e-mail with attachment is a common task of any business process. Inbound e-mail adapter which, integrated with OSB support attachment but outbound adapter doesn't. This post is all about sending attachment though JavaCallout action.
There are two ways to handle attachment in OSB:
1) Use JavaCallout action to pass the binary data for further manipulation. It means write down a small java library which will get the attachment and send the e-mail.
2) Use integrated outbound e-mail adapter to send attachment, here you have to add a custom variable named attachment and assign the binary data to the body of the attachment variable.
First option is very common and easy to implement through javax.mail api, however a much more developer manage to send the binary attachment by second option but i couldn't figure out it yet.
Here, we are going to describe all the necessary step to implement the first option describe above.
First of all we will develop a small java library to send the mail. Java class will be contain one static method with all the necessary parameter to send mail, including smtp server address and the receptions address, moreover it will have one byte array parameter (byte[]) to get the binary data. The java class is as follows:
package com.blu.nsi.transport;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.DataHandler;
import java.io.*;

import javax.mail.Multipart;

public class MailClient {

/**
* public method that will invoked by business service to send mail
* */
public static void  sendMail(String smtpServer,
String from,
String to,
String subject,
String body,
String fileName,
byte[] zipFile) throws Exception
{
java.util.Properties props = System.getProperties();

props.setProperty("mail.smtp.host", smtpServer);
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
message.setFrom( new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setSentDate(new java.util.Date());
message.setHeader("X-Mailer", "MailClient");

//Set content to the mime body
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(body);
MimeBodyPart messageAttach = new MimeBodyPart();
String fName = fileName.substring(fileName.lastIndexOf("\\")+1);

MailDataSource dataSource = new MailClient.MailDataSource();
dataSource.setContentType("application/x-zip-compressed");
dataSource.setData(zipFile);
dataSource.setName(fName);

messageAttach.setDataHandler(new DataHandler(dataSource));
messageAttach.setFileName(fName);
messageAttach.addHeader("charset", "windows-1251");

// add multipart
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(messagePart);
multiPart.addBodyPart(messageAttach);
// add to message
message.setContent(multiPart);

Transport.send(message);

}
static class MailDataSource implements javax.activation.DataSource{
private byte[] data;
private String contentType;
private String name;


public void setContentType(String contentType) {
this.contentType = contentType;
}

public void setData(byte[] data) {
this.data = data;
}

public void setName(String name) {
this.name = name;
}

public String getContentType() {

return contentType;
}

public InputStream getInputStream() throws IOException {

return new java.io.ByteArrayInputStream(data);
}

public String getName() {

return name;
}

public OutputStream getOutputStream() throws IOException {

return null;
}

}
}

Now we are ready to develop project in OSB to send the attachment. First we will create a wsdl to send the soap message with attachment to proxy service. The wsdl file contain only one port and binding will be the style with rpc/literal. Only rpc style could define multipart message. The wsdl file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.com.blu/SOAPwithAttachment/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
name="SOAPwithAttachment"
targetNamespace="http://www.com.blu/SOAPwithAttachment/">
<wsdl:types>
<xsd:schema targetNamespace="http://www.com.blu/SOAPwithAttachment/">
<xsd:complexType name="SubmitAttachmentResponseType">
<xsd:sequence>
<xsd:element name="response" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="SubmitAttachmentRequestType">
<xsd:sequence>
<xsd:element name="smtpserver" type="xsd:string" />
<xsd:element name="to" type="xsd:string" />
<xsd:element name="from" type="xsd:string" />
<xsd:element name="subject" type="xsd:string" />
<xsd:element name="body" type="xsd:string" />
<xsd:element name="fileName" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="submitAttachmentRequest" type="tns:SubmitAttachmentRequestType" />
<xsd:element name="zipFile" type="xsd:base64Binary" />
</xsd:schema>
</wsdl:types>

<wsdl:message name="submitAttachmentRequest">
<wsdl:part name="submitAttachment" type="tns:SubmitAttachmentRequestType"  />
<wsdl:part name="zipFile" type="xsd:base64Binary" />
</wsdl:message>

<wsdl:message name="submitAttachmentResponse">
<wsdl:part name="submitAttachmentResponse" type="tns:SubmitAttachmentResponseType" />
</wsdl:message>
<wsdl:portType name="SOAPwithAttachmentPort">
<wsdl:operation name="submitAttachment">
<wsdl:input message="tns:submitAttachmentRequest" />
<wsdl:output message="tns:submitAttachmentResponse" />
</wsdl:operation>
</wsdl:portType>

<wsdl:binding name="SOAPwithAttachmentSOAP"
type="tns:SOAPwithAttachmentPort">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="submitAttachment">
<soap:operation
soapAction="http://www.com.blu/SOAPwithAttachment/submitAttachment" />
<wsdl:input>
<mime:multipartRelated>
<mime:part>
<soap:body parts="submitAttachment" use="literal" namespace="http://www.com.blu/SOAPwithAttachment/"/>
</mime:part>
<mime:part>
<mime:content part="zipFile" type="application/zip"/>
</mime:part>
</mime:multipartRelated>
</wsdl:input>
<wsdl:output>
<soap:body parts="submitAttachmentResponse" use="literal" namespace="http://www.com.blu/SOAPwithAttachment/"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>

<wsdl:service name="SOAPwithAttachment">
<wsdl:port binding="tns:SOAPwithAttachmentSOAP"
name="SOAPwithAttachmentSOAP">
<soap:address location="http://localhost:7001/SOAPwithAttachment_WS/SOAPwithAttachment" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>


Now we will create a proxy service based on this wsdl file and import the jar file in the project.
Add one pipeline node on the proxy and add one stage node on the request pipeline.
In the stage node add one assign action and set the following xpath expression
$attachments/ctx:attachment/ctx:body/ctx:binary-content
and set the name for variable for example attachData, where $attachments is the variable of the attachment. binary-content element hold the reference of the binary data to hash table. binary-content element looks like this:
<binary-content ref="ccid:2321f-fa-edf21"/>
XML and text attachments are represented as XML and text, respectively, and can be manipulated directly with XQuery or XSLT. Binary attachment data can be manipulated only by passing the binary data to a Javacallout for processing. Remember you should send the content of the binary-content element not its reference id.
Add a JavaCallout action in the stage node and assaign it to the jar file. Fill up all the expression from the $body variable as follows:
$body/soap:submitAttachment/submitAttachment/subject/text()
also set the variable named attachData to byte[] parameter of the java class method.

Add one stage node on the response pipeline and add one replace and delete action. In the response pipleline we will make up the following response:
<ns0:submitAttachmentResponse xmlns:ns0="http://www.alsb.com/SOAPwithAttachment/">
<submitAttachmentResponse>
<response>OK</response>
</submitAttachmentResponse>
</ns0:submitAttachmentResponse>

In the replace action set the variable to the body element and xpath as ./*, also set the above xml fragment. It means we will replace the content of body element with this fragment of xml.
Now in the properties of the delete action, set the attachment variable to delete.

Here, you have just complete the tutorial and are ready to deploy it on the server. After that you have to generate stab or proxy java class from the proxy service wsdl and test the service.
Resources:
See additional information about OSB message context model.

Comments

Popular posts from this blog

8 things every developer should know about the Apache Ignite caching

Any technology, no matter how advanced it is, will not be able to solve your problems if you implement it improperly. Caching, precisely when it comes to the use of a distributed caching, can only accelerate your application with the proper use and configurations of it. From this point of view, Apache Ignite is no different, and there are a few steps to consider before using it in the production environment. In this article, we describe various technics that can help you to plan and adequately use of Apache Ignite as cutting-edge caching technology. Do proper capacity planning before using Ignite cluster. Do paperwork for understanding the size of the cache, number of CPUs or how many JVMs will be required. Let’s assume that you are using Hibernate as an ORM in 10 application servers and wish to use Ignite as an L2 cache. Calculate the total memory usages and the number of Ignite nodes you have to need for maintaining your SLA. An incorrect number of the Ignite nodes can become a b...

Analyse with ANT - a sonar way

After the Javaone conference in Moscow, i have found some free hours to play with Sonar . Here is a quick steps to start analyzing with ANT projects. Sonar provides Analyze with ANT document to play around with ANT, i have just modify some parts. Here is it. 1) Download the Sonar Ant Task and put it in your ${ANT_HOME}/lib directory 2) Modify your ANT build.xml as follows: <?xml version = '1.0' encoding = 'windows-1251'?> <project name="abc" default="build" basedir="."> <!-- Define the Sonar task if this hasn't been done in a common script --> <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml"> <classpath path="E:\java\ant\1.8\apache-ant-1.8.0\lib" /> </taskdef> <!-- Out-of-the-box those parameters are optional --> <property name="sonar.jdbc.url" value="jdbc:oracle:thin:@xyz/sirius.xyz" /> <property na...

Writing weblogic logs to database table

By default, oracle weblogic server logging service uses an implementation, based on the Java Logging APIs by using the LogMBean.isLog4jLoggingEnabled attribute. With a few effort you can use log4j with weblogic logging service. In the Administration Console, you can specify Log4j or keep the default Java Logging implementation. In this blog i will describe how to configure log4j with weblogic logging service and writes all the logs messages to database table. Most of all cases it's sufficient to writes log on files, however it's better to get all the logs on table to query on it. In our case we have 3 different web logic servers in our project and our consumer need to get all the logs in one central place to diagnose if something goes wrong. First of all we will create a simple table on our oracle database schema and next configure all other parts. Here we go: 1) CREATE TABLE LOGS (USER_ID VARCHAR2(20), DOMAIN varchar2(50), DATED DATE NOT NULL, LOGGER VARCHAR2(500) NOT...