1 // Copyright 2010 Google Inc. All Rights Reserved.
3 package com
.google
.appengine
.api
.search
.checkers
;
5 import com
.google
.appengine
.api
.search
.SearchQueryException
;
6 import com
.google
.appengine
.api
.search
.SearchServicePb
.SearchParams
;
7 import com
.google
.appengine
.api
.search
.query
.QueryTreeBuilder
;
9 import org
.antlr
.runtime
.RecognitionException
;
11 import java
.io
.UnsupportedEncodingException
;
14 * Checks values of {@link com.google.appengine.api.search.Query}.
17 public final class QueryChecker
{
19 * The maximum length of a query string.
21 public static final int MAXIMUM_QUERY_LENGTH
= 2000;
24 * Checks that query is not null and is parsable.
25 * @param query the query to check
26 * @return the checked query
27 * @throws SearchQueryException if the query is not parsable
28 * @throws IllegalArgumentException if the query is too long
30 public static String
checkQuery(String query
) {
31 Preconditions
.checkNotNull(query
, "query cannot be null");
34 length
= query
.getBytes("UTF-8").length
;
35 } catch (UnsupportedEncodingException e
){
36 throw new IllegalArgumentException("Unsupported encoding UTF-8. Shouldn't happen, ever!");
38 Preconditions
.checkArgument(
39 length
<= MAXIMUM_QUERY_LENGTH
,
40 String
.format("query string must not be longer than %d bytes, was %d", MAXIMUM_QUERY_LENGTH
,
43 new QueryTreeBuilder().parse(query
);
44 } catch (RecognitionException e
) {
45 throw new SearchQueryException("Unable to parse query: " + query
);
51 * Checks the search specification is valid, specifically, has a valid
52 * index specification, a non-null query, a non-null number of documents
53 * to return specification, a valid cursor if present, valid sort
54 * specification list, a valid collection of field names for sorting,
55 * and a valid scorer specification.
57 * @param params the SearchParams to check
58 * @return this checked SearchParams
59 * @throws IllegalArgumentException if some part of the specification is
61 * @throws SearchQueryException if the query is unparsable
63 public static SearchParams
checkValid(SearchParams params
) {
64 IndexChecker
.checkName(params
.getIndexSpec().getName());
65 checkQuery(params
.getQuery());
66 QueryOptionsChecker
.checkValid(params
);