KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portlet > forums > helper > ForumsTools


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Forums JBoss Portlet *
6  * *
7  * Distributable under GPL license. *
8  * See terms of license at gnu.org. *
9  * *
10  *****************************************/

11 package org.jboss.portlet.forums.helper;
12
13 import java.lang.reflect.Field JavaDoc;
14 import java.lang.reflect.Method JavaDoc;
15 import java.lang.reflect.Modifier JavaDoc;
16 import java.sql.Connection JavaDoc;
17 import java.sql.PreparedStatement JavaDoc;
18 import java.sql.ResultSet JavaDoc;
19 import java.sql.SQLException JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.List JavaDoc;
24
25 import javax.ejb.EJBLocalHome JavaDoc;
26 import javax.ejb.EJBLocalObject JavaDoc;
27
28 import org.apache.log4j.Logger;
29 import org.apache.lucene.analysis.standard.StandardAnalyzer;
30 import org.apache.lucene.queryParser.ParseException;
31 import org.apache.lucene.queryParser.QueryParser;
32 import org.apache.lucene.search.BooleanQuery;
33 import org.apache.lucene.search.Query;
34 import org.jboss.portal.common.util.Tools;
35 import org.jboss.portlet.forums.ForumsConstants;
36 import org.jboss.portlet.forums.model.Category;
37 import org.jboss.portlet.forums.model.Forum;
38
39 /**
40  * @author <a HREF="mailto:julien@jboss.org">Julien Viet</a>
41  * @version $Revision: 1.5 $
42  */

