KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > echo2example > email > faux > MessageGenerator


1 /*
2  * This file is part of the Echo Web Application Framework (hereinafter "Echo").
3  * Copyright (C) 2002-2005 NextApp, Inc.
4  *
5  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * Alternatively, the contents of this file may be used under the terms of
18  * either the GNU General Public License Version 2 or later (the "GPL"), or
19  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
20  * in which case the provisions of the GPL or the LGPL are applicable instead
21  * of those above. If you wish to allow use of your version of this file only
22  * under the terms of either the GPL or the LGPL, and not to allow others to
23  * use your version of this file under the terms of the MPL, indicate your
24  * decision by deleting the provisions above and replace them with the notice
25  * and other provisions required by the GPL or the LGPL. If you do not delete
26  * the provisions above, a recipient may use your version of this file under
27  * the terms of any one of the MPL, the GPL or the LGPL.
28  */

29
30 package echo2example.email.faux;
31
32 import java.io.BufferedReader JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.io.InputStream JavaDoc;
35 import java.io.InputStreamReader JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 import java.util.Calendar JavaDoc;
38 import java.util.Date JavaDoc;
39 import java.util.GregorianCalendar JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.StringTokenizer JavaDoc;
42
43 import javax.mail.Address JavaDoc;
44 import javax.mail.MessagingException JavaDoc;
45 import javax.mail.internet.AddressException JavaDoc;
46 import javax.mail.internet.InternetAddress JavaDoc;
47
48 /**
49  * Generates random fake content for the fake JavaMail <code>Message</code>
50  * objects.
51  */

52 public class MessageGenerator {
53     
54     private static final String JavaDoc DOMAIN = "nextapp.com";
55     private static final Address JavaDoc YOUR_ADDRESS;
56     static {
57         try {
58             YOUR_ADDRESS = new InternetAddress JavaDoc("Joe Smith <joe.smith@nextapp.com>");
59         } catch (AddressException JavaDoc ex) {
60             throw new RuntimeException JavaDoc(ex);
61         }
62     }
63     
64     private static final int MINIMUM_DATE_DELTA = -365;
65     private static final int MAXIMUM_DATE_DELTA = 0;
66
67     /**
68      * Generates a text document from random artificial text.
69      *
70      * @param sentenceArray the source array from which strings are randomly
71      * retrieved
72      * @param minimumSentences the minimum number of sentences each paragraph
73      * may contain
74      * @param maximumSentences the maximum number of sentences each paragraph
75      * may contain
76      * @param minimumParagraphs the minimum number of paragraphs the document
77      * may contain
78      * @param maximumParagraphs the maximum number of paragraphs the document
79      * may contain
80      * @return the document
81      */

82     private static String JavaDoc generateText(String JavaDoc[] sentenceArray, int minimumSentences, int maximumSentences,
83             int minimumParagraphs, int maximumParagraphs) {
84     
85         int paragraphCount = randomInteger(minimumParagraphs, maximumParagraphs);
86         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
87         for (int paragraphIndex = 0; paragraphIndex < paragraphCount; ++paragraphIndex) {
88             int sentenceCount = randomInteger(minimumSentences, maximumSentences);
89             for (int sentenceIndex = 0; sentenceIndex < sentenceCount; ++sentenceIndex) {
90                 text.append(sentenceArray[randomInteger(sentenceArray.length)]);
91                 text.append(".");
92                 if (sentenceIndex < sentenceCount - 1) {
93                     text.append(" ");
94                 }
95             }
96             if (paragraphIndex < paragraphCount - 1) {
97                 text.append("\n\n");
98             }
99         }
100         return text.toString();
101     }
102
103     /**
104      * Returns a text resource as an array of strings.
105      *
106      * @param resourceName the name of resource available from the
107      * <code>CLASSPATH</code>
108      * @return the resource as an array of strings
109      */

110     private static String JavaDoc[] loadStrings(String JavaDoc resourceName) {
111         InputStream JavaDoc in = null;
112         List JavaDoc strings = new ArrayList JavaDoc();
113         try {
114             in = MessageGenerator.class.getResourceAsStream(resourceName);
115             if (in == null) {
116                 throw new IllegalArgumentException JavaDoc("Resource does not exist: \"" + resourceName + "\"");
117             }
118             BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(in));
119             String JavaDoc line;
120             while ((line = reader.readLine()) != null) {
121                 line = line.trim();
122                 if (line.length() > 0) {
123                     strings.add(Character.toUpperCase(line.charAt(0)) + line.substring(1).toLowerCase());
124                 }
125             }
126             return (String JavaDoc[]) strings.toArray(new String JavaDoc[strings.size()]);
127         } catch (IOException JavaDoc ex) {
128             throw new IllegalArgumentException JavaDoc("Cannot get resource: \"" + resourceName + "\": " + ex);
129         } finally {
130             if (in != null) { try { in.close(); } catch (IOException JavaDoc ex) { } }
131         }
132     }
133
134     /**
135      * Returns a random boolean value.
136      *
137      * @param truePercent The percentage of 'true' values to be returned.
138      * @return The random boolean value.
139      */

