Search.java 14.4 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4 5
 * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
 * Yahoo!, Inc.
K
kohsuke 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
25 26
package hudson.search;

27
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
28
import hudson.Util;
K
bug fix  
kohsuke 已提交
29
import hudson.util.EditDistance;
30

31
import java.io.IOException;
32 33
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
34 35 36 37 38 39
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
40 41 42
import java.util.logging.Level;
import java.util.logging.Logger;

43
import javax.servlet.ServletException;
44

45 46
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
K
kohsuke 已提交
47
import org.kohsuke.stapler.Ancestor;
48
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
49 50
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
51
import org.kohsuke.stapler.export.DataWriter;
52
import org.kohsuke.stapler.export.Exported;
53 54
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Flavor;
K
bug fix  
kohsuke 已提交
55

56
/**
K
Kohsuke Kawaguchi 已提交
57 58 59 60 61
 * Web-bound object that provides search/navigation capability.
 *
 * <p>
 * This object is bound to "./search" of a model object via {@link SearchableModelObject} and serves
 * HTTP requests coming from JavaScript to provide search result and auto-completion.
K
bug fix  
kohsuke 已提交
62
 *
63
 * @author Kohsuke Kawaguchi
K
Kohsuke Kawaguchi 已提交
64
 * @see SearchableModelObject
65 66
 */
public class Search {
67 68 69 70 71
    @Restricted(NoExternalUse.class) // used from stapler views only
    public static String encodeQuery(String query) throws UnsupportedEncodingException {
        return URLEncoder.encode(query, "UTF-8");
    }

72
    public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
73 74 75
        List<Ancestor> l = req.getAncestors();
        for( int i=l.size()-1; i>=0; i-- ) {
            Ancestor a = l.get(i);
K
bug fix  
kohsuke 已提交
76 77
            if (a.getObject() instanceof SearchableModelObject) {
                SearchableModelObject smo = (SearchableModelObject) a.getObject();
78 79
                if(LOGGER.isLoggable(Level.FINE)){
                    LOGGER.fine(String.format("smo.displayName=%s, searchName=%s",smo.getDisplayName(), smo.getSearchName()));
80
                }
K
bug fix  
kohsuke 已提交
81 82 83

                SearchIndex index = smo.getSearchIndex();
                String query = req.getParameter("q");
84
                if(query!=null) {
85
                    SuggestedItem target = find(index, query, smo);
86 87
                    if(target!=null) {
                        // found
88
                        rsp.sendRedirect2(req.getContextPath()+target.getUrl());
89 90
                        return;
                    }
K
bug fix  
kohsuke 已提交
91 92 93 94
                }
            }
        }

95 96 97
        // no exact match. show the suggestions
        rsp.setStatus(SC_NOT_FOUND);
        req.getView(this,"search-failed.jelly").forward(req,rsp);
K
bug fix  
kohsuke 已提交
98 99
    }

100
    /**
101 102 103 104 105
     * Used by OpenSearch auto-completion. Returns JSON array of the form:
     *
     * <pre>
     * ["queryString",["comp1","comp2",...]]
     * </pre>
K
kohsuke 已提交
106 107
     *
     * See http://developer.mozilla.org/en/docs/Supporting_search_suggestions_in_search_plugins
108
     */
109
    public void doSuggestOpenSearch(StaplerRequest req, StaplerResponse rsp, @QueryParameter String q) throws IOException, ServletException {
K
Kohsuke Kawaguchi 已提交
110
        rsp.setContentType(Flavor.JSON.contentType);
111 112
        DataWriter w = Flavor.JSON.createDataWriter(null, rsp);
        w.startArray();
113
        w.value(q);
114 115

        w.startArray();
116
        for (SuggestedItem item : getSuggestions(req, q))
117
            w.value(item.getPath());
118 119 120
        w.endArray();
        w.endArray();
    }
121

122 123 124
    /**
     * Used by search box auto-completion. Returns JSON array.
     */
125
    public void doSuggest(StaplerRequest req, StaplerResponse rsp, @QueryParameter String query) throws IOException, ServletException {
126
        Result r = new Result();
127 128
        for (SuggestedItem item : getSuggestions(req, query))
            r.suggestions.add(new Item(item.getPath()));
129 130 131 132

        rsp.serveExposedBean(req,r,Flavor.JSON);
    }

133 134 135 136 137 138 139
    /**
     * Gets the list of suggestions that match the given query.
     *
     * @return
     *      can be empty but never null. The size of the list is always smaller than
     *      a certain threshold to avoid showing too many options. 
     */
