KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jresearch > gossip > util > MessageProcessor


1 /*
2  * $$Id: MessageProcessor.java,v 1.3 2005/06/07 12:32:27 bel70 Exp $$
3  *
4  * ***** BEGIN LICENSE BLOCK *****
5  * The contents of this file are subject to the Mozilla Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License
8  * at http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific language governing rights and
13  * limitations under the License.
14  *
15  * The Original Code is JGossip forum code.
16  *
17  * The Initial Developer of the Original Code is the JResearch, Org.
18  * Portions created by the Initial Developer are Copyright (C) 2004
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  * Dmitry Belov <bel@jresearch.org>
23  *
24  * ***** END LICENSE BLOCK ***** */

25 package org.jresearch.gossip.util;
26
27 import java.text.MessageFormat JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.ResourceBundle JavaDoc;
35
36 import org.apache.oro.text.PatternCacheLRU;
37 import org.apache.oro.text.perl.Perl5Util;
38 import org.apache.struts.util.MessageResources;
39 import org.jresearch.gossip.IConst;
40 import org.jresearch.gossip.configuration.Configurator;
41 import org.jresearch.gossip.exception.ConfiguratorException;
42 import org.tiling.memo.LruCacheFactory;
43
44 /**
45  * DOCUMENT ME!
46  *
47  * @author dbelov
48  */