140     private static boolean randomBoolean(int truePercent) {
141         int number = (int) (Math.random() * 100);
142         return number < truePercent;
143     }
144
145     /**
146      * Returns a random integer between the specified bounds.
147      *
148      * @param minimum the minimum possible value
149      * @param maximum the maximum possible value
150      * @return the random integer
151      */

152     private static int randomInteger(int minimum, int maximum) {
153         return minimum + (int) (Math.random() * (maximum - minimum + 1));
154     }
155
156     /**
157      * Returns a random integer between 0 and <code>size</code> - 1.
158      *
159      * @param size the number of possible random values
160      * @return a random integer between 0 and <code>size</code> - 1
161      */

162     private static int randomInteger(int size) {
163         return (int) (Math.random() * size);
164     }
165
166     /**
167      * Returns a version of a sentence with every word capitalized.
168      *
169      * @param title The title sentence to capitalize.
170      * @return A version of the sentence with every word capitalized.
171      */

172     private static String JavaDoc titleCapitalize(String JavaDoc title) {
173         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(title);
174         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
175         while (st.hasMoreTokens()) {
176             String JavaDoc token = st.nextToken();
177             sb.append(Character.toUpperCase(token.charAt(0)));
178             sb.append(token.substring(1));
179             if (st.hasMoreTokens()) {
180                 sb.append(" ");
181             }
182         }
183         return sb.toString();
184     }
185
186     private String JavaDoc[] lastNames = loadStrings("resource/LastNames.txt");
187     private String JavaDoc[] maleFirstNames = loadStrings("resource/MaleFirstNames.txt");
188     private String JavaDoc[] femaleFirstNames = loadStrings("resource/FemaleFirstNames.txt");
189     private String JavaDoc[] latinSentences = loadStrings("resource/LatinSentences.txt");
190     
191     private Address JavaDoc createAddress()
192     throws MessagingException JavaDoc {
193         // Create Name.
194
String JavaDoc firstName;
195         
196         boolean male = randomBoolean(50);
197         if (male) {
198             int firstNameIndex = randomInteger(maleFirstNames.length);
199             firstName = maleFirstNames[firstNameIndex];
200         } else {
201             int firstNameIndex = randomInteger(femaleFirstNames.length);
202             firstName = femaleFirstNames[firstNameIndex];
203         }
204         String JavaDoc lastName = lastNames[randomInteger(lastNames.length)];
205         String JavaDoc email = firstName + "." + lastName + "@" + DOMAIN;
206         InternetAddress JavaDoc address = new InternetAddress JavaDoc(firstName + " " + lastName + " <" + email + ">");
207         return address;
208     }
209     
210     public Date JavaDoc randomDate() {
211         Calendar JavaDoc cal = new GregorianCalendar JavaDoc();
212         cal.add(Calendar.DAY_OF_MONTH, randomInteger(MINIMUM_DATE_DELTA, MAXIMUM_DATE_DELTA));
213         cal.add(Calendar.SECOND, -randomInteger(86400));
214         return cal.getTime();
215     }
216     
217     public FauxMessage generateMessage()
218     throws MessagingException JavaDoc {
219         
220         Date JavaDoc receivedDate = randomDate();
221         Address JavaDoc from = createAddress();
222
223         Address JavaDoc[] to = null;
224         Address JavaDoc[] cc = null;
225         Address JavaDoc[] bcc = null;
226         switch (randomInteger(0, 3)) {
227         case 0:
228             to = new Address JavaDoc[]{YOUR_ADDRESS};
229             break;
230         case 1:
231             to = new Address JavaDoc[]{createAddress(), createAddress()};
232             cc = new Address JavaDoc[]{createAddress(), createAddress(), createAddress()};
233             bcc = new Address JavaDoc[]{YOUR_ADDRESS};
234             break;
235         case 2:
236             to = new Address JavaDoc[]{YOUR_ADDRESS};
237             cc = new Address JavaDoc[]{createAddress(), createAddress()};
238             break;
239         case 3:
240             to = new Address JavaDoc[]{createAddress()};
241             cc = new Address JavaDoc[]{createAddress(), YOUR_ADDRESS, createAddress()};
242             break;
243         }
244         // Create Article Title
245
String JavaDoc subject = latinSentences[randomInteger(latinSentences.length)];
246         if (subject.length() > 40) {
247             subject = subject.substring(0, subject.lastIndexOf(" ", 40));
248         }
249         if (subject.endsWith(",")) {
250             subject = subject.substring(0, subject.length() - 1);
251         }
252         subject = titleCapitalize(subject);
253
254         String JavaDoc content = generateText(latinSentences, 2, 8, 6, 26);
255
256         return new FauxMessage(from, receivedDate, to, cc, bcc, subject, content);
257         
258     }
259 }
260
Popular Tags