pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / xml-query-parser / src / test / org / apache / lucene / xmlparser / TestQueryTemplateManager.java
1 package org.apache.lucene.xmlparser;
2
3 import java.io.IOException;
4 import java.util.Locale;
5 import java.util.Properties;
6 import java.util.StringTokenizer;
7
8 import javax.xml.parsers.ParserConfigurationException;
9 import javax.xml.transform.TransformerException;
10
11 import org.apache.lucene.analysis.Analyzer;
12 import org.apache.lucene.analysis.standard.StandardAnalyzer;
13 import org.apache.lucene.document.Field;
14 import org.apache.lucene.index.IndexWriter;
15 import org.apache.lucene.search.IndexSearcher;
16 import org.apache.lucene.search.Query;
17 import org.apache.lucene.store.Directory;
18 import org.apache.lucene.util.Constants;
19 import org.apache.lucene.util.LuceneTestCase;
20
21 import org.w3c.dom.Document;
22 import org.xml.sax.SAXException;
23
24 /**
25  * Licensed to the Apache Software Foundation (ASF) under one or more
26  * contributor license agreements.  See the NOTICE file distributed with
27  * this work for additional information regarding copyright ownership.
28  * The ASF licenses this file to You under the Apache License, Version 2.0
29  * (the "License"); you may not use this file except in compliance with
30  * the License.  You may obtain a copy of the License at
31  *
32  *     http://www.apache.org/licenses/LICENSE-2.0
33  *
34  * Unless required by applicable law or agreed to in writing, software
35  * distributed under the License is distributed on an "AS IS" BASIS,
36  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
37  * See the License for the specific language governing permissions and
38  * limitations under the License.
39  */
40 /**
41  * This class illustrates how form input (such as from a web page or Swing gui) can be
42  * turned into Lucene queries using a choice of XSL templates for different styles of queries.
43  */
44 public class TestQueryTemplateManager extends LuceneTestCase {
45
46         CoreParser builder;
47         Analyzer analyzer=new StandardAnalyzer(TEST_VERSION_CURRENT);
48         private IndexSearcher searcher;
49         private Directory dir;
50         
51         //A collection of documents' field values for use in our tests
52         String docFieldValues []=
53         {
54                         "artist=Jeff Buckley \talbum=Grace \treleaseDate=1999 \tgenre=rock",
55                         "artist=Fugazi \talbum=Repeater \treleaseDate=1990 \tgenre=alternative",
56                         "artist=Fugazi \talbum=Red Medicine \treleaseDate=1995 \tgenre=alternative",
57                         "artist=Peeping Tom \talbum=Peeping Tom \treleaseDate=2006 \tgenre=rock",
58                         "artist=Red Snapper \talbum=Prince Blimey \treleaseDate=1996 \tgenre=electronic"
59         };
60         
61         //A collection of example queries, consisting of name/value pairs representing form content plus 
62         // a choice of query style template to use in the test, with expected number of hits
63         String queryForms[]=
64         {
65                         "artist=Fugazi \texpectedMatches=2 \ttemplate=albumBooleanQuery",
66                         "artist=Fugazi \treleaseDate=1990 \texpectedMatches=1 \ttemplate=albumBooleanQuery",
67                         "artist=Buckley \tgenre=rock \texpectedMatches=1 \ttemplate=albumFilteredQuery",
68                         "artist=Buckley \tgenre=electronic \texpectedMatches=0 \ttemplate=albumFilteredQuery",
69                         "queryString=artist:buckly~ NOT genre:electronic \texpectedMatches=1 \ttemplate=albumLuceneClassicQuery"
70         };
71         
72         
73         public void testFormTransforms() throws SAXException, IOException, ParserConfigurationException, TransformerException, ParserException 
74         {
75           // Sun 1.5 suffers from http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6240963
76           if (Constants.JAVA_VENDOR.startsWith("Sun") && Constants.JAVA_VERSION.startsWith("1.5")) {
77             String defLang = Locale.getDefault().getLanguage();
78             assumeFalse("Sun JRE 1.5 suffers from http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6240963 under Turkish locale", defLang.equals("tr") || defLang.equals("az"));
79           }
80                 //Cache all the query templates we will be referring to.
81                 QueryTemplateManager qtm=new QueryTemplateManager();
82                 qtm.addQueryTemplate("albumBooleanQuery", getClass().getResourceAsStream("albumBooleanQuery.xsl"));
83                 qtm.addQueryTemplate("albumFilteredQuery", getClass().getResourceAsStream("albumFilteredQuery.xsl"));
84                 qtm.addQueryTemplate("albumLuceneClassicQuery", getClass().getResourceAsStream("albumLuceneClassicQuery.xsl"));
85                 //Run all of our test queries
86                 for (int i = 0; i < queryForms.length; i++)
87                 {
88                         Properties queryFormProperties=getPropsFromString(queryForms[i]);
89                         
90                         //Get the required query XSL template for this test
91 //                      Templates template=getTemplate(queryFormProperties.getProperty("template"));
92                         
93                         //Transform the queryFormProperties into a Lucene XML query
94                         Document doc=qtm.getQueryAsDOM(queryFormProperties,queryFormProperties.getProperty("template"));
95                         
96                         //Parse the XML query using the XML parser
97                         Query q=builder.getQuery(doc.getDocumentElement());
98                         
99                         //Run the query
100                         int h=searcher.search(q, null, 1000).totalHits;
101                         
102                         //Check we have the expected number of results
103                         int expectedHits=Integer.parseInt(queryFormProperties.getProperty("expectedMatches"));
104                         assertEquals("Number of results should match for query "+queryForms[i],expectedHits,h);
105                         
106                 }
107         }
108         
109         //Helper method to construct Lucene query forms used in our test
110         Properties getPropsFromString(String nameValuePairs)
111         {
112                 Properties result=new Properties();
113                 StringTokenizer st=new StringTokenizer(nameValuePairs,"\t=");
114                 while(st.hasMoreTokens())
115                 {
116                         String name=st.nextToken().trim();
117                         if(st.hasMoreTokens())
118                         {
119                                 String value=st.nextToken().trim();
120                                 result.setProperty(name,value);
121                         }
122                 }
123                 return result;
124         }
125         
126         //Helper method to construct Lucene documents used in our tests
127         org.apache.lucene.document.Document getDocumentFromString(String nameValuePairs)
128         {
129                 org.apache.lucene.document.Document result=new org.apache.lucene.document.Document();
130                 StringTokenizer st=new StringTokenizer(nameValuePairs,"\t=");
131                 while(st.hasMoreTokens())
132                 {
133                         String name=st.nextToken().trim();
134                         if(st.hasMoreTokens())
135                         {
136                                 String value=st.nextToken().trim();
137                                 result.add(newField(name,value,Field.Store.YES,Field.Index.ANALYZED));
138                         }
139                 }
140                 return result;
141         }
142         
143         /*
144          * @see TestCase#setUp()
145          */
146         @Override
147         public void setUp() throws Exception {
148                 super.setUp();
149                 
150                 
151                 //Create an index
152                 dir=newDirectory();
153                 IndexWriter w=new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
154                 for (int i = 0; i < docFieldValues.length; i++)
155                 {
156                         w.addDocument(getDocumentFromString(docFieldValues[i]));
157                 }
158                 w.optimize();
159                 w.close();
160                 searcher=new IndexSearcher(dir, true);
161                 
162                 //initialize the parser
163                 builder=new CorePlusExtensionsParser("artist", analyzer);
164                 
165         }
166         
167         
168         @Override
169         public void tearDown() throws Exception {
170                 searcher.close();
171                 dir.close();
172     super.tearDown();
173         }
174 }