KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > highlight > GoogleHighlightPlugin


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.plugin.highlight;
32
33 import org.blojsom.blog.Blog;
34 import org.blojsom.blog.Entry;
35 import org.blojsom.plugin.Plugin;
36 import org.blojsom.plugin.PluginException;
37
38 import javax.servlet.http.HttpServletRequest JavaDoc;
39 import javax.servlet.http.HttpServletResponse JavaDoc;
40 import java.util.Map JavaDoc;
41 import java.util.StringTokenizer JavaDoc;
42 import java.util.regex.Matcher JavaDoc;
43 import java.util.regex.Pattern JavaDoc;
44
45 /**
46  * The GoogleHighlightPlugin will highlight words on your blog if the referer came from a Google
47  * query.
48  * <p/>
49  * Based on work from http://www.textism.com/
50  *
51  * @author Mark Lussier
52  * @version $Id: GoogleHighlightPlugin.java,v 1.2 2006/03/20 22:50:40 czarneckid Exp $
53  * @since blojsom 3.0
54  */

55 public class GoogleHighlightPlugin implements Plugin {
56
57     /**
58      * HTTP Header for Referer Information
59      */

60     private static final String JavaDoc HEADER_REFERER = "referer";
61
62     private static final String JavaDoc START_BOUNDRY = "(\\b";
63     private static final String JavaDoc END_BOUNDRY = "\\b)";
64
65     /**
66      * Expression used to identify the referer as a Google referer
67      */

68     private static final String JavaDoc EXPRESSSION_GOOGLE = "^http:\\/\\/w?w?w?\\.?google.*";
69
70     private static final String JavaDoc EXPRESSION_HTMLPREFIX = "(?<=>)([^<]+)?";
71     private static final String JavaDoc EXPRESSION_HASTAGS = "<.+>";
72
73     /**
74      * Expression used to extract the Query string portion of the referer
75      */

76     private static final String JavaDoc GOOGLE_QUERY = "^.*q=([^&]+)&?.*$";
77
78     /**
79      * Expression used to clean quotes
80      */

81     private static final String JavaDoc GOOGLE_CLEANQUOTES = "'/\'|\"/\"";
82
83     /**
84      * Used to replace matches in entries that DO NOT have html tags
85      */

86     private static final String JavaDoc HIGHLIGHT_PLAINTEXT = "<span class=\"searchhighlight\">$1</span>";
87
88     /**
89      * Used to replace matches in entries that HAVE html tags
90      */

91     private static final String JavaDoc HIGHLIGHT_HTML = "$1<span class=\"searchhighlight\">$2</span>";
92
93     /**
94      * Initialize this plugin. This method only called when the plugin is instantiated.
95      *
96      * @throws PluginException If there is an error initializing the plugin
97      */

98     public void init() throws PluginException {
99     }
100
101
102     /**
103      * Extract search tokens from the Google Query String
104      *
105      * @param referer The Google referer
106      * @return A string array of search words or <code>null</code> if no search query match is found
107      */

108     private String JavaDoc[] extractQueryTokens(String JavaDoc referer) {
109         String JavaDoc[] result = null;
110         Matcher JavaDoc matcher = Pattern.compile(GOOGLE_QUERY, Pattern.CASE_INSENSITIVE).matcher(referer);
111         if (matcher.find()) {
112             String JavaDoc _query = matcher.group(1);
113             _query = _query.replaceAll(GOOGLE_CLEANQUOTES, "");
114             StringTokenizer JavaDoc _st = new StringTokenizer JavaDoc(_query, "+, .", false);
115             result = new String JavaDoc[_st.countTokens()];
116             int cnt = 0;
117             while (_st.hasMoreElements()) {
118                 result[cnt] = _st.nextToken();
119                 cnt += 1;
120             }
121         }
122
123         return result;
124     }
125
126     /**
127      * Process the blog entries
128      *
129      * @param httpServletRequest Request
130      * @param httpServletResponse Response
131      * @param blog {@link Blog} instance
132      * @param context Context
133      * @param entries Blog entries retrieved for the particular request
134      * @return Modified set of blog entries
135      * @throws PluginException If there is an error processing the blog entries
136      */

137     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
138         String JavaDoc referer = httpServletRequest.getHeader(HEADER_REFERER);
139
140         if (referer != null && referer.matches(EXPRESSSION_GOOGLE)) {
141             String JavaDoc[] searchwords = extractQueryTokens(referer);
142
143             if (searchwords != null) {
144                 Pattern JavaDoc hasTags = Pattern.compile(EXPRESSION_HASTAGS);
145
146                 for (int x = 0; x < entries.length; x++) {
147                     Entry entry = entries[x];
148                     Matcher JavaDoc matcher = hasTags.matcher(entry.getDescription());
149                     boolean isHtml = matcher.find();
150                     for (int y = 0; y < searchwords.length; y++) {
151                         String JavaDoc word = searchwords[y];
152                         if (!isHtml) {
153                             entry.setDescription(entry.getDescription().replaceAll(START_BOUNDRY + word + END_BOUNDRY, HIGHLIGHT_PLAINTEXT));
154                         } else {
155                             entry.setDescription(entry.getDescription().replaceAll(EXPRESSION_HTMLPREFIX + START_BOUNDRY + word + END_BOUNDRY, HIGHLIGHT_HTML));
156                         }
157                     }
158                 }
159             }
160         }
161
162         return entries;
163     }
164
165     /**
166      * Perform any cleanup for the plugin. Called after {@link #process}.
167      *
168      * @throws PluginException If there is an error performing cleanup for this plugin
169      */

170     public void cleanup() throws PluginException {
171     }
172
173     /**
174      * Called when BlojsomServlet is taken out of service
175      *
176      * @throws PluginException If there is an error in finalizing this plugin
177      */

178     public void destroy() throws PluginException {
179     }
180 }
181
Popular Tags