View Javadoc
1   /**
2    * This file Copyright (c) 2012-2016 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.templating.jsp.taglib;
35  
36  import info.magnolia.jcr.util.NodeTypes;
37  import info.magnolia.jcr.util.NodeUtil;
38  
39  import java.io.IOException;
40  import java.util.ArrayList;
41  import java.util.Collection;
42  import java.util.Iterator;
43  import java.util.regex.Pattern;
44  
45  import javax.jcr.Node;
46  import javax.jcr.Property;
47  import javax.jcr.PropertyType;
48  import javax.servlet.jsp.JspException;
49  import javax.servlet.jsp.JspWriter;
50  import javax.servlet.jsp.tagext.TagSupport;
51  
52  import org.apache.commons.lang3.ArrayUtils;
53  import org.apache.commons.lang3.StringUtils;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  import org.tldgen.annotations.BodyContent;
57  import org.tldgen.annotations.Tag;
58  
59  
60  /**
61   * Output a set of snippets taken from any paragraph in the given page mathing any of the search term.
62   * @jsp.tag name="searchResultSnippet" body-content="empty"
63   * @jsp.tag-example
64   * <pre>
65   * &lt;cmsu:simplesearch query="${param.search}" var="results" /&gt;
66   * &lt;c:forEach items="${results}" var="page"&gt;
67   *   &lt;cmsu:searchResultSnippet query="${param.search}" page="${page}" /&gt;
68   * &lt;/c:forEach&gt;
69   *</pre>
70   */
71  @Tag(name="searchResultSnippet", bodyContent=BodyContent.EMPTY)
72  
73  public class SearchResultSnippetTag extends TagSupport {
74  
75      private static final Pattern HTML_STRIP = Pattern.compile("<.*?>", Pattern.DOTALL);
76  
77      private static final Logger log = LoggerFactory.getLogger(SearchResultSnippetTag.class);
78  
79      /**
80       * Start level.
81       */
82      private Node page;
83  
84      /**
85       * Query, natural language.
86       */
87      private String query;
88  
89      /**
90       * Number of chars to include in result.
91       */
92      private int chars = 100;
93  
94      /**
95       * Maximum number of snippets to include in result.
96       */
97      private int maxSnippets = 3;
98  
99      /**
100      * Search query.
101      * @jsp.attribute required="true" rtexprvalue="true"
102      */
103     public void setQuery(String query) {
104         this.query = query;
105     }
106 
107     /**
108      * Number of characters to include in search snippets. Default is 100.
109      * @jsp.attribute required="false" rtexprvalue="true" type="int"
110      */
111     public void setChars(int chars) {
112         this.chars = chars;
113     }
114 
115     /**
116      * Maximum number of snippets to print out.
117      * @jsp.attribute required="false" rtexprvalue="true" type="int"
118      */
119     public void setMaxSnippets(int maxSnippets) {
120         this.maxSnippets = maxSnippets;
121     }
122 
123     /**
124      * A Content node of type mgnl:content (a magnolia page), typically returned by the simpleSearch tag.
125      * @jsp.attribute required="true" rtexprvalue="true" type="info.magnolia.cms.core.Content"
126      */
127     public void setPage(Node page) {
128         this.page = page;
129     }
130 
131     /**
132      * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
133      */
134     @Override
135     public int doStartTag() throws JspException {
136 
137         JspWriter out = this.pageContext.getOut();
138         try {
139             Iterator iterator = getSnippets().iterator();
140             while (iterator.hasNext()) {
141                 out.println(iterator.next());
142             }
143         }
144         catch (IOException e) {
145             // should never happen
146             throw new JspException(e);
147         }
148         return EVAL_PAGE;
149     }
150 
151     /**
152      * Extract a collection of snippets from any paragraph in the given page.
153      * @return a collection of Strings.
154      * @todo avoid overlapping snippets (use regexp insted of simple indexOfs)
155      * @todo only extract snippets from user-configured properties
156      * @todo abbreviate on whitespace and puntuation, detect start of sentences
157      * @todo replace ampersand in regexp
158      * @todo break methods and write junits
159      */
160     public Collection getSnippets() {
161 
162         log.debug("collecting snippets");
163 
164         Collection snippets = new ArrayList();
165         String[] searchTerms = StringUtils.split(this.query);
166 
167         try{
168         Iterator<Node> iterator = NodeUtil.getNodes(this.page, NodeTypes.ContentNode.NAME).iterator();
169 
170         outer : while (iterator.hasNext()) {
171             Node paragraphCollection = iterator.next();
172 
173             Iterator<Node> parIterator = NodeUtil.getNodes(paragraphCollection, NodeTypes.ContentNode.NAME).iterator();
174             while (parIterator.hasNext()) {
175                 Node paragraph = parIterator.next();
176 
177                 log.debug("Iterating on paragraph {}", paragraph);
178 
179                 Iterator dataIterator = paragraph.getProperties();
180 
181                 while (dataIterator.hasNext()) {
182                     Property property = (Property) dataIterator.next();
183                     if (property.getType() != PropertyType.BINARY) {
184 
185                         String resultString = property.getString();
186 
187                         log.debug("Iterating on property {}", property.getName());
188                         log.debug("Property value is {}", resultString);
189 
190                         // a quick and buggy way to avoid configuration properties, we should allow the user to
191                         // configure a list of nodeData to search for...
192                         if (resultString.length() < 20) {
193                             continue;
194                         }
195 
196                         for (int j = 0; j < searchTerms.length; j++) {
197                             String searchTerm = StringUtils.lowerCase(searchTerms[j]);
198 
199                             // exclude keywords and words with less than 2 chars
200                             if (!ArrayUtils.contains(new String[]{"and", "or"}, searchTerm) && searchTerm.length() > 2) {
201 
202                                 log.debug("Looking for search term [{}] in [{}]", searchTerm, resultString);
203 
204                                 // first check, avoid using heavy string replaceAll operations if the search term is not
205                                 // there
206                                 if (!StringUtils.contains(resultString.toLowerCase(), searchTerm)) {
207                                     continue;
208                                 }
209 
210                                 // strips out html tags using a regexp
211                                 resultString = stripHtmlTags(resultString);
212 
213                                 // only get first matching keyword
214                                 int pos = resultString.toLowerCase().indexOf(searchTerm);
215                                 if (pos > -1) {
216 
217                                     int posEnd = pos + searchTerm.length();
218                                     int from = (pos - chars / 2);
219                                     if (from < 0) {
220                                         from = 0;
221                                     }
222 
223                                     int to = from + chars;
224                                     if (to > resultString.length()) {
225                                         to = resultString.length();
226                                     }
227 
228                                     StringBuffer snippet = new StringBuffer();
229 
230                                     snippet.append(StringUtils.substring(resultString, from, pos));
231                                     snippet.append("<strong>");
232                                     snippet.append(StringUtils.substring(resultString, pos, posEnd));
233                                     snippet.append("</strong>");
234                                     snippet.append(StringUtils.substring(resultString, posEnd, to));
235 
236                                     if (from > 0) {
237                                         snippet.insert(0, "... ");
238                                     }
239                                     if (to < resultString.length()) {
240                                         snippet.append("... ");
241                                     }
242 
243                                     log.debug("Search term found, adding snippet {}", snippet);
244 
245                                     snippets.add(snippet);
246                                     if (snippets.size() >= this.maxSnippets) {
247 
248                                         log.debug("Maximum number of snippets ({}) reached, exiting",
249                                             Integer.toString(this.maxSnippets));
250 
251                                         break outer;
252                                     }
253                                 }
254                             }
255                         }
256                     }
257                 }
258             }
259             
260         }
261         return snippets;
262         }catch(Exception e){
263             log.error(e.getMessage(), e);
264             return null;
265         }
266     }
267 
268     protected String stripHtmlTags(String input) {
269         return HTML_STRIP.matcher(input).replaceAll("");
270     }
271 
272     /**
273      * @see javax.servlet.jsp.tagext.TagSupport#release()
274      */
275     @Override
276     public void release() {
277         this.query = null;
278         this.page = null;
279         this.chars = 100;
280         this.maxSnippets = 3;
281         super.release();
282     }
283 
284 }