KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > ui > rendering > model > UtilitiesModel


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. The ASF licenses this file to You
4  * under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License. For additional information regarding
15  * copyright in this work, please see the NOTICE file in the top level
16  * directory of this distribution.
17  */

18
19 package org.apache.roller.ui.rendering.model;
20
21 import java.io.UnsupportedEncodingException JavaDoc;
22 import java.net.URLDecoder JavaDoc;
23 import java.net.URLEncoder JavaDoc;
24 import java.text.SimpleDateFormat JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.TimeZone JavaDoc;
28 import java.util.regex.Matcher JavaDoc;
29 import java.util.regex.Pattern JavaDoc;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31 import org.apache.commons.lang.StringEscapeUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.roller.RollerException;
36 import org.apache.roller.pojos.wrapper.WeblogEntryDataWrapper;
37 import org.apache.roller.pojos.wrapper.WebsiteDataWrapper;
38 import org.apache.roller.ui.core.RollerSession;
39 import org.apache.roller.ui.rendering.util.WeblogRequest;
40 import org.apache.roller.util.DateUtil;
41 import org.apache.roller.util.RegexUtil;
42 import org.apache.roller.util.Utilities;
43
44 /**
45  * Model which provides access to a set of general utilities.
46  */

47 public class UtilitiesModel implements Model {
48     
49     private static Log log = LogFactory.getLog(UtilitiesModel.class);
50     
51     private static Pattern JavaDoc mLinkPattern =
52             Pattern.compile("<a HREF=.*?>", Pattern.CASE_INSENSITIVE);
53     private static final Pattern JavaDoc OPENING_B_TAG_PATTERN =
54             Pattern.compile("&lt;b&gt;", Pattern.CASE_INSENSITIVE);
55     private static final Pattern JavaDoc CLOSING_B_TAG_PATTERN =
56             Pattern.compile("&lt;/b&gt;", Pattern.CASE_INSENSITIVE);
57     private static final Pattern JavaDoc OPENING_I_TAG_PATTERN =
58             Pattern.compile("&lt;i&gt;", Pattern.CASE_INSENSITIVE);
59     private static final Pattern JavaDoc CLOSING_I_TAG_PATTERN =
60             Pattern.compile("&lt;/i&gt;", Pattern.CASE_INSENSITIVE);
61     private static final Pattern JavaDoc OPENING_BLOCKQUOTE_TAG_PATTERN =
62             Pattern.compile("&lt;blockquote&gt;", Pattern.CASE_INSENSITIVE);
63     private static final Pattern JavaDoc CLOSING_BLOCKQUOTE_TAG_PATTERN =
64             Pattern.compile("&lt;/blockquote&gt;", Pattern.CASE_INSENSITIVE);
65     private static final Pattern JavaDoc BR_TAG_PATTERN =
66             Pattern.compile("&lt;br */*&gt;", Pattern.CASE_INSENSITIVE);
67     private static final Pattern JavaDoc OPENING_P_TAG_PATTERN =
68             Pattern.compile("&lt;p&gt;", Pattern.CASE_INSENSITIVE);
69     private static final Pattern JavaDoc CLOSING_P_TAG_PATTERN =
70             Pattern.compile("&lt;/p&gt;", Pattern.CASE_INSENSITIVE);
71     private static final Pattern JavaDoc OPENING_PRE_TAG_PATTERN =
72             Pattern.compile("&lt;pre&gt;", Pattern.CASE_INSENSITIVE);
73     private static final Pattern JavaDoc CLOSING_PRE_TAG_PATTERN =
74             Pattern.compile("&lt;/pre&gt;", Pattern.CASE_INSENSITIVE);
75     private static final Pattern JavaDoc OPENING_UL_TAG_PATTERN =
76             Pattern.compile("&lt;ul&gt;", Pattern.CASE_INSENSITIVE);
77     private static final Pattern JavaDoc CLOSING_UL_TAG_PATTERN =
78             Pattern.compile("&lt;/ul&gt;", Pattern.CASE_INSENSITIVE);
79     private static final Pattern JavaDoc OPENING_OL_TAG_PATTERN =
80             Pattern.compile("&lt;ol&gt;", Pattern.CASE_INSENSITIVE);
81     private static final Pattern JavaDoc CLOSING_OL_TAG_PATTERN =
82             Pattern.compile("&lt;/ol&gt;", Pattern.CASE_INSENSITIVE);
83     private static final Pattern JavaDoc OPENING_LI_TAG_PATTERN =
84             Pattern.compile("&lt;li&gt;", Pattern.CASE_INSENSITIVE);
85     private static final Pattern JavaDoc CLOSING_LI_TAG_PATTERN =
86             Pattern.compile("&lt;/li&gt;", Pattern.CASE_INSENSITIVE);
87     private static final Pattern JavaDoc CLOSING_A_TAG_PATTERN =
88             Pattern.compile("&lt;/a&gt;", Pattern.CASE_INSENSITIVE);
89     private static final Pattern JavaDoc OPENING_A_TAG_PATTERN =
90             Pattern.compile("&lt;a HREF=.*?&gt;", Pattern.CASE_INSENSITIVE);
91     private static final Pattern JavaDoc QUOTE_PATTERN =
92             Pattern.compile("&quot;", Pattern.CASE_INSENSITIVE);
93     
94     private HttpServletRequest JavaDoc request = null;
95     private TimeZone JavaDoc tz = null;
96     
97     
98     /** Template context name to be used for model */
99     public String JavaDoc getModelName() {
100         return "utils";
101     }
102     
103     
104     /** Init page model based on request */
105     public void init(Map JavaDoc initData) throws RollerException {
106         
107         // extract request object
108
this.request = (HttpServletRequest JavaDoc) initData.get("request");
109
110         // extract timezone if available
111
WeblogRequest weblogRequest = (WeblogRequest)initData.get("weblogRequest");
112         if (weblogRequest != null && weblogRequest.getWeblog() != null) {
113             tz = weblogRequest.getWeblog().getTimeZoneInstance();
114         }
115     }
116      
117     
118     //---------------------------------------------------- Authentication utils
119

120     public boolean isUserAuthorizedToAuthor(WebsiteDataWrapper weblog) {
121         try {
122             RollerSession rses = RollerSession.getRollerSession(request);
123             if (rses.getAuthenticatedUser() != null) {
124                 return rses.isUserAuthorizedToAuthor(weblog.getPojo());
125             }
126         } catch (Exception JavaDoc e) {
127             log.warn("ERROR: checking user authorization", e);
128         }
129         return false;
130     }
131     
132     public boolean isUserAuthorizedToAdmin(WebsiteDataWrapper weblog) {
133         try {
134             RollerSession rses = RollerSession.getRollerSession(request);
135             if (rses.getAuthenticatedUser() != null) {
136                 return rses.isUserAuthorizedToAdmin(weblog.getPojo());
137             }
138         } catch (Exception JavaDoc e) {
139             log.warn("ERROR: checking user authorization", e);
140         }
141         return false;
142     }
143     
144     public boolean isUserAuthenticated() {
145         return (request.getUserPrincipal() != null);
146     }
147         
148     //-------------------------------------------------------------- Date utils
149
/**
150      * Return date for current time.
151      */

152     public static Date JavaDoc getNow() {
153         return new Date JavaDoc();
154     }
155     
156     /**
157      * Format date using SimpleDateFormat format string.
158      */

159     public String JavaDoc formatDate(Date JavaDoc d, String JavaDoc fmt) {
160         if(d == null || fmt == null)
161             return fmt;
162         
163         SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc(fmt);
164         if (tz != null) {
165             format.setTimeZone(tz);
166         }
167         return format.format(d);
168     }
169     
170     /**
171      * Format date using SimpleDateFormat format string.
172      */

173     public static String JavaDoc formatDate(Date JavaDoc d, String JavaDoc fmt, TimeZone JavaDoc tzOverride) {
174         if(d == null || fmt == null)
175             return fmt;
176         
177         SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc(fmt);
178         format.setTimeZone(tzOverride);
179         return format.format(d);
180     }
181     
182     /**
183      * Format date in ISO-8601 format.
184      */

185     public static String JavaDoc formatIso8601Date(Date JavaDoc d) {
186         return DateUtil.formatIso8601(d);
187     }
188     
189     /**
190      * Format date in ISO-8601 format.
191      */

192     public static String JavaDoc formatIso8601Day(Date JavaDoc d) {
193         return DateUtil.formatIso8601Day(d);
194     }
195     
196     /**
197      * Return a date in RFC-822 format.
198      */

199     public static String JavaDoc formatRfc822Date(Date JavaDoc date) {
200         return DateUtil.formatRfc822(date);
201     }
202     
203     /**
204      * Return a date in RFC-822 format.
205      */

206     public static String JavaDoc format8charsDate(Date JavaDoc date) {
207         return DateUtil.format8chars(date);
208     }
209
210     //------------------------------------------------------------ String utils
211

212     public static boolean isEmpty(String JavaDoc str) {
213         if (str == null) return true;
214         return "".equals(str.trim());
215     }
216     
217     public static boolean isNotEmpty(String JavaDoc str) {
218         return !isEmpty(str);
219     }
220     
221     public static String JavaDoc[] split(String JavaDoc str1, String JavaDoc str2) {
222         return StringUtils.split(str1, str2);
223     }
224     
225     
226     public static boolean equals(String JavaDoc str1, String JavaDoc str2) {
227         return StringUtils.equals(str1, str2);
228     }
229     
230     public static boolean isAlphanumeric(String JavaDoc str) {
231         return StringUtils.isAlphanumeric(str);
232     }
233     
234     public static String JavaDoc[] stripAll(String JavaDoc[] strs) {
235         return StringUtils.stripAll(strs);
236     }
237     
238     public static String JavaDoc left(String JavaDoc str, int length) {
239         return StringUtils.left(str, length);
240     }
241     
242     public static String JavaDoc escapeHTML(String JavaDoc str) {
243         return StringEscapeUtils.escapeHtml(str);
244     }
245     
246     public static String JavaDoc unescapeHTML(String JavaDoc str) {
247         return StringEscapeUtils.unescapeHtml(str);
248     }
249     
250     public static String JavaDoc escapeXML(String JavaDoc str) {
251         return StringEscapeUtils.escapeXml(str);
252     }
253     
254     public static String JavaDoc unescapeXML(String JavaDoc str) {
255         return StringEscapeUtils.unescapeXml(str);
256     }
257     
258     public static String JavaDoc replace(String JavaDoc src, String JavaDoc target, String JavaDoc rWith) {
259         return StringUtils.replace(src, target, rWith);
260     }
261     
262     public static String JavaDoc replace(String JavaDoc src, String JavaDoc target, String JavaDoc rWith, int maxCount) {
263         return StringUtils.replace(src, target, rWith, maxCount);
264     }
265     
266     private static String JavaDoc replace(String JavaDoc string, Pattern JavaDoc pattern, String JavaDoc replacement) {
267         Matcher JavaDoc m = pattern.matcher(string);
268         return m.replaceAll(replacement);
269     }
270     
271     /**
272      * Remove occurences of html, defined as any text
273      * between the characters "&lt;" and "&gt;". Replace
274      * any HTML tags with a space.
275      */

276     public static String JavaDoc removeHTML(String JavaDoc str) {
277         return removeHTML(str, true);
278     }
279     
280     /**
281      * Remove occurences of html, defined as any text
282      * between the characters "&lt;" and "&gt;".
283      * Optionally replace HTML tags with a space.
284      */

285     public static String JavaDoc removeHTML(String JavaDoc str, boolean addSpace) {
286         return Utilities.removeHTML(str, addSpace);
287     }
288         
289     /**
290      * Autoformat.
291      */

292     public static String JavaDoc autoformat(String JavaDoc s) {
293         String JavaDoc ret = StringUtils.replace(s, "\n", "<br />");
294         return ret;
295     }
296     /**
297      * Strips HTML and truncates.
298      */

299     public static String JavaDoc truncate(
300             String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
301         // strip markup from the string
302
String JavaDoc str2 = removeHTML(str, false);
303         
304         // quickly adjust the upper if it is set lower than 'lower'
305
if (upper < lower) {
306             upper = lower;
307         }
308         
309         // now determine if the string fits within the upper limit
310
// if it does, go straight to return, do not pass 'go' and collect $200
311
if(str2.length() > upper) {
312             // the magic location int
313
int loc;
314             
315             // first we determine where the next space appears after lower
316
loc = str2.lastIndexOf(' ', upper);
317             
318             // now we'll see if the location is greater than the lower limit
319
if(loc >= lower) {
320                 // yes it was, so we'll cut it off here
321
str2 = str2.substring(0, loc);
322             } else {
323                 // no it wasnt, so we'll cut it off at the upper limit
324
str2 = str2.substring(0, upper);
325                 loc = upper;
326             }
327             
328             // the string was truncated, so we append the appendToEnd String
329
str2 = str2 + appendToEnd;
330         }
331         
332         return str2;
333     }
334     
335     public static String JavaDoc truncateNicely(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
336         return Utilities.truncateNicely(str, lower, upper, appendToEnd);
337     }
338     
339     public static String JavaDoc truncateText(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
340         // strip markup from the string
341
String JavaDoc str2 = removeHTML(str, false);
342         boolean diff = (str2.length() < str.length());
343         
344         // quickly adjust the upper if it is set lower than 'lower'
345
if(upper < lower) {
346             upper = lower;
347         }
348         
349         // now determine if the string fits within the upper limit
350
// if it does, go straight to return, do not pass 'go' and collect $200
351
if(str2.length() > upper) {
352             // the magic location int
353
int loc;
354             
355             // first we determine where the next space appears after lower
356
loc = str2.lastIndexOf(' ', upper);
357             
358             // now we'll see if the location is greater than the lower limit
359
if(loc >= lower) {
360                 // yes it was, so we'll cut it off here
361
str2 = str2.substring(0, loc);
362             } else {
363                 // no it wasnt, so we'll cut it off at the upper limit
364
str2 = str2.substring(0, upper);
365                 loc = upper;
366             }
367             // the string was truncated, so we append the appendToEnd String
368
str = str2 + appendToEnd;
369         }
370         return str;
371     }
372     
373     public static String JavaDoc hexEncode(String JavaDoc str) {
374         if (StringUtils.isEmpty(str)) return str;
375         
376         return RegexUtil.encode(str);
377     }
378     
379     public static String JavaDoc encodeEmail(String JavaDoc str) {
380         return str!=null ? RegexUtil.encodeEmail(str) : null;
381     }
382     
383     /**
384      * URL encoding.
385      * @param s a string to be URL-encoded
386      * @return URL encoding of s using character encoding UTF-8; null if s is null.
387      */

388     public static final String JavaDoc encode(String JavaDoc s) {
389         try {
390             if (s != null)
391                 return URLEncoder.encode(s, "UTF-8");
392             else
393                 return s;
394         } catch (UnsupportedEncodingException JavaDoc e) {
395             // Java Spec requires UTF-8 be in all Java environments, so this should not happen
396
return s;
397         }
398     }
399     
400     /**
401      * URL decoding.
402      * @param s a URL-encoded string to be URL-decoded
403      * @return URL decoded value of s using character encoding UTF-8; null if s is null.
404      */

405     public static final String JavaDoc decode(String JavaDoc s) {
406         try {
407             if (s != null)
408                 return URLDecoder.decode(s, "UTF-8");
409             else
410                 return s;
411         } catch (UnsupportedEncodingException JavaDoc e) {
412             // Java Spec requires UTF-8 be in all Java environments, so this should not happen
413
return s;
414         }
415     }
416         
417     /**
418      * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML.
419      */

420     public static String JavaDoc addNofollow(String JavaDoc html) {
421         if (html == null || html.length() == 0) {
422             return html;
423         }
424         Matcher JavaDoc m = mLinkPattern.matcher(html);
425         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
426         while (m.find()) {
427             int start = m.start();
428             int end = m.end();
429             String JavaDoc link = html.substring(start, end);
430             buf.append(html.substring(0, start));
431             if (link.indexOf("rel=\"nofollow\"") == -1) {
432                 buf.append(
433                         link.substring(0, link.length() - 1) + " rel=\"nofollow\">");
434             } else {
435                 buf.append(link);
436             }
437             html = html.substring(end, html.length());
438             m = mLinkPattern.matcher(html);
439         }
440         buf.append(html);
441         return buf.toString();
442     }
443     
444     /**
445      * Transforms the given String into a subset of HTML displayable on a web
446      * page. The subset includes &lt;b&gt;, &lt;i&gt;, &lt;p&gt;, &lt;br&gt;,
447      * &lt;pre&gt; and &lt;a href&gt; (and their corresponding end tags).
448      *
449      * @param s the String to transform
450      * @return the transformed String
451      */

452     public static String JavaDoc transformToHTMLSubset(String JavaDoc s) {
453         
454         if (s == null) {
455             return null;
456         }
457         
458         s = replace(s, OPENING_B_TAG_PATTERN, "<b>");
459         s = replace(s, CLOSING_B_TAG_PATTERN, "</b>");
460         s = replace(s, OPENING_I_TAG_PATTERN, "<i>");
461         s = replace(s, CLOSING_I_TAG_PATTERN, "</i>");
462         s = replace(s, OPENING_BLOCKQUOTE_TAG_PATTERN, "<blockquote>");
463         s = replace(s, CLOSING_BLOCKQUOTE_TAG_PATTERN, "</blockquote>");
464         s = replace(s, BR_TAG_PATTERN, "<br />");
465         s = replace(s, OPENING_P_TAG_PATTERN, "<p>");
466         s = replace(s, CLOSING_P_TAG_PATTERN, "</p>");
467         s = replace(s, OPENING_PRE_TAG_PATTERN, "<pre>");
468         s = replace(s, CLOSING_PRE_TAG_PATTERN, "</pre>");
469         s = replace(s, OPENING_UL_TAG_PATTERN, "<ul>");
470         s = replace(s, CLOSING_UL_TAG_PATTERN, "</ul>");
471         s = replace(s, OPENING_OL_TAG_PATTERN, "<ol>");
472         s = replace(s, CLOSING_OL_TAG_PATTERN, "</ol>");
473         s = replace(s, OPENING_LI_TAG_PATTERN, "<li>");
474         s = replace(s, CLOSING_LI_TAG_PATTERN, "</li>");
475         s = replace(s, QUOTE_PATTERN, "\"");
476         
477         // HTTP links
478
s = replace(s, CLOSING_A_TAG_PATTERN, "</a>");
479         Matcher JavaDoc m = OPENING_A_TAG_PATTERN.matcher(s);
480         while (m.find()) {
481             int start = m.start();
482             int end = m.end();
483             String JavaDoc link = s.substring(start, end);
484             link = "<" + link.substring(4, link.length() - 4) + ">";
485             s = s.substring(0, start) + link + s.substring(end, s.length());
486             m = OPENING_A_TAG_PATTERN.matcher(s);
487         }
488         
489         // escaped angle brackets
490
s = s.replaceAll("&amp;lt;", "&lt;");
491         s = s.replaceAll("&amp;gt;", "&gt;");
492         s = s.replaceAll("&amp;#", "&#");
493         
494         return s;
495     }
496     
497     /**
498      * Convert a byte array into a Base64 string (as used in mime formats)
499      */

500     public static String JavaDoc toBase64(byte[] aValue) {
501         
502         final String JavaDoc m_strBase64Chars =
503                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
504         
505         int byte1;
506         int byte2;
507         int byte3;
508         int iByteLen = aValue.length;
509         StringBuffer JavaDoc tt = new StringBuffer JavaDoc();
510         
511         for (int i = 0; i < iByteLen; i += 3) {
512             boolean bByte2 = (i + 1) < iByteLen;
513             boolean bByte3 = (i + 2) < iByteLen;
514             byte1 = aValue[i] & 0xFF;
515             byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0;
516             byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0;
517             
518             tt.append(m_strBase64Chars.charAt(byte1 / 4));
519             tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16)));
520             tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '='));
521             tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '='));
522         }
523         
524         return tt.toString();
525     }
526        
527 }
528
Popular Tags