KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > javabb > lucene > search > CSSFormatter


1 /*
2  * Copyright 28/03/2005 - Vicinity - www.vicinity.com.br All rights reserveds
3  */

4 package org.javabb.lucene.search;
5
6
7 import java.util.Iterator JavaDoc;
8 import java.util.Map JavaDoc;
9
10 import org.apache.lucene.search.highlight.Formatter;
11 import org.apache.lucene.search.highlight.TokenGroup;
12
13
14 /**
15  * Simple {@link org.apache.lucene.search.highlight.Formatter Formatter} to
16  * highlight a term with a <a HREF="http://www.w3c.org/CSS">Cascade Style Sheet</a>
17  * class. With CSS class you can alter highlight form easily.
18  *
19  * @author Marcos Silva Pereira - marcos.pereira@vicinity.com.br
20  *
21  * @since 05/03/2005
22  *
23  * @version $Id$
24  *
25  * @see org.apache.lucene.search.highlight.SpanGradientFormatter
26  */

27 public class CSSFormatter implements Formatter {
28
29     private String JavaDoc cssClass;
30
31     private String JavaDoc cssStyle;
32
33     /**
34      * @param cssClass
35      */

36     public CSSFormatter ( String JavaDoc cssClass ) {
37
38         this.cssClass = cssClass;
39
40     }
41
42     /**
43      * @param properties
44      */

45     public CSSFormatter ( Map JavaDoc properties ) {
46
47         cssStyle = constructStyle(properties);
48
49     }
50
51     /**
52      * @see Formatter#highlightTerm(String, TokenGroup)
53      */

54     public String JavaDoc highlightTerm( String JavaDoc originalText, TokenGroup tokenGroup ) {
55
56         if (tokenGroup.getTotalScore() > 0) {
57
58             return doHighlightTerm(originalText);
59
60         }
61
62         return originalText;
63
64     }
65
66     private String JavaDoc doHighlightTerm( String JavaDoc originalText ) {
67
68         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
69
70         if ((cssClass != null) && !cssClass.trim().equals("")) {
71
72             buffer.append("<span class=\"").append(cssClass).append("\">");
73             buffer.append(originalText);
74             buffer.append("</span>");
75
76         } else {
77
78             buffer.append("<span style=\"").append(cssStyle).append("\">");
79             buffer.append(originalText);
80             buffer.append("</span>");
81
82         }
83
84         return buffer.toString();
85
86     }
87
88     private String JavaDoc constructStyle( Map JavaDoc cssProperties ) {
89
90         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
91         Iterator JavaDoc iterator = cssProperties.entrySet().iterator();
92
93         while (iterator.hasNext()) {
94
95             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
96
97             buffer.append(entry.getKey()).append(":");
98             buffer.append(entry.getValue()).append(";");
99
100         }
101
102         return buffer.toString();
103
104     }
105
106 }
107
Popular Tags