View Javadoc

1   /**
2    * This file Copyright (c) 2008-2011 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.module.templatingkit.search;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.MgnlNodeType;
38  import info.magnolia.cms.core.search.Query;
39  import info.magnolia.cms.core.search.QueryResult;
40  import info.magnolia.context.MgnlContext;
41  import info.magnolia.jcr.wrapper.I18nNodeWrapper;
42  import info.magnolia.module.templatingkit.functions.STKTemplatingFunctions;
43  import info.magnolia.module.templatingkit.templates.AbstractSTKTemplateModel;
44  import info.magnolia.rendering.model.RenderingModel;
45  import info.magnolia.rendering.template.TemplateDefinition;
46  import info.magnolia.repository.RepositoryConstants;
47  import info.magnolia.templating.functions.TemplatingFunctions;
48  
49  import java.text.MessageFormat;
50  import java.util.ArrayList;
51  import java.util.Collection;
52  import java.util.List;
53  
54  import javax.inject.Inject;
55  import javax.jcr.Node;
56  
57  import org.apache.commons.lang.StringUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  /**
62   * STK Rendable Model definition dedicated to
63   * Display and execute Search Result Model.
64   * @author tmiyar
65   * @version $Id$
66   */
67  public class SearchResultModel extends AbstractSTKTemplateModel  <TemplateDefinition> {
68  
69      private static final String SEARCH_QUERY_PATTERN = "select * from nt:base where jcr:path like ''{0}/%'' and contains(*, ''{1}'') order by jcr:path";
70  
71  
72      protected String repository = RepositoryConstants.WEBSITE;
73      protected List<Content> result = new ArrayList<Content>();
74      protected int count;
75      protected int maxResultsPerPage;
76      protected int currentPage = 1;
77      protected int numPages = 0;
78  
79      private static final Logger log = LoggerFactory.getLogger(SearchResultModel.class);
80  
81      @Inject
82      public SearchResultModel(Node content, TemplateDefinition definition, RenderingModel<?> parent, STKTemplatingFunctions stkFunctions, TemplatingFunctions templatingFunctions) {
83          super(content, definition, parent, stkFunctions, templatingFunctions);
84      }
85  
86      protected int getMaxResultsPerPage() {
87  
88          maxResultsPerPage = Integer.MAX_VALUE;
89          try {
90              if (content.hasProperty("maxResultsPerPage")) {
91                  maxResultsPerPage = Integer.parseInt(content.getProperty("maxResultsPerPage").getString());
92              }
93          } catch (Exception e) {
94              //do nothing
95          }
96          return maxResultsPerPage;
97      }
98  
99      @Override
100     public String execute() {
101 
102         Query q = null;
103         String queryString = generateSimpleQuery(this.getQueryStr());
104         if (StringUtils.isBlank(queryString)){
105             return null;
106         }
107         try {
108             maxResultsPerPage = getMaxResultsPerPage();
109             q = MgnlContext.getQueryManager(repository).createQuery(queryString, "sql");
110 
111             QueryResult queryResult = q.execute();
112 
113             count = pagedQuery(queryResult.getContent(MgnlNodeType.NT_PAGE), getOffset(), maxResultsPerPage);
114 
115             numPages = count/maxResultsPerPage;
116             if((count % maxResultsPerPage) > 0 ) {
117                 numPages++;
118             }
119 
120         } catch (Exception e) {
121             log.error(MessageFormat.format("{0} caught while parsing query for search term [{1}] - query is [{2}]: {3}", e.getClass().getName(), q, queryString, e.getMessage()), e);
122         }
123 
124         return "";
125 
126     }
127 
128     protected int getOffset() {
129         return ((getCurrentPage() -1) * maxResultsPerPage);
130 
131     }
132 
133     protected int pagedQuery(Collection<Content> queryResult, int offset, int limit) throws Exception {
134         int total = queryResult.size();
135         int newLimit = limit;
136         if(total > offset) {
137             if(total < offset + limit) {
138                 newLimit = total - offset;
139             }
140 
141             result = ((List<Content>)queryResult).subList(offset, offset + newLimit);
142         }
143 
144         return total;
145     }
146 
147     protected String generateSimpleQuery(String input) {
148         if(StringUtils.isBlank(input)){
149             return null;
150         }
151 
152         //escape single quote
153         String searchString = input.replace("'", "''");
154         return MessageFormat.format(SEARCH_QUERY_PATTERN, new String[]{this.getPath(), searchString});
155     }
156 
157     public String getPath() {
158         try {
159             return stkFunctions.siteRoot(content).getPath();
160 
161         } catch (Exception e) {
162             log.warn("no site");
163         }
164         return "";
165     }
166     /**
167      * FIXME usage of deprecated classes: {@link Content}.
168      * To remove when SearchResultItem will be fully migrated.
169      */
170     public List<Node> getQueryResult(){
171         List<Node> res = new ArrayList<Node>();
172         if(result!=null) {
173             for(Content c:result){
174                 res.add(new I18nNodeWrapper(c.getJCRNode()));
175             }
176         }
177         return res;
178     }
179 
180     public Collection<SearchResultItem> getResult() {
181         final Collection<SearchResultItem> searchResults = new ArrayList<SearchResultItem>();
182         for (Node content : this.getQueryResult()) {
183             searchResults.add(new SearchResultItem(content, this.getQueryStr(), templatingFunctions));
184         }
185         return searchResults;
186     }
187 
188     public String getQueryStr() {
189         return MgnlContext.getParameter("queryStr");
190     }
191 
192 
193     public int getCount(){
194         return this.count;
195     }
196 
197     public int getCurrentPage() {
198 
199         if(MgnlContext.getParameter("currentPage") != null) {
200             currentPage = Integer.parseInt(MgnlContext.getParameter("currentPage"));
201         }
202 
203         return currentPage;
204     }
205 
206     public int getNumPages() {
207         return numPages;
208     }
209 
210     /**
211      * Not used.
212      * @deprecated Not used anymore.
213      * @param i
214      * @return
215      */
216     public String getPageLink(int i) {
217         String link = "";
218         try {
219             link = stkFunctions.searchPageLink(content);
220             String current = "&amp;currentPage=";
221             link =  link + "?queryStr=" + getQueryStr() + current + i;
222         } catch (Exception e) {
223             log.error("could not find search result page");
224         }
225         return link;
226     }
227 
228 
229 
230 
231 
232     public int getBeginIndex() {
233         if (currentPage - 2 <= 1) {
234             return 1;
235         } else {
236             return currentPage - 2;
237         }
238     }
239 
240     public int getEndIndex() {
241         if (currentPage + 2 >= numPages) {
242             return numPages;
243         } else {
244             return currentPage + 2;
245         }
246     }
247 
248     public String getPosition() {
249         try {
250             if(content.hasProperty("pager")) {
251                 return content.getProperty("pager").getString();
252             }
253         } catch (Exception e) {
254             log.debug("no pagination position found");
255         }
256         return "";
257 
258     }
259 
260 
261 }