KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > velocity > plugins > smileys > SmileysPlugin


1 package org.roller.presentation.velocity.plugins.smileys;
2
3 import org.apache.commons.lang.StringEscapeUtils;
4 import org.apache.commons.logging.Log;
5 import org.apache.commons.logging.LogFactory;
6 import org.apache.velocity.context.Context;
7 import org.roller.RollerException;
8 import org.roller.pojos.WeblogEntryData;
9 import org.roller.presentation.RollerRequest;
10 import org.roller.presentation.velocity.PagePlugin;
11
12 import java.util.Enumeration JavaDoc;
13 import java.util.Properties JavaDoc;
14 import java.util.regex.Matcher JavaDoc;
15 import java.util.regex.Pattern JavaDoc;
16
17 /**
18  * Converts ascii emoticons into HTML image tags.
19  *
20  * @author lance.lavandowska
21  * Created on Jun 8, 2004
22  */

23 public class SmileysPlugin implements PagePlugin
24 {
25     private String JavaDoc name = "Emoticons";
26     private String JavaDoc description = "Change ASCII emoticons to graphics. " +
27         ":-) becomes <img SRC='./images/smileys/smile.gif'>";
28     
29     public String JavaDoc toString() { return name; }
30     
31     static Pattern JavaDoc[] smileyPatterns = new Pattern JavaDoc[0];
32     static String JavaDoc[] imageTags = new String JavaDoc[0];
33
34     private static Log mLogger =
35         LogFactory.getFactory().getInstance(SmileysPlugin.class);
36
37     /*
38      * Definition of the emoticons 'glyph' and graphic.
39      */

40     private static Properties JavaDoc smileyDefs = new Properties JavaDoc();
41     static
42     {
43         try
44         {
45             smileyDefs.load(SmileysPlugin.class.getResourceAsStream("smileys.properties"));
46         }
47         catch (Exception JavaDoc e)
48         {
49             mLogger.error("Unable to load smileys.properties", e);
50         }
51     }
52     
53     public SmileysPlugin()
54     {
55         mLogger.debug("SmileysPlugin instantiated.");
56     }
57
58     /*
59      * Find occurences of ascii emoticons and turn them into
60      * HTML image pointers.
61      *
62      * @see org.roller.presentation.velocity.PagePlugin#render(java.lang.String)
63      */

64     public String JavaDoc render(String JavaDoc text)
65     {
66         Matcher JavaDoc matcher = null;
67         for (int i=0; i<smileyPatterns.length; i++)
68         {
69             matcher = smileyPatterns[i].matcher(text);
70             text = matcher.replaceAll(imageTags[i]);
71         }
72         return text;
73     }
74
75     /*
76      * Convert the SmileyDefs into RegEx patterns and img tags for
77      * later use. Need an HttpServletRequest though so that we can
78      * get the ServletContext Path. But only do it once.
79      *
80      * @see org.roller.presentation.velocity.PagePlugin#init(org.roller.presentation.RollerRequest, org.apache.velocity.context.Context)
81      */

82     public synchronized void init(RollerRequest rreq, Context ctx) throws RollerException
83     {
84         // don't do this work if Smileys already loaded
85
if (SmileysPlugin.smileyPatterns.length < 1)
86         {
87             String JavaDoc contextPath = "";
88             if (rreq != null && rreq.getRequest() != null)
89             {
90                 contextPath = rreq.getRequest().getContextPath();
91             }
92             Pattern JavaDoc[] tempP = new Pattern JavaDoc[SmileysPlugin.smileyDefs.size()];
93             String JavaDoc[] tempS = new String JavaDoc[SmileysPlugin.smileyDefs.size()];
94             //System.out.println("# smileys: " + smileyDefs.size());
95
int count = 0;
96             Enumeration JavaDoc enum1 = SmileysPlugin.smileyDefs.propertyNames();
97             while(enum1.hasMoreElements())
98             {
99                 String JavaDoc smiley = (String JavaDoc)enum1.nextElement();
100                 String JavaDoc smileyAlt = htmlEscape(smiley);
101                 tempP[count] = Pattern.compile(regexEscape(smiley));
102                 tempS[count] = "<img SRC=\"" +
103                                contextPath + "/images/smileys/" +
104                                smileyDefs.getProperty(smiley, "smile.gif") +
105                                "\" class=\"smiley\"" +
106                                " alt=\"" + smileyAlt + "\"" +
107                                " title=\"" + smileyAlt +"\">";
108                 //System.out.println(smiley + "=" + tempS[count]);
109
count++;
110             }
111             SmileysPlugin.smileyPatterns = tempP;
112             SmileysPlugin.imageTags = tempS;
113         }
114     }
115     
116     /*
117      * To display the smiley 'glyph' certain characters
118      * must be HTML escaped.
119      */

120     private String JavaDoc htmlEscape(String JavaDoc smiley)
121     {
122         char[] chars = smiley.toCharArray();
123         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
124         for (int i=0; i<chars.length; i++)
125         {
126             if (chars[i] == '"')
127             {
128                 buf.append("&quot;");
129             }
130             else if (chars[i] == '>')
131             {
132                 buf.append("&gt;");
133             }
134             else if (chars[i] == '<')
135             {
136                 buf.append("&lt;");
137             }
138             else
139             {
140                 buf.append(chars[i]);
141             }
142         }
143         return buf.toString();
144     }
145
146     /**
147      * Some characters have to escaped with a backslash before
148      * being compiled into a Regular Expression.
149      *
150      * @param smiley
151      * @return
152      */

153     private static char[] escape_regex = new char[]
154         {'-', '(', ')', '\\', '|', ':', '^', '$', '*', '+', '?',
155          '{', '}', '!', '=', '<', '>', '&', '[', ']' };
156     private String JavaDoc regexEscape(String JavaDoc smiley)
157     {
158         char[] chars = smiley.toCharArray();
159         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
160         for (int i=0; i<chars.length; i++)
161         {
162             for (int x=0; x<escape_regex.length; x++)
163             {
164                 if (escape_regex[x] == chars[i])
165                 {
166                     buf.append("\\");
167                     break;
168                 }
169             }
170             buf.append(chars[i]);
171         }
172         return buf.toString();
173     }
174
175     /*
176      * @see org.roller.presentation.velocity.PagePlugin#render(org.roller.pojos.WeblogEntryData, boolean)
177      */

178     public String JavaDoc render(WeblogEntryData entry, boolean skipFlag)
179     {
180         return render(entry.getText());
181     }
182
183     public String JavaDoc getName() { return name; }
184     public String JavaDoc getDescription() { return StringEscapeUtils.escapeJavaScript(description); }
185 }
186
Popular Tags