Invoking a Service Using a Mail Transport

This document basically explains how to invoke a service through Mail transports. Content for this document has been listed as follows,

Send your feedback or questions to: axis-dev@ws.apache.org. Prefix subject with [Axis2]. To subscribe to mailing list see here.

Content

Prologue

Most of Web services that we interact with are synchronous and request-response in nature. However, we see that the synchronous request-response type of interaction is only a part of the messaging scenarios we encounter in real life. Asynchronous messaging is very important in constructing loosely coupled systems. Take for instance a chain of stores, at the end of the day all the stores all over can send a mail to the central system telling it what that days business activity was and in the morning when the store opens there will be a reply to that mail with new instructions and updates. It is a lot like the way the old business worked but with a modern touch. Similarly Axis2 mail transport can be used to implement asynchronous messaging through mail.

Introduction

To start you will first need to go through the Mail Transport Configuration document. It will provide the user with the first hand experience in setting up the mail transports to co-exists with Axis2.

Broadly speaking there are 3 ways of calling a service through mail.

1. Using the simple mail server included in Axis2(not recommended in production).
2. Using a generic mail server.
3. Using mailets.

Options 1 and 2 are fairly simple and easy to implement, whereas option 3 is somewhat harder.The mailet scenario however does provide a more robust and useful solution in a production environment.

It is very easy to start learning the workings of mail transports with the aid of Simple Mail Server that provides with Axis2. Once you get the hang of the Axis2 related issues then you can move on to tackle the mail beast. Please do note that the Simple Mail Server that provides with Axis2 is not graded for production use.

1. Using Simple Mail Server Included in Axis2

The SMTP/POP server that we have included has the ability to function as a standalone SMTP/POP server and also has the ability to work as a mailet. All this is done through a small filter that keeps watch for certain pre-configured email addresses. These pre-configured email addresses can be changed by doing a simple edit of the filter class org.apache.axis2.transport.mail.server.Sorter.

Now that we have the environment set up, let us start pumping out some code to get the mail functionality off the ground. First we'll have a look at it from the mail server side.

        // Start the mail server using the default configurations.
        ConfigurationContext configContext = UtilsMailServer.start();

        // Start the default mail listener. It will starting poling for mail
        // using the configuration from the XML file.
        SimpleMailListener ml = new SimpleMailListener();
        ml.init(configContext,
                configContext.getAxisConfiguration().getTransportIn(
                        new QName(Constants.TRANSPORT_MAIL)));
        ml.start();

        private QName serviceName = new QName("EchoXMLService");
        private QName operationName = new QName("echoOMElement");
    
        // Setup a service that will echo what we send to the server.
        AxisService service = Utils.createSimpleService(serviceName, Echo.class
                .getName(), operationName);
        serverConfigContext.getAxisConfiguration().addService(service);

This code sets up your Axis2 server working through mail, with a single service. If you need to have a look under the hood check out the MailServer and UtilsMailServer classes.

Moving onto the client side have a look at the code listing below. It will call the axisService that was setup on the previous code listing.

        ConfigurationContext configContext = UtilsMailServer
                .createClientConfigurationContext();
        AxisService service = new AxisService(serviceName.getLocalPart());
        AxisOperation axisOperation = new OutInAxisOperation();
        axisOperation.setName(operationName);
        axisOperation.setMessageReceiver(new MessageReceiver() {
            public void receive(MessageContext messageCtx) {
                envelope = messageCtx.getEnvelope();
            }
        });
        service.addOperation(axisOperation);
        configContext.getAxisConfiguration().addService(service);
        ServiceContext serviceContext = new ServiceGroupContext(configContext,
        		(AxisServiceGroup) service.getParent()).getServiceContext(service);

        Options options = new Options();
        options.setTo(targetEPR);
        options.setAction(operationName.getLocalPart());
        options.setTransportInProtocol(Constants.TRANSPORT_MAIL);
        options.setUseSeparateListener(true);

        Callback callback = new Callback() {
            public void onComplete(AsyncResult result) {
                try {
                    result.getResponseEnvelope().serializeAndConsume(
                            XMLOutputFactory.newInstance()
                                    .createXMLStreamWriter(System.out));
                } catch (XMLStreamException e) {
                    onError(e);
                } finally {
                    finish = true;
                }
            }

            public void onError(Exception e) {
                log.info(e.getMessage());
                finish = true;
            }
        };

        ServiceClient sender = new ServiceClient(configContext, service);
        sender.setOptions(options);
        //options.setTo(targetEPR);
        sender.sendReceiveNonBlocking(operationName, createEnvelope(), callback);

        int index = 0;
        while (!finish) {
            Thread.sleep(1000);
            index++;
            if (index > 10) {
                throw new AxisFault(
                        "Server was shutdown as the async response is taking too long to complete.");
            }
        }

    }

This will call the service that was setup on the server and will poll the mail server till the response is received.Please do note that serviceName and operationName need to be QNames.

2. Using a Generic Mail Server

First you need two email accounts that works with POP/SMTP. One will act as a server and the other will act as the client. For the time being we will use server@somewhere.org and client@somewhere.org as the server and the client email addresses. Now that we have the email addresses you will have to set up the client and the server with Mail Transport configuration document.

When calling the generic mail server the client side code will remain the same and there will be some modification to the server-side code.

        // Create a configuration context. This will also load the details about the mail
        // address to listen to from the configuration file.
        File file = new File(MAIL_TRANSPORT_SERVER_ENABLED_REPO_PATH);
        ConfigurationContextFactory builder = new ConfigurationContextFactory();
        ConfigurationContext configContext = configContextbuilder
                .buildConfigurationContext(file.getAbsolutePath());

        // Start the default mail listener. It will starting poling for mail
        // using the configuration from the XML file.
        SimpleMailListener ml = new SimpleMailListener();
        ml.init(configContext,
                configContext.getAxisConfiguration().getTransportIn(
                        new QName(Constants.TRANSPORT_MAIL)));
        ml.start();

        private QName serviceName = new QName("EchoXMLService");
        private QName operationName = new QName("echoOMElement");
    
        // Setup a service that will echo what we send to the server.
        AxisService service = Utils.createSimpleService(serviceName, Echo.class
                .getName(), operationName);
        serverConfigContext.getAxisConfiguration().addService(service);

Note that a separate ConfigurationContext needs to be created and used.