add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / backwards / src / test / org / apache / lucene / queryParser / TestQueryParser.java
1 package org.apache.lucene.queryParser;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import java.io.IOException;
21 import java.io.Reader;
22 import java.text.Collator;
23 import java.text.DateFormat;
24 import java.util.Calendar;
25 import java.util.Date;
26 import java.util.GregorianCalendar;
27 import java.util.HashSet;
28 import java.util.Locale;
29 import java.util.Set;
30
31 import org.apache.lucene.analysis.Analyzer;
32 import org.apache.lucene.analysis.KeywordAnalyzer;
33 import org.apache.lucene.analysis.LowerCaseTokenizer;
34 import org.apache.lucene.analysis.MockAnalyzer;
35 import org.apache.lucene.analysis.MockTokenizer;
36 import org.apache.lucene.analysis.SimpleAnalyzer;
37 import org.apache.lucene.analysis.StopAnalyzer;
38 import org.apache.lucene.analysis.StopFilter;
39 import org.apache.lucene.analysis.TokenFilter;
40 import org.apache.lucene.analysis.TokenStream;
41 import org.apache.lucene.analysis.WhitespaceAnalyzer;
42 import org.apache.lucene.analysis.standard.StandardAnalyzer;
43 import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
44 import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
45 import org.apache.lucene.document.DateField;
46 import org.apache.lucene.document.DateTools;
47 import org.apache.lucene.document.Document;
48 import org.apache.lucene.document.Field;
49 import org.apache.lucene.index.IndexWriter;
50 import org.apache.lucene.index.Term;
51 import org.apache.lucene.index.IndexReader;
52 import org.apache.lucene.search.BooleanQuery;
53 import org.apache.lucene.search.BooleanClause;
54 import org.apache.lucene.search.MultiTermQuery;
55 import org.apache.lucene.search.FuzzyQuery;
56 import org.apache.lucene.search.IndexSearcher;
57 import org.apache.lucene.search.MatchAllDocsQuery;
58 import org.apache.lucene.search.PhraseQuery;
59 import org.apache.lucene.search.PrefixQuery;
60 import org.apache.lucene.search.Query;
61 import org.apache.lucene.search.TermRangeQuery;
62 import org.apache.lucene.search.ScoreDoc;
63 import org.apache.lucene.search.TermQuery;
64 import org.apache.lucene.search.WildcardQuery;
65 import org.apache.lucene.store.Directory;
66 import org.apache.lucene.util.LuceneTestCase;
67
68 /**
69  * Tests QueryParser.
70  */
71 public class TestQueryParser extends LuceneTestCase {
72   
73   public static Analyzer qpAnalyzer = new QPTestAnalyzer();
74
75   public static final class QPTestFilter extends TokenFilter {
76     CharTermAttribute termAtt;
77     OffsetAttribute offsetAtt;
78         
79     /**
80      * Filter which discards the token 'stop' and which expands the
81      * token 'phrase' into 'phrase1 phrase2'
82      */
83     public QPTestFilter(TokenStream in) {
84       super(in);
85       termAtt = addAttribute(CharTermAttribute.class);
86       offsetAtt = addAttribute(OffsetAttribute.class);
87     }
88
89     boolean inPhrase = false;
90     int savedStart = 0, savedEnd = 0;
91
92     @Override
93     public boolean incrementToken() throws IOException {
94       if (inPhrase) {
95         inPhrase = false;
96         clearAttributes();
97         termAtt.append("phrase2");
98         offsetAtt.setOffset(savedStart, savedEnd);
99         return true;
100       } else
101         while (input.incrementToken()) {
102           if (termAtt.toString().equals("phrase")) {
103             inPhrase = true;
104             savedStart = offsetAtt.startOffset();
105             savedEnd = offsetAtt.endOffset();
106             termAtt.setEmpty().append("phrase1");
107             offsetAtt.setOffset(savedStart, savedEnd);
108             return true;
109           } else if (!termAtt.toString().equals("stop"))
110             return true;
111         }
112       return false;
113     }
114   }
115
116   
117   public static final class QPTestAnalyzer extends Analyzer {
118
119     /** Filters LowerCaseTokenizer with StopFilter. */
120     @Override
121     public final TokenStream tokenStream(String fieldName, Reader reader) {
122       return new QPTestFilter(new LowerCaseTokenizer(TEST_VERSION_CURRENT, reader));
123     }
124   }
125
126   public static class QPTestParser extends QueryParser {
127     public QPTestParser(String f, Analyzer a) {
128       super(TEST_VERSION_CURRENT, f, a);
129     }
130
131     @Override
132     protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException {
133       throw new ParseException("Fuzzy queries not allowed");
134     }
135
136     @Override
137     protected Query getWildcardQuery(String field, String termStr) throws ParseException {
138       throw new ParseException("Wildcard queries not allowed");
139     }
140   }
141
142   private int originalMaxClauses;
143
144   @Override
145   public void setUp() throws Exception {
146     super.setUp();
147     originalMaxClauses = BooleanQuery.getMaxClauseCount();
148   }
149
150   public QueryParser getParser(Analyzer a) throws Exception {
151     if (a == null)
152       a = new MockAnalyzer(random, MockTokenizer.SIMPLE, true);
153     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", a);
154     qp.setDefaultOperator(QueryParser.OR_OPERATOR);
155     return qp;
156   }
157
158   public Query getQuery(String query, Analyzer a) throws Exception {
159     return getParser(a).parse(query);
160   }
161
162   public void assertQueryEquals(String query, Analyzer a, String result)
163     throws Exception {
164     Query q = getQuery(query, a);
165     String s = q.toString("field");
166     if (!s.equals(result)) {
167       fail("Query /" + query + "/ yielded /" + s
168            + "/, expecting /" + result + "/");
169     }
170   }
171
172   public void assertQueryEquals(QueryParser qp, String field, String query, String result) 
173     throws Exception {
174     Query q = qp.parse(query);
175     String s = q.toString(field);
176     if (!s.equals(result)) {
177       fail("Query /" + query + "/ yielded /" + s
178            + "/, expecting /" + result + "/");
179     }
180   }
181   
182   public void assertEscapedQueryEquals(String query, Analyzer a, String result)
183     throws Exception {
184     String escapedQuery = QueryParser.escape(query);
185     if (!escapedQuery.equals(result)) {
186       fail("Query /" + query + "/ yielded /" + escapedQuery
187           + "/, expecting /" + result + "/");
188     }
189   }
190
191   public void assertWildcardQueryEquals(String query, boolean lowercase, String result, boolean allowLeadingWildcard)
192     throws Exception {
193     QueryParser qp = getParser(null);
194     qp.setLowercaseExpandedTerms(lowercase);
195     qp.setAllowLeadingWildcard(allowLeadingWildcard);
196     Query q = qp.parse(query);
197     String s = q.toString("field");
198     if (!s.equals(result)) {
199       fail("WildcardQuery /" + query + "/ yielded /" + s
200            + "/, expecting /" + result + "/");
201     }
202   }
203
204   public void assertWildcardQueryEquals(String query, boolean lowercase, String result)
205     throws Exception {
206     assertWildcardQueryEquals(query, lowercase, result, false);
207   }
208
209   public void assertWildcardQueryEquals(String query, String result) throws Exception {
210     QueryParser qp = getParser(null);
211     Query q = qp.parse(query);
212     String s = q.toString("field");
213     if (!s.equals(result)) {
214       fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /"
215           + result + "/");
216     }
217   }
218
219   public Query getQueryDOA(String query, Analyzer a)
220     throws Exception {
221     if (a == null)
222       a = new MockAnalyzer(random, MockTokenizer.SIMPLE, true);
223     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", a);
224     qp.setDefaultOperator(QueryParser.AND_OPERATOR);
225     return qp.parse(query);
226   }
227
228   public void assertQueryEqualsDOA(String query, Analyzer a, String result)
229     throws Exception {
230     Query q = getQueryDOA(query, a);
231     String s = q.toString("field");
232     if (!s.equals(result)) {
233       fail("Query /" + query + "/ yielded /" + s
234            + "/, expecting /" + result + "/");
235     }
236   }
237
238   public void testCJK() throws Exception {
239          // Test Ideographic Space - As wide as a CJK character cell (fullwidth)
240          // used google to translate the word "term" to japanese -> ç”¨èªž
241          assertQueryEquals("term\u3000term\u3000term", null, "term\u0020term\u0020term");
242          assertQueryEquals("用語\u3000用語\u3000用語", null, "用語\u0020用語\u0020用語");
243   }
244
245   public void testCJKTerm() throws Exception {
246     // individual CJK chars as terms
247     StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT); 
248     
249     BooleanQuery expected = new BooleanQuery();
250     expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
251     expected.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
252     
253     assertEquals(expected, getQuery("中国", analyzer));
254   }
255   
256   public void testCJKBoostedTerm() throws Exception {
257     // individual CJK chars as terms
258     StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
259     
260     BooleanQuery expected = new BooleanQuery();
261     expected.setBoost(0.5f);
262     expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
263     expected.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
264     
265     assertEquals(expected, getQuery("中国^0.5", analyzer));
266   }
267   
268   public void testCJKPhrase() throws Exception {
269     // individual CJK chars as terms
270     StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
271     
272     PhraseQuery expected = new PhraseQuery();
273     expected.add(new Term("field", "中"));
274     expected.add(new Term("field", "国"));
275     
276     assertEquals(expected, getQuery("\"中国\"", analyzer));
277   }
278   
279   public void testCJKBoostedPhrase() throws Exception {
280     // individual CJK chars as terms
281     StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
282     
283     PhraseQuery expected = new PhraseQuery();
284     expected.setBoost(0.5f);
285     expected.add(new Term("field", "中"));
286     expected.add(new Term("field", "国"));
287     
288     assertEquals(expected, getQuery("\"中国\"^0.5", analyzer));
289   }
290   
291   public void testCJKSloppyPhrase() throws Exception {
292     // individual CJK chars as terms
293     StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
294     
295     PhraseQuery expected = new PhraseQuery();
296     expected.setSlop(3);
297     expected.add(new Term("field", "中"));
298     expected.add(new Term("field", "国"));
299     
300     assertEquals(expected, getQuery("\"中国\"~3", analyzer));
301   }
302   
303   public void testAutoGeneratePhraseQueriesOn() throws Exception {
304     // individual CJK chars as terms
305     StandardAnalyzer analyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
306   
307     PhraseQuery expected = new PhraseQuery();
308     expected.add(new Term("field", "中"));
309     expected.add(new Term("field", "国"));
310     QueryParser parser = new QueryParser(TEST_VERSION_CURRENT, "field", analyzer);
311     parser.setAutoGeneratePhraseQueries(true);
312     assertEquals(expected, parser.parse("中国"));
313   }
314
315   public void testSimple() throws Exception {
316     assertQueryEquals("term term term", null, "term term term");
317     assertQueryEquals("türm term term", new MockAnalyzer(random), "türm term term");
318     assertQueryEquals("ümlaut", new MockAnalyzer(random), "ümlaut");
319
320     assertQueryEquals("\"\"", new KeywordAnalyzer(), "");
321     assertQueryEquals("foo:\"\"", new KeywordAnalyzer(), "foo:");
322
323     assertQueryEquals("a AND b", null, "+a +b");
324     assertQueryEquals("(a AND b)", null, "+a +b");
325     assertQueryEquals("c OR (a AND b)", null, "c (+a +b)");
326     assertQueryEquals("a AND NOT b", null, "+a -b");
327     assertQueryEquals("a AND -b", null, "+a -b");
328     assertQueryEquals("a AND !b", null, "+a -b");
329     assertQueryEquals("a && b", null, "+a +b");
330     assertQueryEquals("a && ! b", null, "+a -b");
331
332     assertQueryEquals("a OR b", null, "a b");
333     assertQueryEquals("a || b", null, "a b");
334     assertQueryEquals("a OR !b", null, "a -b");
335     assertQueryEquals("a OR ! b", null, "a -b");
336     assertQueryEquals("a OR -b", null, "a -b");
337
338     assertQueryEquals("+term -term term", null, "+term -term term");
339     assertQueryEquals("foo:term AND field:anotherTerm", null,
340                       "+foo:term +anotherterm");
341     assertQueryEquals("term AND \"phrase phrase\"", null,
342                       "+term +\"phrase phrase\"");
343     assertQueryEquals("\"hello there\"", null, "\"hello there\"");
344     assertTrue(getQuery("a AND b", null) instanceof BooleanQuery);
345     assertTrue(getQuery("hello", null) instanceof TermQuery);
346     assertTrue(getQuery("\"hello there\"", null) instanceof PhraseQuery);
347
348     assertQueryEquals("germ term^2.0", null, "germ term^2.0");
349     assertQueryEquals("(term)^2.0", null, "term^2.0");
350     assertQueryEquals("(germ term)^2.0", null, "(germ term)^2.0");
351     assertQueryEquals("term^2.0", null, "term^2.0");
352     assertQueryEquals("term^2", null, "term^2.0");
353     assertQueryEquals("\"germ term\"^2.0", null, "\"germ term\"^2.0");
354     assertQueryEquals("\"term germ\"^2", null, "\"term germ\"^2.0");
355
356     assertQueryEquals("(foo OR bar) AND (baz OR boo)", null,
357                       "+(foo bar) +(baz boo)");
358     assertQueryEquals("((a OR b) AND NOT c) OR d", null,
359                       "(+(a b) -c) d");
360     assertQueryEquals("+(apple \"steve jobs\") -(foo bar baz)", null,
361                       "+(apple \"steve jobs\") -(foo bar baz)");
362     assertQueryEquals("+title:(dog OR cat) -author:\"bob dole\"", null,
363                       "+(title:dog title:cat) -author:\"bob dole\"");
364     
365     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random));
366     // make sure OR is the default:
367     assertEquals(QueryParser.OR_OPERATOR, qp.getDefaultOperator());
368     qp.setDefaultOperator(QueryParser.AND_OPERATOR);
369     assertEquals(QueryParser.AND_OPERATOR, qp.getDefaultOperator());
370     qp.setDefaultOperator(QueryParser.OR_OPERATOR);
371     assertEquals(QueryParser.OR_OPERATOR, qp.getDefaultOperator());
372   }
373
374   public void testPunct() throws Exception {
375     Analyzer a = new MockAnalyzer(random, MockTokenizer.WHITESPACE, false);
376     assertQueryEquals("a&b", a, "a&b");
377     assertQueryEquals("a&&b", a, "a&&b");
378     assertQueryEquals(".NET", a, ".NET");
379   }
380
381   public void testSlop() throws Exception {
382     assertQueryEquals("\"term germ\"~2", null, "\"term germ\"~2");
383     assertQueryEquals("\"term germ\"~2 flork", null, "\"term germ\"~2 flork");
384     assertQueryEquals("\"term\"~2", null, "term");
385     assertQueryEquals("\" \"~2 germ", null, "germ");
386     assertQueryEquals("\"term germ\"~2^2", null, "\"term germ\"~2^2.0");
387   }
388
389   public void testNumber() throws Exception {
390 // The numbers go away because SimpleAnalzyer ignores them
391     assertQueryEquals("3", null, "");
392     assertQueryEquals("term 1.0 1 2", null, "term");
393     assertQueryEquals("term term1 term2", null, "term term term");
394
395     Analyzer a = new MockAnalyzer(random, MockTokenizer.WHITESPACE, true);
396     assertQueryEquals("3", a, "3");
397     assertQueryEquals("term 1.0 1 2", a, "term 1.0 1 2");
398     assertQueryEquals("term term1 term2", a, "term term1 term2");
399   }
400
401   public void testWildcard() throws Exception {
402     assertQueryEquals("term*", null, "term*");
403     assertQueryEquals("term*^2", null, "term*^2.0");
404     assertQueryEquals("term~", null, "term~0.5");
405     assertQueryEquals("term~0.7", null, "term~0.7");
406     assertQueryEquals("term~^2", null, "term~0.5^2.0");
407     assertQueryEquals("term^2~", null, "term~0.5^2.0");
408     assertQueryEquals("term*germ", null, "term*germ");
409     assertQueryEquals("term*germ^3", null, "term*germ^3.0");
410
411     assertTrue(getQuery("term*", null) instanceof PrefixQuery);
412     assertTrue(getQuery("term*^2", null) instanceof PrefixQuery);
413     assertTrue(getQuery("term~", null) instanceof FuzzyQuery);
414     assertTrue(getQuery("term~0.7", null) instanceof FuzzyQuery);
415     FuzzyQuery fq = (FuzzyQuery)getQuery("term~0.7", null);
416     assertEquals(0.7f, fq.getMinSimilarity(), 0.1f);
417     assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());
418     fq = (FuzzyQuery)getQuery("term~", null);
419     assertEquals(0.5f, fq.getMinSimilarity(), 0.1f);
420     assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());
421     
422     assertParseException("term~1.1"); // value > 1, throws exception
423
424     assertTrue(getQuery("term*germ", null) instanceof WildcardQuery);
425
426 /* Tests to see that wild card terms are (or are not) properly
427          * lower-cased with propery parser configuration
428          */
429 // First prefix queries:
430     // by default, convert to lowercase:
431     assertWildcardQueryEquals("Term*", true, "term*");
432     // explicitly set lowercase:
433     assertWildcardQueryEquals("term*", true, "term*");
434     assertWildcardQueryEquals("Term*", true, "term*");
435     assertWildcardQueryEquals("TERM*", true, "term*");
436     // explicitly disable lowercase conversion:
437     assertWildcardQueryEquals("term*", false, "term*");
438     assertWildcardQueryEquals("Term*", false, "Term*");
439     assertWildcardQueryEquals("TERM*", false, "TERM*");
440 // Then 'full' wildcard queries:
441     // by default, convert to lowercase:
442     assertWildcardQueryEquals("Te?m", "te?m");
443     // explicitly set lowercase:
444     assertWildcardQueryEquals("te?m", true, "te?m");
445     assertWildcardQueryEquals("Te?m", true, "te?m");
446     assertWildcardQueryEquals("TE?M", true, "te?m");
447     assertWildcardQueryEquals("Te?m*gerM", true, "te?m*germ");
448     // explicitly disable lowercase conversion:
449     assertWildcardQueryEquals("te?m", false, "te?m");
450     assertWildcardQueryEquals("Te?m", false, "Te?m");
451     assertWildcardQueryEquals("TE?M", false, "TE?M");
452     assertWildcardQueryEquals("Te?m*gerM", false, "Te?m*gerM");
453 //  Fuzzy queries:
454     assertWildcardQueryEquals("Term~", "term~0.5");
455     assertWildcardQueryEquals("Term~", true, "term~0.5");
456     assertWildcardQueryEquals("Term~", false, "Term~0.5");
457 //  Range queries:
458     assertWildcardQueryEquals("[A TO C]", "[a TO c]");
459     assertWildcardQueryEquals("[A TO C]", true, "[a TO c]");
460     assertWildcardQueryEquals("[A TO C]", false, "[A TO C]");
461     // Test suffix queries: first disallow
462     try {
463       assertWildcardQueryEquals("*Term", true, "*term");
464       fail();
465     } catch(ParseException pe) {
466       // expected exception
467     }
468     try {
469       assertWildcardQueryEquals("?Term", true, "?term");
470       fail();
471     } catch(ParseException pe) {
472       // expected exception
473     }
474     // Test suffix queries: then allow
475     assertWildcardQueryEquals("*Term", true, "*term", true);
476     assertWildcardQueryEquals("?Term", true, "?term", true);
477   }
478   
479   public void testLeadingWildcardType() throws Exception {
480     QueryParser qp = getParser(null);
481     qp.setAllowLeadingWildcard(true);
482     assertEquals(WildcardQuery.class, qp.parse("t*erm*").getClass());
483     assertEquals(WildcardQuery.class, qp.parse("?term*").getClass());
484     assertEquals(WildcardQuery.class, qp.parse("*term*").getClass());
485   }
486
487   public void testQPA() throws Exception {
488     assertQueryEquals("term term^3.0 term", qpAnalyzer, "term term^3.0 term");
489     assertQueryEquals("term stop^3.0 term", qpAnalyzer, "term term");
490     
491     assertQueryEquals("term term term", qpAnalyzer, "term term term");
492     assertQueryEquals("term +stop term", qpAnalyzer, "term term");
493     assertQueryEquals("term -stop term", qpAnalyzer, "term term");
494
495     assertQueryEquals("drop AND (stop) AND roll", qpAnalyzer, "+drop +roll");
496     assertQueryEquals("term +(stop) term", qpAnalyzer, "term term");
497     assertQueryEquals("term -(stop) term", qpAnalyzer, "term term");
498     
499     assertQueryEquals("drop AND stop AND roll", qpAnalyzer, "+drop +roll");
500     assertQueryEquals("term phrase term", qpAnalyzer,
501                       "term (phrase1 phrase2) term");
502     assertQueryEquals("term AND NOT phrase term", qpAnalyzer,
503                       "+term -(phrase1 phrase2) term");
504     assertQueryEquals("stop^3", qpAnalyzer, "");
505     assertQueryEquals("stop", qpAnalyzer, "");
506     assertQueryEquals("(stop)^3", qpAnalyzer, "");
507     assertQueryEquals("((stop))^3", qpAnalyzer, "");
508     assertQueryEquals("(stop^3)", qpAnalyzer, "");
509     assertQueryEquals("((stop)^3)", qpAnalyzer, "");
510     assertQueryEquals("(stop)", qpAnalyzer, "");
511     assertQueryEquals("((stop))", qpAnalyzer, "");
512     assertTrue(getQuery("term term term", qpAnalyzer) instanceof BooleanQuery);
513     assertTrue(getQuery("term +stop", qpAnalyzer) instanceof TermQuery);
514   }
515
516   public void testRange() throws Exception {
517     assertQueryEquals("[ a TO z]", null, "[a TO z]");
518     assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((TermRangeQuery)getQuery("[ a TO z]", null)).getRewriteMethod());
519
520     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.SIMPLE, true));
521     qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
522     assertEquals(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE,((TermRangeQuery)qp.parse("[ a TO z]")).getRewriteMethod());
523     
524     assertQueryEquals("[ a TO z ]", null, "[a TO z]");
525     assertQueryEquals("{ a TO z}", null, "{a TO z}");
526     assertQueryEquals("{ a TO z }", null, "{a TO z}");
527     assertQueryEquals("{ a TO z }^2.0", null, "{a TO z}^2.0");
528     assertQueryEquals("[ a TO z] OR bar", null, "[a TO z] bar");
529     assertQueryEquals("[ a TO z] AND bar", null, "+[a TO z] +bar");
530     assertQueryEquals("( bar blar { a TO z}) ", null, "bar blar {a TO z}");
531     assertQueryEquals("gack ( bar blar { a TO z}) ", null, "gack (bar blar {a TO z})");
532   }
533     
534   public void testFarsiRangeCollating() throws Exception {
535     Directory ramDir = newDirectory();
536     IndexWriter iw = new IndexWriter(ramDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
537     Document doc = new Document();
538     doc.add(newField("content","\u0633\u0627\u0628", 
539                       Field.Store.YES, Field.Index.NOT_ANALYZED));
540     iw.addDocument(doc);
541     iw.close();
542     IndexSearcher is = new IndexSearcher(ramDir, true);
543
544     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "content", new WhitespaceAnalyzer(TEST_VERSION_CURRENT));
545
546     // Neither Java 1.4.2 nor 1.5.0 has Farsi Locale collation available in
547     // RuleBasedCollator.  However, the Arabic Locale seems to order the Farsi
548     // characters properly.
549     Collator c = Collator.getInstance(new Locale("ar"));
550     qp.setRangeCollator(c);
551
552     // Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
553     // orders the U+0698 character before the U+0633 character, so the single
554     // index Term below should NOT be returned by a ConstantScoreRangeQuery
555     // with a Farsi Collator (or an Arabic one for the case when Farsi is not
556     // supported).
557       
558     // Test ConstantScoreRangeQuery
559     qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE);
560     ScoreDoc[] result = is.search(qp.parse("[ \u062F TO \u0698 ]"), null, 1000).scoreDocs;
561     assertEquals("The index Term should not be included.", 0, result.length);
562
563     result = is.search(qp.parse("[ \u0633 TO \u0638 ]"), null, 1000).scoreDocs;
564     assertEquals("The index Term should be included.", 1, result.length);
565
566     // Test TermRangeQuery
567     qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
568     result = is.search(qp.parse("[ \u062F TO \u0698 ]"), null, 1000).scoreDocs;
569     assertEquals("The index Term should not be included.", 0, result.length);
570
571     result = is.search(qp.parse("[ \u0633 TO \u0638 ]"), null, 1000).scoreDocs;
572     assertEquals("The index Term should be included.", 1, result.length);
573
574     is.close();
575     ramDir.close();
576   }
577   
578   private String escapeDateString(String s) {
579     if (s.indexOf(" ") > -1) {
580       return "\"" + s + "\"";
581     } else {
582       return s;
583     }
584   }
585   
586   /** for testing legacy DateField support */
587   private String getLegacyDate(String s) throws Exception {
588     DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
589     return DateField.dateToString(df.parse(s));
590   }
591
592   /** for testing DateTools support */
593   private String getDate(String s, DateTools.Resolution resolution) throws Exception {
594     DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
595     return getDate(df.parse(s), resolution);      
596   }
597   
598   /** for testing DateTools support */
599   private String getDate(Date d, DateTools.Resolution resolution) throws Exception {
600       if (resolution == null) {
601         return DateField.dateToString(d);      
602       } else {
603         return DateTools.dateToString(d, resolution);
604       }
605     }
606   
607   private String getLocalizedDate(int year, int month, int day) {
608     DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
609     Calendar calendar = new GregorianCalendar();
610     calendar.clear();
611     calendar.set(year, month, day);
612     calendar.set(Calendar.HOUR_OF_DAY, 23);
613     calendar.set(Calendar.MINUTE, 59);
614     calendar.set(Calendar.SECOND, 59);
615     calendar.set(Calendar.MILLISECOND, 999);
616     return df.format(calendar.getTime());
617   }
618
619   /** for testing legacy DateField support */
620   public void testLegacyDateRange() throws Exception {
621     String startDate = getLocalizedDate(2002, 1, 1);
622     String endDate = getLocalizedDate(2002, 1, 4);
623     Calendar endDateExpected = new GregorianCalendar();
624     endDateExpected.clear();
625     endDateExpected.set(2002, 1, 4, 23, 59, 59);
626     endDateExpected.set(Calendar.MILLISECOND, 999);
627     assertQueryEquals("[ " + escapeDateString(startDate) + " TO " + escapeDateString(endDate) + "]", null,
628                       "[" + getLegacyDate(startDate) + " TO " + DateField.dateToString(endDateExpected.getTime()) + "]");
629     assertQueryEquals("{  " + escapeDateString(startDate) + "    " + escapeDateString(endDate) + "   }", null,
630                       "{" + getLegacyDate(startDate) + " TO " + getLegacyDate(endDate) + "}");
631   }
632   
633   public void testDateRange() throws Exception {
634     String startDate = getLocalizedDate(2002, 1, 1);
635     String endDate = getLocalizedDate(2002, 1, 4);
636     Calendar endDateExpected = new GregorianCalendar();
637     endDateExpected.clear();
638     endDateExpected.set(2002, 1, 4, 23, 59, 59);
639     endDateExpected.set(Calendar.MILLISECOND, 999);
640     final String defaultField = "default";
641     final String monthField = "month";
642     final String hourField = "hour";
643     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.SIMPLE, true));
644     
645     // Don't set any date resolution and verify if DateField is used
646     assertDateRangeQueryEquals(qp, defaultField, startDate, endDate, 
647                                endDateExpected.getTime(), null);
648     
649     // set a field specific date resolution
650     qp.setDateResolution(monthField, DateTools.Resolution.MONTH);
651     
652     // DateField should still be used for defaultField
653     assertDateRangeQueryEquals(qp, defaultField, startDate, endDate, 
654                                endDateExpected.getTime(), null);
655     
656     // set default date resolution to MILLISECOND 
657     qp.setDateResolution(DateTools.Resolution.MILLISECOND);
658     
659     // set second field specific date resolution    
660     qp.setDateResolution(hourField, DateTools.Resolution.HOUR);
661
662     // for this field no field specific date resolution has been set,
663     // so verify if the default resolution is used
664     assertDateRangeQueryEquals(qp, defaultField, startDate, endDate, 
665             endDateExpected.getTime(), DateTools.Resolution.MILLISECOND);
666
667     // verify if field specific date resolutions are used for these two fields
668     assertDateRangeQueryEquals(qp, monthField, startDate, endDate, 
669             endDateExpected.getTime(), DateTools.Resolution.MONTH);
670
671     assertDateRangeQueryEquals(qp, hourField, startDate, endDate, 
672             endDateExpected.getTime(), DateTools.Resolution.HOUR);  
673   }
674   
675   public void assertDateRangeQueryEquals(QueryParser qp, String field, String startDate, String endDate, 
676                                          Date endDateInclusive, DateTools.Resolution resolution) throws Exception {
677     assertQueryEquals(qp, field, field + ":[" + escapeDateString(startDate) + " TO " + escapeDateString(endDate) + "]",
678                "[" + getDate(startDate, resolution) + " TO " + getDate(endDateInclusive, resolution) + "]");
679     assertQueryEquals(qp, field, field + ":{" + escapeDateString(startDate) + " TO " + escapeDateString(endDate) + "}",
680                "{" + getDate(startDate, resolution) + " TO " + getDate(endDate, resolution) + "}");
681   }
682
683   public void testEscaped() throws Exception {
684     Analyzer a = new MockAnalyzer(random, MockTokenizer.WHITESPACE, false);
685     
686     /*assertQueryEquals("\\[brackets", a, "\\[brackets");
687     assertQueryEquals("\\[brackets", null, "brackets");
688     assertQueryEquals("\\\\", a, "\\\\");
689     assertQueryEquals("\\+blah", a, "\\+blah");
690     assertQueryEquals("\\(blah", a, "\\(blah");
691
692     assertQueryEquals("\\-blah", a, "\\-blah");
693     assertQueryEquals("\\!blah", a, "\\!blah");
694     assertQueryEquals("\\{blah", a, "\\{blah");
695     assertQueryEquals("\\}blah", a, "\\}blah");
696     assertQueryEquals("\\:blah", a, "\\:blah");
697     assertQueryEquals("\\^blah", a, "\\^blah");
698     assertQueryEquals("\\[blah", a, "\\[blah");
699     assertQueryEquals("\\]blah", a, "\\]blah");
700     assertQueryEquals("\\\"blah", a, "\\\"blah");
701     assertQueryEquals("\\(blah", a, "\\(blah");
702     assertQueryEquals("\\)blah", a, "\\)blah");
703     assertQueryEquals("\\~blah", a, "\\~blah");
704     assertQueryEquals("\\*blah", a, "\\*blah");
705     assertQueryEquals("\\?blah", a, "\\?blah");
706     //assertQueryEquals("foo \\&\\& bar", a, "foo \\&\\& bar");
707     //assertQueryEquals("foo \\|| bar", a, "foo \\|| bar");
708     //assertQueryEquals("foo \\AND bar", a, "foo \\AND bar");*/
709
710     assertQueryEquals("\\a", a, "a");
711     
712     assertQueryEquals("a\\-b:c", a, "a-b:c");
713     assertQueryEquals("a\\+b:c", a, "a+b:c");
714     assertQueryEquals("a\\:b:c", a, "a:b:c");
715     assertQueryEquals("a\\\\b:c", a, "a\\b:c");
716
717     assertQueryEquals("a:b\\-c", a, "a:b-c");
718     assertQueryEquals("a:b\\+c", a, "a:b+c");
719     assertQueryEquals("a:b\\:c", a, "a:b:c");
720     assertQueryEquals("a:b\\\\c", a, "a:b\\c");
721
722     assertQueryEquals("a:b\\-c*", a, "a:b-c*");
723     assertQueryEquals("a:b\\+c*", a, "a:b+c*");
724     assertQueryEquals("a:b\\:c*", a, "a:b:c*");
725
726     assertQueryEquals("a:b\\\\c*", a, "a:b\\c*");
727
728     assertQueryEquals("a:b\\-?c", a, "a:b-?c");
729     assertQueryEquals("a:b\\+?c", a, "a:b+?c");
730     assertQueryEquals("a:b\\:?c", a, "a:b:?c");
731
732     assertQueryEquals("a:b\\\\?c", a, "a:b\\?c");
733
734     assertQueryEquals("a:b\\-c~", a, "a:b-c~0.5");
735     assertQueryEquals("a:b\\+c~", a, "a:b+c~0.5");
736     assertQueryEquals("a:b\\:c~", a, "a:b:c~0.5");
737     assertQueryEquals("a:b\\\\c~", a, "a:b\\c~0.5");
738
739     assertQueryEquals("[ a\\- TO a\\+ ]", null, "[a- TO a+]");
740     assertQueryEquals("[ a\\: TO a\\~ ]", null, "[a: TO a~]");
741     assertQueryEquals("[ a\\\\ TO a\\* ]", null, "[a\\ TO a*]");
742
743     assertQueryEquals("[\"c\\:\\\\temp\\\\\\~foo0.txt\" TO \"c\\:\\\\temp\\\\\\~foo9.txt\"]", a, 
744                       "[c:\\temp\\~foo0.txt TO c:\\temp\\~foo9.txt]");
745     
746     assertQueryEquals("a\\\\\\+b", a, "a\\+b");
747     
748     assertQueryEquals("a \\\"b c\\\" d", a, "a \"b c\" d");
749     assertQueryEquals("\"a \\\"b c\\\" d\"", a, "\"a \"b c\" d\"");
750     assertQueryEquals("\"a \\+b c d\"", a, "\"a +b c d\"");
751     
752     assertQueryEquals("c\\:\\\\temp\\\\\\~foo.txt", a, "c:\\temp\\~foo.txt");
753     
754     assertParseException("XY\\"); // there must be a character after the escape char
755     
756     // test unicode escaping
757     assertQueryEquals("a\\u0062c", a, "abc");
758     assertQueryEquals("XY\\u005a", a, "XYZ");
759     assertQueryEquals("XY\\u005A", a, "XYZ");
760     assertQueryEquals("\"a \\\\\\u0028\\u0062\\\" c\"", a, "\"a \\(b\" c\"");
761     
762     assertParseException("XY\\u005G");  // test non-hex character in escaped unicode sequence
763     assertParseException("XY\\u005");   // test incomplete escaped unicode sequence
764     
765     // Tests bug LUCENE-800
766     assertQueryEquals("(item:\\\\ item:ABCD\\\\)", a, "item:\\ item:ABCD\\");
767     assertParseException("(item:\\\\ item:ABCD\\\\))"); // unmatched closing paranthesis 
768     assertQueryEquals("\\*", a, "*");
769     assertQueryEquals("\\\\", a, "\\");  // escaped backslash
770     
771     assertParseException("\\"); // a backslash must always be escaped
772     
773     // LUCENE-1189
774     assertQueryEquals("(\"a\\\\\") or (\"b\")", a ,"a\\ or b");
775   }
776
777   public void testQueryStringEscaping() throws Exception {
778     Analyzer a = new MockAnalyzer(random, MockTokenizer.WHITESPACE, false);
779
780     assertEscapedQueryEquals("a-b:c", a, "a\\-b\\:c");
781     assertEscapedQueryEquals("a+b:c", a, "a\\+b\\:c");
782     assertEscapedQueryEquals("a:b:c", a, "a\\:b\\:c");
783     assertEscapedQueryEquals("a\\b:c", a, "a\\\\b\\:c");
784
785     assertEscapedQueryEquals("a:b-c", a, "a\\:b\\-c");
786     assertEscapedQueryEquals("a:b+c", a, "a\\:b\\+c");
787     assertEscapedQueryEquals("a:b:c", a, "a\\:b\\:c");
788     assertEscapedQueryEquals("a:b\\c", a, "a\\:b\\\\c");
789
790     assertEscapedQueryEquals("a:b-c*", a, "a\\:b\\-c\\*");
791     assertEscapedQueryEquals("a:b+c*", a, "a\\:b\\+c\\*");
792     assertEscapedQueryEquals("a:b:c*", a, "a\\:b\\:c\\*");
793
794     assertEscapedQueryEquals("a:b\\\\c*", a, "a\\:b\\\\\\\\c\\*");
795
796     assertEscapedQueryEquals("a:b-?c", a, "a\\:b\\-\\?c");
797     assertEscapedQueryEquals("a:b+?c", a, "a\\:b\\+\\?c");
798     assertEscapedQueryEquals("a:b:?c", a, "a\\:b\\:\\?c");
799
800     assertEscapedQueryEquals("a:b?c", a, "a\\:b\\?c");
801
802     assertEscapedQueryEquals("a:b-c~", a, "a\\:b\\-c\\~");
803     assertEscapedQueryEquals("a:b+c~", a, "a\\:b\\+c\\~");
804     assertEscapedQueryEquals("a:b:c~", a, "a\\:b\\:c\\~");
805     assertEscapedQueryEquals("a:b\\c~", a, "a\\:b\\\\c\\~");
806
807     assertEscapedQueryEquals("[ a - TO a+ ]", null, "\\[ a \\- TO a\\+ \\]");
808     assertEscapedQueryEquals("[ a : TO a~ ]", null, "\\[ a \\: TO a\\~ \\]");
809     assertEscapedQueryEquals("[ a\\ TO a* ]", null, "\\[ a\\\\ TO a\\* \\]");
810     
811     // LUCENE-881
812     assertEscapedQueryEquals("|| abc ||", a, "\\|\\| abc \\|\\|");
813     assertEscapedQueryEquals("&& abc &&", a, "\\&\\& abc \\&\\&");
814   }
815   
816   public void testTabNewlineCarriageReturn()
817     throws Exception {
818     assertQueryEqualsDOA("+weltbank +worlbank", null,
819       "+weltbank +worlbank");
820
821     assertQueryEqualsDOA("+weltbank\n+worlbank", null,
822       "+weltbank +worlbank");
823     assertQueryEqualsDOA("weltbank \n+worlbank", null,
824       "+weltbank +worlbank");
825     assertQueryEqualsDOA("weltbank \n +worlbank", null,
826       "+weltbank +worlbank");
827
828     assertQueryEqualsDOA("+weltbank\r+worlbank", null,
829       "+weltbank +worlbank");
830     assertQueryEqualsDOA("weltbank \r+worlbank", null,
831       "+weltbank +worlbank");
832     assertQueryEqualsDOA("weltbank \r +worlbank", null,
833       "+weltbank +worlbank");
834
835     assertQueryEqualsDOA("+weltbank\r\n+worlbank", null,
836       "+weltbank +worlbank");
837     assertQueryEqualsDOA("weltbank \r\n+worlbank", null,
838       "+weltbank +worlbank");
839     assertQueryEqualsDOA("weltbank \r\n +worlbank", null,
840       "+weltbank +worlbank");
841     assertQueryEqualsDOA("weltbank \r \n +worlbank", null,
842       "+weltbank +worlbank");
843
844     assertQueryEqualsDOA("+weltbank\t+worlbank", null,
845       "+weltbank +worlbank");
846     assertQueryEqualsDOA("weltbank \t+worlbank", null,
847       "+weltbank +worlbank");
848     assertQueryEqualsDOA("weltbank \t +worlbank", null,
849       "+weltbank +worlbank");
850   }
851
852   public void testSimpleDAO()
853     throws Exception {
854     assertQueryEqualsDOA("term term term", null, "+term +term +term");
855     assertQueryEqualsDOA("term +term term", null, "+term +term +term");
856     assertQueryEqualsDOA("term term +term", null, "+term +term +term");
857     assertQueryEqualsDOA("term +term +term", null, "+term +term +term");
858     assertQueryEqualsDOA("-term term term", null, "-term +term +term");
859   }
860
861   public void testBoost()
862     throws Exception {
863     Set<Object> stopWords = new HashSet<Object>(1);
864     stopWords.add("on");
865     StandardAnalyzer oneStopAnalyzer = new StandardAnalyzer(TEST_VERSION_CURRENT, stopWords);
866     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", oneStopAnalyzer);
867     Query q = qp.parse("on^1.0");
868     assertNotNull(q);
869     q = qp.parse("\"hello\"^2.0");
870     assertNotNull(q);
871     assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
872     q = qp.parse("hello^2.0");
873     assertNotNull(q);
874     assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
875     q = qp.parse("\"on\"^1.0");
876     assertNotNull(q);
877
878     QueryParser qp2 = new QueryParser(TEST_VERSION_CURRENT, "field", new StandardAnalyzer(TEST_VERSION_CURRENT));
879     q = qp2.parse("the^3");
880     // "the" is a stop word so the result is an empty query:
881     assertNotNull(q);
882     assertEquals("", q.toString());
883     assertEquals(1.0f, q.getBoost(), 0.01f);
884   }
885
886   public void assertParseException(String queryString) throws Exception {
887     try {
888       getQuery(queryString, null);
889     } catch (ParseException expected) {
890       return;
891     }
892     fail("ParseException expected, not thrown");
893   }
894        
895   public void testException() throws Exception {
896     assertParseException("\"some phrase");
897     assertParseException("(foo bar");
898     assertParseException("foo bar))");
899     assertParseException("field:term:with:colon some more terms");
900     assertParseException("(sub query)^5.0^2.0 plus more");
901     assertParseException("secret AND illegal) AND access:confidential");
902   }
903   
904
905   public void testCustomQueryParserWildcard() {
906     try {
907       new QPTestParser("contents", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)).parse("a?t");
908       fail("Wildcard queries should not be allowed");
909     } catch (ParseException expected) {
910       // expected exception
911     }
912   }
913
914   public void testCustomQueryParserFuzzy() throws Exception {
915     try {
916       new QPTestParser("contents", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)).parse("xunit~");
917       fail("Fuzzy queries should not be allowed");
918     } catch (ParseException expected) {
919       // expected exception
920     }
921   }
922
923   public void testBooleanQuery() throws Exception {
924     BooleanQuery.setMaxClauseCount(2);
925     try {
926       QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false));
927       qp.parse("one two three");
928       fail("ParseException expected due to too many boolean clauses");
929     } catch (ParseException expected) {
930       // too many boolean clauses, so ParseException is expected
931     }
932   }
933
934   /**
935    * This test differs from TestPrecedenceQueryParser
936    */
937   public void testPrecedence() throws Exception {
938     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false));
939     Query query1 = qp.parse("A AND B OR C AND D");
940     Query query2 = qp.parse("+A +B +C +D");
941     assertEquals(query1, query2);
942   }
943
944   public void testLocalDateFormat() throws IOException, ParseException {
945     Directory ramDir = newDirectory();
946     IndexWriter iw = new IndexWriter(ramDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
947
948     addDateDoc("a", 2005, 12, 2, 10, 15, 33, iw);
949     addDateDoc("b", 2005, 12, 4, 22, 15, 00, iw);
950     iw.close();
951     IndexSearcher is = new IndexSearcher(ramDir, true);
952     assertHits(1, "[12/1/2005 TO 12/3/2005]", is);
953     assertHits(2, "[12/1/2005 TO 12/4/2005]", is);
954     assertHits(1, "[12/3/2005 TO 12/4/2005]", is);
955     assertHits(1, "{12/1/2005 TO 12/3/2005}", is);
956     assertHits(1, "{12/1/2005 TO 12/4/2005}", is);
957     assertHits(0, "{12/3/2005 TO 12/4/2005}", is);
958     is.close();
959     ramDir.close();
960   }
961
962   public void testStarParsing() throws Exception {
963     final int[] type = new int[1];
964     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false)) {
965       @Override
966       protected Query getWildcardQuery(String field, String termStr) throws ParseException {
967         // override error checking of superclass
968         type[0]=1;
969         return new TermQuery(new Term(field,termStr));
970       }
971       @Override
972       protected Query getPrefixQuery(String field, String termStr) throws ParseException {
973         // override error checking of superclass
974         type[0]=2;        
975         return new TermQuery(new Term(field,termStr));
976       }
977
978       @Override
979       protected Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException {
980         type[0]=3;
981         return super.getFieldQuery(field, queryText, quoted);
982       }
983     };
984
985     TermQuery tq;
986
987     tq = (TermQuery)qp.parse("foo:zoo*");
988     assertEquals("zoo",tq.getTerm().text());
989     assertEquals(2,type[0]);
990
991     tq = (TermQuery)qp.parse("foo:zoo*^2");
992     assertEquals("zoo",tq.getTerm().text());
993     assertEquals(2,type[0]);
994     assertEquals(tq.getBoost(),2,0);
995
996     tq = (TermQuery)qp.parse("foo:*");
997     assertEquals("*",tq.getTerm().text());
998     assertEquals(1,type[0]);  // could be a valid prefix query in the future too
999
1000     tq = (TermQuery)qp.parse("foo:*^2");
1001     assertEquals("*",tq.getTerm().text());
1002     assertEquals(1,type[0]);
1003     assertEquals(tq.getBoost(),2,0);    
1004
1005     tq = (TermQuery)qp.parse("*:foo");
1006     assertEquals("*",tq.getTerm().field());
1007     assertEquals("foo",tq.getTerm().text());
1008     assertEquals(3,type[0]);
1009
1010     tq = (TermQuery)qp.parse("*:*");
1011     assertEquals("*",tq.getTerm().field());
1012     assertEquals("*",tq.getTerm().text());
1013     assertEquals(1,type[0]);  // could be handled as a prefix query in the future
1014
1015      tq = (TermQuery)qp.parse("(*:*)");
1016     assertEquals("*",tq.getTerm().field());
1017     assertEquals("*",tq.getTerm().text());
1018     assertEquals(1,type[0]);
1019
1020   }
1021
1022   public void testStopwords() throws Exception {
1023     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "a", new StopAnalyzer(TEST_VERSION_CURRENT, StopFilter.makeStopSet(TEST_VERSION_CURRENT, "the", "foo")));
1024     Query result = qp.parse("a:the OR a:foo");
1025     assertNotNull("result is null and it shouldn't be", result);
1026     assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
1027     assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: " + 0, ((BooleanQuery) result).clauses().size() == 0);
1028     result = qp.parse("a:woo OR a:the");
1029     assertNotNull("result is null and it shouldn't be", result);
1030     assertTrue("result is not a TermQuery", result instanceof TermQuery);
1031     result = qp.parse("(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)");
1032     assertNotNull("result is null and it shouldn't be", result);
1033     assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
1034     if (VERBOSE) System.out.println("Result: " + result);
1035     assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: " + 2, ((BooleanQuery) result).clauses().size() == 2);
1036   }
1037
1038   public void testPositionIncrement() throws Exception {
1039     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "a", new StopAnalyzer(TEST_VERSION_CURRENT, StopFilter.makeStopSet(TEST_VERSION_CURRENT, "the", "in", "are", "this")));
1040     qp.setEnablePositionIncrements(true);
1041     String qtxt = "\"the words in poisitions pos02578 are stopped in this phrasequery\"";
1042     //               0         2                      5           7  8
1043     int expectedPositions[] = {1,3,4,6,9};
1044     PhraseQuery pq = (PhraseQuery) qp.parse(qtxt);
1045     //System.out.println("Query text: "+qtxt);
1046     //System.out.println("Result: "+pq);
1047     Term t[] = pq.getTerms();
1048     int pos[] = pq.getPositions();
1049     for (int i = 0; i < t.length; i++) {
1050       //System.out.println(i+". "+t[i]+"  pos: "+pos[i]);
1051       assertEquals("term "+i+" = "+t[i]+" has wrong term-position!",expectedPositions[i],pos[i]);
1052     }
1053   }
1054
1055   public void testMatchAllDocs() throws Exception {
1056     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "field", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false));
1057     assertEquals(new MatchAllDocsQuery(), qp.parse("*:*"));
1058     assertEquals(new MatchAllDocsQuery(), qp.parse("(*:*)"));
1059     BooleanQuery bq = (BooleanQuery)qp.parse("+*:* -*:*");
1060     assertTrue(bq.getClauses()[0].getQuery() instanceof MatchAllDocsQuery);
1061     assertTrue(bq.getClauses()[1].getQuery() instanceof MatchAllDocsQuery);
1062   }
1063   
1064   private void assertHits(int expected, String query, IndexSearcher is) throws ParseException, IOException {
1065     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "date", new MockAnalyzer(random, MockTokenizer.WHITESPACE, false));
1066     qp.setLocale(Locale.ENGLISH);
1067     Query q = qp.parse(query);
1068     ScoreDoc[] hits = is.search(q, null, 1000).scoreDocs;
1069     assertEquals(expected, hits.length);
1070   }
1071
1072   private void addDateDoc(String content, int year, int month,
1073       int day, int hour, int minute, int second, IndexWriter iw) throws IOException {
1074     Document d = new Document();
1075     d.add(newField("f", content, Field.Store.YES, Field.Index.ANALYZED));
1076     Calendar cal = Calendar.getInstance(Locale.ENGLISH);
1077     cal.set(year, month-1, day, hour, minute, second);
1078     d.add(newField("date", DateField.dateToString(cal.getTime()), Field.Store.YES, Field.Index.NOT_ANALYZED));
1079     iw.addDocument(d);
1080   }
1081
1082   @Override
1083   public void tearDown() throws Exception {
1084     BooleanQuery.setMaxClauseCount(originalMaxClauses);
1085     super.tearDown();
1086   }
1087
1088   // LUCENE-2002: make sure defaults for StandardAnalyzer's
1089   // enableStopPositionIncr & QueryParser's enablePosIncr
1090   // "match"
1091   public void testPositionIncrements() throws Exception {
1092     Directory dir = newDirectory();
1093     Analyzer a = new StandardAnalyzer(TEST_VERSION_CURRENT);
1094     IndexWriter w = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, a));
1095     Document doc = new Document();
1096     doc.add(newField("f", "the wizard of ozzy", Field.Store.NO, Field.Index.ANALYZED));
1097     w.addDocument(doc);
1098     IndexReader r = IndexReader.open(w, true);
1099     w.close();
1100     IndexSearcher s = newSearcher(r);
1101     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "f", a);
1102     Query q = qp.parse("\"wizard of ozzy\"");
1103     assertEquals(1, s.search(q, 1).totalHits);
1104     s.close();
1105     r.close();
1106     dir.close();
1107   }
1108
1109   // LUCENE-2002: when we run javacc to regen QueryParser,
1110   // we also run a replaceregexp step to fix 2 of the public
1111   // ctors (change them to protected):
1112   //
1113   //   protected QueryParser(CharStream stream)
1114   //
1115   //   protected QueryParser(QueryParserTokenManager tm)
1116   //
1117   // This test is here as a safety, in case that ant step
1118   // doesn't work for some reason.
1119   public void testProtectedCtors() throws Exception {
1120     try {
1121       QueryParser.class.getConstructor(new Class[] {CharStream.class});
1122       fail("please switch public QueryParser(CharStream) to be protected");
1123     } catch (NoSuchMethodException nsme) {
1124       // expected
1125     }
1126     try {
1127       QueryParser.class.getConstructor(new Class[] {QueryParserTokenManager.class});
1128       fail("please switch public QueryParser(QueryParserTokenManager) to be protected");
1129     } catch (NoSuchMethodException nsme) {
1130       // expected
1131     }
1132   }
1133
1134 }