49 public class MessageProcessor {
50
51     private static MessageProcessor ourInstance;
52
53     private PatternCacheLRU cache = new PatternCacheLRU(50);
54
55     private Map JavaDoc resultCache = new LruCacheFactory(1000).createCache();
56
57     private static HashMap JavaDoc emoticonsMap;
58
59     private static final String JavaDoc EMOTICON_IMG_TAG = "<img SRC=\"{0}images/emoticons/{1}.gif\" alt=\"{2}\" title=\"{2}\">";
60
61     private static final String JavaDoc TAG_NOSMILE_NAME = "NOSMILE";
62
63     private static final String JavaDoc TAG_NOSMILE = "[" + TAG_NOSMILE_NAME + "]";
64
65     private static final String JavaDoc TAG_NOSMILE_END = "[/" + TAG_NOSMILE_NAME + "]";
66
67     private Perl5Util perlUtil;
68
69     private static Object JavaDoc lock = new Object JavaDoc();
70
71     /**
72      * DOCUMENT ME!
73      *
74      * @param bundle
75      * DOCUMENT ME!
76      */

77     public synchronized static void setEmoticonsMap(ResourceBundle JavaDoc bundle) {
78         Enumeration JavaDoc keys = bundle.getKeys();
79         emoticonsMap = new HashMap JavaDoc();
80
81         while (keys.hasMoreElements()) {
82             String JavaDoc key = (String JavaDoc) keys.nextElement();
83             String JavaDoc pattern = bundle.getString(key);
84
85             emoticonsMap.put(key, HtmlCodec.encode(pattern));
86         }
87     }
88
89     /**
90      * DOCUMENT ME!
91      *
92      * @return DOCUMENT ME!
93      */

94     public static HashMap JavaDoc getEmoticonsMap() {
95         return emoticonsMap;
96     }
97
98     /**
99      * Method <code>getInstance</code> return instance
100      *
101      * @return instance
102      */

103     public static MessageProcessor getInstance() {
104         if (ourInstance == null) {
105             synchronized (lock) {
106                 if (ourInstance == null) {
107                     ourInstance = new MessageProcessor();
108                 }
109             }
110         }
111
112         return ourInstance;
113     }
114
115     private MessageProcessor() {
116         perlUtil = new Perl5Util(cache);
117     }
118
119     /**
120      * DOCUMENT ME!
121      *
122      * @param result
123      * DOCUMENT ME!
124      * @param cutToLength
125      * DOCUMENT ME!
126      * @param messages
127      * DOCUMENT ME!
128      *
129      * @return DOCUMENT ME!
130      */

131     public String JavaDoc prepareMessage(String JavaDoc result, int cutToLength,
132             MessageResources messages) {
133         String JavaDoc key = Integer.toString(result.hashCode()) + cutToLength;
134         Object JavaDoc value = resultCache.get(key);
135
136         if ((value == null) && !resultCache.containsKey(key)) {
137             value = prepare(result, cutToLength, messages);
138             resultCache.put(key, value);
139         }
140
141         return (String JavaDoc) value;
142     }
143
144     /**
145      * @param result
146      * @return
147      */

148     public String JavaDoc cleanup(String JavaDoc result) {
149         return perlUtil.substitute("s/\\[(.*?)\\]/\r/gsi", result);
150     }
151
152     private String JavaDoc prepare(String JavaDoc result, int cutToLength,
153             MessageResources messages) {
154
155         if (cutToLength > 0) {
156             result = cleanup(result);
157
158             if (result.length() > cutToLength) {
159                 result = result.substring(0, cutToLength);
160                 result += "...";
161             }
162         } else {
163             // String expression="s/pattern/replacement/gsi"
164
result = perlUtil.substitute(
165                     "s/\\[b\\](.*?)\\[\\/b\\]/<strong>$1<\\/strong>/gsi",
166                     result);
167             result = perlUtil.substitute(
168                     "s/\\[i\\](.*?)\\[\\/i\\]/<em>$1<\\/em>/gsi", result);
169             result = perlUtil
170                     .substitute(
171                             "s/\\[url\\](http[s]?:\\/\\/){1}(.*?)\\[\\/url\\]/<A HREF=\"$1$2\" TARGET=\"_blank\">$2<\\/A>/gsi",
172                             result);
173             result = perlUtil
174                     .substitute(
175                             "s/\\[url=(http[s]?:\\/\\/){1}(.*?)\\](.*?)\\[\\/url\\]/<A HREF=\"$1$2\" TARGET=\"_blank\">$3<\\/A>/gsi",
176                             result);
177             result = perlUtil
178                     .substitute(
179                             "s/\\[img\\](http[s]?:\\/\\/){1}(.*?)\\[\\/img\\]/<IMG SRC=\"$1$2\" BORDER=0>/gsi",
180                             result);
181             result = perlUtil.substitute(
182                     "s/\\[HR\\]/<hr size=\"1\" width=\"90%\" noshade>/gsi",
183                     result);
184             result = perlUtil.substitute("s/\\[QUOTE\\]/<blockquote>/gsi",
185                     result);
186             result = perlUtil.substitute(
187                     "s/\\[\\/QUOTE\\]/<\\/blockquote>/gsi", result);
188             result = perlUtil.substitute(
189                     "s/\\[code\\](.*?)\\[\\/code\\]/<code>$1<\\/code>/gsi",
190                     result);
191             result = nl2br(result);
192         }
193
194         return result;
195     }
196
197     /**
198      * DOCUMENT ME!
199      *
200      * @param result
201      * DOCUMENT ME!
202      *
203      * @return DOCUMENT ME!
204      */

205     public String JavaDoc nl2br(String JavaDoc result) {
206         return perlUtil.substitute("s/\\n/<br>/g", result);
207     }
208
209     /**
210      * DOCUMENT ME!
211      *
212      * @param result
213      * DOCUMENT ME!
214      * @param messages
215      * DOCUMENT ME!
216      *
217      * @return DOCUMENT ME!
218      *
219      * @throws ConfiguratorException
220      * DOCUMENT ME!
221      */

222
223     public String JavaDoc processEmoticons(String JavaDoc result, MessageResources messages)
224             throws ConfiguratorException {
225         // normalize NOSMILE tag to upper case
226
result = perlUtil.substitute("s/" + TAG_NOSMILE_NAME + "\\]/"
227                 + TAG_NOSMILE_NAME + "\\]/gsi", result);
228
229         List JavaDoc tokens = splitOnNoSmileTag(result);
230         StringBuffer JavaDoc res = new StringBuffer JavaDoc();
231         for (int i = 0; i < tokens.size(); i++) {
232             MPToken token = (MPToken) tokens.get(i);
233             if (token.processSmiles) {
234                 res.append(replaceEmoticons(token.text, messages));
235             } else {
236                 res.append(token.text);
237             }
238         }
239         return res.toString();
240     }
241
242     private String JavaDoc replaceEmoticons(String JavaDoc result, MessageResources messages)
243             throws ConfiguratorException {
244         Iterator JavaDoc it = emoticonsMap.keySet().iterator();
245         Object JavaDoc[] args = {
246                 Configurator.getInstance().get(IConst.CONFIG.WEB_ROOT), "", "" };
247         // For tests - use next string
248
// Object[] args = { "WEB_ROOT/", "", "" };
249

250         while (it.hasNext()) {
251             String JavaDoc key = (String JavaDoc) it.next();
252             String JavaDoc pattern = (String JavaDoc) emoticonsMap.get(key);
253             args[1] = key;
254             args[2] = messages.getMessage(Configurator.getInstance().getLocale(
255                     IConst.CONFIG.DEFAULT_LOCALE), key);
256             result = replace(result, pattern, MessageFormat.format(
257                     EMOTICON_IMG_TAG, args));
258         }
259
260         return result;
261     }
262
263     private List JavaDoc splitOnNoSmileTag(String JavaDoc result) {
264         ArrayList JavaDoc tokens = new ArrayList JavaDoc();
265         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(result);
266         int ind1 = 0;
267         int ind2 = 0;
268         int length = sb.length();
269         while (ind1 < length && ind2 < length) {
270             ind2 = sb.indexOf(TAG_NOSMILE, ind1);
271             if (ind2 == -1) {
272                 ind2 = length;
273             }
274             tokens.add(new MPToken(true, sb.substring(ind1, ind2)));
275             if (ind2 != length) {
276                 ind1 = ind2 + TAG_NOSMILE.length();
277                 ind2 = sb.indexOf(TAG_NOSMILE_END, ind1);
278                 if (ind2 == -1) {
279                     ind2 = length;
280                 }
281                 tokens.add(new MPToken(false, sb.substring(ind1, ind2)));
282                 if (ind2 != length) {
283                     ind1 = ind2 + TAG_NOSMILE_END.length();
284                 }
285             }
286         }
287         return tokens;
288     }
289
290     private class MPToken {
291
292         /**
293          * @param processSmiles
294          * @param text
295          */

296         protected MPToken(boolean processSmiles, String JavaDoc text) {
297             super();
298             this.processSmiles = processSmiles;
299             this.text = text;
300         }
301
302         boolean processSmiles;
303
304         String JavaDoc text;
305     }
306
307     /**
308      * DOCUMENT ME!
309      *
310      * @param result
311      * DOCUMENT ME!
312      * @param pattern
313      * DOCUMENT ME!
314      * @param replace
315      * DOCUMENT ME!
316      *
317      * @return DOCUMENT ME!
318      *
319      * @throws IllegalArgumentException
320      * DOCUMENT ME!
321      */

322     public String JavaDoc replace(String JavaDoc result, String JavaDoc pattern, String JavaDoc replace) {
323         if (result == null) {
324             throw new IllegalArgumentException JavaDoc("result parameter, value = "
325                     + result);
326         }
327
328         if (replace == null) {
329             throw new IllegalArgumentException JavaDoc("replace parameter, value = "
330                     + replace);
331         }
332
333         if ((pattern == null) || "".equals(pattern)) {
334             throw new IllegalArgumentException JavaDoc("pattern parameter, value = "
335                     + pattern);
336         }
337
338         if ("".equals(result)) {
339             return result;
340         }
341
342         int s = 0;
343         int e = 0;
344         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(result);
345
346         while ((e = sb.indexOf(pattern, s)) > -1) {
347             sb.replace(e, e + pattern.length(), replace);
348             s = e + replace.length();
349         }
350
351         return sb.toString();
352     }
353 }
Popular Tags