Use Guava’s predicate instead of utils’ filter.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / SearchPage.java
index fab7a57..002e4f2 100644 (file)
@@ -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,22 +28,22 @@ 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.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.Mapper;
-import net.pterodactylus.util.collection.Mappers;
 import net.pterodactylus.util.collection.Pagination;
 import net.pterodactylus.util.collection.TimedMap;
-import net.pterodactylus.util.filter.Filter;
-import net.pterodactylus.util.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;
@@ -51,6 +51,9 @@ import net.pterodactylus.util.template.TemplateContext;
 import net.pterodactylus.util.text.StringEscaper;
 import net.pterodactylus.util.text.TextException;
 
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+
 /**
  * This page lets the user search for posts and replies that contain certain
  * words.
@@ -65,13 +68,14 @@ public class SearchPage extends SoneTemplatePage {
        /** Short-term cache. */
        private final Cache<List<Phrase>, Set<Hit<Post>>> hitCache = new MemoryCache<List<Phrase>, Set<Hit<Post>>>(new ValueRetriever<List<Phrase>, Set<Hit<Post>>>() {
 
+               @Override
                @SuppressWarnings("synthetic-access")
                public CacheItem<Set<Hit<Post>>> retrieve(List<Phrase> phrases) throws CacheException {
                        Set<Post> posts = new HashSet<Post>();
                        for (Sone sone : webInterface.getCore().getSones()) {
                                posts.addAll(sone.getPosts());
                        }
-                       return new DefaultCacheItem<Set<Hit<Post>>>(getHits(Filters.filteredSet(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator()));
+                       return new DefaultCacheItem<Set<Hit<Post>>>(getHits(Collections2.filter(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator()));
                }
 
        }, new TimedMap<List<Phrase>, CacheItem<Set<Hit<Post>>>>(300000));
@@ -96,7 +100,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) {
@@ -108,10 +112,30 @@ public class SearchPage extends SoneTemplatePage {
                        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<Sone> sones = webInterface.getCore().getSones();
-               Set<Hit<Sone>> soneHits = getHits(sones, phrases, SoneStringGenerator.COMPLETE_GENERATOR);
+               Collection<Hit<Sone>> soneHits = getHits(sones, phrases, SoneStringGenerator.COMPLETE_GENERATOR);
 
-               Set<Hit<Post>> postHits;
+               Collection<Hit<Post>> postHits;
                try {
                        postHits = hitCache.get(phrases);
                } catch (CacheException ce1) {
@@ -121,8 +145,8 @@ public class SearchPage extends SoneTemplatePage {
                }
 
                /* now filter. */
-               soneHits = Filters.filteredSet(soneHits, Hit.POSITIVE_FILTER);
-               postHits = Filters.filteredSet(postHits, Hit.POSITIVE_FILTER);
+               soneHits = Collections2.filter(soneHits, Hit.POSITIVE_FILTER);
+               postHits = Collections2.filter(postHits, Hit.POSITIVE_FILTER);
 
                /* now sort. */
                List<Hit<Sone>> sortedSoneHits = new ArrayList<Hit<Sone>>(soneHits);
@@ -165,7 +189,7 @@ public class SearchPage extends SoneTemplatePage {
         *            The string generator for the objects
         * @return The hits for the given phrases
         */
-       private <T> Set<Hit<T>> getHits(Collection<T> objects, List<Phrase> phrases, StringGenerator<T> stringGenerator) {
+       private static <T> Set<Hit<T>> getHits(Collection<T> objects, List<Phrase> phrases, StringGenerator<T> stringGenerator) {
                Set<Hit<T>> hits = new HashSet<Hit<T>>();
                for (T object : objects) {
                        String objectString = stringGenerator.generateString(object);
@@ -186,7 +210,7 @@ public class SearchPage extends SoneTemplatePage {
         *            The query to parse
         * @return The parsed phrases
         */
-       private List<Phrase> parseSearchPhrases(String query) {
+       private static List<Phrase> parseSearchPhrases(String query) {
                List<String> parsedPhrases = null;
                try {
                        parsedPhrases = StringEscaper.parseLine(query);
@@ -226,8 +250,8 @@ public class SearchPage extends SoneTemplatePage {
         *            The expression to search
         * @return The score of the expression
         */
-       private double calculateScore(List<Phrase> phrases, String expression) {
-               logger.log(Level.FINEST, "Calculating Score for “%s”…", expression);
+       private static double calculateScore(List<Phrase> phrases, String expression) {
+               logger.log(Level.FINEST, String.format("Calculating Score for “%s”…", expression));
                double optionalHits = 0;
                double requiredHits = 0;
                int forbiddenHits = 0;
@@ -247,10 +271,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;
                        }
@@ -268,6 +292,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().getPostReply(replyId, false) != null) ? webInterface.getCore().getPostReply(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 <T>
@@ -364,7 +473,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 : Collections2.filter(webInterface.getCore().getReplies(post), Reply.FUTURE_REPLY_FILTER)) {
                                postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(reply.getSone()));
                                postString.append(' ').append(reply.getText());
                        }
@@ -474,10 +583,10 @@ public class SearchPage extends SoneTemplatePage {
        private static class Hit<T> {
 
                /** Filter for {@link Hit}s with a score of more than 0. */
-               public static final Filter<Hit<?>> POSITIVE_FILTER = new Filter<Hit<?>>() {
+               public static final Predicate<Hit<?>> POSITIVE_FILTER = new Predicate<Hit<?>>() {
 
                        @Override
-                       public boolean filterObject(Hit<?> hit) {
+                       public boolean apply(Hit<?> hit) {
                                return hit.getScore() > 0;
                        }