pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / xml-query-parser / src / demo / java / org / apache / lucene / xmlparser / webdemo / FormBasedXmlQueryDemo.java
1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.apache.lucene.xmlparser.webdemo;
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.util.Enumeration;
25 import java.util.Properties;
26 import java.util.StringTokenizer;
27
28 import javax.servlet.RequestDispatcher;
29 import javax.servlet.ServletConfig;
30 import javax.servlet.ServletException;
31 import javax.servlet.http.HttpServlet;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35 import org.apache.lucene.analysis.Analyzer;
36 import org.apache.lucene.analysis.standard.StandardAnalyzer;
37 import org.apache.lucene.document.Document;
38 import org.apache.lucene.document.Field;
39 import org.apache.lucene.index.CorruptIndexException;
40 import org.apache.lucene.index.IndexWriter;
41 import org.apache.lucene.search.IndexSearcher;
42 import org.apache.lucene.search.Query;
43 import org.apache.lucene.search.ScoreDoc;
44 import org.apache.lucene.search.TopDocs;
45 import org.apache.lucene.store.RAMDirectory;
46 import org.apache.lucene.xmlparser.CorePlusExtensionsParser;
47 import org.apache.lucene.xmlparser.QueryTemplateManager;
48
49 public class FormBasedXmlQueryDemo extends HttpServlet {
50
51         private QueryTemplateManager queryTemplateManager;
52         private CorePlusExtensionsParser xmlParser;
53         private IndexSearcher searcher;
54         private Analyzer analyzer=new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_CURRENT);
55
56         @Override
57         public void init(ServletConfig config) throws ServletException {
58                 super.init(config);
59                 try {
60                         openExampleIndex();
61
62                         //load servlet configuration settings
63                         String xslFile=config.getInitParameter("xslFile");
64                         String defaultStandardQueryParserField = config.getInitParameter("defaultStandardQueryParserField");
65
66
67                         //Load and cache choice of XSL query template using QueryTemplateManager
68                         queryTemplateManager=new QueryTemplateManager(
69                                         getServletContext().getResourceAsStream("/WEB-INF/"+xslFile));
70
71                         //initialize an XML Query Parser for use by all threads
72                         xmlParser=new CorePlusExtensionsParser(defaultStandardQueryParserField,analyzer);
73                 } catch (Exception e) {
74                         throw new ServletException("Error loading query template",e);
75                 }
76         }
77
78         @Override
79         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
80                 //Take all completed form fields and add to a Properties object
81                 Properties completedFormFields=new Properties();
82                 Enumeration pNames = request.getParameterNames();
83                 while(pNames.hasMoreElements()){
84                         String propName=(String) pNames.nextElement();
85                         String value=request.getParameter(propName);
86                         if((value!=null)&&(value.trim().length()>0)){
87                                 completedFormFields.setProperty(propName, value);
88                         }
89                 }
90
91                 try{
92
93                         //Create an XML query by populating template with given user criteria
94                         org.w3c.dom.Document xmlQuery=queryTemplateManager.getQueryAsDOM(completedFormFields);
95
96                         //Parse the XML to produce a Lucene query
97                         Query query=xmlParser.getQuery(xmlQuery.getDocumentElement());
98
99                         //Run the query
100                         TopDocs topDocs = searcher.search(query,10);
101
102                         //and package the results and forward to JSP
103                         if(topDocs!=null)       {
104                                 ScoreDoc[] sd = topDocs.scoreDocs;
105                                 Document[] results=new Document[sd.length];
106                                 for (int i = 0; i < results.length; i++) {
107                                         results[i]=searcher.doc(sd[i].doc);
108                                         request.setAttribute("results", results);
109                                 }
110                         }
111                         RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
112                         dispatcher.forward(request,response);
113                 }
114                 catch(Exception e){
115                         throw new ServletException("Error processing query",e);
116                 }
117         }
118
119         private void openExampleIndex() throws CorruptIndexException, IOException {
120
121                 //Create a RAM-based index from our test data file
122                 RAMDirectory rd=new RAMDirectory();
123                 IndexWriter writer=new IndexWriter (rd,analyzer,IndexWriter.MaxFieldLength.LIMITED);
124                 InputStream dataIn=getServletContext().getResourceAsStream("/WEB-INF/data.tsv");
125                 BufferedReader br = new BufferedReader(new InputStreamReader(dataIn));
126                 String line = br.readLine();
127                 while(line!=null)
128                 {
129                         line=line.trim();
130                         if(line.length()>0)
131                         {
132                                 //parse row and create a document
133                                 StringTokenizer st=new StringTokenizer(line,"\t");
134                                 Document doc=new Document();
135                                 doc.add(new Field("location",st.nextToken(),Field.Store.YES,
136                                                 Field.Index.ANALYZED_NO_NORMS));
137                                 doc.add(new Field("salary",st.nextToken(),Field.Store.YES,
138                                                 Field.Index.ANALYZED_NO_NORMS));
139                                 doc.add(new Field("type",st.nextToken(),Field.Store.YES,
140                                                 Field.Index.ANALYZED_NO_NORMS));
141                                 doc.add(new Field("description",st.nextToken(),Field.Store.YES,
142                                                 Field.Index.ANALYZED));
143                                 writer.addDocument(doc);
144                         }
145                         line=br.readLine();
146                 }
147                 writer.close();
148
149                 //open searcher
150                 searcher=new IndexSearcher(rd, true);
151         }
152 }