axis-java-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Chamil Thanthrimudalige <cham...@gmail.com>
Subject [Axis2] Mail Transport patch
Date Thu, 03 Mar 2005 09:23:19 GMT
Hi,

This is a redone version of the code I submitted before. It was based
on the Axis1 mail code. A test case is also included now.

Addition to the normal external jars used in axis2 the following jars
are needed to run the code,
jaf
javamail
common-net

Best Regards,
Chamil Thanthrimudalige.
www.itambalama.com

Index: transport/mail/MailConstants.java
===================================================================
--- transport/mail/MailConstants.java   (revision 0)
+++ transport/mail/MailConstants.java   (revision 0)
@@ -0,0 +1,25 @@
+/*
+ * Created on Jan 28, 2005
+ *
+ * TODO To change the template for this generated file go to Window -
+ * Preferences - Java - Code Style - Code Templates
+ */
+package org.apache.axis.transport.mail;
+
+public class MailConstants {
+    public final static String FROM_ADDRESS = "transport.mail.from";
+
+    public final static String TO_ADDRESS = "transport.mail.to";
+
+    public final static String SUBJECT = "transport.mail.subject";
+
+    public final static String SMTP_HOST = "transport.mail.smtp.host";
+
+    public final static String POP3_HOST = "transport.mail.pop3.host";
+
+    public final static String POP3_USERID = "transport.mail.pop3.userid";
+
+    public final static String POP3_PASSWORD = "transport.mail.pop3.password";
+
+    public final static String HEADER_SOAP_ACTION =
"transport.mail.soapaction";
+}
\ No newline at end of file
Index: transport/mail/MailTransportSender.java
===================================================================
--- transport/mail/MailTransportSender.java     (revision 0)
+++ transport/mail/MailTransportSender.java     (revision 0)
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2001-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may
obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and
limitations under
+ * the License.
+ */
+
+package org.apache.axis.transport.mail;
+
+import java.io.Writer;
+import java.net.Socket;
+
+import org.apache.axis.addressing.EndpointReference;
+import org.apache.axis.context.MessageContext;
+import org.apache.axis.engine.AxisFault;
+import org.apache.axis.transport.AbstractTransportSender;
+
+public class MailTransportSender extends AbstractTransportSender {
+    protected Writer out;
+
+    private Socket socket;
+
+    public MailTransportSender() {
+
+    }
+
+    protected Writer obtainOutputStream(MessageContext msgContext)
+            throws AxisFault {
+        out = (Writer) msgContext.getProperty(MessageContext.TRANSPORT_WRITER);
+        if (out == null) {
+            throw new AxisFault(
+                    "Can not find the suffient information to find end point");
+        } else {
+            return out;
+        }
+
+    }
+
+    protected Writer obtainOutputStream(MessageContext msgContext,
+            EndpointReference epr) throws AxisFault {
+        return obtainOutputStream(msgContext);
+    }
+
+    protected Writer obtainWriter(MessageContext msgContext) throws AxisFault {
+        return obtainOutputStream(msgContext);
+    }
+
+    protected Writer obtainWriter(MessageContext msgContext,
+            EndpointReference epr) throws AxisFault {
+        //TODO this is temporay work around
+        return obtainOutputStream(msgContext);
+    }
+
+    protected void finalizeSending(MessageContext msgContext) throws
AxisFault {
+    }
+
+    protected void finalizeSending(MessageContext msgContext, Writer
writer) throws AxisFault {
+    }
+
+    protected void startSending(MessageContext msgContext) throws AxisFault {
+        try {
+            Writer writer = (Writer) msgContext
+                    .getProperty(MessageContext.TRANSPORT_WRITER);
+            startSending(msgContext, writer);
+        } catch (Exception e) {
+            throw new AxisFault(e.getMessage());
+        }
+    }
+
+    protected void startSending(MessageContext msgContext, Writer
writer) throws AxisFault {
+        try {
+            writer.write("Content-Type: text/plain; charset=us-ascii\n");
+            writer.write("Content-Transfer-Encoding: 7bit\n");
+            writer
+                    .write("Accept: application/soap+xml,
application/dime, multipart/related, text\n");
+            //writer.write("MIME-Version: 1.0\n");
+            writer.write("User-Agent: Axis2 M1\n");
+            writer.write("Cache-Control: no-cache\n");
+            writer.write("Pragma: no-cache\n");
+            writer.write("Subject: Re:"
+                    + msgContext.getProperty(MailConstants.SUBJECT) + "\n\n");
+        } catch (Exception e) {
+            throw new AxisFault(e.getMessage());
+        }
+    }
+
+}
+
Index: transport/mail/MailClient.java
===================================================================
--- transport/mail/MailClient.java      (revision 0)
+++ transport/mail/MailClient.java      (revision 0)
@@ -0,0 +1,103 @@
+package org.apache.axis.transport.mail;
+import java.io.*;
+import java.util.*;
+import javax.mail.*;
+import javax.mail.internet.*;
+
+public class MailClient
+  extends Authenticator
+{
+  public static final int SHOW_MESSAGES = 1;
+  public static final int CLEAR_MESSAGES = 2;
+  public static final int SHOW_AND_CLEAR =
+    SHOW_MESSAGES + CLEAR_MESSAGES;
+
+  protected String from;
+  protected Session session;
+  protected PasswordAuthentication authentication;
+
+  public MailClient(String user, String host)
+  {
+    this(user, host, user, false);
+  }
+
+  public MailClient(String user, String host, String password)
+  {
+    this(user, host, password , false);
+  }
+
+  public MailClient(String user, String host, String password, boolean debug)
+  {
+    from = user + '@' + host;
+    authentication = new PasswordAuthentication(user, password);
+    Properties props = new Properties();
+    props.put("mail.user", user);
+    props.put("mail.host", host);
+    props.put("mail.debug", debug ? "true" : "false");
+    props.put("mail.store.protocol", "pop3");
+    props.put("mail.transport.protocol", "smtp");
+    session = Session.getInstance(props, this);
+  }
+
+  public PasswordAuthentication getPasswordAuthentication()
+  {
+    return authentication;
+  }
+
+  public void sendMessage(
+    String to, String subject, String content, String soapAction)
+      throws MessagingException
+  {
+    System.out.println("SENDING message from " + from + " to " + to);
+    System.out.println();
+    MimeMessage msg = new MimeMessage(session);
+    msg.setHeader("transport.mail.soapaction",soapAction);
+    msg.addRecipients(Message.RecipientType.TO, to);
+    msg.setSubject(subject);
+    msg.setText(content);
+    Transport.send(msg);
+  }
+
+  public int checkInbox(int mode)
+    throws MessagingException, IOException
+  {
+      int numMessages = 0;
+    if (mode == 0) return 0;
+    boolean show = (mode & SHOW_MESSAGES) > 0;
+    boolean clear = (mode & CLEAR_MESSAGES) > 0;
+    String action =
+      (show ? "Show" : "") +
+      (show && clear ? " and " : "") +
+      (clear ? "Clear" : "");
+    System.out.println(action + " INBOX for " + from);
+    Store store = session.getStore();
+    store.connect();
+    Folder root = store.getDefaultFolder();
+    Folder inbox = root.getFolder("inbox");
+    inbox.open(Folder.READ_WRITE);
+    Message[] msgs = inbox.getMessages();
+    numMessages = msgs.length;
+    if (msgs.length == 0 && show)
+    {
+      System.out.println("No messages in inbox");
+    }
+    for (int i = 0; i < msgs.length; i++)
+    {
+      MimeMessage msg = (MimeMessage)msgs[i];
+      if (show)
+      {
+        System.out.println("    From: " + msg.getFrom()[0]);
+        System.out.println(" Subject: " + msg.getSubject());
+        System.out.println(" Content: " + msg.getContent());
+      }
+      if (clear)
+      {
+        msg.setFlag(Flags.Flag.DELETED, true);
+      }
+    }
+    inbox.close(true);
+    store.close();
+    System.out.println();
+    return numMessages;
+  }
+}
Index: transport/mail/MailWorker.java
===================================================================
--- transport/mail/MailWorker.java      (revision 0)
+++ transport/mail/MailWorker.java      (revision 0)
@@ -0,0 +1,268 @@
+/*
+ * Copyright 2001-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may
obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and
limitations under
+ * the License.
+ */
+
+package org.apache.axis.transport.mail;
+
+import java.io.ByteArrayInputStream;
+import java.io.Writer;
+import java.util.Properties;
+
+import javax.mail.Message;
+import javax.mail.Session;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.axis.addressing.AddressingConstants;
+import org.apache.axis.addressing.EndpointReference;
+import org.apache.axis.context.MessageContext;
+import org.apache.axis.engine.AxisEngine;
+import org.apache.axis.engine.AxisFault;
+import org.apache.axis.engine.EngineRegistry;
+import org.apache.axis.om.OMFactory;
+import org.apache.axis.om.SOAPEnvelope;
+import org.apache.axis.om.impl.llom.builder.StAXBuilder;
+import org.apache.axis.om.impl.llom.builder.StAXSOAPModelBuilder;
+import org.apache.axis.Constants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.net.smtp.SMTPClient;
+import org.apache.commons.net.smtp.SMTPReply;
+
+public class MailWorker implements Runnable {
+    protected static Log log = LogFactory.getLog(MailWorker.class.getName());
+
+    private String contentType = "text/xml";
+
+    // Server
+    private SimpleMailListner server;
+
+    private SMTPClient client = null;
+
+    private EngineRegistry reg = null;
+
+    // Current message
+    private MimeMessage mimeMessage;
+
+    //Processed responce CT 08-Feb-2005
+    private MimeMessage outputMimeMessage;
+
+    // Axis specific constants
+    private static String transportName = "mail";
+
+    private Properties prop = new Properties();
+
+    private Session session = Session.getDefaultInstance(prop, null);
+
+    /**
+     * Constructor for MailWorker
+     *
+     * @param server
+     * @param mimeMessage
+     */
+    public MailWorker(SimpleMailListner server, MimeMessage mimeMessage,
+            EngineRegistry reg) {
+        this.server = server;
+        this.mimeMessage = mimeMessage;
+        this.reg = reg;
+    }
+
+    /**
+     * The main workhorse method.
+     */
+    public void run() {
+        // create an Axis server
+        AxisEngine engine = SimpleMailListner.getAxisEngine();
+        MessageContext msgContext = null;
+        // create and initialize a message context
+        try {
+            msgContext = new MessageContext(this.reg, null, null);
+            msgContext.setServerSide(true);
+        } catch (AxisFault af) {
+            log.error("Error occured while creating the message context", af);
+        }
+
+        Message requestMsg = null;
+
+        // buffers for the headers we care about
+        StringBuffer soapAction = new StringBuffer();
+        StringBuffer fileName = new StringBuffer();
+        StringBuffer contentType = new StringBuffer();
+        StringBuffer contentLocation = new StringBuffer();
+
+        Message responseMsg = null;
+
+        // prepare request (do as much as possible while waiting for the
+        // next connection).
+        try {
+            msgContext.setService(null);
+        } catch (Exception e) {
+        }
+        //msgContext.setResponseMessage(null);
+        //msgContext.reset();
+        // msgContext.setTransport(new AxisTransport(transportName)); There is
+        // no way to set the transport. CT 07-Feb-2005.
+
+        responseMsg = null;
+
+            try {
+                // parse all headers into hashtable
+                parseHeaders(mimeMessage, contentType, contentLocation,
+                        soapAction);
+
+                String soapActionString = soapAction.toString();
+                if (soapActionString != null) {
+                    //msgContext.setUseSOAPAction(true); Not present CT
+                    // 07-Feb-2005
+                    msgContext.setProperty(MessageContext.SOAP_ACTION,
+                            soapActionString);
+                }
+
+                System.out
+                        .println("This is the data that is to be
processed  \n "
+                                + mimeMessage.getContent().toString() + "\n");
+
+                ByteArrayInputStream bais = new ByteArrayInputStream(
+                        mimeMessage.getContent().toString().getBytes());
+                XMLStreamReader reader = XMLInputFactory.newInstance()
+                        .createXMLStreamReader(bais);
+                StAXBuilder builder = new StAXSOAPModelBuilder(OMFactory
+                        .newInstance(), reader);
+
+                msgContext.setEnvelope((SOAPEnvelope) builder
+                        .getDocumentElement());
+
+                msgContext.setProperty(MessageContext.TRANSPORT_TYPE,
+                        Constants.TRANSPORT_MAIL);
+
+                //A writer is created and sent to the engine so that the engine
+                // can write straight to the writer
+                String replyTo = ((InternetAddress)
mimeMessage.getReplyTo()[0])
+                        .getAddress();
+                String sendFrom = ((InternetAddress) mimeMessage
+                        .getAllRecipients()[0]).getAddress();
+                String subject = mimeMessage.getSubject();
+                msgContext.setProperty(MailConstants.FROM_ADDRESS, sendFrom);
+                msgContext.setProperty(MailConstants.TO_ADDRESS, replyTo);
+                msgContext.setProperty(MailConstants.SUBJECT, subject);
+                Writer wr = getMailWriter(server.getHost(), msgContext);
+
+                msgContext.setProperty(MessageContext.TRANSPORT_WRITER, wr);
+                msgContext.setTo(new EndpointReference(
+                        AddressingConstants.WSA_TO, replyTo));
+
+                // invoke the Axis engine
+                engine.receive(msgContext);
+
+                sendMessage(wr);
+
+            } catch (Exception e) {
+                e.printStackTrace();
+                AxisFault af;
+                if (e instanceof AxisFault) {
+                    af = (AxisFault) e;
+                    //log.debug(Messages.getMessage("serverFault00"), af);
+                    // CT 07-Feb-2005
+                    log.debug(
+                            "Error occured while trying to process the mail.",
+                            af);
+                } else {
+                    af = AxisFault.makeFault(e);
+                }
+            }
+
+        /*
+         *
+         * This part is ignored for the time being. CT 07-Feb-2005.
+         *
+         * if (msgContext.getProperty(MessageContext.QUIT_REQUESTED)
!= null) { //
+         * why then, quit! try { server.stop(); } catch (Exception e) { } }
+         */
+    }
+
+    private Writer getMailWriter(String smtpHost, MessageContext msgContext)
+            throws Exception {
+        client = new SMTPClient();
+        client.connect(smtpHost);
+
+        // After connection attempt, you should check the reply code to verify
+        // success.
+        int reply = client.getReplyCode();
+        if (!SMTPReply.isPositiveCompletion(reply)) {
+            client.disconnect();
+            AxisFault fault = new AxisFault("SMTP"
+                    + "( SMTP server refused connection )"); //Issue #2 CT
+            // 07-Feb-2005.
+            throw fault;
+        }
+
+        client.login(smtpHost);
+        reply = client.getReplyCode();
+        if (!SMTPReply.isPositiveCompletion(reply)) {
+            client.disconnect();
+            AxisFault fault = new AxisFault("SMTP"
+                    + "( SMTP server refused connection )");
+            throw fault;
+        }
+        client.setSender((String) msgContext
+                .getProperty(MailConstants.FROM_ADDRESS));
+        client.addRecipient((String) msgContext
+                .getProperty(MailConstants.TO_ADDRESS));
+        Writer writer = client.sendMessageData();
+
+        return writer;
+    }
+
+    private void sendMessage(Writer writer) throws Exception {
+        writer.flush();
+        writer.close();
+
+        System.out.print(client.getReplyString());
+        if (!client.completePendingCommand()) {
+            System.out.print(client.getReplyString());
+            AxisFault fault = new AxisFault("SMTP" + "( Failed to
send email )");
+            throw fault;
+        }
+        client.logout();
+        client.disconnect();
+    }
+
+    /**
+     * Read all mime headers, returning the value of Content-Length and
+     * SOAPAction.
+     *
+     * @param mimeMessage
+     *            InputStream to read from
+     * @param contentType
+     *            The content type.
+     * @param contentLocation
+     *            The content location
+     * @param soapAction
+     *            StringBuffer to return the soapAction into
+     */
+    private void parseHeaders(MimeMessage mimeMessage,
+            StringBuffer contentType, StringBuffer contentLocation,
+            StringBuffer soapAction) throws Exception {
+        contentType.append(mimeMessage.getContentType());
+        contentLocation.append(mimeMessage.getContentID());
+        String values[] = mimeMessage
+                .getHeader(MailConstants.HEADER_SOAP_ACTION);
+        if (values != null)
+            soapAction.append(values[0]);
+        System.out.println("Calling soap action " + soapAction);
+    }
+}
\ No newline at end of file
Index: transport/mail/SimpleMailListner.java
===================================================================
--- transport/mail/SimpleMailListner.java       (revision 0)
+++ transport/mail/SimpleMailListner.java       (revision 0)
@@ -0,0 +1,326 @@
+/*
+ * Copyright 2001-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.axis.transport.mail;
+
+import org.apache.axis.deployment.DeploymentEngine;
+import org.apache.axis.engine.AxisEngine;
+import org.apache.axis.engine.EngineRegistry;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.net.pop3.POP3Client;
+import org.apache.commons.net.pop3.POP3MessageInfo;
+
+import javax.mail.Session;
+import javax.mail.internet.MimeMessage;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.Reader;
+import java.util.Properties;
+
+/**
+ * This is a simple implementation of an SMTP/POP3 server for processing SOAP
+ * requests via Apache's xml-axis. This is not intended for production use. Its
+ * intended uses are for demos, debugging, and performance profiling.
+ *
+ * @author Davanum Srinivas <dims@yahoo.com>
+ * @author Rob Jellinghaus (robj@unrealities.com)
+ *
+ * @author Chamil Thanthrimudalige <chamilt@gmail.com>Changes done to make the
+ *         Class work inside Axis 2.
+ */
+
+/*
+ * TODO ISSUES -- 1. Message.getMessage -- All messages are hardcoded in the
+ * code till a replacement or a working verion of this is put into Axis 2. When
+ * internationalization work is done this can be fixed. CT 15-Feb-2005
+ *
+ */
+
+public class SimpleMailListner implements Runnable {
+
+
+    protected static Log log =
LogFactory.getLog(SimpleMailListner.class.getName());
+
+    private String host;
+
+    private int port;
+
+    private String userid;
+
+    private String password;
+
+    private static EngineRegistry er = null;
+
+    public SimpleMailListner(String host, int port, String userid,
String password,
+            String dir) {
+        this.host = host;
+        this.port = port;
+        this.userid = userid;
+        this.password = password;
+        try {
+            DeploymentEngine deploymentEngine = new DeploymentEngine(dir);
+            er = deploymentEngine.start();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        try {
+            System.out
+                    .println("Sleeping for a bit to let the engine start up.");
+            Thread.sleep(9000);
+        } catch (InterruptedException e1) {
+            log.debug(e1.getMessage(), e1);
+        }
+    }
+
+    // Are we doing threads?
+    private static boolean doThreads = true;
+
+    public void setDoThreads(boolean value) {
+        doThreads = value;
+    }
+
+    public boolean getDoThreads() {
+        return doThreads;
+    }
+
+    public String getHost() {
+        return host;
+    }
+
+    // Axis server (shared between instances)
+    // In axis2 AxisEngine gives the functionality of AxisServer in axis 1.
+    private static AxisEngine myAxisEngine = null;
+
+    //This is needed to create the AxisEngine. Have to find out how to get this
+    // wrking in the class -- CT 07-Feb-2005.
+    private static EngineRegistry reg = null;
+
+    protected static synchronized AxisEngine getAxisEngine() {
+        if (myAxisEngine == null) {
+            myAxisEngine = new AxisEngine(er);
+        }
+        return myAxisEngine;
+    }
+
+    // are we stopped?
+    // latch to true if stop() is called
+    private boolean stopped = false;
+
+    /**
+     * Accept requests from a given TCP port and send them through the Axis
+     * engine for processing.
+     */
+    public void run() {
+        // log.info(Message.getMessage("start00",
"SimpleMailListner", host + ":" +
+        // port)); TODO Issue #1 CT 07-Feb-2005.
+        // Accept and process requests from the socket
+        if (!stopped) {
+            System.out
+                    .println("Mail listner is being setup to listen
to the address "
+                            + userid + "@" + host + " On port " + port);
+            log.info("Mail listner is being setup to listen to the address "
+                    + userid + "@" + host + " On port " + port);
+        }
+        while (!stopped) {
+            try {
+                pop3.connect(host, port);
+                pop3.login(userid, password);
+                System.out.println("Checking for messages");
+                log.info("Checking for messages");
+                POP3MessageInfo[] messages = pop3.listMessages();
+                if (messages != null && messages.length > 0) {
+                    System.out.println("Found messages " + messages.length);
+                    log.info("Found messages " + messages.length);
+                    for (int i = 0; i < messages.length; i++) {
+                        Reader reader = pop3
+                                .retrieveMessage(messages[i].number);
+                        if (reader == null) {
+                            continue;
+                        }
+
+                        StringBuffer buffer = new StringBuffer();
+                        BufferedReader bufferedReader = new BufferedReader(
+                                reader);
+                        int ch;
+                        while ((ch = bufferedReader.read()) != -1) {
+                            buffer.append((char) ch);
+                        }
+                        bufferedReader.close();
+                        ByteArrayInputStream bais = new ByteArrayInputStream(
+                                buffer.toString().getBytes());
+                        Properties prop = new Properties();
+                        Session session = Session
+                                .getDefaultInstance(prop, null);
+
+                        MimeMessage mimeMsg = new MimeMessage(session, bais);
+                        pop3.deleteMessage(messages[i].number);
+                        if (mimeMsg != null) {
+                            MailWorker worker = new MailWorker(this, mimeMsg,
+                                    er);
+                            if (doThreads) {
+                                Thread thread = new Thread(worker);
+                                thread.setDaemon(true);
+                                thread.start();
+                            } else {
+                                worker.run();
+                            }
+                        }
+                    }
+                }
+            } catch (java.io.InterruptedIOException iie) {
+                log.debug(
+                        "InterruptedIOException error occured in the
mail listner."
+                                + iie.getMessage(), iie);
+                System.out
+                        .println("InterruptedIOException error
occured in the mail listner."
+                                + iie.getMessage());
+            } catch (Exception e) {
+                //log.debug(Messages.getMessage("exception00"), e); TODO Issue
+                // #1 CT 07-Feb-2005.
+                log.debug("An error occured when running the mail listner."
+                        + e.getMessage(), e);
+                System.out
+                        .println("An error occured when running the
mail listner."
+                                + e.getMessage());
+                break;
+            }
+            try {
+                pop3.logout();
+                pop3.disconnect();
+                Thread.sleep(3000);
+            } catch (Exception e) {
+                //log.error(Messages.getMessage("exception00"), e); TODO Issue
+                // #1 CT 07-Feb-2005.
+                log.debug(
+                        "An error occured when trying to disconnect
from the Server."
+                                + e.getMessage(), e);
+                System.out
+                        .println("An error occured when trying to
disconnect from the Server."
+                                + e.getMessage());
+            }
+        }
+
+        log.info("Mail listner has been stoped.");
+        System.out.println("Mail listner has been stoped.");
+        //log.info(Messages.getMessage("quit00",
"SimpleMailListner")); TODO Issue #1
+        // CT 07-Feb-2005.
+
+    }
+
+    /**
+     * POP3 connection
+     */
+    private POP3Client pop3;
+
+    /**
+     * Obtain the serverSocket that that SimpleMailListner is listening on.
+     */
+    public POP3Client getPOP3() {
+        return pop3;
+    }
+
+    /**
+     * Set the serverSocket this server should listen on. (note : changing this
+     * will not affect a running server, but if you stop() and then start() the
+     * server, the new socket will be used).
+     */
+    public void setPOP3(POP3Client pop3) {
+        this.pop3 = pop3;
+    }
+
+    //CT 03-Feb-2005 I think it should be POP instead of HTTP
+    /**
+     * Start this server.
+     *
+     * Spawns a worker thread to listen for HTTP requests.
+     *
+     * @param daemon
+     *            a boolean indicating if the thread should be a daemon.
+     */
+    public void start(boolean daemon) throws Exception {
+        if (doThreads) {
+            Thread thread = new Thread(this);
+            thread.setDaemon(daemon);
+            thread.start();
+        } else {
+            run();
+        }
+    }
+
+    /**
+     * Start this server as a NON-daemon.
+     */
+    public void start() throws Exception {
+        start(false);
+    }
+
+    /**
+     * Stop this server.
+     *
+     * This will interrupt any pending accept().
+     */
+    public void stop() throws Exception {
+        /*
+         * Close the server socket cleanly, but avoid fresh accepts while the
+         * socket is closing.
+         */
+        stopped = true;
+        //log.info(Messages.getMessage("quit00",
"SimpleMailListner")); TODO Issue #1
+        // CT 07-Feb-2005.
+        log.info("Quiting the mail listner");
+    }
+
+    /**
+     * Server process.
+     */
+    public static void main(String args[]) {
+        boolean optDoThreads = true;
+        String optHostName = "localhost";
+        boolean optUseCustomPort = false;
+        int optCustomPortToUse = 0;
+        String optDir = "/home/chamil/temp";
+        String optUserName = "server";
+        String optPassword = "server";
+        System.out.println("Starting the mail listner");
+        // Options object is not used for now. Hard coded values will be used.
+        // TODO have to meke this a bit more generic. CT 07-Feb-2005.
+        //Options opts = null;
+
+        /*
+         * try { opts = new Options(args); } catch (MalformedURLException e) {
+         * log.error(Messages.getMessage("malformedURLException00"),
e); return; }
+         */
+        try {
+            doThreads = optDoThreads; //(opts.isFlagSet('t') > 0);
+            String host = optHostName; //opts.getHost();
+            int port = ((optUseCustomPort) ? optCustomPortToUse : 110);
+            POP3Client pop3 = new POP3Client();
+            SimpleMailListner sas = new SimpleMailListner(host, port,
optUserName,
+                    optPassword, optDir);
+            sas.setPOP3(pop3);
+            sas.start();
+        } catch (Exception e) {
+            // log.error(Messages.getMessage("exception00"), e); TODO Issue #1
+            // CT 07-Feb-2005.
+            log
+                    .error("An error occured in the main method of
SimpleMailListner. TODO Detailed error message needs to be inserted
here.");
+            return;
+        }
+
+    }
+}
\ No newline at end of file
Index: transport/mail/SimpleMailListnerTest.java
===================================================================
--- transport/mail/SimpleMailListnerTest.java   (revision 0)
+++ transport/mail/SimpleMailListnerTest.java   (revision 0)
@@ -0,0 +1,86 @@
+/*
+ * Created on Mar 3, 2005
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+package org.apache.axis.transport.mail;
+
+import org.apache.axis.AbstractTestCase;
+import org.apache.axis.engine.AxisFault;
+import org.apache.axis.transport.mail.MailConstants;
+import org.apache.commons.net.pop3.POP3Client;
+
+/**
+ * @author chamil
+ *
+ * TODO To change the template for this generated type comment go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+public class SimpleMailListnerTest extends AbstractTestCase {
+    private SimpleMailListner sas;
+    public SimpleMailListnerTest(String testName) {
+        super(testName);
+    }
+
+    public void setUp(){
+        Thread thread = new Thread(new Runnable() {
+            public void run() {
+                boolean optDoThreads = true;
+                String optHostName = "localhost";
+                boolean optUseCustomPort = false;
+                int optCustomPortToUse = 0;
+                String optDir = "/home/chamil/temp";
+                String optUserName = "server";
+                String optPassword = "server";
+                System.out.println("Starting the mail listner");
+                try {
+                    String host = optHostName;
+                    int port = ((optUseCustomPort) ? optCustomPortToUse : 110);
+                    POP3Client pop3 = new POP3Client();
+                    sas = new SimpleMailListner(host, port, optUserName,
+                            optPassword, optDir);
+                    sas.setDoThreads(optDoThreads);
+                    sas.setPOP3(pop3);
+                    sas.start();
+                } catch (Exception e) {
+                    System.out.println("An error occured in the main
method of SimpleMailListner. TODO Detailed error message needs to be
inserted here.");
+                    return;
+                }
+
+
+            }
+        });
+        thread.start();
+
+    }
+
+    public void testSendViaMailAndRecieve() throws Exception {
+               // CREATE CLIENT INSTANCE MailClient(String user,
String host, String password)
+               MailClient mailclient = new MailClient("client",
"localhost", "client");
+
+               String fileContents = "<soapenv:Envelope
xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">  
<soapenv:Header></soapenv:Header>    <soapenv:Body>         
<samples:echo xmlns:samples=\"http://apache.ws.apache.org/samples\">  
                 <samples:param1
xmlns:arrays=\"http://axis.apache.org/encoding/Arrays\">              
              <arrays:item>Hello testing1</arrays:item>          
<arrays:item>Hello testing2</arrays:item>                             
  <arrays:item>Hello testing3</arrays:item>                          
<arrays:item>Hello testing4</arrays:item>                             
  <arrays:item>Hello testing5</arrays:item>                      
</samples:param1>            </samples:echo>
</soapenv:Body></soapenv:Envelope>";
+               String soapService = "sample1";
+
+               // SEND A MESSAGE TO THE SERVER
+               mailclient.sendMessage(
+                     "server@localhost",
+                     "Testing SOAP with service - " + soapService,
+                     fileContents, soapService);
+
+               int count =0;
+               boolean success = false;
+
+               while (count<10 && !success) {
+               Thread.sleep(10000);
+               success = (mailclient.checkInbox(3)>0);
+               }
+
+    }
+
+    public  void tearDown() throws Exception{
+        sas.stop();
+    }
+
+}
+
Index: transport/TransportSenderLocator.java
===================================================================
--- transport/TransportSenderLocator.java       (revision 156023)
+++ transport/TransportSenderLocator.java       (working copy)
@@ -19,6 +19,7 @@
 import org.apache.axis.context.MessageContext;
 import org.apache.axis.engine.AxisFault;
 import org.apache.axis.transport.http.HTTPTransportSender;
+import org.apache.axis.transport.mail.MailTransportSender;

 /**
  * Class TransportSenderLocator
@@ -37,7 +38,13 @@
                 (String) msgContext.getProperty(MessageContext.TRANSPORT_TYPE);
         if (Constants.TRANSPORT_HTTP.equals(type)) {
             return new HTTPTransportSender();
+        } else {
+            if (Constants.TRANSPORT_MAIL.equals(type)) {
+                MailTransportSender mts = new MailTransportSender();
+                return mts;
+            }
         }
+
         throw new AxisFault("No transport found");
     }
 }

Mime
View raw message