N
Nicolas De Loof 已提交
140
    public SearchResult getSuggestions(StaplerRequest req, String query) {
141
        Set<String> paths = new HashSet<String>();  // paths already added, to control duplicates
N
Nicolas De Loof 已提交
142 143
        SearchResultImpl r = new SearchResultImpl();
        int max = req.hasParameter("max") ? Integer.parseInt(req.getParameter("max")) : 20;
144 145
        SearchableModelObject smo = findClosestSearchableModelObject(req);
        for (SuggestedItem i : suggest(makeSuggestIndex(req), query, smo)) {
N
Nicolas De Loof 已提交
146 147 148 149
            if(r.size()>=max) {
                r.hasMoreResults = true;
                break;
            }
150 151 152 153 154 155
            if(paths.add(i.getPath()))
                r.add(i);
        }
        return r;
    }

156 157 158 159 160 161 162 163 164 165 166
    private SearchableModelObject findClosestSearchableModelObject(StaplerRequest req) {
        List<Ancestor> l = req.getAncestors();
        for( int i=l.size()-1; i>=0; i-- ) {
            Ancestor a = l.get(i);
            if (a.getObject() instanceof SearchableModelObject) {
                return (SearchableModelObject)a.getObject();
            }
        }
        return null;
    }

167 168 169 170 171 172 173 174 175 176 177 178 179 180
    /**
     * Creates merged search index for suggestion.
     */
    private SearchIndex makeSuggestIndex(StaplerRequest req) {
        SearchIndexBuilder builder = new SearchIndexBuilder();
        for (Ancestor a : req.getAncestors()) {
            if (a.getObject() instanceof SearchableModelObject) {
                SearchableModelObject smo = (SearchableModelObject) a.getObject();
                builder.add(smo.getSearchIndex());
            }
        }
        return builder.make();
    }

N
Nicolas De Loof 已提交
181 182 183 184 185 186 187 188 189
    private static class SearchResultImpl extends ArrayList<SuggestedItem> implements SearchResult {

        private boolean hasMoreResults = false;

        public boolean hasMoreResults() {
            return hasMoreResults;
        }
    }

190 191 192
    @ExportedBean
    public static class Result {
        @Exported
193
        public List<Item> suggestions = new ArrayList<Item>();
194 195 196 197 198 199 200 201 202 203 204 205
    }

    @ExportedBean(defaultVisibility=999)
    public static class Item {
        @Exported
        public String name;

        public Item(String name) {
            this.name = name;
        }
    }

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    private enum Mode {
        FIND {
            void find(SearchIndex index, String token, List<SearchItem> result) {
                index.find(token, result);
            }
        },
        SUGGEST {
            void find(SearchIndex index, String token, List<SearchItem> result) {
                index.suggest(token, result);
            }
        };

        abstract void find(SearchIndex index, String token, List<SearchItem> result);

    }

K
bug fix  
kohsuke 已提交
222
    /**
223
     * When there are multiple suggested items, this method can narrow down the resultset
224 225 226 227 228 229 230 231 232 233 234
     * to the SuggestedItem that has a url that contains the query. This is useful is one
     * job has a display name that matches another job's project name.
     * @param r A list of Suggested items. It is assumed that there is at least one 
     * SuggestedItem in r.
     * @param query A query string
     * @return Returns the SuggestedItem which has a search url that contains the query.
     * If no SuggestedItems have a search url which contains the query, then the first
     * SuggestedItem in the List is returned.
     */
    static SuggestedItem findClosestSuggestedItem(List<SuggestedItem> r, String query) {
        for(SuggestedItem curItem : r) {
235 236
            if(LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(String.format("item's searchUrl:%s;query=%s", curItem.item.getSearchUrl(), query));
237 238 239 240 241 242 243 244 245 246 247 248
            }
            if(curItem.item.getSearchUrl().contains(Util.rawEncode(query))) {
                return curItem;
            }
        }
        
        // couldn't find an item with the query in the url so just
        // return the first one
        return r.get(0);        
    }
    
    /**
249
     * @deprecated Use {@link Search#find(SearchIndex, String, SearchableModelObject)} instead.
K
bug fix  
kohsuke 已提交
250
     */
251
    @Deprecated
K
bug fix  
kohsuke 已提交
252
    public static SuggestedItem find(SearchIndex index, String query) {
253 254 255 256 257 258
        return find(index, query, null);
    }
    
    /**
     * Performs a search and returns the match, or null if no match was found
     * or more than one match was found.
259
     * @since 1.527
260 261 262
     */
    public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) {
        List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext);
263 264 265 266 267 268 269 270 271 272 273 274
        if(r.isEmpty()){ 
            return null;
        }
        else if(1==r.size()){
            return r.get(0);
        }
        else  {
            // we have more than one suggested item, so return the item who's url
            // contains the query as this is probably the job's name
            return findClosestSuggestedItem(r, query);
        }
                    
275 276
    }

277 278 279 280
    /**
     * @deprecated use {@link Search#suggest(SearchIndex, String, SearchableModelObject)} instead. 
     */
    @Deprecated
