View Javadoc

1   /*$Id: SendMailApplicationDescription.java,v 1.6 2004/11/27 13:20:02 pah Exp $
2    * Created on 11-Aug-2004
3    *
4    * Copyright (C) AstroGrid. All rights reserved.
5    *
6    * This software is published under the terms of the AstroGrid 
7    * Software License version 1.2, a copy of which has been included 
8    * with this distribution in the LICENSE.txt file.  
9    *
10  **/
11  package org.astrogrid.applications.apps;
12  
13  import org.astrogrid.applications.AbstractApplication;
14  import org.astrogrid.applications.Application;
15  import org.astrogrid.applications.CeaException;
16  import org.astrogrid.applications.DefaultIDs;
17  import org.astrogrid.applications.Status;
18  import org.astrogrid.applications.beans.v1.parameters.types.ParameterTypes;
19  import org.astrogrid.applications.description.ApplicationInterface;
20  import org.astrogrid.applications.description.base.AbstractApplicationDescription;
21  import org.astrogrid.applications.description.base.ApplicationDescriptionEnvironment;
22  import org.astrogrid.applications.description.base.BaseApplicationInterface;
23  import org.astrogrid.applications.description.base.BaseParameterDescription;
24  import org.astrogrid.applications.description.exception.ParameterDescriptionNotFoundException;
25  import org.astrogrid.applications.parameter.ParameterAdapter;
26  import org.astrogrid.applications.parameter.protocol.ProtocolLibrary;
27  import org.astrogrid.community.User;
28  import org.astrogrid.component.descriptor.ComponentDescriptor;
29  import org.astrogrid.workflow.beans.v1.Tool;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  
34  import java.util.HashMap;
35  import java.util.Iterator;
36  import java.util.Map;
37  
38  import javax.mail.Message;
39  import javax.mail.MessagingException;
40  import javax.mail.Session;
41  import javax.mail.Transport;
42  import javax.mail.internet.InternetAddress;
43  import javax.mail.internet.MimeMessage;
44  import javax.naming.Context;
45  import javax.naming.InitialContext;
46  import javax.naming.NamingException;
47  
48  import junit.framework.Test;
49  import junit.framework.TestCase;
50  import junit.framework.TestSuite;
51  
52  /*** Implementation of a send-mail application
53   * <P>
54   * Requires a javax.mail.Session object to be placed in jndi under <tt>java:comp/env/mail/session</tt>
55   * @see http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-resources-howto.html for details of how to configure mail session object for Tomcat
56   * @todo add support ofr optional parameters, advanced emailing features - attachements, etc. maybe use jakarta-commons-email to make this easier.
57   * @author Noel Winstanley nw@jb.man.ac.uk 11-Aug-2004
58   *
59   */
60  public class SendMailApplicationDescription extends AbstractApplicationDescription implements ComponentDescriptor {
61      private static final String SIMPLE = "simple";
62      private static final String ADVANCED = "advanced";
63      private static final String ATTACHMENT = "attachment";
64      private static final String CC = "cc";
65      private static final String TO = "to";
66      private static final String REPLYTO = "replyTo";
67      private static final String SUBJECT = "subject";
68      private static final String MESSAGE = "message";
69      /*** Construct a new SendMailApp
70       * @param env
71       */
72      public SendMailApplicationDescription(ApplicationDescriptionEnvironment env ) {
73          super(env);
74          this.setMetaData();
75      }
76      
77      /*** set up metadata for this instance */
78      private final void setMetaData() {
79          StringBuffer thename = new StringBuffer(env.getAuthIDResolver().getAuthorityID());
80          thename.append("/sendmail");
81          setName(thename.toString());
82          BaseParameterDescription to = new BaseParameterDescription();
83          to.setName(TO);
84          to.setDisplayName("To-Address");
85          to.setDisplayDescription("Email address to send message to");
86          to.setType(ParameterTypes.TEXT);
87          this.addParameterDescription(to);
88          /* later..
89          BaseParameterDescription cc = new BaseParameterDescription();
90          cc.setName(CC);
91          cc.setDisplayName("CC-Address");
92          cc.setDisplayDescription("Email address to CC message to");
93          cc.setType(ParameterTypes.TEXT);
94          this.addParameterDescription(cc);
95          */
96          /* later
97          BaseParameterDescription replyTo = new BaseParameterDescription();
98          replyTo.setName( REPLYTO );
99          replyTo.setDisplayName("ReplyTo-Address");
100         replyTo.setDisplayDescription("Email address to reply to");
101         replyTo.setType(ParameterTypes.TEXT);
102         this.addParameterDescription(replyTo);             
103         */
104         BaseParameterDescription message = new BaseParameterDescription();
105         message.setName( MESSAGE);
106         message.setDisplayName("Your Message");
107         message.setDisplayDescription("The message to send");
108         message.setType(ParameterTypes.TEXT);
109         this.addParameterDescription(message);
110         
111         BaseParameterDescription subject = new BaseParameterDescription();
112         subject.setName(SUBJECT);
113         subject.setDisplayName("Subject of the email");
114         subject.setDisplayDescription("text to use as the subject of this email");
115         subject.setDefaultValue("Message from JES");
116         subject.setType(ParameterTypes.TEXT);
117         this.addParameterDescription(subject);
118         /* later
119         BaseParameterDescription attachment = new BaseParameterDescription();
120         attachment.setName(ATTACHMENT);
121         attachment.setDisplayName("Message Attachment");
122         attachment.setDisplayDescription("Data to attach to message");
123         attachment.setType(ParameterTypes.BINARY);
124         this.addParameterDescription(attachment);
125         */
126 
127         BaseApplicationInterface simple = new BaseApplicationInterface(SIMPLE,this);
128         try {
129             simple.addInputParameter(to.getName());
130             simple.addInputParameter(subject.getName());
131             simple.addInputParameter(message.getName());
132         } catch (ParameterDescriptionNotFoundException e) {
133             logger.fatal("Programming error",e);// really shouldn't happen.
134             throw new RuntimeException("Programming error",e);
135         }
136         this.addInterface(simple);
137         /* maybe add later - could do with having optioinal parameters
138         BaseApplicationInterface full = new BaseApplicationInterface(ADVANCED,this);
139         try {
140         full.addInputParameter(to.getName());
141         full.addInputParameter(cc.getName());
142         full.addInputParameter(replyTo.getName());
143         full.addInputParameter(subject.getName());
144         full.addInputParameter(message.getName());
145         full.addInputParameter(attachment.getName());        
146         } catch (ParameterDescriptionNotFoundException e) {
147             logger.fatal("Programming error",e);// really shouldn't happen.
148             throw new RuntimeException("Programming error",e);
149         }        
150         this.addInterface(full);
151         */
152     }
153 
154     /***
155      * Commons Logger for this class
156      */
157     private static final Log logger = LogFactory.getLog(SendMailApplicationDescription.class);
158 
159 
160 
161     /***
162      * @see org.astrogrid.component.descriptor.ComponentDescriptor#getDescription()
163      */
164     public String getDescription() {
165         return "Email application\n" + this.toString();
166     }
167 
168     /*** installation test verifies mailer session object is present in jndi.
169      * @see org.astrogrid.component.descriptor.ComponentDescriptor#getInstallationTest()
170      */
171     public Test getInstallationTest() {        
172         return new TestSuite(InstallationTest.class);
173     }
174     
175     public static class InstallationTest extends TestCase {
176         public void testJNDI() throws Exception {
177             assertNotNull(SendMailApplication.getSessionFromContext());
178         }
179     }
180 
181     /***
182      * @see org.astrogrid.applications.description.ApplicationDescription#initializeApplication(java.lang.String, org.astrogrid.community.User, org.astrogrid.workflow.beans.v1.Tool)
183      */
184     public Application initializeApplication(String callerAssignedID, User user, Tool tool) throws Exception {
185         String newID = env.getIdGen().getNewID();
186         final DefaultIDs ids = new DefaultIDs(callerAssignedID,newID,user);
187         ApplicationInterface iface = this.getInterface(tool.getInterface());
188         return new SendMailApplication(ids,tool,iface,env.getProtocolLib());
189     }
190 
191     public static class SendMailApplication extends AbstractApplication {
192 
193         /*** Construct a new SendMailApplication
194          * @param ids
195          * @param tool
196          * @param applicationInterface
197          * @param lib
198          */
199         public SendMailApplication(IDs ids, Tool tool, ApplicationInterface applicationInterface, ProtocolLibrary lib) {
200             super(ids, tool, applicationInterface, lib);
201         }
202 
203         public Runnable createExecutionTask() throws CeaException {
204 
205             createAdapters();
206             setStatus(Status.INITIALIZED);
207             return new Runnable() {
208                     public void run() {
209                         final Map args = new HashMap();
210                         try {
211                         for (Iterator i = inputParameterAdapters(); i.hasNext();) {
212                             ParameterAdapter a = (ParameterAdapter)i.next();
213                             args.put(a.getWrappedParameter().getName(),a.process());
214                         }                        
215                         setStatus(Status.RUNNING);
216                         // send the message here.
217 
218                         Session session = getSessionFromContext();
219                         Message message = new MimeMessage(session);
220                         message.setFrom(new InternetAddress("sendmail@builtin.astrogrid.org"));
221                         message.setSubject(args.get(SUBJECT).toString());
222                         message.setContent(args.get(MESSAGE).toString(),"text/plain");
223                         message.setRecipient(Message.RecipientType.TO,new InternetAddress(args.get(TO).toString()));
224                         Transport.send(message);
225                         setStatus(Status.COMPLETED);
226                         reportMessage("message sent");
227                         } catch (NamingException e) {
228                             reportError("Could not find mail session in JNDI",e);
229                         } catch (MessagingException e) {
230                             reportError("Failed to construct email message",e);
231                         } catch (Throwable t) {
232                             reportError("Something went wrong",t);
233                         }
234                     }
235             };
236 
237             
238         }
239 
240         /*** Get mail session from JNDI context.
241          * expects to find it under 'java:comp/env/mail/session'
242          * @return
243          * @throws NamingException
244          */
245         static Session getSessionFromContext() throws NamingException {
246             Context init = new InitialContext();
247             Context env = (Context) init.lookup("java:comp/env");
248             Session session = (Session)env.lookup("mail/session");
249             return session;
250         }
251     }
252     
253 }
254 
255 
256 /* 
257 $Log: SendMailApplicationDescription.java,v $
258 Revision 1.6  2004/11/27 13:20:02  pah
259 result of merge of pah_cea_bz561 branch
260 
261 Revision 1.5.16.1  2004/11/09 09:21:16  pah
262 initial attempt to rationalise authorityID use & self registering
263 
264 Revision 1.5  2004/09/17 01:21:12  nw
265 altered to work with new threadpool
266 
267 Revision 1.4.12.1  2004/09/14 13:46:04  nw
268 upgraded to new threading practice.
269 
270 Revision 1.4  2004/09/03 13:19:14  nw
271 added some progress messages
272 
273 Revision 1.3  2004/08/28 11:25:10  nw
274 tried to improve error trapping - seems to fail to complete at the moment.
275 
276 Revision 1.2  2004/08/16 11:03:46  nw
277 first stab at a cat application
278 
279 Revision 1.1  2004/08/11 17:40:49  nw
280 implemented send mail application
281  
282 */