KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > rm > commands > CmdEmail


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.rm.commands;
20
21 import java.io.StringWriter JavaDoc;
22 import java.util.*;
23
24 import javax.xml.transform.*;
25 import javax.xml.transform.dom.DOMSource JavaDoc;
26 import javax.xml.transform.stream.StreamResult JavaDoc;
27
28 import org.openharmonise.commons.dsi.*;
29 import org.openharmonise.commons.net.Email;
30 import org.openharmonise.rm.DataAccessException;
31 import org.openharmonise.rm.config.*;
32 import org.openharmonise.rm.dsi.DataStoreInterfaceFactory;
33 import org.openharmonise.rm.factory.*;
34 import org.openharmonise.rm.metadata.*;
35 import org.openharmonise.rm.publishing.*;
36 import org.openharmonise.rm.resources.*;
37 import org.openharmonise.rm.resources.publishing.Template;
38 import org.openharmonise.rm.resources.xml.XSLResource;
39 import org.w3c.dom.*;
40
41 /**
42  * Publishes the 'command object' using a <code>Template</code> specified in the parameters
43  * and sends the result as an email to the recipient specified in the parameters.
44  *
45  * @author Michael Bell
46  * @version $Revision: 1.3 $
47  *
48  */

49 public class CmdEmail extends AbstractCmd {
50     
51     /**
52      * Email recipient tag
53      */

54     public static final String JavaDoc TAG_EMAILRECIPIENT = "EmailRecipient";
55     
56     /**
57      * Send type attribute, i.e. 'user' or 'test'
58      */

59     public static final String JavaDoc ATTRIB_SEND_TYPE = "sendType";
60     
61     /**
62      * Possible value for <code>EMAILFORMID_PNAME</code> parameter to indicate
63      * the submitted for should be used to publish the 'command object'
64      */

65     static final String JavaDoc USE_SUBMITTED_FORM = "submitted";
66     
67     /**
68      * Property name for the 'recipient' property
69      */

70     static final String JavaDoc EMAIL_PROPNAME = "RECIPIENT";
71     
72     /**
73      * Property name for the 'sender' property
74      */

75     static final String JavaDoc SENDER_PROPNAME = "SENDER";
76     
77     /**
78      * Parameter name for the id of the template to be used
79      * in publishing the 'command object'
80      */

81     static final String JavaDoc EMAILFORMID_PNAME = "publish_using_template_id";
82     
83     /**
84      * Parameter name for the recipient list
85      */

86     static final String JavaDoc RECEPIENTLIST_PNAME = "recipient";
87     
88     /**
89      * Parameter name for the sender
90      */

91     static final String JavaDoc SENDER_PNAME = "sender";
92     
93     /**
94      * Parameter name for email subject
95      */

96     static final String JavaDoc SUBJECT_PNAME = "subject";
97     
98     /**
99      * Parameter name for email content type
100      */

101     static final String JavaDoc CONTENTTYPE_PNAME = "content_type";
102     
103     /**
104      * Parameter name for the XSLT file to be used in transforming
105      * the result of publishing the 'command object' to XML
106      */

107     static final String JavaDoc XSL_PNAME = "xsl_file";
108     
109     /**
110      * Parameter name for the output text
111      */

112     static final String JavaDoc OUTTEXT_PNAME = "out_text";
113     
114     /**
115      * Parameter name for sending the published XML
116      */

117     static final String JavaDoc SENDXML_PNAME = "xml_recipient"; // for debugging
118

119     /**
120      * Name replacement pattern
121      */

122     static final String JavaDoc SUBJECT_INMARKER = "#!N"; // name replacement
123

124     /**
125      * Property value pattern
126      */

127     static final String JavaDoc SUBJECT_IPMARKER = "#!P:"; // property replacement
128

129     /**
130      * Config parameter name for the email host
131      */

132     static final String JavaDoc PNAME_EMAIL_HOST = "EMAIL_HOST";
133
134
135     /**
136      * Creates a new instance of the command.
137      *
138      */

139     public CmdEmail() {
140         super();
141     }
142
143     /* (non-Javadoc)
144      * @see org.openharmonise.rm.commands.AbstractCmd#execute()
145      */

146     public Object JavaDoc execute(Context context) throws CommandException {
147         int nTemplateId = -1;
148         String JavaDoc publish_using_form_id = this.getParameter(EMAILFORMID_PNAME);
149         String JavaDoc xsl_filename = this.getParameter(XSL_PNAME);
150         String JavaDoc sender_address = this.getParameter(SENDER_PNAME);
151
152         if ((publish_using_form_id != null) &&
153                 publish_using_form_id.equals(USE_SUBMITTED_FORM)) {
154             String JavaDoc sTemplateId = getParameter(AbstractCmd.PARAM_TEMPLATE_ID);
155             if(sTemplateId != null) {
156                 nTemplateId = Integer.parseInt(sTemplateId);
157             }
158             
159         } else if (publish_using_form_id != null) {
160             try {
161                 nTemplateId = Integer.parseInt(publish_using_form_id);
162             } catch (NumberFormatException JavaDoc e) {
163                 throw new RuntimeException JavaDoc(
164                         " The parameter check_with_form is invalid " + ":" +
165                         publish_using_form_id + " must be a valid number" +
166                         ", or " + USE_SUBMITTED_FORM +
167                         " to use the submitted form");
168             }
169         } else {
170             throw new CommandExecutionException(
171                     "A form id must be supplied in order to publish the user" +
172                     " parameter:" + EMAILFORMID_PNAME + " must be set.");
173         }
174
175         List recipient_addresses = this.getParameters(RECEPIENTLIST_PNAME);
176
177         Object JavaDoc cmdObj = getCommandObject(context);
178         
179         try {
180             if ((recipient_addresses == null) ||
181                     (recipient_addresses.size() == 0)) {
182                 org.w3c.dom.Document JavaDoc state = getState();
183                 Element root = state.getDocumentElement();
184             
185                 NodeList nlEmailRecip = root.getElementsByTagName(
186                                                 TAG_EMAILRECIPIENT);
187             
188                 if (nlEmailRecip.getLength() > 0) {
189                     Element elEmailRecip = (Element) nlEmailRecip.item(0);
190             
191                     if (recipient_addresses == null) {
192                         recipient_addresses = new Vector(16);
193                     }
194             
195                     String JavaDoc sSendType = elEmailRecip.getAttribute(ATTRIB_SEND_TYPE);
196             
197                     if (sSendType.equalsIgnoreCase("test")) {
198                         Text txt = (Text) elEmailRecip.getFirstChild();
199             
200                         if (txt.getNodeValue().indexOf("@") < 0) {
201                             throw new CommandException(
202                                     "Need valid email address.");
203                         }
204             
205                         recipient_addresses.add(txt.getNodeValue());
206                     } else if (sSendType.equalsIgnoreCase("user")) {
207             
208                         Profile pro = ((AbstractProfiledObject) cmdObj).getProfile();
209             
210                         AbstractDataStoreInterface dbintrf = DataStoreInterfaceFactory.getDataStoreInterface();
211             
212                         
213                     }
214                 }
215                 else {
216                     // see if the working object has email addresses
217
AbstractProfiledObject obj = (AbstractProfiledObject)cmdObj ;
218                     Profile pro = obj.getProfile() ;
219                     AbstractPropertyInstance prop = pro.getPropertyInstance( EMAIL_PROPNAME ) ;
220                     if( prop != null ) {
221                         recipient_addresses = prop.getValues() ;
222                     }
223                     if( sender_address == null ) {
224                         prop = pro.getPropertyInstance( SENDER_PROPNAME ) ;
225                         if( prop != null ) {
226                             sender_address = (String JavaDoc) prop.getValue() ;
227                         }
228                     }
229                 }
230             }
231             
232             String JavaDoc subject_text = buildSubjectLine((AbstractObject) cmdObj);
233             
234             if ((subject_text == null) || (subject_text.length() == 0)) {
235                 subject_text = ((AbstractObject)cmdObj).getName();
236             }
237             
238             Template template = (Template) HarmoniseObjectFactory.instantiateHarmoniseObject(getDataStoreInteface(),Template.class.getName(),nTemplateId);
239             
240             HarmoniseOutput doc = new HarmoniseOutput(this.getDataStoreInteface()) ;
241             
242             
243             org.w3c.dom.Element JavaDoc workflow_obj_root = template.publishObjectToElement((Publishable) cmdObj,doc,getState());
244             
245             
246             doc.appendChild( doc.copyNode( workflow_obj_root ) ) ;
247             
248             String JavaDoc obj_as_txt = processXSLT(doc.getDocumentElement(), xsl_filename);
249             
250             Iterator recipient_addresses_it = recipient_addresses.iterator();
251             
252             while (recipient_addresses_it.hasNext()) {
253                 String JavaDoc recipient_address = (String JavaDoc) recipient_addresses_it.next();
254                 Email email = new Email(ConfigSettings.getProperty(PNAME_EMAIL_HOST),recipient_address, sender_address,
255                                         subject_text, obj_as_txt);
256                 String JavaDoc ctype = this.getParameter(CONTENTTYPE_PNAME);
257             
258                 if (ctype != null) {
259             
260                     email.SetContentType(ctype);
261                 }
262             
263                 email.send();
264             }
265             
266             String JavaDoc xml_recepient = null;
267             
268             
269         } catch (DataAccessException e) {
270             throw new CommandExecutionException("DataAccessException",e);
271         } catch (HarmoniseFactoryException e) {
272             throw new CommandExecutionException(e);
273         } catch (PublishException e) {
274             throw new CommandExecutionException("PublishException",e);
275         } catch (ConfigException e) {
276             throw new CommandExecutionException("ConfigException",e);
277         } catch (DataStoreException e) {
278             throw new CommandExecutionException("DataStoreException",e);
279         } catch (InvalidPropertyInstanceException e) {
280             throw new CommandExecutionException(e.getLocalizedMessage(),e);
281         }
282
283         return null;
284     }
285
286
287     /* (non-Javadoc)
288      * @see org.openharmonise.rm.commands.AbstractCmd#getName()
289      */

290     public String JavaDoc getName() {
291         return "Email";
292     }
293
294     /* (non-Javadoc)
295      * @see org.openharmonise.rm.commands.AbstractCmd#isValidCommandObject(java.lang.Object)
296      */

297     public boolean isValidCommandObject(Object JavaDoc obj) {
298         return (obj instanceof Publishable);
299     }
300     
301     /**
302      * Transforms the given XML node using the XSLT specified and returns the result as
303      * a <code>String</code>
304      *
305      * @param xml_node the XML node
306      * @param xsl_filename the XSLT file name
307      * @return the result of transforming the XML using the specified XSLT
308      * @throws CommandException if any errors occur
309      */

310     private String JavaDoc processXSLT(Node xml_node, String JavaDoc xsl_filename) throws CommandException {
311         StringWriter JavaDoc out_str = new StringWriter JavaDoc();
312
313         try {
314             XSLResource xsl = (XSLResource) HarmoniseObjectFactory.instantiateHarmoniseObject(getDataStoreInteface(),XSLResource.class.getName(),xsl_filename);
315             
316             Transformer trans = xsl.getTemplates().newTransformer();
317             
318             DOMSource JavaDoc ds = new DOMSource JavaDoc(xml_node);
319             
320             StreamResult JavaDoc res = new StreamResult JavaDoc(out_str);
321             
322             trans.transform(ds, res);
323         } catch (HarmoniseFactoryException e) {
324             throw new CommandException("Error getting xsl from factory - " + xsl_filename,e);
325         } catch (TransformerConfigurationException e) {
326             throw new CommandException("TransformerConfigurationException",e);
327         } catch (DataAccessException e) {
328             throw new CommandException("DataAccessException",e);
329         } catch (TransformerException e) {
330             throw new CommandException("TransformerException",e);
331         }
332
333         return out_str.toString();
334     }
335     
336     /**
337      * Returns the subject line for the email, taken from a parameter and
338      * making appropriate substitutions
339      *
340      * @return the subject line for the email
341      * @throws DataAccessException if any errors occur substituting with the required data
342      */

343     private String JavaDoc buildSubjectLine(AbstractObject obj) throws DataAccessException {
344         String JavaDoc subject_line = null;
345         subject_line = this.getParameter(SUBJECT_PNAME);
346
347         if (subject_line == null) {
348             return "";
349         } else {
350             return (processSubjectLine(obj,subject_line));
351         }
352     }
353
354     /**
355      * Processes the given subject line making replacements for place holders where
356      * appropriate and returns the result
357      *
358      * @param subject_line the subject line
359      * @return the subject line with appropriate substitions made
360      * @throws DataAccessException if any errors occur accessing data for substitution
361      */

362     private String JavaDoc processSubjectLine(AbstractObject obj, String JavaDoc subject_line) throws DataAccessException {
363         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
364
365         StringTokenizer tokens = new StringTokenizer(subject_line, " \t\n\r",
366                                                      true);
367
368         while (tokens.hasMoreTokens()) {
369             String JavaDoc subject_bit = tokens.nextToken();
370
371             if (subject_bit.startsWith(SUBJECT_IPMARKER)) {
372                 strbuf.append(getProperty((AbstractProfiledObject) obj,subject_bit));
373             } else if (subject_bit.startsWith(SUBJECT_INMARKER)) {
374                 strbuf.append(obj.getName());
375             } else {
376                 strbuf.append(subject_bit);
377             }
378         }
379
380         return strbuf.toString();
381     }
382
383     /**
384      * Returns the value of the property of the specified name
385      *
386      * @param prop_desc the property name
387      * @return the value of the property of the specified name
388      * @throws DataAccessException if an error occurs accessing
389      * the value of the property
390      */

391     private String JavaDoc getProperty(AbstractProfiledObject profObj,String JavaDoc prop_desc) throws DataAccessException {
392         String JavaDoc property_name = prop_desc.substring(SUBJECT_IPMARKER.length())
393                                         .trim();
394
395         List property_descs = null;
396         boolean got_pvalue = true;
397
398        
399         Profile object_profile = profObj.getProfile();
400
401
402         try {
403             property_descs = object_profile.getPropertyInstance(prop_desc).getValues();
404         } catch (InvalidPropertyInstanceException e) {
405             throw new DataAccessException(e.getLocalizedMessage(),e);
406         }
407         
408         got_pvalue = (property_descs.size() > 0);
409
410
411         if (got_pvalue) {
412             return (separatedList(property_descs, ","));
413         } else {
414             return "*NoValue*";
415         }
416     }
417
418     /**
419      * Returns the given collection as a <code>String</code> of values
420      * seperated by the given separator <code>String</code>
421      *
422      * @param collection the collection
423      * @param separator the separator
424      * @return the given collection as a <code>String</code> of values
425      * seperated by the given separator <code>String</code>
426      */

427     private String JavaDoc separatedList(Collection collection, String JavaDoc seperator) {
428         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
429
430         Iterator coll_it = collection.iterator();
431
432         while (coll_it.hasNext()) {
433             strbuf.append((String JavaDoc) coll_it.next());
434
435             if (coll_it.hasNext()) {
436                 strbuf.append(seperator);
437             }
438         }
439
440         return strbuf.toString();
441     }
442
443 }
Popular Tags