43 public class ForumsTools
44 {
45    private static final Logger log = Logger.getLogger(ForumsTools.class);
46    private static final StandardAnalyzer analyzer = new StandardAnalyzer();
47
48    /**
49     * DOCUMENT_ME
50     *
51     * @param buffer DOCUMENT_ME
52     * @param name DOCUMENT_ME
53     * @param value DOCUMENT_ME
54     * @param selected DOCUMENT_ME
55     */

56    public static void radioButton(StringBuffer JavaDoc buffer,
57                                   String JavaDoc name,
58                                   String JavaDoc value,
59                                   boolean selected)
60    {
61       buffer.append("<input type=\"radio\" name=\"").append(name).append("\" value=\"").append(value).append("\"")
62             .append(selected ? " checked=\"checked\"/>" : "/>");
63    }
64
65    /**
66     * DOCUMENT_ME
67     *
68     * @param url DOCUMENT_ME
69     * @param target DOCUMENT_ME
70     * @param image DOCUMENT_ME
71     * @param title DOCUMENT_ME
72     * @param alt DOCUMENT_ME
73     *
74     * @return DOCUMENT_ME
75     */

76    public static String JavaDoc createImageLink(String JavaDoc url,
77                                         String JavaDoc target,
78                                         String JavaDoc image,
79                                         String JavaDoc title,
80                                         String JavaDoc alt)
81    {
82       return "<a HREF=\"" + url + "\" target=\"" + target + "\"><img SRC=\"" + image + "\" " + "alt=\"" + alt
83              + "\" title=\"" + title + "\" border=\"0\"></a>";
84    }
85
86    /**
87     * DOCUMENT_ME
88     *
89     * @param url DOCUMENT_ME
90     * @param image DOCUMENT_ME
91     * @param title DOCUMENT_ME
92     * @param alt DOCUMENT_ME
93     *
94     * @return DOCUMENT_ME
95     */

96    public static String JavaDoc createImageLink(String JavaDoc url,
97                                         String JavaDoc image,
98                                         String JavaDoc title,
99                                         String JavaDoc alt)
100    {
101       return "<a HREF=\"" + url + "\"><img SRC=\"" + image + "\" " + "alt=\"" + alt + "\" title=\"" + title
102              + "\" border=\"0\"></a>";
103    }
104
105    /**
106     * DOCUMENT_ME
107     *
108     * @param url DOCUMENT_ME
109     * @param image DOCUMENT_ME
110     * @param title DOCUMENT_ME
111     *
112     * @return DOCUMENT_ME
113     */

114    public static String JavaDoc createImageLink(String JavaDoc url,
115                                         String JavaDoc image,
116                                         String JavaDoc title)
117    {
118       return createImageLink(url, image, title, title);
119    }
120
121    /**
122     * DOCUMENT_ME
123     *
124     * @param url DOCUMENT_ME
125     * @param text DOCUMENT_ME
126     *
127     * @return DOCUMENT_ME
128     */

129    public static String JavaDoc createLink(String JavaDoc url,
130                                    String JavaDoc text)
131    {
132       return "<a HREF=\"" + url + "\">" + text + "</a>";
133    }
134
135    /**
136     * DOCUMENT_ME
137     *
138     * @param url DOCUMENT_ME
139     * @param target DOCUMENT_ME
140     * @param text DOCUMENT_ME
141     *
142     * @return DOCUMENT_ME
143     */

144    public static String JavaDoc createLink(String JavaDoc url,
145                                    String JavaDoc target,
146                                    String JavaDoc text)
147    {
148       return "<a HREF=\"" + url + "\" target=\"" + target + "\">" + text + "</a>";
149    }
150
151    /**
152     * DOCUMENT_ME
153     *
154     * @param text DOCUMENT_ME
155     * @param field DOCUMENT_ME
156     * @param isOr DOCUMENT_ME
157     *
158     * @return DOCUMENT_ME
159     */

160    public static Query createQuery(String JavaDoc text,
161                                    String JavaDoc field,
162                                    boolean isOr)
163    {
164       try
165       {
166          QueryParser parser = new QueryParser(field, analyzer);
167          parser.setOperator(isOr ? QueryParser.DEFAULT_OPERATOR_OR : QueryParser.DEFAULT_OPERATOR_AND);
168          return parser.parse(text);
169       }
170       catch (ParseException e)
171       {
172          log.error("Cannot parse query " + text, e);
173          return DUMMY_QUERY;
174       }
175    }
176
177    private static final Query DUMMY_QUERY = new BooleanQuery();
178
179    /**
180     * DOCUMENT_ME
181     *
182     * @param forums DOCUMENT_ME
183     * @param selectedId DOCUMENT_ME
184     *
185     * @return DOCUMENT_ME
186     */

187    public static String JavaDoc listForums(List JavaDoc forums,
188                                    int selectedId)
189    {
190       Iterator JavaDoc result = forums.iterator();
191
192       // hold the result
193
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
194
195       // do the work
196
while (result.hasNext())
197       {
198          Forum forum = (Forum) result.next();
199          buffer.append("<option value=\"").append(forum.getID()).append("\"")
200                .append((selectedId == forum.getID().intValue()) ? " selected=\"selected\"" : "").append(">")
201                .append(forum.getName()).append("</option>\n");
202       }
203
204       return buffer.toString();
205    }
206
207    /**
208     * DOCUMENT_ME
209     *
210     * @param categories DOCUMENT_ME
211     * @param selectedId DOCUMENT_ME
212     *
213     * @return DOCUMENT_ME
214     */

215    public static String JavaDoc listCategories(List JavaDoc categories,
216                                        int selectedId)
217    {
218       Iterator JavaDoc result = categories.iterator();
219
220       // hold the result
221
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
222
223       // do the work
224
while (result.hasNext())
225       {
226          Category category = (Category) result.next();
227          buffer.append("<option value=\"").append(category.getID()).append("\"")
228                .append((selectedId == category.getID().intValue()) ? " selected=\"selected\"" : "").append(">")
229                .append(category.getTitle()).append("</option>\n");
230       }
231
232       return buffer.toString();
233    }
234
235    /**
236     * DOCUMENT_ME
237     *
238     * @param name DOCUMENT_ME
239     * @param days DOCUMENT_ME
240     *
241     * @return DOCUMENT_ME
242     */

243    public static String JavaDoc selectDays(String JavaDoc name,
244                                    int days)
245    {
246       StringBuffer JavaDoc selectDays = new StringBuffer JavaDoc("<select name=\"").append(name).append("\">");
247       for (int i = 0; i < ForumsConstants.PREVIOUS_DAYS.length; i++)
248       {
249          selectDays.append("<option value=\"").append(ForumsConstants.PREVIOUS_DAYS[i]).append("\"")
250                    .append((days == ForumsConstants.PREVIOUS_DAYS[i]) ? " selected=\"selected\"" : "").append(">")
251                    .append(ForumsConstants.PREVIOUS_DAYS_TEXT_TOPICS[i]).append("</option>");
252       }
253
254       selectDays.append("</select>");
255       return selectDays.toString();
256    }
257
258    /**
259     * Performs a generic batch update.
260     */

261    public static void batchUpdate(Connection JavaDoc conn,
262                                   String JavaDoc updateQuery,
263                                   String JavaDoc selectQuery,
264                                   int size)
265    throws SQLException JavaDoc
266    {
267       PreparedStatement JavaDoc updater = null;
268       PreparedStatement JavaDoc selecter = null;
269       ResultSet JavaDoc rs = null;
270       try
271       {
272          updater = conn.prepareStatement(updateQuery);
273
274          // not yet implemented in MySQL Connector/J driver 3.0.9
275
// int size = updater.getParameterMetaData().getParameterCount();
276
selecter = conn.prepareStatement(selectQuery);
277          rs = selecter.executeQuery();
278          while (rs.next())
279          {
280             for (int i = 1; i <= size; i++)
281             {
282                updater.setObject(i,
283                                  rs.getObject(i));
284             }
285
286             updater.executeUpdate();
287          }
288       }
289       finally
290       {
291          if (!conn.getAutoCommit())
292          {
293             conn.commit();
294          }
295
296          Tools.safeClose(rs);
297          Tools.safeClose(updater);
298          Tools.safeClose(selecter);
299       }
300    }
301
302 // /**
303
// * DOCUMENT_ME
304
// *
305
// * @param authCan DOCUMENT_ME
306
// * @param forum DOCUMENT_ME
307
// * @param loggedIn DOCUMENT_ME
308
// * @param level DOCUMENT_ME
309
// */
310
// public static void authCan(StringBuffer authCan,
311
// Forum forum,
312
// boolean loggedIn,
313
// Level level)
314
// {
315
// /*
316
// authCan.append(Auth.hasLevel(forum.getAuth().getPost(), loggedIn, level) ? "${bb.Rules_post_can}" : "${bb.Rules_post_cannot}").
317
// append("<br/>").
318
// append(Auth.hasLevel(forum.getAuth().getReply(), loggedIn, level) ? "${bb.Rules_reply_can}" : "${bb.Rules_reply_cannot}").
319
// append("<br/>").
320
// append(Auth.hasLevel(forum.getAuth().getEdit(), loggedIn, level) ? "${bb.Rules_edit_can}" : "${bb.Rules_edit_cannot}").
321
// append("<br/>").
322
// append(Auth.hasLevel(forum.getAuth().getDelete(), loggedIn, level) ? "${bb.Rules_delete_can}" : "${bb.Rules_delete_cannot}").
323
// append("<br/>").
324
// append(Auth.hasLevel(forum.getAuth().getVote(), loggedIn, level) ? "${bb.Rules_vote_can}" : "${bb.Rules_vote_cannot}").
325
// append("<br/>");
326
// */
327
// }
328

329    /**
330     * DOCUMENT_ME
331     *
332     * @param start DOCUMENT_ME
333     * @param size DOCUMENT_ME
334     * @param per DOCUMENT_ME
335     *
336     * @return DOCUMENT_ME
337     */

338    public static String JavaDoc pageNumber(int start,
339                                    int size,
340                                    int per)
341    {
342       return "${bb.Page_of_0}" + (int) Math.ceil((double) start / (double) (per)) + "${bb.Page_of_1}"
343              + (int) Math.ceil((double) size / (double) per) + "${bb.Page_of_2}";
344    }
345
346    /**
347     *
348     * @param home where the EJBs are taken
349     * @param getter how to get some info about the EJB
350     * @param key the key used to set the skip or select the item in the list according the all parameter
351     * @param all force all the items to be displayed
352     * @return
353     */

354    public static String JavaDoc selectEJBs(EJBLocalHome JavaDoc home,
355                                    Method JavaDoc getter,
356                                    Object JavaDoc key,
357                                    boolean all)
358    {
359       try
360       {
361          // empty args for the reflection call
362
Object JavaDoc[] empty = new Object JavaDoc[0];
363
364          // the findAll method will give us all the EJBs
365
Method JavaDoc findAll = home.getClass().getMethod("findAll",
366                                                       new Class JavaDoc[0]);
367          Iterator JavaDoc result = ((Collection JavaDoc) findAll.invoke(home, empty)).iterator();
368
369          // hold the result
370
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
371
372          // do the work
373
while (result.hasNext())
374          {
375             EJBLocalObject JavaDoc ejb = (EJBLocalObject JavaDoc) result.next();
376             Object JavaDoc ejbKey = ejb.getPrimaryKey();
377             boolean equals = ejbKey.equals(key);
378             if (all || equals)
379             {
380                buffer.append("<option value=\"").append(ejbKey).append("\"")
381                      .append(equals ? " selected=\"selected\"" : "").append(">").append(getter.invoke(ejb, empty))
382                      .append("</option>\n");
383             }
384          }
385
386          // return the string buffer content
387
return buffer.toString();
388       }
389       catch (Exception JavaDoc e)
390       {
391          log.error("Cannot list ejbs", e);
392          return "";
393       }
394    }
395
396    /**
397     * DOCUMENT_ME
398     *
399     * @param clazz DOCUMENT_ME
400     * @param prefix DOCUMENT_ME
401     *
402     * @return DOCUMENT_ME
403     */

404    public static String JavaDoc[][] collectFields(Class JavaDoc clazz,
405                                           String JavaDoc prefix)
406    {
407       Field JavaDoc[] fields = clazz.getDeclaredFields();
408       List JavaDoc values = new ArrayList JavaDoc(fields.length);
409       for (int i = 0; i < fields.length; i++)
410       {
411          Field JavaDoc field = fields[i];
412          int modifier = field.getModifiers();
413          if (field.getName().startsWith(prefix)
414              && Modifier.isFinal(modifier)
415              && Modifier.isPublic(modifier)
416              && Modifier.isStatic(modifier))
417          {
418             try
419             {
420                values.add(new String JavaDoc[]
421                           {
422                              field.getName(),
423                              (String JavaDoc) field.get(null)
424                           });
425             }
426             catch (Exception JavaDoc ignore)
427             {
428                Logger.getLogger(clazz).error("", ignore);
429             }
430          }
431       }
432
433       return (String JavaDoc[][]) values.toArray(new String JavaDoc[values.size()][]);
434    }
435
436    /**
437     * DOCUMENT_ME
438     *
439     * @param c DOCUMENT_ME
440     *
441     * @return DOCUMENT_ME
442     */

443    public static Object JavaDoc head(Collection JavaDoc c)
444    {
445       Iterator JavaDoc iterator = c.iterator();
446       return iterator.hasNext() ? iterator.next() : null;
447    }
448
449    /**
450     * DOCUMENT_ME
451     *
452     * @param format_1_00 DOCUMENT_ME
453     * @param forumId DOCUMENT_ME
454     *
455     * @return DOCUMENT_ME
456     */

457    public static final String JavaDoc computeCacheKey(boolean format_1_00,
458                                               String JavaDoc forumId)
459    {
460       return (format_1_00 ? "rss/1.00" : "rss/0.91") + ((forumId != null) ? ("/" + forumId) : "");
461    }
462
463    /**
464     * DOCUMENT_ME
465     *
466     * @param s DOCUMENT_ME
467     *
468     * @return DOCUMENT_ME
469     */

470    public static boolean isNullOrBlank(String JavaDoc s)
471    {
472       if (s != null)
473       {
474          for (int i = 0; i < s.length(); i++)
475          {
476             if (!Character.isWhitespace(s.charAt(i)))
477             {
478                return false;
479             }
480          }
481       }
482
483       return true;
484    }
485 }
Popular Tags