2 * Sone - SearchPage.java - Copyright © 2010 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.web;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.data.Post;
31 import net.pterodactylus.sone.data.Profile;
32 import net.pterodactylus.sone.data.Profile.Field;
33 import net.pterodactylus.sone.data.Reply;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.web.page.FreenetRequest;
36 import net.pterodactylus.util.cache.Cache;
37 import net.pterodactylus.util.cache.CacheException;
38 import net.pterodactylus.util.cache.CacheItem;
39 import net.pterodactylus.util.cache.DefaultCacheItem;
40 import net.pterodactylus.util.cache.MemoryCache;
41 import net.pterodactylus.util.cache.ValueRetriever;
42 import net.pterodactylus.util.collection.Mapper;
43 import net.pterodactylus.util.collection.Mappers;
44 import net.pterodactylus.util.collection.Pagination;
45 import net.pterodactylus.util.collection.TimedMap;
46 import net.pterodactylus.util.filter.Filter;
47 import net.pterodactylus.util.filter.Filters;
48 import net.pterodactylus.util.logging.Logging;
49 import net.pterodactylus.util.number.Numbers;
50 import net.pterodactylus.util.template.Template;
51 import net.pterodactylus.util.template.TemplateContext;
52 import net.pterodactylus.util.text.StringEscaper;
53 import net.pterodactylus.util.text.TextException;
56 * This page lets the user search for posts and replies that contain certain
59 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61 public class SearchPage extends SoneTemplatePage {
64 private static final Logger logger = Logging.getLogger(SearchPage.class);
66 /** Short-term cache. */
67 private final Cache<List<Phrase>, Set<Hit<Post>>> hitCache = new MemoryCache<List<Phrase>, Set<Hit<Post>>>(new ValueRetriever<List<Phrase>, Set<Hit<Post>>>() {
69 @SuppressWarnings("synthetic-access")
70 public CacheItem<Set<Hit<Post>>> retrieve(List<Phrase> phrases) throws CacheException {
71 Set<Post> posts = new HashSet<Post>();
72 for (Sone sone : webInterface.getCore().getSones()) {
73 posts.addAll(sone.getPosts());
75 return new DefaultCacheItem<Set<Hit<Post>>>(getHits(Filters.filteredSet(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator()));
78 }, new TimedMap<List<Phrase>, CacheItem<Set<Hit<Post>>>>(300000));
81 * Creates a new search page.
84 * The template to render
86 * The Sone web interface
88 public SearchPage(Template template, WebInterface webInterface) {
89 super("search.html", template, "Page.Search.Title", webInterface);
93 // SONETEMPLATEPAGE METHODS
100 protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
101 super.processTemplate(request, templateContext);
102 String query = request.getHttpRequest().getParam("query").trim();
103 if (query.length() == 0) {
104 throw new RedirectException("index.html");
107 List<Phrase> phrases = parseSearchPhrases(query);
108 if (phrases.isEmpty()) {
109 throw new RedirectException("index.html");
112 Set<Sone> sones = webInterface.getCore().getSones();
113 Set<Hit<Sone>> soneHits = getHits(sones, phrases, SoneStringGenerator.COMPLETE_GENERATOR);
115 Set<Hit<Post>> postHits;
117 postHits = hitCache.get(phrases);
118 } catch (CacheException ce1) {
119 /* should never happen. */
120 logger.log(Level.SEVERE, "Could not get search results from cache!", ce1);
121 postHits = Collections.emptySet();
125 soneHits = Filters.filteredSet(soneHits, Hit.POSITIVE_FILTER);
126 postHits = Filters.filteredSet(postHits, Hit.POSITIVE_FILTER);
129 List<Hit<Sone>> sortedSoneHits = new ArrayList<Hit<Sone>>(soneHits);
130 Collections.sort(sortedSoneHits, Hit.DESCENDING_COMPARATOR);
131 List<Hit<Post>> sortedPostHits = new ArrayList<Hit<Post>>(postHits);
132 Collections.sort(sortedPostHits, Hit.DESCENDING_COMPARATOR);
134 /* extract Sones and posts. */
135 List<Sone> resultSones = Mappers.mappedList(sortedSoneHits, new HitMapper<Sone>());
136 List<Post> resultPosts = Mappers.mappedList(sortedPostHits, new HitMapper<Post>());
139 Pagination<Sone> sonePagination = new Pagination<Sone>(resultSones, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(Numbers.safeParseInteger(request.getHttpRequest().getParam("sonePage"), 0));
140 Pagination<Post> postPagination = new Pagination<Post>(resultPosts, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(Numbers.safeParseInteger(request.getHttpRequest().getParam("postPage"), 0));
142 templateContext.set("sonePagination", sonePagination);
143 templateContext.set("soneHits", sonePagination.getItems());
144 templateContext.set("postPagination", postPagination);
145 templateContext.set("postHits", postPagination.getItems());
153 * Collects hit information for the given objects. The objects are converted
154 * to a {@link String} using the given {@link StringGenerator}, and the
155 * {@link #calculateScore(List, String) calculated score} is stored together
156 * with the object in a {@link Hit}, and all resulting {@link Hit}s are then
160 * The type of the objects
162 * The objects to search over
164 * The phrases to search for
165 * @param stringGenerator
166 * The string generator for the objects
167 * @return The hits for the given phrases
169 private <T> Set<Hit<T>> getHits(Collection<T> objects, List<Phrase> phrases, StringGenerator<T> stringGenerator) {
170 Set<Hit<T>> hits = new HashSet<Hit<T>>();
171 for (T object : objects) {
172 String objectString = stringGenerator.generateString(object);
173 double score = calculateScore(phrases, objectString);
174 hits.add(new Hit<T>(object, score));
180 * Parses the given query into search phrases. The query is split on
181 * whitespace while allowing to group words using single or double quotes.
182 * Isolated phrases starting with a “+” are
183 * {@link Phrase.Optionality#REQUIRED}, phrases with a “-” are
184 * {@link Phrase.Optionality#FORBIDDEN}.
188 * @return The parsed phrases
190 private List<Phrase> parseSearchPhrases(String query) {
191 List<String> parsedPhrases = null;
193 parsedPhrases = StringEscaper.parseLine(query);
194 } catch (TextException te1) {
196 return Collections.emptyList();
199 List<Phrase> phrases = new ArrayList<Phrase>();
200 for (String phrase : parsedPhrases) {
201 if (phrase.startsWith("+")) {
202 if (phrase.length() > 1) {
203 phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.REQUIRED));
205 phrases.add(new Phrase("+", Phrase.Optionality.OPTIONAL));
207 } else if (phrase.startsWith("-")) {
208 if (phrase.length() > 1) {
209 phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.FORBIDDEN));
211 phrases.add(new Phrase("-", Phrase.Optionality.OPTIONAL));
214 phrases.add(new Phrase(phrase, Phrase.Optionality.OPTIONAL));
221 * Calculates the score for the given expression when using the given
225 * The phrases to search for
227 * The expression to search
228 * @return The score of the expression
230 private double calculateScore(List<Phrase> phrases, String expression) {
231 logger.log(Level.FINEST, "Calculating Score for “%s”…", expression);
232 double optionalHits = 0;
233 double requiredHits = 0;
234 int forbiddenHits = 0;
235 int requiredPhrases = 0;
236 for (Phrase phrase : phrases) {
237 String phraseString = phrase.getPhrase().toLowerCase();
238 if (phrase.getOptionality() == Phrase.Optionality.REQUIRED) {
244 while (index < expression.length()) {
245 int position = expression.toLowerCase().indexOf(phraseString, index);
246 if (position == -1) {
249 score += Math.pow(1 - position / (double) expression.length(), 2);
250 index = position + phraseString.length();
251 logger.log(Level.FINEST, "Got hit at position %d.", position);
254 logger.log(Level.FINEST, "Score: %f", score);
258 if (phrase.getOptionality() == Phrase.Optionality.REQUIRED) {
259 requiredHits += score;
261 if (phrase.getOptionality() == Phrase.Optionality.OPTIONAL) {
262 optionalHits += score;
264 if (phrase.getOptionality() == Phrase.Optionality.FORBIDDEN) {
265 forbiddenHits += matches;
268 return requiredHits * 3 + optionalHits + (requiredHits - requiredPhrases) * 5 - (forbiddenHits * 2);
272 * Converts a given object into a {@link String}.
275 * The type of the objects
276 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
278 private static interface StringGenerator<T> {
281 * Generates a {@link String} for the given object.
284 * The object to generate the {@link String} for
285 * @return The generated {@link String}
287 public String generateString(T object);
292 * Generates a {@link String} from a {@link Sone}, concatenating the name of
293 * the Sone and all {@link Profile} {@link Field} values.
295 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
297 private static class SoneStringGenerator implements StringGenerator<Sone> {
299 /** A static instance of a complete Sone string generator. */
300 public static final SoneStringGenerator COMPLETE_GENERATOR = new SoneStringGenerator(true);
303 * A static instance of a Sone string generator that will only use the
306 public static final SoneStringGenerator NAME_GENERATOR = new SoneStringGenerator(false);
308 /** Whether to generate a string from all data of a Sone. */
309 private final boolean complete;
312 * Creates a new Sone string generator.
315 * {@code true} to use the profile’s fields, {@code false} to
316 * not to use the profile‘s fields
318 private SoneStringGenerator(boolean complete) {
319 this.complete = complete;
326 public String generateString(Sone sone) {
327 StringBuilder soneString = new StringBuilder();
328 soneString.append(sone.getName());
329 Profile soneProfile = sone.getProfile();
330 if (soneProfile.getFirstName() != null) {
331 soneString.append(' ').append(soneProfile.getFirstName());
333 if (soneProfile.getMiddleName() != null) {
334 soneString.append(' ').append(soneProfile.getMiddleName());
336 if (soneProfile.getLastName() != null) {
337 soneString.append(' ').append(soneProfile.getLastName());
340 for (Field field : soneProfile.getFields()) {
341 soneString.append(' ').append(field.getValue());
344 return soneString.toString();
350 * Generates a {@link String} from a {@link Post}, concatenating the text of
351 * the post, the text of all {@link Reply}s, and the name of all
352 * {@link Sone}s that have replied.
354 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
356 private class PostStringGenerator implements StringGenerator<Post> {
362 public String generateString(Post post) {
363 StringBuilder postString = new StringBuilder();
364 postString.append(post.getText());
365 if (post.getRecipient() != null) {
366 postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(post.getRecipient()));
368 for (Reply reply : Filters.filteredList(webInterface.getCore().getReplies(post), Reply.FUTURE_REPLIES_FILTER)) {
369 postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(reply.getSone()));
370 postString.append(' ').append(reply.getText());
372 return postString.toString();
380 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
382 private static class Phrase {
385 * The optionality of a search phrase.
387 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
390 public enum Optionality {
392 /** The phrase is optional. */
395 /** The phrase is required. */
398 /** The phrase is forbidden. */
403 /** The phrase to search for. */
404 private final String phrase;
406 /** The optionality of the phrase. */
407 private final Optionality optionality;
410 * Creates a new phrase.
413 * The phrase to search for
415 * The optionality of the phrase
417 public Phrase(String phrase, Optionality optionality) {
418 this.optionality = optionality;
419 this.phrase = phrase;
423 * Returns the phrase to search for.
425 * @return The phrase to search for
427 public String getPhrase() {
432 * Returns the optionality of the phrase.
434 * @return The optionality of the phrase
436 public Optionality getOptionality() {
448 public int hashCode() {
449 return phrase.hashCode() ^ ((optionality == Optionality.FORBIDDEN) ? (0xaaaaaaaa) : ((optionality == Optionality.REQUIRED) ? 0x55555555 : 0));
456 public boolean equals(Object object) {
457 if (!(object instanceof Phrase)) {
460 Phrase phrase = (Phrase) object;
461 return (this.optionality == phrase.optionality) && this.phrase.equals(phrase.phrase);
467 * A hit consists of a searched object and the score it got for the phrases
470 * @see SearchPage#calculateScore(List, String)
472 * The type of the searched object
473 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
475 private static class Hit<T> {
477 /** Filter for {@link Hit}s with a score of more than 0. */
478 public static final Filter<Hit<?>> POSITIVE_FILTER = new Filter<Hit<?>>() {
481 public boolean filterObject(Hit<?> hit) {
482 return hit.getScore() > 0;
487 /** Comparator that sorts {@link Hit}s descending by score. */
488 public static final Comparator<Hit<?>> DESCENDING_COMPARATOR = new Comparator<Hit<?>>() {
491 public int compare(Hit<?> leftHit, Hit<?> rightHit) {
492 return (rightHit.getScore() < leftHit.getScore()) ? -1 : ((rightHit.getScore() > leftHit.getScore()) ? 1 : 0);
497 /** The object that was searched. */
498 private final T object;
500 /** The score of the object. */
501 private final double score;
507 * The object that was searched
509 * The score of the object
511 public Hit(T object, double score) {
512 this.object = object;
517 * Returns the object that was searched.
519 * @return The object that was searched
521 public T getObject() {
526 * Returns the score of the object.
528 * @return The score of the object
530 public double getScore() {
537 * Extracts the object from a {@link Hit}.
540 * The type of the object to extract
541 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
543 public static class HitMapper<T> implements Mapper<Hit<T>, T> {
549 public T map(Hit<T> input) {
550 return input.getObject();