X-Git-Url: https://git.pterodactylus.net/?p=Sone.git;a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Fweb%2FSearchPage.java;h=0f12abff77de543cfa29aa462a9481d28426096a;hp=94b296c8c38f3e1a7d3fd5d070ad6bfe689bc14b;hb=07168fffdb181d70937183301d06cd39900c4e22;hpb=d0ae5f106a59d7ac808e03287af2e5a33e50ba8b diff --git a/src/main/java/net/pterodactylus/sone/web/SearchPage.java b/src/main/java/net/pterodactylus/sone/web/SearchPage.java index 94b296c..0f12abf 100644 --- a/src/main/java/net/pterodactylus/sone/web/SearchPage.java +++ b/src/main/java/net/pterodactylus/sone/web/SearchPage.java @@ -1,5 +1,5 @@ /* - * Sone - SearchPage.java - Copyright © 2010 David Roden + * Sone - SearchPage.java - Copyright © 2010–2012 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -28,15 +28,24 @@ import java.util.logging.Level; import java.util.logging.Logger; import net.pterodactylus.sone.data.Post; +import net.pterodactylus.sone.data.PostReply; import net.pterodactylus.sone.data.Profile; import net.pterodactylus.sone.data.Profile.Field; import net.pterodactylus.sone.data.Reply; import net.pterodactylus.sone.data.Sone; -import net.pterodactylus.util.collection.Converter; -import net.pterodactylus.util.collection.Converters; +import net.pterodactylus.sone.web.page.FreenetRequest; +import net.pterodactylus.util.cache.Cache; +import net.pterodactylus.util.cache.CacheException; +import net.pterodactylus.util.cache.CacheItem; +import net.pterodactylus.util.cache.DefaultCacheItem; +import net.pterodactylus.util.cache.MemoryCache; +import net.pterodactylus.util.cache.ValueRetriever; import net.pterodactylus.util.collection.Pagination; -import net.pterodactylus.util.filter.Filter; -import net.pterodactylus.util.filter.Filters; +import net.pterodactylus.util.collection.TimedMap; +import net.pterodactylus.util.collection.filter.Filter; +import net.pterodactylus.util.collection.filter.Filters; +import net.pterodactylus.util.collection.mapper.Mapper; +import net.pterodactylus.util.collection.mapper.Mappers; import net.pterodactylus.util.logging.Logging; import net.pterodactylus.util.number.Numbers; import net.pterodactylus.util.template.Template; @@ -55,6 +64,21 @@ public class SearchPage extends SoneTemplatePage { /** The logger. */ private static final Logger logger = Logging.getLogger(SearchPage.class); + /** Short-term cache. */ + private final Cache, Set>> hitCache = new MemoryCache, Set>>(new ValueRetriever, Set>>() { + + @Override + @SuppressWarnings("synthetic-access") + public CacheItem>> retrieve(List phrases) throws CacheException { + Set posts = new HashSet(); + for (Sone sone : webInterface.getCore().getSones()) { + posts.addAll(sone.getPosts()); + } + return new DefaultCacheItem>>(getHits(Filters.filteredSet(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator())); + } + + }, new TimedMap, CacheItem>>>(300000)); + /** * Creates a new search page. * @@ -75,7 +99,7 @@ public class SearchPage extends SoneTemplatePage { * {@inheritDoc} */ @Override - protected void processTemplate(Request request, TemplateContext templateContext) throws RedirectException { + protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException { super.processTemplate(request, templateContext); String query = request.getHttpRequest().getParam("query").trim(); if (query.length() == 0) { @@ -83,16 +107,41 @@ public class SearchPage extends SoneTemplatePage { } List phrases = parseSearchPhrases(query); + if (phrases.isEmpty()) { + throw new RedirectException("index.html"); + } + + /* check for a couple of shortcuts. */ + if (phrases.size() == 1) { + String phrase = phrases.get(0).getPhrase(); + + /* is it a Sone ID? */ + redirectIfNotNull(getSoneId(phrase), "viewSone.html?sone="); + + /* is it a post ID? */ + redirectIfNotNull(getPostId(phrase), "viewPost.html?post="); + + /* is it a reply ID? show the post. */ + redirectIfNotNull(getReplyPostId(phrase), "viewPost.html?post="); + + /* is it an album ID? */ + redirectIfNotNull(getAlbumId(phrase), "imageBrowser.html?album="); + + /* is it an image ID? */ + redirectIfNotNull(getImageId(phrase), "imageBrowser.html?image="); + } Set sones = webInterface.getCore().getSones(); Set> soneHits = getHits(sones, phrases, SoneStringGenerator.COMPLETE_GENERATOR); - Set posts = new HashSet(); - for (Sone sone : sones) { - posts.addAll(sone.getPosts()); + Set> postHits; + try { + postHits = hitCache.get(phrases); + } catch (CacheException ce1) { + /* should never happen. */ + logger.log(Level.SEVERE, "Could not get search results from cache!", ce1); + postHits = Collections.emptySet(); } - @SuppressWarnings("synthetic-access") - Set> postHits = getHits(Filters.filteredSet(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator()); /* now filter. */ soneHits = Filters.filteredSet(soneHits, Hit.POSITIVE_FILTER); @@ -105,8 +154,8 @@ public class SearchPage extends SoneTemplatePage { Collections.sort(sortedPostHits, Hit.DESCENDING_COMPARATOR); /* extract Sones and posts. */ - List resultSones = Converters.convertList(sortedSoneHits, new HitConverter()); - List resultPosts = Converters.convertList(sortedPostHits, new HitConverter()); + List resultSones = Mappers.mappedList(sortedSoneHits, new HitMapper()); + List resultPosts = Mappers.mappedList(sortedPostHits, new HitMapper()); /* pagination. */ Pagination sonePagination = new Pagination(resultSones, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(Numbers.safeParseInteger(request.getHttpRequest().getParam("sonePage"), 0)); @@ -139,7 +188,7 @@ public class SearchPage extends SoneTemplatePage { * The string generator for the objects * @return The hits for the given phrases */ - private Set> getHits(Collection objects, List phrases, StringGenerator stringGenerator) { + private static Set> getHits(Collection objects, List phrases, StringGenerator stringGenerator) { Set> hits = new HashSet>(); for (T object : objects) { String objectString = stringGenerator.generateString(object); @@ -160,7 +209,7 @@ public class SearchPage extends SoneTemplatePage { * The query to parse * @return The parsed phrases */ - private List parseSearchPhrases(String query) { + private static List parseSearchPhrases(String query) { List parsedPhrases = null; try { parsedPhrases = StringEscaper.parseLine(query); @@ -172,11 +221,20 @@ public class SearchPage extends SoneTemplatePage { List phrases = new ArrayList(); for (String phrase : parsedPhrases) { if (phrase.startsWith("+")) { - phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.REQUIRED)); + if (phrase.length() > 1) { + phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.REQUIRED)); + } else { + phrases.add(new Phrase("+", Phrase.Optionality.OPTIONAL)); + } } else if (phrase.startsWith("-")) { - phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.FORBIDDEN)); + if (phrase.length() > 1) { + phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.FORBIDDEN)); + } else { + phrases.add(new Phrase("-", Phrase.Optionality.OPTIONAL)); + } + } else { + phrases.add(new Phrase(phrase, Phrase.Optionality.OPTIONAL)); } - phrases.add(new Phrase(phrase, Phrase.Optionality.OPTIONAL)); } return phrases; } @@ -191,8 +249,8 @@ public class SearchPage extends SoneTemplatePage { * The expression to search * @return The score of the expression */ - private double calculateScore(List phrases, String expression) { - logger.log(Level.FINEST, "Calculating Score for “" + expression + "”…"); + private static double calculateScore(List phrases, String expression) { + logger.log(Level.FINEST, String.format("Calculating Score for “%s”…", expression)); double optionalHits = 0; double requiredHits = 0; int forbiddenHits = 0; @@ -212,10 +270,10 @@ public class SearchPage extends SoneTemplatePage { } score += Math.pow(1 - position / (double) expression.length(), 2); index = position + phraseString.length(); - logger.log(Level.FINEST, "Got hit at position %d.", position); + logger.log(Level.FINEST, String.format("Got hit at position %d.", position)); ++matches; } - logger.log(Level.FINEST, "Score: %f", score); + logger.log(Level.FINEST, String.format("Score: %f", score)); if (matches == 0) { continue; } @@ -233,6 +291,91 @@ public class SearchPage extends SoneTemplatePage { } /** + * Throws a + * {@link net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException} + * if the given object is not {@code null}, appending the object to the + * given target URL. + * + * @param object + * The object on which to redirect + * @param target + * The target of the redirect + * @throws RedirectException + * if {@code object} is not {@code null} + */ + private static void redirectIfNotNull(String object, String target) throws RedirectException { + if (object != null) { + throw new RedirectException(target + object); + } + } + + /** + * If the given phrase contains a Sone ID (optionally prefixed by + * “sone://”), returns said Sone ID, otherwise return {@code null}. + * + * @param phrase + * The phrase that maybe is a Sone ID + * @return The Sone ID, or {@code null} + */ + private String getSoneId(String phrase) { + String soneId = phrase.startsWith("sone://") ? phrase.substring(7) : phrase; + return (webInterface.getCore().getSone(soneId, false) != null) ? soneId : null; + } + + /** + * If the given phrase contains a post ID (optionally prefixed by + * “post://”), returns said post ID, otherwise return {@code null}. + * + * @param phrase + * The phrase that maybe is a post ID + * @return The post ID, or {@code null} + */ + private String getPostId(String phrase) { + String postId = phrase.startsWith("post://") ? phrase.substring(7) : phrase; + return (webInterface.getCore().getPost(postId, false) != null) ? postId : null; + } + + /** + * If the given phrase contains a reply ID (optionally prefixed by + * “reply://”), returns the ID of the post the reply belongs to, otherwise + * return {@code null}. + * + * @param phrase + * The phrase that maybe is a reply ID + * @return The reply’s post ID, or {@code null} + */ + private String getReplyPostId(String phrase) { + String replyId = phrase.startsWith("reply://") ? phrase.substring(8) : phrase; + return (webInterface.getCore().getReply(replyId, false) != null) ? webInterface.getCore().getReply(replyId, false).getPost().getId() : null; + } + + /** + * If the given phrase contains an album ID (optionally prefixed by + * “album://”), returns said album ID, otherwise return {@code null}. + * + * @param phrase + * The phrase that maybe is an album ID + * @return The album ID, or {@code null} + */ + private String getAlbumId(String phrase) { + String albumId = phrase.startsWith("album://") ? phrase.substring(8) : phrase; + return (webInterface.getCore().getAlbum(albumId, false) != null) ? albumId : null; + } + + /** + * If the given phrase contains an image ID (optionally prefixed by + * “image://”), returns said image ID, otherwise return {@code null}. + * + * @param phrase + * The phrase that maybe is an image ID + * @return The image ID, or {@code null} + */ + private String getImageId(String phrase) { + String imageId = phrase.startsWith("image://") ? phrase.substring(8) : phrase; + return (webInterface.getCore().getImage(imageId, false) != null) ? imageId : null; + } + + /** * Converts a given object into a {@link String}. * * @param @@ -329,7 +472,7 @@ public class SearchPage extends SoneTemplatePage { if (post.getRecipient() != null) { postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(post.getRecipient())); } - for (Reply reply : Filters.filteredList(webInterface.getCore().getReplies(post), Reply.FUTURE_REPLIES_FILTER)) { + for (PostReply reply : Filters.filteredList(webInterface.getCore().getReplies(post), Reply.FUTURE_REPLY_FILTER)) { postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(reply.getSone())); postString.append(' ').append(reply.getText()); } @@ -401,6 +544,30 @@ public class SearchPage extends SoneTemplatePage { return optionality; } + // + // OBJECT METHODS + // + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return phrase.hashCode() ^ ((optionality == Optionality.FORBIDDEN) ? (0xaaaaaaaa) : ((optionality == Optionality.REQUIRED) ? 0x55555555 : 0)); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object object) { + if (!(object instanceof Phrase)) { + return false; + } + Phrase phrase = (Phrase) object; + return (this.optionality == phrase.optionality) && this.phrase.equals(phrase.phrase); + } + } /** @@ -480,13 +647,13 @@ public class SearchPage extends SoneTemplatePage { * The type of the object to extract * @author David ‘Bombe’ Roden */ - public static class HitConverter implements Converter, T> { + public static class HitMapper implements Mapper, T> { /** * {@inheritDoc} */ @Override - public T convert(Hit input) { + public T map(Hit input) { return input.getObject(); }