281
    public static List<SuggestedItem> suggest(SearchIndex index, final String tokenList) {
282 283 284 285
        return suggest(index, tokenList, null);
    }

    /**
286
     * @since 1.527
287 288
     */
    public static List<SuggestedItem> suggest(SearchIndex index, final String tokenList, SearchableModelObject searchContext) {
289 290

        class Tag implements Comparable<Tag>{
K
kohsuke 已提交
291 292 293
            final SuggestedItem item;
            final int distance;
            /** If the path to this suggestion starts with the token list, 1. Otherwise 0. */
K
kohsuke 已提交
294
            final int prefixMatch;
295 296

            Tag(SuggestedItem i) {
K
kohsuke 已提交
297
                item = i;
298
                distance = EditDistance.editDistance(i.getPath(),tokenList);
K
kohsuke 已提交
299
                prefixMatch = i.getPath().startsWith(tokenList)?1:0;
300 301 302
            }

            public int compareTo(Tag that) {
K
kohsuke 已提交
303
                int r = this.prefixMatch -that.prefixMatch;
K
kohsuke 已提交
304
                if(r!=0)    return -r;  // ones with head match should show up earlier
305 306 307 308 309
                return this.distance-that.distance;
            }
        }

        List<Tag> buf = new ArrayList<Tag>();
310
        List<SuggestedItem> items = find(Mode.SUGGEST, index, tokenList, searchContext);
311 312 313 314 315 316 317 318 319 320 321 322

        // sort them
        for( SuggestedItem i : items)
            buf.add(new Tag(i));
        Collections.sort(buf);
        items.clear();
        for (Tag t : buf)
            items.add(t.item);

        return items;
    }

323 324 325
    static final class TokenList {
        private final String[] tokens;

326 327
        private final static String[] EMPTY = new String[0];

328
        public TokenList(String tokenList) {
329
            tokens = tokenList!=null ? tokenList.split("(?<=\\s)(?=\\S)") : EMPTY;
330 331 332 333 334 335
        }

        public int length() { return tokens.length; }

        /**
         * Returns {@link List} such that its <tt>get(end)</tt>
336
         * returns the concatenation of [token_start,...,token_end]
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
         * (both end inclusive.)
         */
        public List<String> subSequence(final int start) {
            return new AbstractList<String>() {
                public String get(int index) {
                    StringBuilder buf = new StringBuilder();
                    for(int i=start; i<=start+index; i++ )
                        buf.append(tokens[i]);
                    return buf.toString().trim();
                }

                public int size() {
                    return tokens.length-start;
                }
            };
        }
353 354 355 356 357 358 359 360 361 362 363 364
        
        
        public String toString() {
            StringBuilder s = new StringBuilder("TokenList{");
            for(String token : tokens) {
                s.append(token);
                s.append(",");
            }
            s.append('}');
            
            return s.toString();
        }
365 366
    }

367
    private static List<SuggestedItem> find(Mode m, SearchIndex index, String tokenList, SearchableModelObject searchContext) {
368 369 370 371 372 373 374
        TokenList tokens = new TokenList(tokenList);
        if(tokens.length()==0) return Collections.emptyList();   // no tokens given

        List<SuggestedItem>[] paths = new List[tokens.length()+1]; // we won't use [0].
        for(int i=1;i<=tokens.length();i++)
            paths[i] = new ArrayList<SuggestedItem>();

375 376
        List<SearchItem> items = new ArrayList<SearchItem>(); // items found in 1 step

J
Jesse Glick 已提交
377
        LOGGER.log(Level.FINE, "tokens={0}", tokens);
378
        
379
        // first token
380 381 382 383
        int w=1;    // width of token
        for (String token : tokens.subSequence(0)) {
            items.clear();
            m.find(index,token,items);
384
            for (SearchItem si : items) {
385
                paths[w].add(SuggestedItem.build(searchContext ,si));
J
Jesse Glick 已提交
386
                LOGGER.log(Level.FINE, "found search item: {0}", si.getSearchName());
387
            }
388 389
            w++;
        }
390 391

        // successive tokens
392 393 394 395 396 397 398 399 400 401 402 403
        for (int j=1; j<tokens.length(); j++) {
            // for each length
            w=1;
            for (String token : tokens.subSequence(j)) {
                // for each candidate
                for (SuggestedItem r : paths[j]) {
                    items.clear();
                    m.find(r.item.getSearchIndex(),token,items);
                    for (SearchItem i : items)
                        paths[j+w].add(new SuggestedItem(r,i));
                }
                w++;
404 405 406
            }
        }

407
        return paths[tokens.length()];
408
    }
409
    
410
    private final static Logger LOGGER = Logger.getLogger(Search.class.getName());
411
}