Apache Solr open-source search software
set svn:eol-style to native on java files
Yonik Seeley8e8e8ddec49e
diff --git a/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekAnalyzer.java b/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekAnalyzer.javaindex 3adcb563b4c..65c5f327818 100644--- a/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekAnalyzer.java+++ b/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekAnalyzer.java@@ -1,222 +1,222 @@-package org.apache.lucene.analysis.el;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.StopFilter;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.analysis.standard.StandardTokenizer;--import java.io.Reader;-import java.util.HashSet;-import java.util.Map;-import java.util.Set;--/**- * Analyzer for the Greek language. Supports an external list of stopwords (words- * that will not be indexed at all).- * A default set of stopwords is used unless an alternative list is specified.- *- */-public final class GreekAnalyzer extends Analyzer-{- // the letters are indexes to the charset array (see GreekCharsets.java)- private static char A = 6;- private static char B = 7;- private static char G = 8;- private static char D = 9;- private static char E = 10;- private static char Z = 11;- private static char H = 12;- private static char TH = 13;- private static char I = 14;- private static char K = 15;- private static char L = 16;- private static char M = 17;- private static char N = 18;- private static char KS = 19;- private static char O = 20;- private static char P = 21;- private static char R = 22;- private static char S = 24; // skip final sigma- private static char T = 25;- private static char Y = 26;- private static char F = 27;- private static char X = 28;- private static char PS = 29;- private static char W = 30;-- /**- * List of typical Greek stopwords.- */- private static char[][] GREEK_STOP_WORDS = {- {O},- {H},- {T, O},- {O, I},- {T, A},- {T, O, Y},- {T, H, S},- {T, W, N},- {T, O, N},- {T, H, N},- {K, A, I},- {K, I},- {K},- {E, I, M, A, I},- {E, I, S, A, I},- {E, I, N, A, I},- {E, I, M, A, S, T, E},- {E, I, S, T, E},- {S, T, O},- {S, T, O, N},- {S, T, H},- {S, T, H, N},- {M, A},- {A, L, L, A},- {A, P, O},- {G, I, A},- {P, R, O, S},- {M, E},- {S, E},- {W, S},- {P, A, R, A},- {A, N, T, I},- {K, A, T, A},- {M, E, T, A},- {TH, A},- {N, A},- {D, E},- {D, E, N},- {M, H},- {M, H, N},- {E, P, I},- {E, N, W},- {E, A, N},- {A, N},- {T, O, T, E},- {P, O, Y},- {P, W, S},- {P, O, I, O, S},- {P, O, I, A},- {P, O, I, O},- {P, O, I, O, I},- {P, O, I, E, S},- {P, O, I, W, N},- {P, O, I, O, Y, S},- {A, Y, T, O, S},- {A, Y, T, H},- {A, Y, T, O},- {A, Y, T, O, I},- {A, Y, T, W, N},- {A, Y, T, O, Y, S},- {A, Y, T, E, S},- {A, Y, T, A},- {E, K, E, I, N, O, S},- {E, K, E, I, N, H},- {E, K, E, I, N, O},- {E, K, E, I, N, O, I},- {E, K, E, I, N, E, S},- {E, K, E, I, N, A},- {E, K, E, I, N, W, N},- {E, K, E, I, N, O, Y, S},- {O, P, W, S},- {O, M, W, S},- {I, S, W, S},- {O, S, O},- {O, T, I}- };-- /**- * Contains the stopwords used with the StopFilter.- */- private Set stopSet = new HashSet();-- /**- * Charset for Greek letters.- * Represents encoding for 24 lowercase Greek letters.- * Predefined charsets can be taken from GreekCharSets class- */- private char[] charset;-- public GreekAnalyzer() {- charset = GreekCharsets.UnicodeGreek;- stopSet = StopFilter.makeStopSet(- makeStopWords(GreekCharsets.UnicodeGreek));- }-- /**- * Builds an analyzer.- */- public GreekAnalyzer(char[] charset)- {- this.charset = charset;- stopSet = StopFilter.makeStopSet(makeStopWords(charset));- }-- /**- * Builds an analyzer with the given stop words.- */- public GreekAnalyzer(char[] charset, String[] stopwords)- {- this.charset = charset;- stopSet = StopFilter.makeStopSet(stopwords);- }-- // Takes greek stop words and translates them to a String array, using- // the given charset- private static String[] makeStopWords(char[] charset)- {- String[] res = new String[GREEK_STOP_WORDS.length];- for (int i = 0; i < res.length; i++)- {- char[] theStopWord = GREEK_STOP_WORDS[i];- // translate the word,using the charset- StringBuffer theWord = new StringBuffer();- for (int j = 0; j < theStopWord.length; j++)- {- theWord.append(charset[theStopWord[j]]);- }- res[i] = theWord.toString();- }- return res;- }-- /**- * Builds an analyzer with the given stop words.- */- public GreekAnalyzer(char[] charset, Map stopwords)- {- this.charset = charset;- stopSet = new HashSet(stopwords.keySet());- }-- /**- * Creates a TokenStream which tokenizes all the text in the provided Reader.- *- * @return A TokenStream build from a StandardTokenizer filtered with- * GreekLowerCaseFilter and StopFilter- */- public TokenStream tokenStream(String fieldName, Reader reader)- {- TokenStream result = new StandardTokenizer(reader);- result = new GreekLowerCaseFilter(result, charset);- result = new StopFilter(result, stopSet);- return result;- }-}+package org.apache.lucene.analysis.el;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.StopFilter;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.standard.StandardTokenizer;++import java.io.Reader;+import java.util.HashSet;+import java.util.Map;+import java.util.Set;++/**+ * Analyzer for the Greek language. Supports an external list of stopwords (words+ * that will not be indexed at all).+ * A default set of stopwords is used unless an alternative list is specified.+ *+ */+public final class GreekAnalyzer extends Analyzer+{+ // the letters are indexes to the charset array (see GreekCharsets.java)+ private static char A = 6;+ private static char B = 7;+ private static char G = 8;+ private static char D = 9;+ private static char E = 10;+ private static char Z = 11;+ private static char H = 12;+ private static char TH = 13;+ private static char I = 14;+ private static char K = 15;+ private static char L = 16;+ private static char M = 17;+ private static char N = 18;+ private static char KS = 19;+ private static char O = 20;+ private static char P = 21;+ private static char R = 22;+ private static char S = 24; // skip final sigma+ private static char T = 25;+ private static char Y = 26;+ private static char F = 27;+ private static char X = 28;+ private static char PS = 29;+ private static char W = 30;++ /**+ * List of typical Greek stopwords.+ */+ private static char[][] GREEK_STOP_WORDS = {+ {O},+ {H},+ {T, O},+ {O, I},+ {T, A},+ {T, O, Y},+ {T, H, S},+ {T, W, N},+ {T, O, N},+ {T, H, N},+ {K, A, I},+ {K, I},+ {K},+ {E, I, M, A, I},+ {E, I, S, A, I},+ {E, I, N, A, I},+ {E, I, M, A, S, T, E},+ {E, I, S, T, E},+ {S, T, O},+ {S, T, O, N},+ {S, T, H},+ {S, T, H, N},+ {M, A},+ {A, L, L, A},+ {A, P, O},+ {G, I, A},+ {P, R, O, S},+ {M, E},+ {S, E},+ {W, S},+ {P, A, R, A},+ {A, N, T, I},+ {K, A, T, A},+ {M, E, T, A},+ {TH, A},+ {N, A},+ {D, E},+ {D, E, N},+ {M, H},+ {M, H, N},+ {E, P, I},+ {E, N, W},+ {E, A, N},+ {A, N},+ {T, O, T, E},+ {P, O, Y},+ {P, W, S},+ {P, O, I, O, S},+ {P, O, I, A},+ {P, O, I, O},+ {P, O, I, O, I},+ {P, O, I, E, S},+ {P, O, I, W, N},+ {P, O, I, O, Y, S},+ {A, Y, T, O, S},+ {A, Y, T, H},+ {A, Y, T, O},+ {A, Y, T, O, I},+ {A, Y, T, W, N},+ {A, Y, T, O, Y, S},+ {A, Y, T, E, S},+ {A, Y, T, A},+ {E, K, E, I, N, O, S},+ {E, K, E, I, N, H},+ {E, K, E, I, N, O},+ {E, K, E, I, N, O, I},+ {E, K, E, I, N, E, S},+ {E, K, E, I, N, A},+ {E, K, E, I, N, W, N},+ {E, K, E, I, N, O, Y, S},+ {O, P, W, S},+ {O, M, W, S},+ {I, S, W, S},+ {O, S, O},+ {O, T, I}+ };++ /**+ * Contains the stopwords used with the StopFilter.+ */+ private Set stopSet = new HashSet();++ /**+ * Charset for Greek letters.+ * Represents encoding for 24 lowercase Greek letters.+ * Predefined charsets can be taken from GreekCharSets class+ */+ private char[] charset;++ public GreekAnalyzer() {+ charset = GreekCharsets.UnicodeGreek;+ stopSet = StopFilter.makeStopSet(+ makeStopWords(GreekCharsets.UnicodeGreek));+ }++ /**+ * Builds an analyzer.+ */+ public GreekAnalyzer(char[] charset)+ {+ this.charset = charset;+ stopSet = StopFilter.makeStopSet(makeStopWords(charset));+ }++ /**+ * Builds an analyzer with the given stop words.+ */+ public GreekAnalyzer(char[] charset, String[] stopwords)+ {+ this.charset = charset;+ stopSet = StopFilter.makeStopSet(stopwords);+ }++ // Takes greek stop words and translates them to a String array, using+ // the given charset+ private static String[] makeStopWords(char[] charset)+ {+ String[] res = new String[GREEK_STOP_WORDS.length];+ for (int i = 0; i < res.length; i++)+ {+ char[] theStopWord = GREEK_STOP_WORDS[i];+ // translate the word,using the charset+ StringBuffer theWord = new StringBuffer();+ for (int j = 0; j < theStopWord.length; j++)+ {+ theWord.append(charset[theStopWord[j]]);+ }+ res[i] = theWord.toString();+ }+ return res;+ }++ /**+ * Builds an analyzer with the given stop words.+ */+ public GreekAnalyzer(char[] charset, Map stopwords)+ {+ this.charset = charset;+ stopSet = new HashSet(stopwords.keySet());+ }++ /**+ * Creates a TokenStream which tokenizes all the text in the provided Reader.+ *+ * @return A TokenStream build from a StandardTokenizer filtered with+ * GreekLowerCaseFilter and StopFilter+ */+ public TokenStream tokenStream(String fieldName, Reader reader)+ {+ TokenStream result = new StandardTokenizer(reader);+ result = new GreekLowerCaseFilter(result, charset);+ result = new StopFilter(result, stopSet);+ return result;+ }+}diff --git a/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekCharsets.java b/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekCharsets.javaindex d6ed048033a..061dbc2cb9d 100644--- a/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekCharsets.java+++ b/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekCharsets.java@@ -1,480 +1,480 @@-package org.apache.lucene.analysis.el;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--/**- * GreekCharsets class contains encodings schemes (charsets) and toLowerCase() method implementation- * for greek characters in Unicode, ISO-8859-7 and Microsoft Windows CP1253.- * Each encoding scheme contains lowercase (positions 0-35) and uppercase (position 36-68) characters,- * including accented ones. One should be able to add other encoding schemes (see RFC 1947) by adding- * the definition of a new charset as well as the required logic in the toLowerCase() method.- *- */-public class GreekCharsets-{- // Unicode Greek charset- public static char[] UnicodeGreek = {- // lower case- '\u0390',- '\u03AC',- '\u03AD',- '\u03AE',- '\u03AF',- '\u03B0',- '\u03B1',- '\u03B2',- '\u03B3',- '\u03B4',- '\u03B5',- '\u03B6',- '\u03B7',- '\u03B8',- '\u03B9',- '\u03BA',- '\u03BB',- '\u03BC',- '\u03BD',- '\u03BE',- '\u03BF',- '\u03C0',- '\u03C1',- '\u03C2',- '\u03C3',- '\u03C4',- '\u03C5',- '\u03C6',- '\u03C7',- '\u03C8',- '\u03C9',- '\u03CA',- '\u03CB',- '\u03CC',- '\u03CD',- '\u03CE',- // upper case- '\u0386',- '\u0388',- '\u0389',- '\u038A',- '\u038C',- '\u038E',- '\u038F',- '\u0391',- '\u0392',- '\u0393',- '\u0394',- '\u0395',- '\u0396',- '\u0397',- '\u0398',- '\u0399',- '\u039A',- '\u039B',- '\u039C',- '\u039D',- '\u039E',- '\u039F',- '\u03A0',- '\u03A1',- '\u03A3',- '\u03A4',- '\u03A5',- '\u03A6',- '\u03A7',- '\u03A8',- '\u03A9',- '\u03AA',- '\u03AB'- };-- // ISO-8859-7 charset (ELOT-928)- public static char[] ISO = {- // lower case- 0xc0,- 0xdc,- 0xdd,- 0xde,- 0xdf,- 0xe0,- 0xe1,- 0xe2,- 0xe3,- 0xe4,- 0xe5,- 0xe6,- 0xe7,- 0xe8,- 0xe9,- 0xea,- 0xeb,- 0xec,- 0xed,- 0xee,- 0xef,- 0xf0,- 0xf1,- 0xf2,- 0xf3,- 0xf4,- 0xf5,- 0xf6,- 0xf7,- 0xf8,- 0xf9,- 0xfa,- 0xfb,- 0xfc,- 0xfd,- 0xfe,- // upper case- 0xb6,- 0xb8,- 0xb9,- 0xba,- 0xbc,- 0xbe,- 0xbf,- 0xc1,- 0xc2,- 0xc3,- 0xc4,- 0xc5,- 0xc6,- 0xc7,- 0xc8,- 0xc9,- 0xca,- 0xcb,- 0xcc,- 0xcd,- 0xce,- 0xcf,- 0xd0,- 0xd1,- 0xd3,- 0xd4,- 0xd5,- 0xd6,- 0xd7,- 0xd8,- 0xd9,- 0xda,- 0xdb- };-- // CP1253 charset- public static char[] CP1253 = {- // lower case- 0xc0,- 0xdc,- 0xdd,- 0xde,- 0xdf,- 0xe0,- 0xe1,- 0xe2,- 0xe3,- 0xe4,- 0xe5,- 0xe6,- 0xe7,- 0xe8,- 0xe9,- 0xea,- 0xeb,- 0xec,- 0xed,- 0xee,- 0xef,- 0xf0,- 0xf1,- 0xf2,- 0xf3,- 0xf4,- 0xf5,- 0xf6,- 0xf7,- 0xf8,- 0xf9,- 0xfa,- 0xfb,- 0xfc,- 0xfd,- 0xfe,- // upper case- 0xa2,- 0xb8,- 0xb9,- 0xba,- 0xbc,- 0xbe,- 0xbf,- 0xc1,- 0xc2,- 0xc3,- 0xc4,- 0xc5,- 0xc6,- 0xc7,- 0xc8,- 0xc9,- 0xca,- 0xcb,- 0xcc,- 0xcd,- 0xce,- 0xcf,- 0xd0,- 0xd1,- 0xd3,- 0xd4,- 0xd5,- 0xd6,- 0xd7,- 0xd8,- 0xd9,- 0xda,- 0xdb- };-- public static char toLowerCase(char letter, char[] charset)- {- if (charset == UnicodeGreek) {- // First deal with lower case, not accented letters- if (letter >= '\u03B1' && letter <= '\u03C9')- {- // Special case 'small final sigma', where we return 'small sigma'- if (letter == '\u03C2') {- return '\u03C3';- } else {- return letter;- }- }- // Then deal with lower case, accented letters- // alpha with acute- if (letter == '\u03AC') {- return '\u03B1';- }- // epsilon with acute- if (letter == '\u03AD') {- return '\u03B5';- }- // eta with acute- if (letter == '\u03AE') {- return '\u03B7';- }- // iota with acute, iota with diaeresis, iota with acute and diaeresis- if (letter == '\u03AF' || letter == '\u03CA' || letter == '\u0390') {- return '\u03B9';- }- // upsilon with acute, upsilon with diaeresis, upsilon with acute and diaeresis- if (letter == '\u03CD' || letter == '\u03CB' || letter == '\u03B0') {- return '\u03C5';- }- // omicron with acute- if (letter == '\u03CC') {- return '\u03BF';- }- // omega with acute- if (letter == '\u03CE') {- return '\u03C9';- }- // After that, deal with upper case, not accented letters- if (letter >= '\u0391' && letter <= '\u03A9')- {- return (char) (letter + 32);- }- // Finally deal with upper case, accented letters- // alpha with acute- if (letter == '\u0386') {- return '\u03B1';- }- // epsilon with acute- if (letter == '\u0388') {- return '\u03B5';- }- // eta with acute- if (letter == '\u0389') {- return '\u03B7';- }- // iota with acute, iota with diaeresis- if (letter == '\u038A' || letter == '\u03AA') {- return '\u03B9';- }- // upsilon with acute, upsilon with diaeresis- if (letter == '\u038E' || letter == '\u03AB') {- return '\u03C5';- }- // omicron with acute- if (letter == '\u038C') {- return '\u03BF';- }- // omega with acute- if (letter == '\u038F') {- return '\u03C9';- }- } else if (charset == ISO) {- // First deal with lower case, not accented letters- if (letter >= 0xe1 && letter <= 0xf9)- {- // Special case 'small final sigma', where we return 'small sigma'- if (letter == 0xf2) {- return 0xf3;- } else {- return letter;- }- }- // Then deal with lower case, accented letters- // alpha with acute- if (letter == 0xdc) {- return 0xe1;- }- // epsilon with acute- if (letter == 0xdd) {- return 0xe5;- }- // eta with acute- if (letter == 0xde) {- return 0xe7;- }- // iota with acute, iota with diaeresis, iota with acute and diaeresis- if (letter == 0xdf || letter == 0xfa || letter == 0xc0) {- return '\u03B9';- }- // upsilon with acute, upsilon with diaeresis, upsilon with acute and diaeresis- if (letter == 0xfd || letter == 0xfb || letter == 0xe0) {- return 0xf5;- }- // omicron with acute- if (letter == 0xfc) {- return 0xef;- }- // omega with acute- if (letter == 0xfe) {- return 0xf9;- }- // After that, deal with upper case, not accented letters- if (letter >= 0xc1 && letter <= 0xd9) {- return (char) (letter + 32);- }- // Finally deal with upper case, accented letters- // alpha with acute- if (letter == 0xb6) {- return 0xe1;- }- // epsilon with acute- if (letter == 0xb8) {- return 0xe5;- }- // eta with acute- if (letter == 0xb9) {- return 0xe7;- }- // iota with acute, iota with diaeresis- if (letter == 0xba || letter == 0xda) {- return 0xe9;- }- // upsilon with acute, upsilon with diaeresis- if (letter == 0xbe || letter == 0xdb) {- return 0xf5;- }- // omicron with acute- if (letter == 0xbc) {- return 0xef;- }- // omega with acute- if (letter == 0xbf) {- return 0xf9;- }- } else if (charset == CP1253) {- // First deal with lower case, not accented letters- if (letter >= 0xe1 && letter <= 0xf9)- {- // Special case 'small final sigma', where we return 'small sigma'- if (letter == 0xf2) {- return 0xf3;- } else {- return letter;- }- }- // Then deal with lower case, accented letters- // alpha with acute- if (letter == 0xdc) {- return 0xe1;- }- // epsilon with acute- if (letter == 0xdd) {- return 0xe5;- }- // eta with acute- if (letter == 0xde) {- return 0xe7;- }- // iota with acute, iota with diaeresis, iota with acute and diaeresis- if (letter == 0xdf || letter == 0xfa || letter == 0xc0) {- return '\u03B9';- }- // upsilon with acute, upsilon with diaeresis, upsilon with acute and diaeresis- if (letter == 0xfd || letter == 0xfb || letter == 0xe0) {- return 0xf5;- }- // omicron with acute- if (letter == 0xfc) {- return 0xef;- }- // omega with acute- if (letter == 0xfe) {- return 0xf9;- }- // After that, deal with upper case, not accented letters- if (letter >= 0xc1 && letter <= 0xd9) {- return (char) (letter + 32);- }- // Finally deal with upper case, accented letters- // alpha with acute- if (letter == 0xa2) {- return 0xe1;- }- // epsilon with acute- if (letter == 0xb8) {- return 0xe5;- }- // eta with acute- if (letter == 0xb9) {- return 0xe7;- }- // iota with acute, iota with diaeresis- if (letter == 0xba || letter == 0xda) {- return 0xe9;- }- // upsilon with acute, upsilon with diaeresis- if (letter == 0xbe || letter == 0xdb) {- return 0xf5;- }- // omicron with acute- if (letter == 0xbc) {- return 0xef;- }- // omega with acute- if (letter == 0xbf) {- return 0xf9;- }- }-- return Character.toLowerCase(letter);- }-}+package org.apache.lucene.analysis.el;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * GreekCharsets class contains encodings schemes (charsets) and toLowerCase() method implementation+ * for greek characters in Unicode, ISO-8859-7 and Microsoft Windows CP1253.+ * Each encoding scheme contains lowercase (positions 0-35) and uppercase (position 36-68) characters,+ * including accented ones. One should be able to add other encoding schemes (see RFC 1947) by adding+ * the definition of a new charset as well as the required logic in the toLowerCase() method.+ *+ */+public class GreekCharsets+{+ // Unicode Greek charset+ public static char[] UnicodeGreek = {+ // lower case+ '\u0390',+ '\u03AC',+ '\u03AD',+ '\u03AE',+ '\u03AF',+ '\u03B0',+ '\u03B1',+ '\u03B2',+ '\u03B3',+ '\u03B4',+ '\u03B5',+ '\u03B6',+ '\u03B7',+ '\u03B8',+ '\u03B9',+ '\u03BA',+ '\u03BB',+ '\u03BC',+ '\u03BD',+ '\u03BE',+ '\u03BF',+ '\u03C0',+ '\u03C1',+ '\u03C2',+ '\u03C3',+ '\u03C4',+ '\u03C5',+ '\u03C6',+ '\u03C7',+ '\u03C8',+ '\u03C9',+ '\u03CA',+ '\u03CB',+ '\u03CC',+ '\u03CD',+ '\u03CE',+ // upper case+ '\u0386',+ '\u0388',+ '\u0389',+ '\u038A',+ '\u038C',+ '\u038E',+ '\u038F',+ '\u0391',+ '\u0392',+ '\u0393',+ '\u0394',+ '\u0395',+ '\u0396',+ '\u0397',+ '\u0398',+ '\u0399',+ '\u039A',+ '\u039B',+ '\u039C',+ '\u039D',+ '\u039E',+ '\u039F',+ '\u03A0',+ '\u03A1',+ '\u03A3',+ '\u03A4',+ '\u03A5',+ '\u03A6',+ '\u03A7',+ '\u03A8',+ '\u03A9',+ '\u03AA',+ '\u03AB'+ };++ // ISO-8859-7 charset (ELOT-928)+ public static char[] ISO = {+ // lower case+ 0xc0,+ 0xdc,+ 0xdd,+ 0xde,+ 0xdf,+ 0xe0,+ 0xe1,+ 0xe2,+ 0xe3,+ 0xe4,+ 0xe5,+ 0xe6,+ 0xe7,+ 0xe8,+ 0xe9,+ 0xea,+ 0xeb,+ 0xec,+ 0xed,+ 0xee,+ 0xef,+ 0xf0,+ 0xf1,+ 0xf2,+ 0xf3,+ 0xf4,+ 0xf5,+ 0xf6,+ 0xf7,+ 0xf8,+ 0xf9,+ 0xfa,+ 0xfb,+ 0xfc,+ 0xfd,+ 0xfe,+ // upper case+ 0xb6,+ 0xb8,+ 0xb9,+ 0xba,+ 0xbc,+ 0xbe,+ 0xbf,+ 0xc1,+ 0xc2,+ 0xc3,+ 0xc4,+ 0xc5,+ 0xc6,+ 0xc7,+ 0xc8,+ 0xc9,+ 0xca,+ 0xcb,+ 0xcc,+ 0xcd,+ 0xce,+ 0xcf,+ 0xd0,+ 0xd1,+ 0xd3,+ 0xd4,+ 0xd5,+ 0xd6,+ 0xd7,+ 0xd8,+ 0xd9,+ 0xda,+ 0xdb+ };++ // CP1253 charset+ public static char[] CP1253 = {+ // lower case+ 0xc0,+ 0xdc,+ 0xdd,+ 0xde,+ 0xdf,+ 0xe0,+ 0xe1,+ 0xe2,+ 0xe3,+ 0xe4,+ 0xe5,+ 0xe6,+ 0xe7,+ 0xe8,+ 0xe9,+ 0xea,+ 0xeb,+ 0xec,+ 0xed,+ 0xee,+ 0xef,+ 0xf0,+ 0xf1,+ 0xf2,+ 0xf3,+ 0xf4,+ 0xf5,+ 0xf6,+ 0xf7,+ 0xf8,+ 0xf9,+ 0xfa,+ 0xfb,+ 0xfc,+ 0xfd,+ 0xfe,+ // upper case+ 0xa2,+ 0xb8,+ 0xb9,+ 0xba,+ 0xbc,+ 0xbe,+ 0xbf,+ 0xc1,+ 0xc2,+ 0xc3,+ 0xc4,+ 0xc5,+ 0xc6,+ 0xc7,+ 0xc8,+ 0xc9,+ 0xca,+ 0xcb,+ 0xcc,+ 0xcd,+ 0xce,+ 0xcf,+ 0xd0,+ 0xd1,+ 0xd3,+ 0xd4,+ 0xd5,+ 0xd6,+ 0xd7,+ 0xd8,+ 0xd9,+ 0xda,+ 0xdb+ };++ public static char toLowerCase(char letter, char[] charset)+ {+ if (charset == UnicodeGreek) {+ // First deal with lower case, not accented letters+ if (letter >= '\u03B1' && letter <= '\u03C9')+ {+ // Special case 'small final sigma', where we return 'small sigma'+ if (letter == '\u03C2') {+ return '\u03C3';+ } else {+ return letter;+ }+ }+ // Then deal with lower case, accented letters+ // alpha with acute+ if (letter == '\u03AC') {+ return '\u03B1';+ }+ // epsilon with acute+ if (letter == '\u03AD') {+ return '\u03B5';+ }+ // eta with acute+ if (letter == '\u03AE') {+ return '\u03B7';+ }+ // iota with acute, iota with diaeresis, iota with acute and diaeresis+ if (letter == '\u03AF' || letter == '\u03CA' || letter == '\u0390') {+ return '\u03B9';+ }+ // upsilon with acute, upsilon with diaeresis, upsilon with acute and diaeresis+ if (letter == '\u03CD' || letter == '\u03CB' || letter == '\u03B0') {+ return '\u03C5';+ }+ // omicron with acute+ if (letter == '\u03CC') {+ return '\u03BF';+ }+ // omega with acute+ if (letter == '\u03CE') {+ return '\u03C9';+ }+ // After that, deal with upper case, not accented letters+ if (letter >= '\u0391' && letter <= '\u03A9')+ {+ return (char) (letter + 32);+ }+ // Finally deal with upper case, accented letters+ // alpha with acute+ if (letter == '\u0386') {+ return '\u03B1';+ }+ // epsilon with acute+ if (letter == '\u0388') {+ return '\u03B5';+ }+ // eta with acute+ if (letter == '\u0389') {+ return '\u03B7';+ }+ // iota with acute, iota with diaeresis+ if (letter == '\u038A' || letter == '\u03AA') {+ return '\u03B9';+ }+ // upsilon with acute, upsilon with diaeresis+ if (letter == '\u038E' || letter == '\u03AB') {+ return '\u03C5';+ }+ // omicron with acute+ if (letter == '\u038C') {+ return '\u03BF';+ }+ // omega with acute+ if (letter == '\u038F') {+ return '\u03C9';+ }+ } else if (charset == ISO) {+ // First deal with lower case, not accented letters+ if (letter >= 0xe1 && letter <= 0xf9)+ {+ // Special case 'small final sigma', where we return 'small sigma'+ if (letter == 0xf2) {+ return 0xf3;+ } else {+ return letter;+ }+ }+ // Then deal with lower case, accented letters+ // alpha with acute+ if (letter == 0xdc) {+ return 0xe1;+ }+ // epsilon with acute+ if (letter == 0xdd) {+ return 0xe5;+ }+ // eta with acute+ if (letter == 0xde) {+ return 0xe7;+ }+ // iota with acute, iota with diaeresis, iota with acute and diaeresis+ if (letter == 0xdf || letter == 0xfa || letter == 0xc0) {+ return '\u03B9';+ }+ // upsilon with acute, upsilon with diaeresis, upsilon with acute and diaeresis+ if (letter == 0xfd || letter == 0xfb || letter == 0xe0) {+ return 0xf5;+ }+ // omicron with acute+ if (letter == 0xfc) {+ return 0xef;+ }+ // omega with acute+ if (letter == 0xfe) {+ return 0xf9;+ }+ // After that, deal with upper case, not accented letters+ if (letter >= 0xc1 && letter <= 0xd9) {+ return (char) (letter + 32);+ }+ // Finally deal with upper case, accented letters+ // alpha with acute+ if (letter == 0xb6) {+ return 0xe1;+ }+ // epsilon with acute+ if (letter == 0xb8) {+ return 0xe5;+ }+ // eta with acute+ if (letter == 0xb9) {+ return 0xe7;+ }+ // iota with acute, iota with diaeresis+ if (letter == 0xba || letter == 0xda) {+ return 0xe9;+ }+ // upsilon with acute, upsilon with diaeresis+ if (letter == 0xbe || letter == 0xdb) {+ return 0xf5;+ }+ // omicron with acute+ if (letter == 0xbc) {+ return 0xef;+ }+ // omega with acute+ if (letter == 0xbf) {+ return 0xf9;+ }+ } else if (charset == CP1253) {+ // First deal with lower case, not accented letters+ if (letter >= 0xe1 && letter <= 0xf9)+ {+ // Special case 'small final sigma', where we return 'small sigma'+ if (letter == 0xf2) {+ return 0xf3;+ } else {+ return letter;+ }+ }+ // Then deal with lower case, accented letters+ // alpha with acute+ if (letter == 0xdc) {+ return 0xe1;+ }+ // epsilon with acute+ if (letter == 0xdd) {+ return 0xe5;+ }+ // eta with acute+ if (letter == 0xde) {+ return 0xe7;+ }+ // iota with acute, iota with diaeresis, iota with acute and diaeresis+ if (letter == 0xdf || letter == 0xfa || letter == 0xc0) {+ return '\u03B9';+ }+ // upsilon with acute, upsilon with diaeresis, upsilon with acute and diaeresis+ if (letter == 0xfd || letter == 0xfb || letter == 0xe0) {+ return 0xf5;+ }+ // omicron with acute+ if (letter == 0xfc) {+ return 0xef;+ }+ // omega with acute+ if (letter == 0xfe) {+ return 0xf9;+ }+ // After that, deal with upper case, not accented letters+ if (letter >= 0xc1 && letter <= 0xd9) {+ return (char) (letter + 32);+ }+ // Finally deal with upper case, accented letters+ // alpha with acute+ if (letter == 0xa2) {+ return 0xe1;+ }+ // epsilon with acute+ if (letter == 0xb8) {+ return 0xe5;+ }+ // eta with acute+ if (letter == 0xb9) {+ return 0xe7;+ }+ // iota with acute, iota with diaeresis+ if (letter == 0xba || letter == 0xda) {+ return 0xe9;+ }+ // upsilon with acute, upsilon with diaeresis+ if (letter == 0xbe || letter == 0xdb) {+ return 0xf5;+ }+ // omicron with acute+ if (letter == 0xbc) {+ return 0xef;+ }+ // omega with acute+ if (letter == 0xbf) {+ return 0xf9;+ }+ }++ return Character.toLowerCase(letter);+ }+}diff --git a/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekLowerCaseFilter.java b/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekLowerCaseFilter.javaindex 39d198d7c86..9737a282c89 100644--- a/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekLowerCaseFilter.java+++ b/contrib/analyzers/src/java/org/apache/lucene/analysis/el/GreekLowerCaseFilter.java@@ -1,53 +1,53 @@-package org.apache.lucene.analysis.el;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.analysis.TokenFilter;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;--/**- * Normalizes token text to lower case, analyzing given ("greek") charset.- *- */-public final class GreekLowerCaseFilter extends TokenFilter-{- char[] charset;-- public GreekLowerCaseFilter(TokenStream in, char[] charset)- {- super(in);- this.charset = charset;- }-- public final Token next(final Token reusableToken) throws java.io.IOException- {- assert reusableToken != null;- Token nextToken = input.next(reusableToken);-- if (nextToken == null)- return null;-- char[] chArray = nextToken.termBuffer();- int chLen = nextToken.termLength();- for (int i = 0; i < chLen; i++)- {- chArray[i] = GreekCharsets.toLowerCase(chArray[i], charset);- }- return nextToken;- }-}+package org.apache.lucene.analysis.el;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.analysis.TokenFilter;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;++/**+ * Normalizes token text to lower case, analyzing given ("greek") charset.+ *+ */+public final class GreekLowerCaseFilter extends TokenFilter+{+ char[] charset;++ public GreekLowerCaseFilter(TokenStream in, char[] charset)+ {+ super(in);+ this.charset = charset;+ }++ public final Token next(final Token reusableToken) throws java.io.IOException+ {+ assert reusableToken != null;+ Token nextToken = input.next(reusableToken);++ if (nextToken == null)+ return null;++ char[] chArray = nextToken.termBuffer();+ int chLen = nextToken.termLength();+ for (int i = 0; i < chLen; i++)+ {+ chArray[i] = GreekCharsets.toLowerCase(chArray[i], charset);+ }+ return nextToken;+ }+}diff --git a/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java b/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.javaindex 934cd27fcf6..d44f743f160 100644--- a/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java+++ b/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java@@ -1,39 +1,39 @@-package org.apache.lucene.analysis.th;--/**- * Copyright 2006 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.Reader;-import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.StopAnalyzer;-import org.apache.lucene.analysis.StopFilter;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.analysis.standard.StandardFilter;-import org.apache.lucene.analysis.standard.StandardTokenizer;--/**- * Analyzer for Thai language. It uses java.text.BreakIterator to break words.- * @version 0.2- */-public class ThaiAnalyzer extends Analyzer {- public TokenStream tokenStream(String fieldName, Reader reader) {- TokenStream ts = new StandardTokenizer(reader);- ts = new StandardFilter(ts);- ts = new ThaiWordFilter(ts);- ts = new StopFilter(ts, StopAnalyzer.ENGLISH_STOP_WORDS);- return ts;- }-}+package org.apache.lucene.analysis.th;++/**+ * Copyright 2006 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.Reader;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.StopAnalyzer;+import org.apache.lucene.analysis.StopFilter;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.standard.StandardFilter;+import org.apache.lucene.analysis.standard.StandardTokenizer;++/**+ * Analyzer for Thai language. It uses java.text.BreakIterator to break words.+ * @version 0.2+ */+public class ThaiAnalyzer extends Analyzer {+ public TokenStream tokenStream(String fieldName, Reader reader) {+ TokenStream ts = new StandardTokenizer(reader);+ ts = new StandardFilter(ts);+ ts = new ThaiWordFilter(ts);+ ts = new StopFilter(ts, StopAnalyzer.ENGLISH_STOP_WORDS);+ return ts;+ }+}diff --git a/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiWordFilter.java b/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiWordFilter.javaindex 0fc564badbf..f87289e6723 100644--- a/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiWordFilter.java+++ b/contrib/analyzers/src/java/org/apache/lucene/analysis/th/ThaiWordFilter.java@@ -1,77 +1,77 @@-package org.apache.lucene.analysis.th;--/**- * Copyright 2006 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.util.Locale;-import java.lang.Character.UnicodeBlock;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenFilter;-import org.apache.lucene.analysis.TokenStream;-import java.text.BreakIterator;--/**- * TokenFilter that use java.text.BreakIterator to break each- * Token that is Thai into separate Token(s) for each Thai word.- * @version 0.2- */-public class ThaiWordFilter extends TokenFilter {-- private BreakIterator breaker = null;- private Token thaiToken = null;-- public ThaiWordFilter(TokenStream input) {- super(input);- breaker = BreakIterator.getWordInstance(new Locale("th"));- }-- public Token next(final Token reusableToken) throws IOException {- assert reusableToken != null;- if (thaiToken != null) {- int start = breaker.current();- int end = breaker.next();- if (end != BreakIterator.DONE) {- reusableToken.reinit(thaiToken, thaiToken.termBuffer(), start, end - start);- reusableToken.setStartOffset(thaiToken.startOffset()+start);- reusableToken.setEndOffset(thaiToken.endOffset()+end);- return reusableToken;- }- thaiToken = null;- }-- Token nextToken = input.next(reusableToken);- if (nextToken == null || nextToken.termLength() == 0) {- return null;- }-- String text = nextToken.term();- if (UnicodeBlock.of(text.charAt(0)) != UnicodeBlock.THAI) {- nextToken.setTermBuffer(text.toLowerCase());- return nextToken;- }-- thaiToken = (Token) nextToken.clone();- breaker.setText(text);- int end = breaker.next();- if (end != BreakIterator.DONE) {- nextToken.setTermBuffer(text, 0, end);- nextToken.setEndOffset(nextToken.startOffset() + end);- return nextToken;- }- return null;- }-}+package org.apache.lucene.analysis.th;++/**+ * Copyright 2006 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.Locale;+import java.lang.Character.UnicodeBlock;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenFilter;+import org.apache.lucene.analysis.TokenStream;+import java.text.BreakIterator;++/**+ * TokenFilter that use java.text.BreakIterator to break each+ * Token that is Thai into separate Token(s) for each Thai word.+ * @version 0.2+ */+public class ThaiWordFilter extends TokenFilter {++ private BreakIterator breaker = null;+ private Token thaiToken = null;++ public ThaiWordFilter(TokenStream input) {+ super(input);+ breaker = BreakIterator.getWordInstance(new Locale("th"));+ }++ public Token next(final Token reusableToken) throws IOException {+ assert reusableToken != null;+ if (thaiToken != null) {+ int start = breaker.current();+ int end = breaker.next();+ if (end != BreakIterator.DONE) {+ reusableToken.reinit(thaiToken, thaiToken.termBuffer(), start, end - start);+ reusableToken.setStartOffset(thaiToken.startOffset()+start);+ reusableToken.setEndOffset(thaiToken.endOffset()+end);+ return reusableToken;+ }+ thaiToken = null;+ }++ Token nextToken = input.next(reusableToken);+ if (nextToken == null || nextToken.termLength() == 0) {+ return null;+ }++ String text = nextToken.term();+ if (UnicodeBlock.of(text.charAt(0)) != UnicodeBlock.THAI) {+ nextToken.setTermBuffer(text.toLowerCase());+ return nextToken;+ }++ thaiToken = (Token) nextToken.clone();+ breaker.setText(text);+ int end = breaker.next();+ if (end != BreakIterator.DONE) {+ nextToken.setTermBuffer(text, 0, end);+ nextToken.setEndOffset(nextToken.startOffset() + end);+ return nextToken;+ }+ return null;+ }+}diff --git a/contrib/analyzers/src/test/org/apache/lucene/analysis/el/GreekAnalyzerTest.java b/contrib/analyzers/src/test/org/apache/lucene/analysis/el/GreekAnalyzerTest.javaindex 912bbc626c6..c7b3c2cb93d 100644--- a/contrib/analyzers/src/test/org/apache/lucene/analysis/el/GreekAnalyzerTest.java+++ b/contrib/analyzers/src/test/org/apache/lucene/analysis/el/GreekAnalyzerTest.java@@ -1,75 +1,75 @@-package org.apache.lucene.analysis.el;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.StringReader;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;--import junit.framework.TestCase;---/**- * A unit test class for verifying the correct operation of the GreekAnalyzer.- *- */-public class GreekAnalyzerTest extends TestCase {-- /**- * A helper method copied from org.apache.lucene.analysis.TestAnalyzers.- *- * @param a the Analyzer to test- * @param input an input String to analyze- * @param output a String[] with the results of the analysis- * @throws Exception in case an error occurs- */- private void assertAnalyzesTo(Analyzer a, String input, String[] output) throws Exception {- TokenStream ts = a.tokenStream("dummy", new StringReader(input));- final Token reusableToken = new Token();- for (int i=0; i<output.length; i++) {- Token nextToken = ts.next(reusableToken);- assertNotNull(nextToken);- assertEquals(nextToken.term(), output[i]);- }- assertNull(ts.next(reusableToken));- ts.close();- }-- /**- * Test the analysis of various greek strings.- *- * @throws Exception in case an error occurs- */- public void testAnalyzer() throws Exception {- Analyzer a = new GreekAnalyzer();- // Verify the correct analysis of capitals and small accented letters- assertAnalyzesTo(a, "\u039c\u03af\u03b1 \u03b5\u03be\u03b1\u03b9\u03c1\u03b5\u03c4\u03b9\u03ba\u03ac \u03ba\u03b1\u03bb\u03ae \u03ba\u03b1\u03b9 \u03c0\u03bb\u03bf\u03cd\u03c3\u03b9\u03b1 \u03c3\u03b5\u03b9\u03c1\u03ac \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03c9\u03bd \u03c4\u03b7\u03c2 \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ae\u03c2 \u03b3\u03bb\u03ce\u03c3\u03c3\u03b1\u03c2",- new String[] { "\u03bc\u03b9\u03b1", "\u03b5\u03be\u03b1\u03b9\u03c1\u03b5\u03c4\u03b9\u03ba\u03b1", "\u03ba\u03b1\u03bb\u03b7", "\u03c0\u03bb\u03bf\u03c5\u03c3\u03b9\u03b1", "\u03c3\u03b5\u03b9\u03c1\u03b1", "\u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03b7\u03c1\u03c9\u03bd",- "\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03b7\u03c3", "\u03b3\u03bb\u03c9\u03c3\u03c3\u03b1\u03c3" });- // Verify the correct analysis of small letters with diaeresis and the elimination- // of punctuation marks- assertAnalyzesTo(a, "\u03a0\u03c1\u03bf\u03ca\u03cc\u03bd\u03c4\u03b1 (\u03ba\u03b1\u03b9) [\u03c0\u03bf\u03bb\u03bb\u03b1\u03c0\u03bb\u03ad\u03c2] - \u0391\u039d\u0391\u0393\u039a\u0395\u03a3",- new String[] { "\u03c0\u03c1\u03bf\u03b9\u03bf\u03bd\u03c4\u03b1", "\u03c0\u03bf\u03bb\u03bb\u03b1\u03c0\u03bb\u03b5\u03c3", "\u03b1\u03bd\u03b1\u03b3\u03ba\u03b5\u03c3" });- // Verify the correct analysis of capital accented letters and capitalletters with diaeresis,- // as well as the elimination of stop words- assertAnalyzesTo(a, "\u03a0\u03a1\u039f\u03ab\u03a0\u039f\u0398\u0395\u03a3\u0395\u0399\u03a3 \u0386\u03c8\u03bf\u03b3\u03bf\u03c2, \u03bf \u03bc\u03b5\u03c3\u03c4\u03cc\u03c2 \u03ba\u03b1\u03b9 \u03bf\u03b9 \u03ac\u03bb\u03bb\u03bf\u03b9",- new String[] { "\u03c0\u03c1\u03bf\u03c5\u03c0\u03bf\u03b8\u03b5\u03c3\u03b5\u03b9\u03c3", "\u03b1\u03c8\u03bf\u03b3\u03bf\u03c3", "\u03bc\u03b5\u03c3\u03c4\u03bf\u03c3", "\u03b1\u03bb\u03bb\u03bf\u03b9" });- }--}+package org.apache.lucene.analysis.el;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.StringReader;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;++import junit.framework.TestCase;+++/**+ * A unit test class for verifying the correct operation of the GreekAnalyzer.+ *+ */+public class GreekAnalyzerTest extends TestCase {++ /**+ * A helper method copied from org.apache.lucene.analysis.TestAnalyzers.+ *+ * @param a the Analyzer to test+ * @param input an input String to analyze+ * @param output a String[] with the results of the analysis+ * @throws Exception in case an error occurs+ */+ private void assertAnalyzesTo(Analyzer a, String input, String[] output) throws Exception {+ TokenStream ts = a.tokenStream("dummy", new StringReader(input));+ final Token reusableToken = new Token();+ for (int i=0; i<output.length; i++) {+ Token nextToken = ts.next(reusableToken);+ assertNotNull(nextToken);+ assertEquals(nextToken.term(), output[i]);+ }+ assertNull(ts.next(reusableToken));+ ts.close();+ }++ /**+ * Test the analysis of various greek strings.+ *+ * @throws Exception in case an error occurs+ */+ public void testAnalyzer() throws Exception {+ Analyzer a = new GreekAnalyzer();+ // Verify the correct analysis of capitals and small accented letters+ assertAnalyzesTo(a, "\u039c\u03af\u03b1 \u03b5\u03be\u03b1\u03b9\u03c1\u03b5\u03c4\u03b9\u03ba\u03ac \u03ba\u03b1\u03bb\u03ae \u03ba\u03b1\u03b9 \u03c0\u03bb\u03bf\u03cd\u03c3\u03b9\u03b1 \u03c3\u03b5\u03b9\u03c1\u03ac \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03c9\u03bd \u03c4\u03b7\u03c2 \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ae\u03c2 \u03b3\u03bb\u03ce\u03c3\u03c3\u03b1\u03c2",+ new String[] { "\u03bc\u03b9\u03b1", "\u03b5\u03be\u03b1\u03b9\u03c1\u03b5\u03c4\u03b9\u03ba\u03b1", "\u03ba\u03b1\u03bb\u03b7", "\u03c0\u03bb\u03bf\u03c5\u03c3\u03b9\u03b1", "\u03c3\u03b5\u03b9\u03c1\u03b1", "\u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03b7\u03c1\u03c9\u03bd",+ "\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03b7\u03c3", "\u03b3\u03bb\u03c9\u03c3\u03c3\u03b1\u03c3" });+ // Verify the correct analysis of small letters with diaeresis and the elimination+ // of punctuation marks+ assertAnalyzesTo(a, "\u03a0\u03c1\u03bf\u03ca\u03cc\u03bd\u03c4\u03b1 (\u03ba\u03b1\u03b9) [\u03c0\u03bf\u03bb\u03bb\u03b1\u03c0\u03bb\u03ad\u03c2] - \u0391\u039d\u0391\u0393\u039a\u0395\u03a3",+ new String[] { "\u03c0\u03c1\u03bf\u03b9\u03bf\u03bd\u03c4\u03b1", "\u03c0\u03bf\u03bb\u03bb\u03b1\u03c0\u03bb\u03b5\u03c3", "\u03b1\u03bd\u03b1\u03b3\u03ba\u03b5\u03c3" });+ // Verify the correct analysis of capital accented letters and capitalletters with diaeresis,+ // as well as the elimination of stop words+ assertAnalyzesTo(a, "\u03a0\u03a1\u039f\u03ab\u03a0\u039f\u0398\u0395\u03a3\u0395\u0399\u03a3 \u0386\u03c8\u03bf\u03b3\u03bf\u03c2, \u03bf \u03bc\u03b5\u03c3\u03c4\u03cc\u03c2 \u03ba\u03b1\u03b9 \u03bf\u03b9 \u03ac\u03bb\u03bb\u03bf\u03b9",+ new String[] { "\u03c0\u03c1\u03bf\u03c5\u03c0\u03bf\u03b8\u03b5\u03c3\u03b5\u03b9\u03c3", "\u03b1\u03c8\u03bf\u03b3\u03bf\u03c3", "\u03bc\u03b5\u03c3\u03c4\u03bf\u03c3", "\u03b1\u03bb\u03bb\u03bf\u03b9" });+ }++}diff --git a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/DefaultEncoder.java b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/DefaultEncoder.javaindex 093012a3e16..4a4572b7c68 100644--- a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/DefaultEncoder.java+++ b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/DefaultEncoder.java@@ -1,32 +1,32 @@-package org.apache.lucene.search.highlight;-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--/**- * Simple {@link Encoder} implementation that does not modify the output- *- */-public class DefaultEncoder implements Encoder-{- public DefaultEncoder()- {- }-- public String encodeText(String originalText)- {- return originalText;- }+package org.apache.lucene.search.highlight;+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * Simple {@link Encoder} implementation that does not modify the output+ *+ */+public class DefaultEncoder implements Encoder+{+ public DefaultEncoder()+ {+ }++ public String encodeText(String originalText)+ {+ return originalText;+ }}\ No newline at end of filediff --git a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/Encoder.java b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/Encoder.javaindex bc212bf9ee9..8e493751f1f 100644--- a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/Encoder.java+++ b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/Encoder.java@@ -1,29 +1,29 @@-package org.apache.lucene.search.highlight;-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---/**- * Encodes original text. The Encoder works with the Formatter to generate the output.- *- */-public interface Encoder-{- /**- * @param originalText The section of text being output- */- String encodeText(String originalText);+package org.apache.lucene.search.highlight;+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++/**+ * Encodes original text. The Encoder works with the Formatter to generate the output.+ *+ */+public interface Encoder+{+ /**+ * @param originalText The section of text being output+ */+ String encodeText(String originalText);}\ No newline at end of filediff --git a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleHTMLEncoder.java b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleHTMLEncoder.javaindex a163177fd9f..55dd68d7206 100644--- a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleHTMLEncoder.java+++ b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleHTMLEncoder.java@@ -1,81 +1,81 @@-package org.apache.lucene.search.highlight;-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--/**- * Simple {@link Encoder} implementation to escape text for HTML output- *- */-public class SimpleHTMLEncoder implements Encoder-{- public SimpleHTMLEncoder()- {- }-- public String encodeText(String originalText)- {- return htmlEncode(originalText);- }-- /**- * Encode string into HTML- */- public final static String htmlEncode(String plainText)- {- if (plainText == null || plainText.length() == 0)- {- return "";- }-- StringBuffer result = new StringBuffer(plainText.length());-- for (int index=0; index<plainText.length(); index++)- {- char ch = plainText.charAt(index);-- switch (ch)- {- case '"':- result.append(""");- break;-- case '&':- result.append("&");- break;-- case '<':- result.append("<");- break;-- case '>':- result.append(">");- break;-- default:- if (ch < 128)- {- result.append(ch);- }- else- {- result.append("&#").append((int)ch).append(";");- }- }- }-- return result.toString();- }+package org.apache.lucene.search.highlight;+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * Simple {@link Encoder} implementation to escape text for HTML output+ *+ */+public class SimpleHTMLEncoder implements Encoder+{+ public SimpleHTMLEncoder()+ {+ }++ public String encodeText(String originalText)+ {+ return htmlEncode(originalText);+ }++ /**+ * Encode string into HTML+ */+ public final static String htmlEncode(String plainText)+ {+ if (plainText == null || plainText.length() == 0)+ {+ return "";+ }++ StringBuffer result = new StringBuffer(plainText.length());++ for (int index=0; index<plainText.length(); index++)+ {+ char ch = plainText.charAt(index);++ switch (ch)+ {+ case '"':+ result.append(""");+ break;++ case '&':+ result.append("&");+ break;++ case '<':+ result.append("<");+ break;++ case '>':+ result.append(">");+ break;++ default:+ if (ch < 128)+ {+ result.append(ch);+ }+ else+ {+ result.append("&#").append((int)ch).append(";");+ }+ }+ }++ return result.toString();+ }}\ No newline at end of filediff --git a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleSpanFragmenter.java b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleSpanFragmenter.javaindex a81c35c2214..20661cd4ba4 100644--- a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleSpanFragmenter.java+++ b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SimpleSpanFragmenter.java@@ -1,95 +1,95 @@-package org.apache.lucene.search.highlight;---/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-import org.apache.lucene.analysis.Token;--import java.util.List;---/**- * {@link Fragmenter} implementation which breaks text up into same-size- * fragments but does not split up Spans. This is a simple sample class.- */-public class SimpleSpanFragmenter implements Fragmenter {- private static final int DEFAULT_FRAGMENT_SIZE = 100;- private int fragmentSize;- private int currentNumFrags;- private int position = -1;- private SpanScorer spanScorer;- private int waitForPos = -1;-- /**- * @param spanscorer SpanScorer that was used to score hits- */- public SimpleSpanFragmenter(SpanScorer spanscorer) {- this(spanscorer, DEFAULT_FRAGMENT_SIZE);- }-- /**- * @param spanscorer SpanScorer that was used to score hits- * @param fragmentSize size in bytes of each fragment- */- public SimpleSpanFragmenter(SpanScorer spanscorer, int fragmentSize) {- this.fragmentSize = fragmentSize;- this.spanScorer = spanscorer;- }-- /* (non-Javadoc)- * @see org.apache.lucene.search.highlight.Fragmenter#isNewFragment(org.apache.lucene.analysis.Token)- */- public boolean isNewFragment(Token token) {- position += token.getPositionIncrement();-- if (waitForPos == position) {- waitForPos = -1;- } else if (waitForPos != -1) {- return false;- }-- WeightedSpanTerm wSpanTerm = spanScorer.getWeightedSpanTerm(token.term());-- if (wSpanTerm != null) {- List positionSpans = wSpanTerm.getPositionSpans();-- for (int i = 0; i < positionSpans.size(); i++) {- if (((PositionSpan) positionSpans.get(i)).start == position) {- waitForPos = ((PositionSpan) positionSpans.get(i)).end + 1;-- return true;- }- }- }-- boolean isNewFrag = token.endOffset() >= (fragmentSize * currentNumFrags);-- if (isNewFrag) {- currentNumFrags++;- }-- return isNewFrag;- }-- /* (non-Javadoc)- * @see org.apache.lucene.search.highlight.Fragmenter#start(java.lang.String)- */- public void start(String originalText) {- position = 0;- currentNumFrags = 1;- }-}+package org.apache.lucene.search.highlight;+++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import org.apache.lucene.analysis.Token;++import java.util.List;+++/**+ * {@link Fragmenter} implementation which breaks text up into same-size+ * fragments but does not split up Spans. This is a simple sample class.+ */+public class SimpleSpanFragmenter implements Fragmenter {+ private static final int DEFAULT_FRAGMENT_SIZE = 100;+ private int fragmentSize;+ private int currentNumFrags;+ private int position = -1;+ private SpanScorer spanScorer;+ private int waitForPos = -1;++ /**+ * @param spanscorer SpanScorer that was used to score hits+ */+ public SimpleSpanFragmenter(SpanScorer spanscorer) {+ this(spanscorer, DEFAULT_FRAGMENT_SIZE);+ }++ /**+ * @param spanscorer SpanScorer that was used to score hits+ * @param fragmentSize size in bytes of each fragment+ */+ public SimpleSpanFragmenter(SpanScorer spanscorer, int fragmentSize) {+ this.fragmentSize = fragmentSize;+ this.spanScorer = spanscorer;+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.search.highlight.Fragmenter#isNewFragment(org.apache.lucene.analysis.Token)+ */+ public boolean isNewFragment(Token token) {+ position += token.getPositionIncrement();++ if (waitForPos == position) {+ waitForPos = -1;+ } else if (waitForPos != -1) {+ return false;+ }++ WeightedSpanTerm wSpanTerm = spanScorer.getWeightedSpanTerm(token.term());++ if (wSpanTerm != null) {+ List positionSpans = wSpanTerm.getPositionSpans();++ for (int i = 0; i < positionSpans.size(); i++) {+ if (((PositionSpan) positionSpans.get(i)).start == position) {+ waitForPos = ((PositionSpan) positionSpans.get(i)).end + 1;++ return true;+ }+ }+ }++ boolean isNewFrag = token.endOffset() >= (fragmentSize * currentNumFrags);++ if (isNewFrag) {+ currentNumFrags++;+ }++ return isNewFrag;+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.search.highlight.Fragmenter#start(java.lang.String)+ */+ public void start(String originalText) {+ position = 0;+ currentNumFrags = 1;+ }+}diff --git a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SpanScorer.java b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SpanScorer.javaindex e0efebb51c5..3d472ce107e 100644--- a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SpanScorer.java+++ b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/SpanScorer.java@@ -1,218 +1,218 @@-package org.apache.lucene.search.highlight;--import java.io.IOException;-import java.util.HashMap;-import java.util.HashSet;-import java.util.Map;-import java.util.Set;--import org.apache.lucene.analysis.CachingTokenFilter;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.search.Query;---/**- * {@link Scorer} implementation which scores text fragments by the number of- * unique query terms found. This class converts appropriate Querys to- * SpanQuerys and attempts to score only those terms that participated in- * generating the 'hit' on the document.- */-public class SpanScorer implements Scorer {- private float totalScore;- private Set foundTerms;- private Map fieldWeightedSpanTerms;- private float maxTermWeight;- private int position = -1;- private String defaultField;- private static boolean highlightCnstScrRngQuery;-- /**- * @param query- * Query to use for highlighting- * @param field- * Field to highlight - pass null to ignore fields- * @param tokenStream- * of source text to be highlighted- * @throws IOException- */- public SpanScorer(Query query, String field,- CachingTokenFilter cachingTokenFilter) throws IOException {- init(query, field, cachingTokenFilter, null);- }-- /**- * @param query- * Query to use for highlighting- * @param field- * Field to highlight - pass null to ignore fields- * @param tokenStream- * of source text to be highlighted- * @param reader- * @throws IOException- */- public SpanScorer(Query query, String field,- CachingTokenFilter cachingTokenFilter, IndexReader reader)- throws IOException {- init(query, field, cachingTokenFilter, reader);- }-- /**- * As above, but with ability to pass in an <tt>IndexReader</tt>- */- public SpanScorer(Query query, String field,- CachingTokenFilter cachingTokenFilter, IndexReader reader, String defaultField)- throws IOException {- this.defaultField = defaultField.intern();- init(query, field, cachingTokenFilter, reader);- }-- /**- * @param defaultField - The default field for queries with the field name unspecified- */- public SpanScorer(Query query, String field,- CachingTokenFilter cachingTokenFilter, String defaultField) throws IOException {- this.defaultField = defaultField.intern();- init(query, field, cachingTokenFilter, null);- }-- /**- * @param weightedTerms- */- public SpanScorer(WeightedSpanTerm[] weightedTerms) {- this.fieldWeightedSpanTerms = new HashMap(weightedTerms.length);-- for (int i = 0; i < weightedTerms.length; i++) {- WeightedSpanTerm existingTerm = (WeightedSpanTerm) fieldWeightedSpanTerms.get(weightedTerms[i].term);-- if ((existingTerm == null) ||- (existingTerm.weight < weightedTerms[i].weight)) {- // if a term is defined more than once, always use the highest- // scoring weight- fieldWeightedSpanTerms.put(weightedTerms[i].term, weightedTerms[i]);- maxTermWeight = Math.max(maxTermWeight, weightedTerms[i].getWeight());- }- }- }-- /*- * (non-Javadoc)- *- * @see org.apache.lucene.search.highlight.Scorer#getFragmentScore()- */- public float getFragmentScore() {- return totalScore;- }-- /**- *- * @return The highest weighted term (useful for passing to- * GradientFormatter to set top end of coloring scale.- */- public float getMaxTermWeight() {- return maxTermWeight;- }-- /*- * (non-Javadoc)- *- * @see org.apache.lucene.search.highlight.Scorer#getTokenScore(org.apache.lucene.analysis.Token,- * int)- */- public float getTokenScore(Token token) {- position += token.getPositionIncrement();- String termText = token.term();-- WeightedSpanTerm weightedSpanTerm;-- if ((weightedSpanTerm = (WeightedSpanTerm) fieldWeightedSpanTerms.get(- termText)) == null) {- return 0;- }-- if (weightedSpanTerm.positionSensitive &&- !weightedSpanTerm.checkPosition(position)) {- return 0;- }-- float score = weightedSpanTerm.getWeight();-- // found a query term - is it unique in this doc?- if (!foundTerms.contains(termText)) {- totalScore += score;- foundTerms.add(termText);- }-- return score;- }-- /**- * Retrieve the WeightedSpanTerm for the specified token. Useful for passing- * Span information to a Fragmenter.- *- * @param token- * @return WeightedSpanTerm for token- */- public WeightedSpanTerm getWeightedSpanTerm(String token) {- return (WeightedSpanTerm) fieldWeightedSpanTerms.get(token);- }-- /**- * @param query- * @param field- * @param tokenStream- * @param reader- * @throws IOException- */- private void init(Query query, String field,- CachingTokenFilter cachingTokenFilter, IndexReader reader)- throws IOException {- WeightedSpanTermExtractor qse = defaultField == null ? new WeightedSpanTermExtractor()- : new WeightedSpanTermExtractor(defaultField);-- qse.setHighlightCnstScrRngQuery(highlightCnstScrRngQuery);-- if (reader == null) {- this.fieldWeightedSpanTerms = qse.getWeightedSpanTerms(query,- cachingTokenFilter, field);- } else {- this.fieldWeightedSpanTerms = qse.getWeightedSpanTermsWithScores(query,- cachingTokenFilter, field, reader);- }- }-- /**- * @return whether ConstantScoreRangeQuerys are set to be highlighted- */- public static boolean isHighlightCnstScrRngQuery() {- return highlightCnstScrRngQuery;- }-- /**- * If you call Highlighter#getBestFragment() more than once you must reset- * the SpanScorer between each call.- */- public void reset() {- position = -1;- }-- /**- * Turns highlighting of ConstantScoreRangeQuery on/off. ConstantScoreRangeQuerys cannot be- * highlighted if you rewrite the query first. Must be called before SpanScorer construction.- *- * @param highlightCnstScrRngQuery- */- public static void setHighlightCnstScrRngQuery(boolean highlight) {- highlightCnstScrRngQuery = highlight;- }-- /*- * (non-Javadoc)- *- * @see org.apache.lucene.search.highlight.Scorer#startFragment(org.apache.lucene.search.highlight.TextFragment)- */- public void startFragment(TextFragment newFragment) {- foundTerms = new HashSet();- totalScore = 0;- }-}+package org.apache.lucene.search.highlight;++import java.io.IOException;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Map;+import java.util.Set;++import org.apache.lucene.analysis.CachingTokenFilter;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.Query;+++/**+ * {@link Scorer} implementation which scores text fragments by the number of+ * unique query terms found. This class converts appropriate Querys to+ * SpanQuerys and attempts to score only those terms that participated in+ * generating the 'hit' on the document.+ */+public class SpanScorer implements Scorer {+ private float totalScore;+ private Set foundTerms;+ private Map fieldWeightedSpanTerms;+ private float maxTermWeight;+ private int position = -1;+ private String defaultField;+ private static boolean highlightCnstScrRngQuery;++ /**+ * @param query+ * Query to use for highlighting+ * @param field+ * Field to highlight - pass null to ignore fields+ * @param tokenStream+ * of source text to be highlighted+ * @throws IOException+ */+ public SpanScorer(Query query, String field,+ CachingTokenFilter cachingTokenFilter) throws IOException {+ init(query, field, cachingTokenFilter, null);+ }++ /**+ * @param query+ * Query to use for highlighting+ * @param field+ * Field to highlight - pass null to ignore fields+ * @param tokenStream+ * of source text to be highlighted+ * @param reader+ * @throws IOException+ */+ public SpanScorer(Query query, String field,+ CachingTokenFilter cachingTokenFilter, IndexReader reader)+ throws IOException {+ init(query, field, cachingTokenFilter, reader);+ }++ /**+ * As above, but with ability to pass in an <tt>IndexReader</tt>+ */+ public SpanScorer(Query query, String field,+ CachingTokenFilter cachingTokenFilter, IndexReader reader, String defaultField)+ throws IOException {+ this.defaultField = defaultField.intern();+ init(query, field, cachingTokenFilter, reader);+ }++ /**+ * @param defaultField - The default field for queries with the field name unspecified+ */+ public SpanScorer(Query query, String field,+ CachingTokenFilter cachingTokenFilter, String defaultField) throws IOException {+ this.defaultField = defaultField.intern();+ init(query, field, cachingTokenFilter, null);+ }++ /**+ * @param weightedTerms+ */+ public SpanScorer(WeightedSpanTerm[] weightedTerms) {+ this.fieldWeightedSpanTerms = new HashMap(weightedTerms.length);++ for (int i = 0; i < weightedTerms.length; i++) {+ WeightedSpanTerm existingTerm = (WeightedSpanTerm) fieldWeightedSpanTerms.get(weightedTerms[i].term);++ if ((existingTerm == null) ||+ (existingTerm.weight < weightedTerms[i].weight)) {+ // if a term is defined more than once, always use the highest+ // scoring weight+ fieldWeightedSpanTerms.put(weightedTerms[i].term, weightedTerms[i]);+ maxTermWeight = Math.max(maxTermWeight, weightedTerms[i].getWeight());+ }+ }+ }++ /*+ * (non-Javadoc)+ *+ * @see org.apache.lucene.search.highlight.Scorer#getFragmentScore()+ */+ public float getFragmentScore() {+ return totalScore;+ }++ /**+ *+ * @return The highest weighted term (useful for passing to+ * GradientFormatter to set top end of coloring scale.+ */+ public float getMaxTermWeight() {+ return maxTermWeight;+ }++ /*+ * (non-Javadoc)+ *+ * @see org.apache.lucene.search.highlight.Scorer#getTokenScore(org.apache.lucene.analysis.Token,+ * int)+ */+ public float getTokenScore(Token token) {+ position += token.getPositionIncrement();+ String termText = token.term();++ WeightedSpanTerm weightedSpanTerm;++ if ((weightedSpanTerm = (WeightedSpanTerm) fieldWeightedSpanTerms.get(+ termText)) == null) {+ return 0;+ }++ if (weightedSpanTerm.positionSensitive &&+ !weightedSpanTerm.checkPosition(position)) {+ return 0;+ }++ float score = weightedSpanTerm.getWeight();++ // found a query term - is it unique in this doc?+ if (!foundTerms.contains(termText)) {+ totalScore += score;+ foundTerms.add(termText);+ }++ return score;+ }++ /**+ * Retrieve the WeightedSpanTerm for the specified token. Useful for passing+ * Span information to a Fragmenter.+ *+ * @param token+ * @return WeightedSpanTerm for token+ */+ public WeightedSpanTerm getWeightedSpanTerm(String token) {+ return (WeightedSpanTerm) fieldWeightedSpanTerms.get(token);+ }++ /**+ * @param query+ * @param field+ * @param tokenStream+ * @param reader+ * @throws IOException+ */+ private void init(Query query, String field,+ CachingTokenFilter cachingTokenFilter, IndexReader reader)+ throws IOException {+ WeightedSpanTermExtractor qse = defaultField == null ? new WeightedSpanTermExtractor()+ : new WeightedSpanTermExtractor(defaultField);++ qse.setHighlightCnstScrRngQuery(highlightCnstScrRngQuery);++ if (reader == null) {+ this.fieldWeightedSpanTerms = qse.getWeightedSpanTerms(query,+ cachingTokenFilter, field);+ } else {+ this.fieldWeightedSpanTerms = qse.getWeightedSpanTermsWithScores(query,+ cachingTokenFilter, field, reader);+ }+ }++ /**+ * @return whether ConstantScoreRangeQuerys are set to be highlighted+ */+ public static boolean isHighlightCnstScrRngQuery() {+ return highlightCnstScrRngQuery;+ }++ /**+ * If you call Highlighter#getBestFragment() more than once you must reset+ * the SpanScorer between each call.+ */+ public void reset() {+ position = -1;+ }++ /**+ * Turns highlighting of ConstantScoreRangeQuery on/off. ConstantScoreRangeQuerys cannot be+ * highlighted if you rewrite the query first. Must be called before SpanScorer construction.+ *+ * @param highlightCnstScrRngQuery+ */+ public static void setHighlightCnstScrRngQuery(boolean highlight) {+ highlightCnstScrRngQuery = highlight;+ }++ /*+ * (non-Javadoc)+ *+ * @see org.apache.lucene.search.highlight.Scorer#startFragment(org.apache.lucene.search.highlight.TextFragment)+ */+ public void startFragment(TextFragment newFragment) {+ foundTerms = new HashSet();+ totalScore = 0;+ }+}diff --git a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTerm.java b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTerm.javaindex 70874dc8323..24d71292ad2 100644--- a/contrib/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTerm.java+++ b/contrib/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTerm.java@@ -1,104 +1,104 @@-package org.apache.lucene.search.highlight;---/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-import java.util.ArrayList;-import java.util.Iterator;-import java.util.List;---/**- * Lightweight class to hold term, weight, and positions used for scoring this- * term.- */-public class WeightedSpanTerm extends WeightedTerm{- boolean positionSensitive;- private List positionSpans = new ArrayList();-- /**- * @param weight- * @param term- */- public WeightedSpanTerm(float weight, String term) {- super(weight, term);- this.positionSpans = new ArrayList();- }-- /**- * @param weight- * @param term- * @param positionSensitive- */- public WeightedSpanTerm(float weight, String term, boolean positionSensitive) {- super(weight, term);- this.positionSensitive = positionSensitive;- }-- /**- * Checks to see if this term is valid at <code>position</code>.- *- * @param position- * to check against valid term postions- * @return true iff this term is a hit at this position- */- public boolean checkPosition(int position) {- // There would probably be a slight speed improvement if PositionSpans- // where kept in some sort of priority queue - that way this method- // could- // bail early without checking each PositionSpan.- Iterator positionSpanIt = positionSpans.iterator();-- while (positionSpanIt.hasNext()) {- PositionSpan posSpan = (PositionSpan) positionSpanIt.next();-- if (((position >= posSpan.start) && (position <= posSpan.end))) {- return true;- }- }-- return false;- }-- public void addPositionSpans(List positionSpans) {- this.positionSpans.addAll(positionSpans);- }-- public boolean isPositionSensitive() {- return positionSensitive;- }-- public void setPositionSensitive(boolean positionSensitive) {- this.positionSensitive = positionSensitive;- }-- public List getPositionSpans() {- return positionSpans;- }-}---// Utility class to store a Span-class PositionSpan {- int start;- int end;-- public PositionSpan(int start, int end) {- this.start = start;- this.end = end;- }-}+package org.apache.lucene.search.highlight;+++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import java.util.ArrayList;+import java.util.Iterator;+import java.util.List;+++/**+ * Lightweight class to hold term, weight, and positions used for scoring this+ * term.+ */+public class WeightedSpanTerm extends WeightedTerm{+ boolean positionSensitive;+ private List positionSpans = new ArrayList();++ /**+ * @param weight+ * @param term+ */+ public WeightedSpanTerm(float weight, String term) {+ super(weight, term);+ this.positionSpans = new ArrayList();+ }++ /**+ * @param weight+ * @param term+ * @param positionSensitive+ */+ public WeightedSpanTerm(float weight, String term, boolean positionSensitive) {+ super(weight, term);+ this.positionSensitive = positionSensitive;+ }++ /**+ * Checks to see if this term is valid at <code>position</code>.+ *+ * @param position+ * to check against valid term postions+ * @return true iff this term is a hit at this position+ */+ public boolean checkPosition(int position) {+ // There would probably be a slight speed improvement if PositionSpans+ // where kept in some sort of priority queue - that way this method+ // could+ // bail early without checking each PositionSpan.+ Iterator positionSpanIt = positionSpans.iterator();++ while (positionSpanIt.hasNext()) {+ PositionSpan posSpan = (PositionSpan) positionSpanIt.next();++ if (((position >= posSpan.start) && (position <= posSpan.end))) {+ return true;+ }+ }++ return false;+ }++ public void addPositionSpans(List positionSpans) {+ this.positionSpans.addAll(positionSpans);+ }++ public boolean isPositionSensitive() {+ return positionSensitive;+ }++ public void setPositionSensitive(boolean positionSensitive) {+ this.positionSensitive = positionSensitive;+ }++ public List getPositionSpans() {+ return positionSpans;+ }+}+++// Utility class to store a Span+class PositionSpan {+ int start;+ int end;++ public PositionSpan(int start, int end) {+ this.start = start;+ this.end = end;+ }+}diff --git a/contrib/queries/src/java/org/apache/lucene/search/BooleanFilter.java b/contrib/queries/src/java/org/apache/lucene/search/BooleanFilter.javaindex 8b5e2ef64d2..552d1b2a539 100644--- a/contrib/queries/src/java/org/apache/lucene/search/BooleanFilter.java+++ b/contrib/queries/src/java/org/apache/lucene/search/BooleanFilter.java@@ -1,206 +1,206 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.util.ArrayList;-import java.util.BitSet;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.util.DocIdBitSet;-import org.apache.lucene.util.OpenBitSet;-import org.apache.lucene.util.OpenBitSetDISI;-import org.apache.lucene.util.SortedVIntList;--/**- * A container Filter that allows Boolean composition of Filters.- * Filters are allocated into one of three logical constructs;- * SHOULD, MUST NOT, MUST- * The results Filter BitSet is constructed as follows:- * SHOULD Filters are OR'd together- * The resulting Filter is NOT'd with the NOT Filters- * The resulting Filter is AND'd with the MUST Filters- */--public class BooleanFilter extends Filter-{- ArrayList shouldFilters = null;- ArrayList notFilters = null;- ArrayList mustFilters = null;-- private DocIdSetIterator getDISI(ArrayList filters, int index, IndexReader reader)- throws IOException- {- return ((Filter)filters.get(index)).getDocIdSet(reader).iterator();- }-- /**- * Returns the a DocIdSetIterator representing the Boolean composition- * of the filters that have been added.- */- public DocIdSet getDocIdSet(IndexReader reader) throws IOException- {- OpenBitSetDISI res = null;-- if (shouldFilters != null) {- for (int i = 0; i < shouldFilters.size(); i++) {- if (res == null) {- res = new OpenBitSetDISI(getDISI(shouldFilters, i, reader), reader.maxDoc());- } else {- DocIdSet dis = ((Filter)shouldFilters.get(i)).getDocIdSet(reader);- if(dis instanceof OpenBitSet) {- // optimized case for OpenBitSets- res.or((OpenBitSet) dis);- } else {- res.inPlaceOr(getDISI(shouldFilters, i, reader));- }- }- }- }-- if (notFilters!=null) {- for (int i = 0; i < notFilters.size(); i++) {- if (res == null) {- res = new OpenBitSetDISI(getDISI(notFilters, i, reader), reader.maxDoc());- res.flip(0, reader.maxDoc()); // NOTE: may set bits on deleted docs- } else {- DocIdSet dis = ((Filter)notFilters.get(i)).getDocIdSet(reader);- if(dis instanceof OpenBitSet) {- // optimized case for OpenBitSets- res.andNot((OpenBitSet) dis);- } else {- res.inPlaceNot(getDISI(notFilters, i, reader));- }- }- }- }-- if (mustFilters!=null) {- for (int i = 0; i < mustFilters.size(); i++) {- if (res == null) {- res = new OpenBitSetDISI(getDISI(mustFilters, i, reader), reader.maxDoc());- } else {- DocIdSet dis = ((Filter)mustFilters.get(i)).getDocIdSet(reader);- if(dis instanceof OpenBitSet) {- // optimized case for OpenBitSets- res.and((OpenBitSet) dis);- } else {- res.inPlaceAnd(getDISI(mustFilters, i, reader));- }- }- }- }-- if (res !=null)- return finalResult(res, reader.maxDoc());-- if (emptyDocIdSet == null)- emptyDocIdSet = new OpenBitSetDISI(1);-- return emptyDocIdSet;- }-- /** Provide a SortedVIntList when it is definitely smaller than an OpenBitSet */- protected DocIdSet finalResult(OpenBitSetDISI result, int maxDocs) {- return (result.cardinality() < (maxDocs / 9))- ? (DocIdSet) new SortedVIntList(result)- : (DocIdSet) result;- }-- private static DocIdSet emptyDocIdSet = null;-- /**- * Adds a new FilterClause to the Boolean Filter container- * @param filterClause A FilterClause object containing a Filter and an Occur parameter- */-- public void add(FilterClause filterClause)- {- if (filterClause.getOccur().equals(Occur.MUST)) {- if (mustFilters==null) {- mustFilters=new ArrayList();- }- mustFilters.add(filterClause.getFilter());- }- if (filterClause.getOccur().equals(Occur.SHOULD)) {- if (shouldFilters==null) {- shouldFilters=new ArrayList();- }- shouldFilters.add(filterClause.getFilter());- }- if (filterClause.getOccur().equals(Occur.MUST_NOT)) {- if (notFilters==null) {- notFilters=new ArrayList();- }- notFilters.add(filterClause.getFilter());- }- }-- private boolean equalFilters(ArrayList filters1, ArrayList filters2)- {- return (filters1 == filters2) ||- ((filters1 != null) && filters1.equals(filters2));- }-- public boolean equals(Object obj)- {- if (this == obj)- return true;-- if ((obj == null) || (obj.getClass() != this.getClass()))- return false;-- BooleanFilter other = (BooleanFilter)obj;- return equalFilters(notFilters, other.notFilters)- && equalFilters(mustFilters, other.mustFilters)- && equalFilters(shouldFilters, other.shouldFilters);- }-- public int hashCode()- {- int hash=7;- hash = 31 * hash + (null == mustFilters ? 0 : mustFilters.hashCode());- hash = 31 * hash + (null == notFilters ? 0 : notFilters.hashCode());- hash = 31 * hash + (null == shouldFilters ? 0 : shouldFilters.hashCode());- return hash;- }-- /** Prints a user-readable version of this query. */- public String toString()- {- StringBuffer buffer = new StringBuffer();- buffer.append("BooleanFilter(");- appendFilters(shouldFilters, "", buffer);- appendFilters(mustFilters, "+", buffer);- appendFilters(notFilters, "-", buffer);- buffer.append(")");- return buffer.toString();- }-- private void appendFilters(ArrayList filters, String occurString, StringBuffer buffer)- {- if (filters != null) {- for (int i = 0; i < filters.size(); i++) {- buffer.append(' ');- buffer.append(occurString);- buffer.append(filters.get(i).toString());- }- }- }-}+package org.apache.lucene.search;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.ArrayList;+import java.util.BitSet;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.util.DocIdBitSet;+import org.apache.lucene.util.OpenBitSet;+import org.apache.lucene.util.OpenBitSetDISI;+import org.apache.lucene.util.SortedVIntList;++/**+ * A container Filter that allows Boolean composition of Filters.+ * Filters are allocated into one of three logical constructs;+ * SHOULD, MUST NOT, MUST+ * The results Filter BitSet is constructed as follows:+ * SHOULD Filters are OR'd together+ * The resulting Filter is NOT'd with the NOT Filters+ * The resulting Filter is AND'd with the MUST Filters+ */++public class BooleanFilter extends Filter+{+ ArrayList shouldFilters = null;+ ArrayList notFilters = null;+ ArrayList mustFilters = null;++ private DocIdSetIterator getDISI(ArrayList filters, int index, IndexReader reader)+ throws IOException+ {+ return ((Filter)filters.get(index)).getDocIdSet(reader).iterator();+ }++ /**+ * Returns the a DocIdSetIterator representing the Boolean composition+ * of the filters that have been added.+ */+ public DocIdSet getDocIdSet(IndexReader reader) throws IOException+ {+ OpenBitSetDISI res = null;++ if (shouldFilters != null) {+ for (int i = 0; i < shouldFilters.size(); i++) {+ if (res == null) {+ res = new OpenBitSetDISI(getDISI(shouldFilters, i, reader), reader.maxDoc());+ } else {+ DocIdSet dis = ((Filter)shouldFilters.get(i)).getDocIdSet(reader);+ if(dis instanceof OpenBitSet) {+ // optimized case for OpenBitSets+ res.or((OpenBitSet) dis);+ } else {+ res.inPlaceOr(getDISI(shouldFilters, i, reader));+ }+ }+ }+ }++ if (notFilters!=null) {+ for (int i = 0; i < notFilters.size(); i++) {+ if (res == null) {+ res = new OpenBitSetDISI(getDISI(notFilters, i, reader), reader.maxDoc());+ res.flip(0, reader.maxDoc()); // NOTE: may set bits on deleted docs+ } else {+ DocIdSet dis = ((Filter)notFilters.get(i)).getDocIdSet(reader);+ if(dis instanceof OpenBitSet) {+ // optimized case for OpenBitSets+ res.andNot((OpenBitSet) dis);+ } else {+ res.inPlaceNot(getDISI(notFilters, i, reader));+ }+ }+ }+ }++ if (mustFilters!=null) {+ for (int i = 0; i < mustFilters.size(); i++) {+ if (res == null) {+ res = new OpenBitSetDISI(getDISI(mustFilters, i, reader), reader.maxDoc());+ } else {+ DocIdSet dis = ((Filter)mustFilters.get(i)).getDocIdSet(reader);+ if(dis instanceof OpenBitSet) {+ // optimized case for OpenBitSets+ res.and((OpenBitSet) dis);+ } else {+ res.inPlaceAnd(getDISI(mustFilters, i, reader));+ }+ }+ }+ }++ if (res !=null)+ return finalResult(res, reader.maxDoc());++ if (emptyDocIdSet == null)+ emptyDocIdSet = new OpenBitSetDISI(1);++ return emptyDocIdSet;+ }++ /** Provide a SortedVIntList when it is definitely smaller than an OpenBitSet */+ protected DocIdSet finalResult(OpenBitSetDISI result, int maxDocs) {+ return (result.cardinality() < (maxDocs / 9))+ ? (DocIdSet) new SortedVIntList(result)+ : (DocIdSet) result;+ }++ private static DocIdSet emptyDocIdSet = null;++ /**+ * Adds a new FilterClause to the Boolean Filter container+ * @param filterClause A FilterClause object containing a Filter and an Occur parameter+ */++ public void add(FilterClause filterClause)+ {+ if (filterClause.getOccur().equals(Occur.MUST)) {+ if (mustFilters==null) {+ mustFilters=new ArrayList();+ }+ mustFilters.add(filterClause.getFilter());+ }+ if (filterClause.getOccur().equals(Occur.SHOULD)) {+ if (shouldFilters==null) {+ shouldFilters=new ArrayList();+ }+ shouldFilters.add(filterClause.getFilter());+ }+ if (filterClause.getOccur().equals(Occur.MUST_NOT)) {+ if (notFilters==null) {+ notFilters=new ArrayList();+ }+ notFilters.add(filterClause.getFilter());+ }+ }++ private boolean equalFilters(ArrayList filters1, ArrayList filters2)+ {+ return (filters1 == filters2) ||+ ((filters1 != null) && filters1.equals(filters2));+ }++ public boolean equals(Object obj)+ {+ if (this == obj)+ return true;++ if ((obj == null) || (obj.getClass() != this.getClass()))+ return false;++ BooleanFilter other = (BooleanFilter)obj;+ return equalFilters(notFilters, other.notFilters)+ && equalFilters(mustFilters, other.mustFilters)+ && equalFilters(shouldFilters, other.shouldFilters);+ }++ public int hashCode()+ {+ int hash=7;+ hash = 31 * hash + (null == mustFilters ? 0 : mustFilters.hashCode());+ hash = 31 * hash + (null == notFilters ? 0 : notFilters.hashCode());+ hash = 31 * hash + (null == shouldFilters ? 0 : shouldFilters.hashCode());+ return hash;+ }++ /** Prints a user-readable version of this query. */+ public String toString()+ {+ StringBuffer buffer = new StringBuffer();+ buffer.append("BooleanFilter(");+ appendFilters(shouldFilters, "", buffer);+ appendFilters(mustFilters, "+", buffer);+ appendFilters(notFilters, "-", buffer);+ buffer.append(")");+ return buffer.toString();+ }++ private void appendFilters(ArrayList filters, String occurString, StringBuffer buffer)+ {+ if (filters != null) {+ for (int i = 0; i < filters.size(); i++) {+ buffer.append(' ');+ buffer.append(occurString);+ buffer.append(filters.get(i).toString());+ }+ }+ }+}diff --git a/contrib/queries/src/java/org/apache/lucene/search/BoostingQuery.java b/contrib/queries/src/java/org/apache/lucene/search/BoostingQuery.javaindex 725f64b8cf7..deaac5152cc 100644--- a/contrib/queries/src/java/org/apache/lucene/search/BoostingQuery.java+++ b/contrib/queries/src/java/org/apache/lucene/search/BoostingQuery.java@@ -1,89 +1,89 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.DefaultSimilarity;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.Searcher;-import org.apache.lucene.search.Similarity;-/**- * The BoostingQuery class can be used to effectively demote results that match a given query.- * Unlike the "NOT" clause, this still selects documents that contain undesirable terms,- * but reduces their overall score:- *- * Query balancedQuery = new BoostingQuery(positiveQuery, negativeQuery, 0.01f);- * In this scenario the positiveQuery contains the mandatory, desirable criteria which is used to- * select all matching documents, and the negativeQuery contains the undesirable elements which- * are simply used to lessen the scores. Documents that match the negativeQuery have their score- * multiplied by the supplied "boost" parameter, so this should be less than 1 to achieve a- * demoting effect- *- * This code was originally made available here: [WWW] http://marc.theaimsgroup.com/?l=lucene-user&m=108058407130459&w=2- * and is documented here: http://wiki.apache.org/lucene-java/CommunityContributions- */-public class BoostingQuery extends Query {- private float boost; // the amount to boost by- private Query match; // query to match- private Query context; // boost when matches too-- public BoostingQuery(Query match, Query context, float boost) {- this.match = match;- this.context = (Query)context.clone(); // clone before boost- this.boost = boost;-- this.context.setBoost(0.0f); // ignore context-only matches- }-- public Query rewrite(IndexReader reader) throws IOException {- BooleanQuery result = new BooleanQuery() {-- public Similarity getSimilarity(Searcher searcher) {- return new DefaultSimilarity() {-- public float coord(int overlap, int max) {- switch (overlap) {-- case 1: // matched only one clause- return 1.0f; // use the score as-is-- case 2: // matched both clauses- return boost; // multiply by boost-- default:- return 0.0f;-- }- }- };- }- };-- result.add(match, BooleanClause.Occur.MUST);- result.add(context, BooleanClause.Occur.SHOULD);-- return result;- }-- public String toString(String field) {- return match.toString(field) + "/" + context.toString(field);- }- }+package org.apache.lucene.search;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.DefaultSimilarity;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.Searcher;+import org.apache.lucene.search.Similarity;+/**+ * The BoostingQuery class can be used to effectively demote results that match a given query.+ * Unlike the "NOT" clause, this still selects documents that contain undesirable terms,+ * but reduces their overall score:+ *+ * Query balancedQuery = new BoostingQuery(positiveQuery, negativeQuery, 0.01f);+ * In this scenario the positiveQuery contains the mandatory, desirable criteria which is used to+ * select all matching documents, and the negativeQuery contains the undesirable elements which+ * are simply used to lessen the scores. Documents that match the negativeQuery have their score+ * multiplied by the supplied "boost" parameter, so this should be less than 1 to achieve a+ * demoting effect+ *+ * This code was originally made available here: [WWW] http://marc.theaimsgroup.com/?l=lucene-user&m=108058407130459&w=2+ * and is documented here: http://wiki.apache.org/lucene-java/CommunityContributions+ */+public class BoostingQuery extends Query {+ private float boost; // the amount to boost by+ private Query match; // query to match+ private Query context; // boost when matches too++ public BoostingQuery(Query match, Query context, float boost) {+ this.match = match;+ this.context = (Query)context.clone(); // clone before boost+ this.boost = boost;++ this.context.setBoost(0.0f); // ignore context-only matches+ }++ public Query rewrite(IndexReader reader) throws IOException {+ BooleanQuery result = new BooleanQuery() {++ public Similarity getSimilarity(Searcher searcher) {+ return new DefaultSimilarity() {++ public float coord(int overlap, int max) {+ switch (overlap) {++ case 1: // matched only one clause+ return 1.0f; // use the score as-is++ case 2: // matched both clauses+ return boost; // multiply by boost++ default:+ return 0.0f;++ }+ }+ };+ }+ };++ result.add(match, BooleanClause.Occur.MUST);+ result.add(context, BooleanClause.Occur.SHOULD);++ return result;+ }++ public String toString(String field) {+ return match.toString(field) + "/" + context.toString(field);+ }+ }diff --git a/contrib/queries/src/java/org/apache/lucene/search/DuplicateFilter.java b/contrib/queries/src/java/org/apache/lucene/search/DuplicateFilter.javaindex 30fe7042222..4262f2cecd6 100644--- a/contrib/queries/src/java/org/apache/lucene/search/DuplicateFilter.java+++ b/contrib/queries/src/java/org/apache/lucene/search/DuplicateFilter.java@@ -1,248 +1,248 @@-package org.apache.lucene.search;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-import java.io.IOException;-import java.util.BitSet;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;-import org.apache.lucene.util.OpenBitSet;--public class DuplicateFilter extends Filter-{-- String fieldName;-- /**- * KeepMode determines which document id to consider as the master, all others being- * identified as duplicates. Selecting the "first occurrence" can potentially save on IO.- */- int keepMode=KM_USE_FIRST_OCCURRENCE;- public static final int KM_USE_FIRST_OCCURRENCE=1;- public static final int KM_USE_LAST_OCCURRENCE=2;-- /**- * "Full" processing mode starts by setting all bits to false and only setting bits- * for documents that contain the given field and are identified as none-duplicates.-- * "Fast" processing sets all bits to true then unsets all duplicate docs found for the- * given field. This approach avoids the need to read TermDocs for terms that are seen- * to have a document frequency of exactly "1" (i.e. no duplicates). While a potentially- * faster approach , the downside is that bitsets produced will include bits set for- * documents that do not actually contain the field given.- *- */- int processingMode=PM_FULL_VALIDATION;- public static final int PM_FULL_VALIDATION=1;- public static final int PM_FAST_INVALIDATION=2;---- public DuplicateFilter(String fieldName)- {- this(fieldName, KM_USE_LAST_OCCURRENCE,PM_FULL_VALIDATION);- }--- public DuplicateFilter(String fieldName, int keepMode, int processingMode)- {- this.fieldName = fieldName;- this.keepMode = keepMode;- this.processingMode = processingMode;- }-- public DocIdSet getDocIdSet(IndexReader reader) throws IOException- {- if(processingMode==PM_FAST_INVALIDATION)- {- return fastBits(reader);- }- else- {- return correctBits(reader);- }- }-- private OpenBitSet correctBits(IndexReader reader) throws IOException- {-- OpenBitSet bits=new OpenBitSet(reader.maxDoc()); //assume all are INvalid- Term startTerm=new Term(fieldName);- TermEnum te = reader.terms(startTerm);- if(te!=null)- {- Term currTerm=te.term();- while((currTerm!=null)&&(currTerm.field()==startTerm.field())) //term fieldnames are interned- {- int lastDoc=-1;- //set non duplicates- TermDocs td = reader.termDocs(currTerm);- if(td.next())- {- if(keepMode==KM_USE_FIRST_OCCURRENCE)- {- bits.set(td.doc());- }- else- {- do- {- lastDoc=td.doc();- }while(td.next());- bits.set(lastDoc);- }- }- if(!te.next())- {- break;- }- currTerm=te.term();- }- }- return bits;- }-- private OpenBitSet fastBits(IndexReader reader) throws IOException- {-- OpenBitSet bits=new OpenBitSet(reader.maxDoc());- bits.set(0,reader.maxDoc()); //assume all are valid- Term startTerm=new Term(fieldName);- TermEnum te = reader.terms(startTerm);- if(te!=null)- {- Term currTerm=te.term();-- while((currTerm!=null)&&(currTerm.field()==startTerm.field())) //term fieldnames are interned- {- if(te.docFreq()>1)- {- int lastDoc=-1;- //unset potential duplicates- TermDocs td = reader.termDocs(currTerm);- td.next();- if(keepMode==KM_USE_FIRST_OCCURRENCE)- {- td.next();- }- do- {- lastDoc=td.doc();- bits.clear(lastDoc);- }while(td.next());- if(keepMode==KM_USE_LAST_OCCURRENCE)- {- //restore the last bit- bits.set(lastDoc);- }- }- if(!te.next())- {- break;- }- currTerm=te.term();- }- }- return bits;- }-- /**- * @param args- * @throws IOException- * @throws Exception- */- public static void main(String[] args) throws Exception- {- IndexReader r=IndexReader.open("/indexes/personCentricAnon");-// IndexReader r=IndexReader.open("/indexes/enron");- long start=System.currentTimeMillis();-// DuplicateFilter df = new DuplicateFilter("threadId",KM_USE_FIRST_OCCURRENCE, PM_FAST_INVALIDATION);-// DuplicateFilter df = new DuplicateFilter("threadId",KM_USE_LAST_OCCURRENCE, PM_FAST_INVALIDATION);- DuplicateFilter df = new DuplicateFilter("vehicle.vrm",KM_USE_LAST_OCCURRENCE, PM_FAST_INVALIDATION);-// DuplicateFilter df = new DuplicateFilter("title",USE_LAST_OCCURRENCE);-// df.setProcessingMode(PM_SLOW_VALIDATION);- BitSet b = df.bits(r);- long end=System.currentTimeMillis()-start;- System.out.println(b.cardinality()+" in "+end+" ms ");-- }--- public String getFieldName()- {- return fieldName;- }--- public void setFieldName(String fieldName)- {- this.fieldName = fieldName;- }--- public int getKeepMode()- {- return keepMode;- }--- public void setKeepMode(int keepMode)- {- this.keepMode = keepMode;- }--- public boolean equals(Object obj)- {- if(this == obj)- return true;- if((obj == null) || (obj.getClass() != this.getClass()))- return false;- DuplicateFilter other = (DuplicateFilter)obj;- return keepMode == other.keepMode &&- processingMode == other.processingMode &&- (fieldName == other.fieldName || (fieldName != null && fieldName.equals(other.fieldName)));- }---- public int hashCode()- {- int hash = 217;- hash = 31 * hash + keepMode;- hash = 31 * hash + processingMode;- hash = 31 * hash + fieldName.hashCode();- return hash;- }--- public int getProcessingMode()- {- return processingMode;- }--- public void setProcessingMode(int processingMode)- {- this.processingMode = processingMode;- }----}+package org.apache.lucene.search;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import java.io.IOException;+import java.util.BitSet;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.index.TermEnum;+import org.apache.lucene.util.OpenBitSet;++public class DuplicateFilter extends Filter+{++ String fieldName;++ /**+ * KeepMode determines which document id to consider as the master, all others being+ * identified as duplicates. Selecting the "first occurrence" can potentially save on IO.+ */+ int keepMode=KM_USE_FIRST_OCCURRENCE;+ public static final int KM_USE_FIRST_OCCURRENCE=1;+ public static final int KM_USE_LAST_OCCURRENCE=2;++ /**+ * "Full" processing mode starts by setting all bits to false and only setting bits+ * for documents that contain the given field and are identified as none-duplicates.++ * "Fast" processing sets all bits to true then unsets all duplicate docs found for the+ * given field. This approach avoids the need to read TermDocs for terms that are seen+ * to have a document frequency of exactly "1" (i.e. no duplicates). While a potentially+ * faster approach , the downside is that bitsets produced will include bits set for+ * documents that do not actually contain the field given.+ *+ */+ int processingMode=PM_FULL_VALIDATION;+ public static final int PM_FULL_VALIDATION=1;+ public static final int PM_FAST_INVALIDATION=2;++++ public DuplicateFilter(String fieldName)+ {+ this(fieldName, KM_USE_LAST_OCCURRENCE,PM_FULL_VALIDATION);+ }+++ public DuplicateFilter(String fieldName, int keepMode, int processingMode)+ {+ this.fieldName = fieldName;+ this.keepMode = keepMode;+ this.processingMode = processingMode;+ }++ public DocIdSet getDocIdSet(IndexReader reader) throws IOException+ {+ if(processingMode==PM_FAST_INVALIDATION)+ {+ return fastBits(reader);+ }+ else+ {+ return correctBits(reader);+ }+ }++ private OpenBitSet correctBits(IndexReader reader) throws IOException+ {++ OpenBitSet bits=new OpenBitSet(reader.maxDoc()); //assume all are INvalid+ Term startTerm=new Term(fieldName);+ TermEnum te = reader.terms(startTerm);+ if(te!=null)+ {+ Term currTerm=te.term();+ while((currTerm!=null)&&(currTerm.field()==startTerm.field())) //term fieldnames are interned+ {+ int lastDoc=-1;+ //set non duplicates+ TermDocs td = reader.termDocs(currTerm);+ if(td.next())+ {+ if(keepMode==KM_USE_FIRST_OCCURRENCE)+ {+ bits.set(td.doc());+ }+ else+ {+ do+ {+ lastDoc=td.doc();+ }while(td.next());+ bits.set(lastDoc);+ }+ }+ if(!te.next())+ {+ break;+ }+ currTerm=te.term();+ }+ }+ return bits;+ }++ private OpenBitSet fastBits(IndexReader reader) throws IOException+ {++ OpenBitSet bits=new OpenBitSet(reader.maxDoc());+ bits.set(0,reader.maxDoc()); //assume all are valid+ Term startTerm=new Term(fieldName);+ TermEnum te = reader.terms(startTerm);+ if(te!=null)+ {+ Term currTerm=te.term();++ while((currTerm!=null)&&(currTerm.field()==startTerm.field())) //term fieldnames are interned+ {+ if(te.docFreq()>1)+ {+ int lastDoc=-1;+ //unset potential duplicates+ TermDocs td = reader.termDocs(currTerm);+ td.next();+ if(keepMode==KM_USE_FIRST_OCCURRENCE)+ {+ td.next();+ }+ do+ {+ lastDoc=td.doc();+ bits.clear(lastDoc);+ }while(td.next());+ if(keepMode==KM_USE_LAST_OCCURRENCE)+ {+ //restore the last bit+ bits.set(lastDoc);+ }+ }+ if(!te.next())+ {+ break;+ }+ currTerm=te.term();+ }+ }+ return bits;+ }++ /**+ * @param args+ * @throws IOException+ * @throws Exception+ */+ public static void main(String[] args) throws Exception+ {+ IndexReader r=IndexReader.open("/indexes/personCentricAnon");+// IndexReader r=IndexReader.open("/indexes/enron");+ long start=System.currentTimeMillis();+// DuplicateFilter df = new DuplicateFilter("threadId",KM_USE_FIRST_OCCURRENCE, PM_FAST_INVALIDATION);+// DuplicateFilter df = new DuplicateFilter("threadId",KM_USE_LAST_OCCURRENCE, PM_FAST_INVALIDATION);+ DuplicateFilter df = new DuplicateFilter("vehicle.vrm",KM_USE_LAST_OCCURRENCE, PM_FAST_INVALIDATION);+// DuplicateFilter df = new DuplicateFilter("title",USE_LAST_OCCURRENCE);+// df.setProcessingMode(PM_SLOW_VALIDATION);+ BitSet b = df.bits(r);+ long end=System.currentTimeMillis()-start;+ System.out.println(b.cardinality()+" in "+end+" ms ");++ }+++ public String getFieldName()+ {+ return fieldName;+ }+++ public void setFieldName(String fieldName)+ {+ this.fieldName = fieldName;+ }+++ public int getKeepMode()+ {+ return keepMode;+ }+++ public void setKeepMode(int keepMode)+ {+ this.keepMode = keepMode;+ }+++ public boolean equals(Object obj)+ {+ if(this == obj)+ return true;+ if((obj == null) || (obj.getClass() != this.getClass()))+ return false;+ DuplicateFilter other = (DuplicateFilter)obj;+ return keepMode == other.keepMode &&+ processingMode == other.processingMode &&+ (fieldName == other.fieldName || (fieldName != null && fieldName.equals(other.fieldName)));+ }++++ public int hashCode()+ {+ int hash = 217;+ hash = 31 * hash + keepMode;+ hash = 31 * hash + processingMode;+ hash = 31 * hash + fieldName.hashCode();+ return hash;+ }+++ public int getProcessingMode()+ {+ return processingMode;+ }+++ public void setProcessingMode(int processingMode)+ {+ this.processingMode = processingMode;+ }++++}diff --git a/contrib/queries/src/java/org/apache/lucene/search/FilterClause.java b/contrib/queries/src/java/org/apache/lucene/search/FilterClause.javaindex 8539aef3e12..d816066a31b 100644--- a/contrib/queries/src/java/org/apache/lucene/search/FilterClause.java+++ b/contrib/queries/src/java/org/apache/lucene/search/FilterClause.java@@ -1,66 +1,66 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.search.BooleanClause.Occur;--/**- * A Filter that wrapped with an indication of how that filter- * is used when composed with another filter.- * (Follows the boolean logic in BooleanClause for composition- * of queries.)- */--public class FilterClause implements java.io.Serializable-{- Occur occur = null;- Filter filter = null;-- /**- * Create a new FilterClause- * @param filter A Filter object containing a BitSet- * @param occur A parameter implementation indicating SHOULD, MUST or MUST NOT- */-- public FilterClause( Filter filter,Occur occur)- {- this.occur = occur;- this.filter = filter;- }-- /**- * Returns this FilterClause's filter- * @return A Filter object- */-- public Filter getFilter()- {- return filter;- }-- /**- * Returns this FilterClause's occur parameter- * @return An Occur object- */-- public Occur getOccur()- {- return occur;- }--}+package org.apache.lucene.search;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.search.BooleanClause.Occur;++/**+ * A Filter that wrapped with an indication of how that filter+ * is used when composed with another filter.+ * (Follows the boolean logic in BooleanClause for composition+ * of queries.)+ */++public class FilterClause implements java.io.Serializable+{+ Occur occur = null;+ Filter filter = null;++ /**+ * Create a new FilterClause+ * @param filter A Filter object containing a BitSet+ * @param occur A parameter implementation indicating SHOULD, MUST or MUST NOT+ */++ public FilterClause( Filter filter,Occur occur)+ {+ this.occur = occur;+ this.filter = filter;+ }++ /**+ * Returns this FilterClause's filter+ * @return A Filter object+ */++ public Filter getFilter()+ {+ return filter;+ }++ /**+ * Returns this FilterClause's occur parameter+ * @return An Occur object+ */++ public Occur getOccur()+ {+ return occur;+ }++}diff --git a/contrib/queries/src/java/org/apache/lucene/search/FuzzyLikeThisQuery.java b/contrib/queries/src/java/org/apache/lucene/search/FuzzyLikeThisQuery.javaindex a5b8440522a..6e7840dd3ec 100644--- a/contrib/queries/src/java/org/apache/lucene/search/FuzzyLikeThisQuery.java+++ b/contrib/queries/src/java/org/apache/lucene/search/FuzzyLikeThisQuery.java@@ -1,322 +1,322 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.io.StringReader;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.HashSet;-import java.util.Iterator;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermEnum;-import org.apache.lucene.util.PriorityQueue;--/**- * Fuzzifies ALL terms provided as strings and then picks the best n differentiating terms.- * In effect this mixes the behaviour of FuzzyQuery and MoreLikeThis but with special consideration- * of fuzzy scoring factors.- * This generally produces good results for queries where users may provide details in a number of- * fields and have no knowledge of boolean query syntax and also want a degree of fuzzy matching and- * a fast query.- *- * For each source term the fuzzy variants are held in a BooleanQuery with no coord factor (because- * we are not looking for matches on multiple variants in any one doc). Additionally, a specialized- * TermQuery is used for variants and does not use that variant term's IDF because this would favour rarer- * terms eg misspellings. Instead, all variants use the same IDF ranking (the one for the source query- * term) and this is factored into the variant's boost. If the source query term does not exist in the- * index the average IDF of the variants is used.- */-public class FuzzyLikeThisQuery extends Query-{- static Similarity sim=new DefaultSimilarity();- Query rewrittenQuery=null;- ArrayList fieldVals=new ArrayList();- Analyzer analyzer;-- ScoreTermQueue q;- int MAX_VARIANTS_PER_TERM=50;- boolean ignoreTF=false;--- /**- *- * @param maxNumTerms The total number of terms clauses that will appear once rewritten as a BooleanQuery- * @param analyzer- */- public FuzzyLikeThisQuery(int maxNumTerms, Analyzer analyzer)- {- q=new ScoreTermQueue(maxNumTerms);- this.analyzer=analyzer;- }-- class FieldVals- {- String queryString;- String fieldName;- float minSimilarity;- int prefixLength;- public FieldVals(String name, float similarity, int length, String queryString)- {- fieldName = name;- minSimilarity = similarity;- prefixLength = length;- this.queryString = queryString;- }-- }-- /**- * Adds user input for "fuzzification"- * @param queryString The string which will be parsed by the analyzer and for which fuzzy variants will be parsed- * @param fieldName- * @param minSimilarity The minimum similarity of the term variants (see FuzzyTermEnum)- * @param prefixLength Length of required common prefix on variant terms (see FuzzyTermEnum)- */- public void addTerms(String queryString, String fieldName,float minSimilarity, int prefixLength)- {- fieldVals.add(new FieldVals(fieldName,minSimilarity,prefixLength,queryString));- }--- private void addTerms(IndexReader reader,FieldVals f) throws IOException- {- if(f.queryString==null) return;- TokenStream ts=analyzer.tokenStream(f.fieldName,new StringReader(f.queryString));- final Token reusableToken = new Token();- int corpusNumDocs=reader.numDocs();- Term internSavingTemplateTerm =new Term(f.fieldName); //optimization to avoid constructing new Term() objects- HashSet processedTerms=new HashSet();- for (Token nextToken = ts.next(reusableToken); nextToken!=null; nextToken = ts.next(reusableToken))- {- String term = nextToken.term();- if(!processedTerms.contains(term))- {- processedTerms.add(term);- ScoreTermQueue variantsQ=new ScoreTermQueue(MAX_VARIANTS_PER_TERM); //maxNum variants considered for any one term- float minScore=0;- Term startTerm=internSavingTemplateTerm.createTerm(term);- FuzzyTermEnum fe=new FuzzyTermEnum(reader,startTerm,f.minSimilarity,f.prefixLength);- TermEnum origEnum = reader.terms(startTerm);- int df=0;- if(startTerm.equals(origEnum.term()))- {- df=origEnum.docFreq(); //store the df so all variants use same idf- }- int numVariants=0;- int totalVariantDocFreqs=0;- do- {- Term possibleMatch=fe.term();- if(possibleMatch!=null)- {- numVariants++;- totalVariantDocFreqs+=fe.docFreq();- float score=fe.difference();- if(variantsQ.size() < MAX_VARIANTS_PER_TERM || score > minScore){- ScoreTerm st=new ScoreTerm(possibleMatch,score,startTerm);- variantsQ.insert(st);- minScore = ((ScoreTerm)variantsQ.top()).score; // maintain minScore- }- }- }- while(fe.next());- if(numVariants>0)- {- int avgDf=totalVariantDocFreqs/numVariants;- if(df==0)//no direct match we can use as df for all variants- {- df=avgDf; //use avg df of all variants- }-- // take the top variants (scored by edit distance) and reset the score- // to include an IDF factor then add to the global queue for ranking- // overall top query terms- int size = variantsQ.size();- for(int i = 0; i < size; i++)- {- ScoreTerm st = (ScoreTerm) variantsQ.pop();- st.score=(st.score*st.score)*sim.idf(df,corpusNumDocs);- q.insert(st);- }- }- }- }- }-- public Query rewrite(IndexReader reader) throws IOException- {- if(rewrittenQuery!=null)- {- return rewrittenQuery;- }- //load up the list of possible terms- for (Iterator iter = fieldVals.iterator(); iter.hasNext();)- {- FieldVals f = (FieldVals) iter.next();- addTerms(reader,f);- }- //clear the list of fields- fieldVals.clear();-- BooleanQuery bq=new BooleanQuery();--- //create BooleanQueries to hold the variants for each token/field pair and ensure it- // has no coord factor- //Step 1: sort the termqueries by term/field- HashMap variantQueries=new HashMap();- int size = q.size();- for(int i = 0; i < size; i++)- {- ScoreTerm st = (ScoreTerm) q.pop();- ArrayList l=(ArrayList) variantQueries.get(st.fuzziedSourceTerm);- if(l==null)- {- l=new ArrayList();- variantQueries.put(st.fuzziedSourceTerm,l);- }- l.add(st);- }- //Step 2: Organize the sorted termqueries into zero-coord scoring boolean queries- for (Iterator iter = variantQueries.values().iterator(); iter.hasNext();)- {- ArrayList variants = (ArrayList) iter.next();- if(variants.size()==1)- {- //optimize where only one selected variant- ScoreTerm st=(ScoreTerm) variants.get(0);- TermQuery tq = new FuzzyTermQuery(st.term,ignoreTF);- tq.setBoost(st.score); // set the boost to a mix of IDF and score- bq.add(tq, BooleanClause.Occur.SHOULD);- }- else- {- BooleanQuery termVariants=new BooleanQuery(true); //disable coord and IDF for these term variants- for (Iterator iterator2 = variants.iterator(); iterator2- .hasNext();)- {- ScoreTerm st = (ScoreTerm) iterator2.next();- TermQuery tq = new FuzzyTermQuery(st.term,ignoreTF); // found a match- tq.setBoost(st.score); // set the boost using the ScoreTerm's score- termVariants.add(tq, BooleanClause.Occur.SHOULD); // add to query- }- bq.add(termVariants, BooleanClause.Occur.SHOULD); // add to query- }- }- //TODO possible alternative step 3 - organize above booleans into a new layer of field-based- // booleans with a minimum-should-match of NumFields-1?- bq.setBoost(getBoost());- this.rewrittenQuery=bq;- return bq;- }-- //Holds info for a fuzzy term variant - initially score is set to edit distance (for ranking best- // term variants) then is reset with IDF for use in ranking against all other- // terms/fields- private static class ScoreTerm{- public Term term;- public float score;- Term fuzziedSourceTerm;-- public ScoreTerm(Term term, float score, Term fuzziedSourceTerm){- this.term = term;- this.score = score;- this.fuzziedSourceTerm=fuzziedSourceTerm;- }- }-- private static class ScoreTermQueue extends PriorityQueue {- public ScoreTermQueue(int size){- initialize(size);- }-- /* (non-Javadoc)- * @see org.apache.lucene.util.PriorityQueue#lessThan(java.lang.Object, java.lang.Object)- */- protected boolean lessThan(Object a, Object b) {- ScoreTerm termA = (ScoreTerm)a;- ScoreTerm termB = (ScoreTerm)b;- if (termA.score== termB.score)- return termA.term.compareTo(termB.term) > 0;- else- return termA.score < termB.score;- }-- }-- //overrides basic TermQuery to negate effects of IDF (idf is factored into boost of containing BooleanQuery)- private static class FuzzyTermQuery extends TermQuery- {- boolean ignoreTF;- public FuzzyTermQuery(Term t, boolean ignoreTF)- {- super(t);- this.ignoreTF=ignoreTF;- }- public Similarity getSimilarity(Searcher searcher)- {- Similarity result = super.getSimilarity(searcher);- result = new SimilarityDelegator(result) {-- public float tf(float freq)- {- if(ignoreTF)- {- return 1; //ignore tf- }- return super.tf(freq);- }- public float idf(int docFreq, int numDocs)- {- //IDF is already factored into individual term boosts- return 1;- }- };- return result;- }- }---- /* (non-Javadoc)- * @see org.apache.lucene.search.Query#toString(java.lang.String)- */- public String toString(String field)- {- return null;- }--- public boolean isIgnoreTF()- {- return ignoreTF;- }--- public void setIgnoreTF(boolean ignoreTF)- {- this.ignoreTF = ignoreTF;- }--}+package org.apache.lucene.search;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.io.StringReader;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Iterator;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermEnum;+import org.apache.lucene.util.PriorityQueue;++/**+ * Fuzzifies ALL terms provided as strings and then picks the best n differentiating terms.+ * In effect this mixes the behaviour of FuzzyQuery and MoreLikeThis but with special consideration+ * of fuzzy scoring factors.+ * This generally produces good results for queries where users may provide details in a number of+ * fields and have no knowledge of boolean query syntax and also want a degree of fuzzy matching and+ * a fast query.+ *+ * For each source term the fuzzy variants are held in a BooleanQuery with no coord factor (because+ * we are not looking for matches on multiple variants in any one doc). Additionally, a specialized+ * TermQuery is used for variants and does not use that variant term's IDF because this would favour rarer+ * terms eg misspellings. Instead, all variants use the same IDF ranking (the one for the source query+ * term) and this is factored into the variant's boost. If the source query term does not exist in the+ * index the average IDF of the variants is used.+ */+public class FuzzyLikeThisQuery extends Query+{+ static Similarity sim=new DefaultSimilarity();+ Query rewrittenQuery=null;+ ArrayList fieldVals=new ArrayList();+ Analyzer analyzer;++ ScoreTermQueue q;+ int MAX_VARIANTS_PER_TERM=50;+ boolean ignoreTF=false;+++ /**+ *+ * @param maxNumTerms The total number of terms clauses that will appear once rewritten as a BooleanQuery+ * @param analyzer+ */+ public FuzzyLikeThisQuery(int maxNumTerms, Analyzer analyzer)+ {+ q=new ScoreTermQueue(maxNumTerms);+ this.analyzer=analyzer;+ }++ class FieldVals+ {+ String queryString;+ String fieldName;+ float minSimilarity;+ int prefixLength;+ public FieldVals(String name, float similarity, int length, String queryString)+ {+ fieldName = name;+ minSimilarity = similarity;+ prefixLength = length;+ this.queryString = queryString;+ }++ }++ /**+ * Adds user input for "fuzzification"+ * @param queryString The string which will be parsed by the analyzer and for which fuzzy variants will be parsed+ * @param fieldName+ * @param minSimilarity The minimum similarity of the term variants (see FuzzyTermEnum)+ * @param prefixLength Length of required common prefix on variant terms (see FuzzyTermEnum)+ */+ public void addTerms(String queryString, String fieldName,float minSimilarity, int prefixLength)+ {+ fieldVals.add(new FieldVals(fieldName,minSimilarity,prefixLength,queryString));+ }+++ private void addTerms(IndexReader reader,FieldVals f) throws IOException+ {+ if(f.queryString==null) return;+ TokenStream ts=analyzer.tokenStream(f.fieldName,new StringReader(f.queryString));+ final Token reusableToken = new Token();+ int corpusNumDocs=reader.numDocs();+ Term internSavingTemplateTerm =new Term(f.fieldName); //optimization to avoid constructing new Term() objects+ HashSet processedTerms=new HashSet();+ for (Token nextToken = ts.next(reusableToken); nextToken!=null; nextToken = ts.next(reusableToken))+ {+ String term = nextToken.term();+ if(!processedTerms.contains(term))+ {+ processedTerms.add(term);+ ScoreTermQueue variantsQ=new ScoreTermQueue(MAX_VARIANTS_PER_TERM); //maxNum variants considered for any one term+ float minScore=0;+ Term startTerm=internSavingTemplateTerm.createTerm(term);+ FuzzyTermEnum fe=new FuzzyTermEnum(reader,startTerm,f.minSimilarity,f.prefixLength);+ TermEnum origEnum = reader.terms(startTerm);+ int df=0;+ if(startTerm.equals(origEnum.term()))+ {+ df=origEnum.docFreq(); //store the df so all variants use same idf+ }+ int numVariants=0;+ int totalVariantDocFreqs=0;+ do+ {+ Term possibleMatch=fe.term();+ if(possibleMatch!=null)+ {+ numVariants++;+ totalVariantDocFreqs+=fe.docFreq();+ float score=fe.difference();+ if(variantsQ.size() < MAX_VARIANTS_PER_TERM || score > minScore){+ ScoreTerm st=new ScoreTerm(possibleMatch,score,startTerm);+ variantsQ.insert(st);+ minScore = ((ScoreTerm)variantsQ.top()).score; // maintain minScore+ }+ }+ }+ while(fe.next());+ if(numVariants>0)+ {+ int avgDf=totalVariantDocFreqs/numVariants;+ if(df==0)//no direct match we can use as df for all variants+ {+ df=avgDf; //use avg df of all variants+ }++ // take the top variants (scored by edit distance) and reset the score+ // to include an IDF factor then add to the global queue for ranking+ // overall top query terms+ int size = variantsQ.size();+ for(int i = 0; i < size; i++)+ {+ ScoreTerm st = (ScoreTerm) variantsQ.pop();+ st.score=(st.score*st.score)*sim.idf(df,corpusNumDocs);+ q.insert(st);+ }+ }+ }+ }+ }++ public Query rewrite(IndexReader reader) throws IOException+ {+ if(rewrittenQuery!=null)+ {+ return rewrittenQuery;+ }+ //load up the list of possible terms+ for (Iterator iter = fieldVals.iterator(); iter.hasNext();)+ {+ FieldVals f = (FieldVals) iter.next();+ addTerms(reader,f);+ }+ //clear the list of fields+ fieldVals.clear();++ BooleanQuery bq=new BooleanQuery();+++ //create BooleanQueries to hold the variants for each token/field pair and ensure it+ // has no coord factor+ //Step 1: sort the termqueries by term/field+ HashMap variantQueries=new HashMap();+ int size = q.size();+ for(int i = 0; i < size; i++)+ {+ ScoreTerm st = (ScoreTerm) q.pop();+ ArrayList l=(ArrayList) variantQueries.get(st.fuzziedSourceTerm);+ if(l==null)+ {+ l=new ArrayList();+ variantQueries.put(st.fuzziedSourceTerm,l);+ }+ l.add(st);+ }+ //Step 2: Organize the sorted termqueries into zero-coord scoring boolean queries+ for (Iterator iter = variantQueries.values().iterator(); iter.hasNext();)+ {+ ArrayList variants = (ArrayList) iter.next();+ if(variants.size()==1)+ {+ //optimize where only one selected variant+ ScoreTerm st=(ScoreTerm) variants.get(0);+ TermQuery tq = new FuzzyTermQuery(st.term,ignoreTF);+ tq.setBoost(st.score); // set the boost to a mix of IDF and score+ bq.add(tq, BooleanClause.Occur.SHOULD);+ }+ else+ {+ BooleanQuery termVariants=new BooleanQuery(true); //disable coord and IDF for these term variants+ for (Iterator iterator2 = variants.iterator(); iterator2+ .hasNext();)+ {+ ScoreTerm st = (ScoreTerm) iterator2.next();+ TermQuery tq = new FuzzyTermQuery(st.term,ignoreTF); // found a match+ tq.setBoost(st.score); // set the boost using the ScoreTerm's score+ termVariants.add(tq, BooleanClause.Occur.SHOULD); // add to query+ }+ bq.add(termVariants, BooleanClause.Occur.SHOULD); // add to query+ }+ }+ //TODO possible alternative step 3 - organize above booleans into a new layer of field-based+ // booleans with a minimum-should-match of NumFields-1?+ bq.setBoost(getBoost());+ this.rewrittenQuery=bq;+ return bq;+ }++ //Holds info for a fuzzy term variant - initially score is set to edit distance (for ranking best+ // term variants) then is reset with IDF for use in ranking against all other+ // terms/fields+ private static class ScoreTerm{+ public Term term;+ public float score;+ Term fuzziedSourceTerm;++ public ScoreTerm(Term term, float score, Term fuzziedSourceTerm){+ this.term = term;+ this.score = score;+ this.fuzziedSourceTerm=fuzziedSourceTerm;+ }+ }++ private static class ScoreTermQueue extends PriorityQueue {+ public ScoreTermQueue(int size){+ initialize(size);+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.util.PriorityQueue#lessThan(java.lang.Object, java.lang.Object)+ */+ protected boolean lessThan(Object a, Object b) {+ ScoreTerm termA = (ScoreTerm)a;+ ScoreTerm termB = (ScoreTerm)b;+ if (termA.score== termB.score)+ return termA.term.compareTo(termB.term) > 0;+ else+ return termA.score < termB.score;+ }++ }++ //overrides basic TermQuery to negate effects of IDF (idf is factored into boost of containing BooleanQuery)+ private static class FuzzyTermQuery extends TermQuery+ {+ boolean ignoreTF;+ public FuzzyTermQuery(Term t, boolean ignoreTF)+ {+ super(t);+ this.ignoreTF=ignoreTF;+ }+ public Similarity getSimilarity(Searcher searcher)+ {+ Similarity result = super.getSimilarity(searcher);+ result = new SimilarityDelegator(result) {++ public float tf(float freq)+ {+ if(ignoreTF)+ {+ return 1; //ignore tf+ }+ return super.tf(freq);+ }+ public float idf(int docFreq, int numDocs)+ {+ //IDF is already factored into individual term boosts+ return 1;+ }+ };+ return result;+ }+ }++++ /* (non-Javadoc)+ * @see org.apache.lucene.search.Query#toString(java.lang.String)+ */+ public String toString(String field)+ {+ return null;+ }+++ public boolean isIgnoreTF()+ {+ return ignoreTF;+ }+++ public void setIgnoreTF(boolean ignoreTF)+ {+ this.ignoreTF = ignoreTF;+ }++}diff --git a/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.java b/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.javaindex 1ecb4a716cb..9a6d68c8b9e 100644--- a/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.java+++ b/contrib/queries/src/java/org/apache/lucene/search/TermsFilter.java@@ -1,130 +1,130 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.util.BitSet;-import java.util.Iterator;-import java.util.Set;-import java.util.TreeSet;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.util.OpenBitSet;--/**- * Constructs a filter for docs matching any of the terms added to this class.- * Unlike a RangeFilter this can be used for filtering on multiple terms that are not necessarily in- * a sequence. An example might be a collection of primary keys from a database query result or perhaps- * a choice of "category" labels picked by the end user. As a filter, this is much faster than the- * equivalent query (a BooleanQuery with many "should" TermQueries)- *- */-public class TermsFilter extends Filter-{- Set terms=new TreeSet();-- /**- * Adds a term to the list of acceptable terms- * @param term- */- public void addTerm(Term term)- {- terms.add(term);- }---- /* (non-Javadoc)- * @see org.apache.lucene.search.Filter#bits(org.apache.lucene.index.IndexReader)- */- public BitSet bits(IndexReader reader) throws IOException- {- BitSet result=new BitSet(reader.maxDoc());- TermDocs td = reader.termDocs();- try- {- for (Iterator iter = terms.iterator(); iter.hasNext();)- {- Term term = (Term) iter.next();- td.seek(term);- while (td.next())- {- result.set(td.doc());- }- }- }- finally- {- td.close();- }- return result;- }----/* (non-Javadoc)- * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.IndexReader)- */- public DocIdSet getDocIdSet(IndexReader reader) throws IOException- {- OpenBitSet result=new OpenBitSet(reader.maxDoc());- TermDocs td = reader.termDocs();- try- {- for (Iterator iter = terms.iterator(); iter.hasNext();)- {- Term term = (Term) iter.next();- td.seek(term);- while (td.next())- {- result.set(td.doc());- }- }- }- finally- {- td.close();- }- return result;- }-- public boolean equals(Object obj)- {- if(this == obj)- return true;- if((obj == null) || (obj.getClass() != this.getClass()))- return false;- TermsFilter test = (TermsFilter)obj;- return (terms == test.terms ||- (terms != null && terms.equals(test.terms)));- }-- public int hashCode()- {- int hash=9;- for (Iterator iter = terms.iterator(); iter.hasNext();)- {- Term term = (Term) iter.next();- hash = 31 * hash + term.hashCode();- }- return hash;- }--}+package org.apache.lucene.search;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.BitSet;+import java.util.Iterator;+import java.util.Set;+import java.util.TreeSet;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.util.OpenBitSet;++/**+ * Constructs a filter for docs matching any of the terms added to this class.+ * Unlike a RangeFilter this can be used for filtering on multiple terms that are not necessarily in+ * a sequence. An example might be a collection of primary keys from a database query result or perhaps+ * a choice of "category" labels picked by the end user. As a filter, this is much faster than the+ * equivalent query (a BooleanQuery with many "should" TermQueries)+ *+ */+public class TermsFilter extends Filter+{+ Set terms=new TreeSet();++ /**+ * Adds a term to the list of acceptable terms+ * @param term+ */+ public void addTerm(Term term)+ {+ terms.add(term);+ }++++ /* (non-Javadoc)+ * @see org.apache.lucene.search.Filter#bits(org.apache.lucene.index.IndexReader)+ */+ public BitSet bits(IndexReader reader) throws IOException+ {+ BitSet result=new BitSet(reader.maxDoc());+ TermDocs td = reader.termDocs();+ try+ {+ for (Iterator iter = terms.iterator(); iter.hasNext();)+ {+ Term term = (Term) iter.next();+ td.seek(term);+ while (td.next())+ {+ result.set(td.doc());+ }+ }+ }+ finally+ {+ td.close();+ }+ return result;+ }++++/* (non-Javadoc)+ * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.IndexReader)+ */+ public DocIdSet getDocIdSet(IndexReader reader) throws IOException+ {+ OpenBitSet result=new OpenBitSet(reader.maxDoc());+ TermDocs td = reader.termDocs();+ try+ {+ for (Iterator iter = terms.iterator(); iter.hasNext();)+ {+ Term term = (Term) iter.next();+ td.seek(term);+ while (td.next())+ {+ result.set(td.doc());+ }+ }+ }+ finally+ {+ td.close();+ }+ return result;+ }++ public boolean equals(Object obj)+ {+ if(this == obj)+ return true;+ if((obj == null) || (obj.getClass() != this.getClass()))+ return false;+ TermsFilter test = (TermsFilter)obj;+ return (terms == test.terms ||+ (terms != null && terms.equals(test.terms)));+ }++ public int hashCode()+ {+ int hash=9;+ for (Iterator iter = terms.iterator(); iter.hasNext();)+ {+ Term term = (Term) iter.next();+ hash = 31 * hash + term.hashCode();+ }+ return hash;+ }++}diff --git a/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThis.java b/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThis.javaindex 2e7a57df5ea..fbc100cfbfc 100644--- a/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThis.java+++ b/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThis.java@@ -1,956 +1,956 @@-/**- * Copyright 2004-2005 The Apache Software Foundation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.lucene.search.similar;--import org.apache.lucene.util.PriorityQueue;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermFreqVector;-import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.DefaultSimilarity;-import org.apache.lucene.search.Similarity;-import org.apache.lucene.search.TermQuery;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.Hits;-import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.analysis.standard.StandardAnalyzer;-import org.apache.lucene.document.Document;--import java.util.Set;-import java.util.HashMap;-import java.util.Map;-import java.util.Collection;-import java.util.Iterator;-import java.io.IOException;-import java.io.Reader;-import java.io.File;-import java.io.PrintStream;-import java.io.StringReader;-import java.io.FileReader;-import java.io.InputStreamReader;-import java.net.URL;-import java.util.ArrayList;---/**- * Generate "more like this" similarity queries.- * Based on this mail:- * <code><pre>- * Lucene does let you access the document frequency of terms, with IndexReader.docFreq().- * Term frequencies can be computed by re-tokenizing the text, which, for a single document,- * is usually fast enough. But looking up the docFreq() of every term in the document is- * probably too slow.- *- * You can use some heuristics to prune the set of terms, to avoid calling docFreq() too much,- * or at all. Since you're trying to maximize a tf*idf score, you're probably most interested- * in terms with a high tf. Choosing a tf threshold even as low as two or three will radically- * reduce the number of terms under consideration. Another heuristic is that terms with a- * high idf (i.e., a low df) tend to be longer. So you could threshold the terms by the- * number of characters, not selecting anything less than, e.g., six or seven characters.- * With these sorts of heuristics you can usually find small set of, e.g., ten or fewer terms- * that do a pretty good job of characterizing a document.- *- * It all depends on what you're trying to do. If you're trying to eek out that last percent- * of precision and recall regardless of computational difficulty so that you can win a TREC- * competition, then the techniques I mention above are useless. But if you're trying to- * provide a "more like this" button on a search results page that does a decent job and has- * good performance, such techniques might be useful.- *- * An efficient, effective "more-like-this" query generator would be a great contribution, if- * anyone's interested. I'd imagine that it would take a Reader or a String (the document's- * text), analyzer Analyzer, and return a set of representative terms using heuristics like those- * above. The frequency and length thresholds could be parameters, etc.- *- * Doug- * </pre></code>- *- *- * <p>- * <h3>Initial Usage</h3>- *- * This class has lots of options to try to make it efficient and flexible.- * See the body of {@link #main main()} below in the source for real code, or- * if you want pseudo code, the simpliest possible usage is as follows. The bold- * fragment is specific to this class.- *- * <code><pre>- *- * IndexReader ir = ...- * IndexSearcher is = ...- * <b>- * MoreLikeThis mlt = new MoreLikeThis(ir);- * Reader target = ... </b><em>// orig source of doc you want to find similarities to</em><b>- * Query query = mlt.like( target);- * </b>- * Hits hits = is.search(query);- * <em>// now the usual iteration thru 'hits' - the only thing to watch for is to make sure- * you ignore the doc if it matches your 'target' document, as it should be similar to itself </em>- *- * </pre></code>- *- * Thus you:- * <ol>- * <li> do your normal, Lucene setup for searching,- * <li> create a MoreLikeThis,- * <li> get the text of the doc you want to find similaries to- * <li> then call one of the like() calls to generate a similarity query- * <li> call the searcher to find the similar docs- * </ol>- *- * <h3>More Advanced Usage</h3>- *- * You may want to use {@link #setFieldNames setFieldNames(...)} so you can examine- * multiple fields (e.g. body and title) for similarity.- * <p>- *- * Depending on the size of your index and the size and makeup of your documents you- * may want to call the other set methods to control how the similarity queries are- * generated:- * <ul>- * <li> {@link #setMinTermFreq setMinTermFreq(...)}- * <li> {@link #setMinDocFreq setMinDocFreq(...)}- * <li> {@link #setMinWordLen setMinWordLen(...)}- * <li> {@link #setMaxWordLen setMaxWordLen(...)}- * <li> {@link #setMaxQueryTerms setMaxQueryTerms(...)}- * <li> {@link #setMaxNumTokensParsed setMaxNumTokensParsed(...)}- * <li> {@link #setStopWords setStopWord(...)}- * </ul>- *- * <hr>- * <pre>- * Changes: Mark Harwood 29/02/04- * Some bugfixing, some refactoring, some optimisation.- * - bugfix: retrieveTerms(int docNum) was not working for indexes without a termvector -added missing code- * - bugfix: No significant terms being created for fields with a termvector - because- * was only counting one occurence per term/field pair in calculations(ie not including frequency info from TermVector)- * - refactor: moved common code into isNoiseWord()- * - optimise: when no termvector support available - used maxNumTermsParsed to limit amount of tokenization- * </pre>- *- */-public final class MoreLikeThis {-- /**- * Default maximum number of tokens to parse in each example doc field that is not stored with TermVector support.- * @see #getMaxNumTokensParsed- */- public static final int DEFAULT_MAX_NUM_TOKENS_PARSED=5000;--- /**- * Default analyzer to parse source doc with.- * @see #getAnalyzer- */- public static final Analyzer DEFAULT_ANALYZER = new StandardAnalyzer();-- /**- * Ignore terms with less than this frequency in the source doc.- * @see #getMinTermFreq- * @see #setMinTermFreq- */- public static final int DEFAULT_MIN_TERM_FREQ = 2;-- /**- * Ignore words which do not occur in at least this many docs.- * @see #getMinDocFreq- * @see #setMinDocFreq- */- public static final int DEFAULT_MIN_DOC_FREQ = 5;-- /**- * Boost terms in query based on score.- * @see #isBoost- * @see #setBoost- */- public static final boolean DEFAULT_BOOST = false;-- /**- * Default field names. Null is used to specify that the field names should be looked- * up at runtime from the provided reader.- */- public static final String[] DEFAULT_FIELD_NAMES = new String[] { "contents"};-- /**- * Ignore words less than this length or if 0 then this has no effect.- * @see #getMinWordLen- * @see #setMinWordLen- */- public static final int DEFAULT_MIN_WORD_LENGTH = 0;-- /**- * Ignore words greater than this length or if 0 then this has no effect.- * @see #getMaxWordLen- * @see #setMaxWordLen- */- public static final int DEFAULT_MAX_WORD_LENGTH = 0;-- /**- * Default set of stopwords.- * If null means to allow stop words.- *- * @see #setStopWords- * @see #getStopWords- */- public static final Set DEFAULT_STOP_WORDS = null;-- /**- * Current set of stop words.- */- private Set stopWords = DEFAULT_STOP_WORDS;-- /**- * Return a Query with no more than this many terms.- *- * @see BooleanQuery#getMaxClauseCount- * @see #getMaxQueryTerms- * @see #setMaxQueryTerms- */- public static final int DEFAULT_MAX_QUERY_TERMS = 25;-- /**- * Analyzer that will be used to parse the doc.- */- private Analyzer analyzer = DEFAULT_ANALYZER;-- /**- * Ignore words less freqent that this.- */- private int minTermFreq = DEFAULT_MIN_TERM_FREQ;-- /**- * Ignore words which do not occur in at least this many docs.- */- private int minDocFreq = DEFAULT_MIN_DOC_FREQ;-- /**- * Should we apply a boost to the Query based on the scores?- */- private boolean boost = DEFAULT_BOOST;-- /**- * Field name we'll analyze.- */- private String[] fieldNames = DEFAULT_FIELD_NAMES;-- /**- * The maximum number of tokens to parse in each example doc field that is not stored with TermVector support- */- private int maxNumTokensParsed=DEFAULT_MAX_NUM_TOKENS_PARSED;---- /**- * Ignore words if less than this len.- */- private int minWordLen = DEFAULT_MIN_WORD_LENGTH;-- /**- * Ignore words if greater than this len.- */- private int maxWordLen = DEFAULT_MAX_WORD_LENGTH;-- /**- * Don't return a query longer than this.- */- private int maxQueryTerms = DEFAULT_MAX_QUERY_TERMS;-- /**- * For idf() calculations.- */- private Similarity similarity;// = new DefaultSimilarity();-- /**- * IndexReader to use- */- private final IndexReader ir;-- /**- * Constructor requiring an IndexReader.- */- public MoreLikeThis(IndexReader ir) {- this(ir, new DefaultSimilarity());- }-- public MoreLikeThis(IndexReader ir, Similarity sim){- this.ir = ir;- this.similarity = sim;- }--- public Similarity getSimilarity() {- return similarity;- }-- public void setSimilarity(Similarity similarity) {- this.similarity = similarity;- }-- /**- * Returns an analyzer that will be used to parse source doc with. The default analyzer- * is the {@link #DEFAULT_ANALYZER}.- *- * @return the analyzer that will be used to parse source doc with.- * @see #DEFAULT_ANALYZER- */- public Analyzer getAnalyzer() {- return analyzer;- }-- /**- * Sets the analyzer to use. An analyzer is not required for generating a query with the- * {@link #like(int)} method, all other 'like' methods require an analyzer.- *- * @param analyzer the analyzer to use to tokenize text.- */- public void setAnalyzer(Analyzer analyzer) {- this.analyzer = analyzer;- }-- /**- * Returns the frequency below which terms will be ignored in the source doc. The default- * frequency is the {@link #DEFAULT_MIN_TERM_FREQ}.- *- * @return the frequency below which terms will be ignored in the source doc.- */- public int getMinTermFreq() {- return minTermFreq;- }-- /**- * Sets the frequency below which terms will be ignored in the source doc.- *- * @param minTermFreq the frequency below which terms will be ignored in the source doc.- */- public void setMinTermFreq(int minTermFreq) {- this.minTermFreq = minTermFreq;- }-- /**- * Returns the frequency at which words will be ignored which do not occur in at least this- * many docs. The default frequency is {@link #DEFAULT_MIN_DOC_FREQ}.- *- * @return the frequency at which words will be ignored which do not occur in at least this- * many docs.- */- public int getMinDocFreq() {- return minDocFreq;- }-- /**- * Sets the frequency at which words will be ignored which do not occur in at least this- * many docs.- *- * @param minDocFreq the frequency at which words will be ignored which do not occur in at- * least this many docs.- */- public void setMinDocFreq(int minDocFreq) {- this.minDocFreq = minDocFreq;- }-- /**- * Returns whether to boost terms in query based on "score" or not. The default is- * {@link #DEFAULT_BOOST}.- *- * @return whether to boost terms in query based on "score" or not.- * @see #setBoost- */- public boolean isBoost() {- return boost;- }-- /**- * Sets whether to boost terms in query based on "score" or not.- *- * @param boost true to boost terms in query based on "score", false otherwise.- * @see #isBoost- */- public void setBoost(boolean boost) {- this.boost = boost;- }-- /**- * Returns the field names that will be used when generating the 'More Like This' query.- * The default field names that will be used is {@link #DEFAULT_FIELD_NAMES}.- *- * @return the field names that will be used when generating the 'More Like This' query.- */- public String[] getFieldNames() {- return fieldNames;- }-- /**- * Sets the field names that will be used when generating the 'More Like This' query.- * Set this to null for the field names to be determined at runtime from the IndexReader- * provided in the constructor.- *- * @param fieldNames the field names that will be used when generating the 'More Like This'- * query.- */- public void setFieldNames(String[] fieldNames) {- this.fieldNames = fieldNames;- }-- /**- * Returns the minimum word length below which words will be ignored. Set this to 0 for no- * minimum word length. The default is {@link #DEFAULT_MIN_WORD_LENGTH}.- *- * @return the minimum word length below which words will be ignored.- */- public int getMinWordLen() {- return minWordLen;- }-- /**- * Sets the minimum word length below which words will be ignored.- *- * @param minWordLen the minimum word length below which words will be ignored.- */- public void setMinWordLen(int minWordLen) {- this.minWordLen = minWordLen;- }-- /**- * Returns the maximum word length above which words will be ignored. Set this to 0 for no- * maximum word length. The default is {@link #DEFAULT_MAX_WORD_LENGTH}.- *- * @return the maximum word length above which words will be ignored.- */- public int getMaxWordLen() {- return maxWordLen;- }-- /**- * Sets the maximum word length above which words will be ignored.- *- * @param maxWordLen the maximum word length above which words will be ignored.- */- public void setMaxWordLen(int maxWordLen) {- this.maxWordLen = maxWordLen;- }-- /**- * Set the set of stopwords.- * Any word in this set is considered "uninteresting" and ignored.- * Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as- * for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".- *- * @param stopWords set of stopwords, if null it means to allow stop words- *- * @see org.apache.lucene.analysis.StopFilter#makeStopSet StopFilter.makeStopSet()- * @see #getStopWords- */- public void setStopWords(Set stopWords) {- this.stopWords = stopWords;- }-- /**- * Get the current stop words being used.- * @see #setStopWords- */- public Set getStopWords() {- return stopWords;- }--- /**- * Returns the maximum number of query terms that will be included in any generated query.- * The default is {@link #DEFAULT_MAX_QUERY_TERMS}.- *- * @return the maximum number of query terms that will be included in any generated query.- */- public int getMaxQueryTerms() {- return maxQueryTerms;- }-- /**- * Sets the maximum number of query terms that will be included in any generated query.- *- * @param maxQueryTerms the maximum number of query terms that will be included in any- * generated query.- */- public void setMaxQueryTerms(int maxQueryTerms) {- this.maxQueryTerms = maxQueryTerms;- }-- /**- * @return The maximum number of tokens to parse in each example doc field that is not stored with TermVector support- * @see #DEFAULT_MAX_NUM_TOKENS_PARSED- */- public int getMaxNumTokensParsed()- {- return maxNumTokensParsed;- }-- /**- * @param i The maximum number of tokens to parse in each example doc field that is not stored with TermVector support- */- public void setMaxNumTokensParsed(int i)- {- maxNumTokensParsed = i;- }----- /**- * Return a query that will return docs like the passed lucene document ID.- *- * @param docNum the documentID of the lucene doc to generate the 'More Like This" query for.- * @return a query that will return docs like the passed lucene document ID.- */- public Query like(int docNum) throws IOException {- if (fieldNames == null) {- // gather list of valid fields from lucene- Collection fields = ir.getFieldNames( IndexReader.FieldOption.INDEXED);- fieldNames = (String[]) fields.toArray(new String[fields.size()]);- }-- return createQuery(retrieveTerms(docNum));- }-- /**- * Return a query that will return docs like the passed file.- *- * @return a query that will return docs like the passed file.- */- public Query like(File f) throws IOException {- if (fieldNames == null) {- // gather list of valid fields from lucene- Collection fields = ir.getFieldNames( IndexReader.FieldOption.INDEXED);- fieldNames = (String[]) fields.toArray(new String[fields.size()]);- }-- return like(new FileReader(f));- }-- /**- * Return a query that will return docs like the passed URL.- *- * @return a query that will return docs like the passed URL.- */- public Query like(URL u) throws IOException {- return like(new InputStreamReader(u.openConnection().getInputStream()));- }-- /**- * Return a query that will return docs like the passed stream.- *- * @return a query that will return docs like the passed stream.- */- public Query like(java.io.InputStream is) throws IOException {- return like(new InputStreamReader(is));- }-- /**- * Return a query that will return docs like the passed Reader.- *- * @return a query that will return docs like the passed Reader.- */- public Query like(Reader r) throws IOException {- return createQuery(retrieveTerms(r));- }-- /**- * Create the More like query from a PriorityQueue- */- private Query createQuery(PriorityQueue q) {- BooleanQuery query = new BooleanQuery();- Object cur;- int qterms = 0;- float bestScore = 0;-- while (((cur = q.pop()) != null)) {- Object[] ar = (Object[]) cur;- TermQuery tq = new TermQuery(new Term((String) ar[1], (String) ar[0]));-- if (boost) {- if (qterms == 0) {- bestScore = ((Float) ar[2]).floatValue();- }- float myScore = ((Float) ar[2]).floatValue();-- tq.setBoost(myScore / bestScore);- }-- try {- query.add(tq, BooleanClause.Occur.SHOULD);- }- catch (BooleanQuery.TooManyClauses ignore) {- break;- }-- qterms++;- if (maxQueryTerms > 0 && qterms >= maxQueryTerms) {- break;- }- }-- return query;- }-- /**- * Create a PriorityQueue from a word->tf map.- *- * @param words a map of words keyed on the word(String) with Int objects as the values.- */- private PriorityQueue createQueue(Map words) throws IOException {- // have collected all words in doc and their freqs- int numDocs = ir.numDocs();- FreqQ res = new FreqQ(words.size()); // will order words by score-- Iterator it = words.keySet().iterator();- while (it.hasNext()) { // for every word- String word = (String) it.next();-- int tf = ((Int) words.get(word)).x; // term freq in the source doc- if (minTermFreq > 0 && tf < minTermFreq) {- continue; // filter out words that don't occur enough times in the source- }-- // go through all the fields and find the largest document frequency- String topField = fieldNames[0];- int docFreq = 0;- for (int i = 0; i < fieldNames.length; i++) {- int freq = ir.docFreq(new Term(fieldNames[i], word));- topField = (freq > docFreq) ? fieldNames[i] : topField;- docFreq = (freq > docFreq) ? freq : docFreq;- }-- if (minDocFreq > 0 && docFreq < minDocFreq) {- continue; // filter out words that don't occur in enough docs- }-- if (docFreq == 0) {- continue; // index update problem?- }-- float idf = similarity.idf(docFreq, numDocs);- float score = tf * idf;-- // only really need 1st 3 entries, other ones are for troubleshooting- res.insert(new Object[]{word, // the word- topField, // the top field- new Float(score), // overall score- new Float(idf), // idf- new Integer(docFreq), // freq in all docs- new Integer(tf)- });- }- return res;- }-- /**- * Describe the parameters that control how the "more like this" query is formed.- */- public String describeParams() {- StringBuffer sb = new StringBuffer();- sb.append("\t" + "maxQueryTerms : " + maxQueryTerms + "\n");- sb.append("\t" + "minWordLen : " + minWordLen + "\n");- sb.append("\t" + "maxWordLen : " + maxWordLen + "\n");- sb.append("\t" + "fieldNames : ");- String delim = "";- for (int i = 0; i < fieldNames.length; i++) {- String fieldName = fieldNames[i];- sb.append(delim).append(fieldName);- delim = ", ";- }- sb.append("\n");- sb.append("\t" + "boost : " + boost + "\n");- sb.append("\t" + "minTermFreq : " + minTermFreq + "\n");- sb.append("\t" + "minDocFreq : " + minDocFreq + "\n");- return sb.toString();- }-- /**- * Test driver.- * Pass in "-i INDEX" and then either "-fn FILE" or "-url URL".- */- public static void main(String[] a) throws Throwable {- String indexName = "localhost_index";- String fn = "c:/Program Files/Apache Group/Apache/htdocs/manual/vhosts/index.html.en";- URL url = null;- for (int i = 0; i < a.length; i++) {- if (a[i].equals("-i")) {- indexName = a[++i];- }- else if (a[i].equals("-f")) {- fn = a[++i];- }- else if (a[i].equals("-url")) {- url = new URL(a[++i]);- }- }-- PrintStream o = System.out;- IndexReader r = IndexReader.open(indexName);- o.println("Open index " + indexName + " which has " + r.numDocs() + " docs");-- MoreLikeThis mlt = new MoreLikeThis(r);-- o.println("Query generation parameters:");- o.println(mlt.describeParams());- o.println();-- Query query = null;- if (url != null) {- o.println("Parsing URL: " + url);- query = mlt.like(url);- }- else if (fn != null) {- o.println("Parsing file: " + fn);- query = mlt.like(new File(fn));- }-- o.println("q: " + query);- o.println();- IndexSearcher searcher = new IndexSearcher(indexName);-- Hits hits = searcher.search(query);- int len = hits.length();- o.println("found: " + len + " documents matching");- o.println();- for (int i = 0; i < Math.min(25, len); i++) {- Document d = hits.doc(i);- String summary = d.get( "summary");- o.println("score : " + hits.score(i));- o.println("url : " + d.get("url"));- o.println("\ttitle : " + d.get("title"));- if ( summary != null)- o.println("\tsummary: " + d.get("summary"));- o.println();- }- }-- /**- * Find words for a more-like-this query former.- *- * @param docNum the id of the lucene document from which to find terms- */- public PriorityQueue retrieveTerms(int docNum) throws IOException {- Map termFreqMap = new HashMap();- for (int i = 0; i < fieldNames.length; i++) {- String fieldName = fieldNames[i];- TermFreqVector vector = ir.getTermFreqVector(docNum, fieldName);-- // field does not store term vector info- if (vector == null) {- Document d=ir.document(docNum);- String text[]=d.getValues(fieldName);- if(text!=null)- {- for (int j = 0; j < text.length; j++) {- addTermFrequencies(new StringReader(text[j]), termFreqMap, fieldName);- }- }- }- else {- addTermFrequencies(termFreqMap, vector);- }-- }-- return createQueue(termFreqMap);- }-- /**- * Adds terms and frequencies found in vector into the Map termFreqMap- * @param termFreqMap a Map of terms and their frequencies- * @param vector List of terms and their frequencies for a doc/field- */- private void addTermFrequencies(Map termFreqMap, TermFreqVector vector)- {- String[] terms = vector.getTerms();- int freqs[]=vector.getTermFrequencies();- for (int j = 0; j < terms.length; j++) {- String term = terms[j];-- if(isNoiseWord(term)){- continue;- }- // increment frequency- Int cnt = (Int) termFreqMap.get(term);- if (cnt == null) {- cnt=new Int();- termFreqMap.put(term, cnt);- cnt.x=freqs[j];- }- else {- cnt.x+=freqs[j];- }- }- }- /**- * Adds term frequencies found by tokenizing text from reader into the Map words- * @param r a source of text to be tokenized- * @param termFreqMap a Map of terms and their frequencies- * @param fieldName Used by analyzer for any special per-field analysis- */- private void addTermFrequencies(Reader r, Map termFreqMap, String fieldName)- throws IOException- {- TokenStream ts = analyzer.tokenStream(fieldName, r);- int tokenCount=0;- // for every token- final Token reusableToken = new Token();- for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {- String word = nextToken.term();- tokenCount++;- if(tokenCount>maxNumTokensParsed)- {- break;- }- if(isNoiseWord(word)){- continue;- }-- // increment frequency- Int cnt = (Int) termFreqMap.get(word);- if (cnt == null) {- termFreqMap.put(word, new Int());- }- else {- cnt.x++;- }- }- }--- /** determines if the passed term is likely to be of interest in "more like" comparisons- *- * @param term The word being considered- * @return true if should be ignored, false if should be used in further analysis- */- private boolean isNoiseWord(String term)- {- int len = term.length();- if (minWordLen > 0 && len < minWordLen) {- return true;- }- if (maxWordLen > 0 && len > maxWordLen) {- return true;- }- if (stopWords != null && stopWords.contains( term)) {- return true;- }- return false;- }--- /**- * Find words for a more-like-this query former.- * The result is a priority queue of arrays with one entry for <b>every word</b> in the document.- * Each array has 6 elements.- * The elements are:- * <ol>- * <li> The word (String)- * <li> The top field that this word comes from (String)- * <li> The score for this word (Float)- * <li> The IDF value (Float)- * <li> The frequency of this word in the index (Integer)- * <li> The frequency of this word in the source document (Integer)- * </ol>- * This is a somewhat "advanced" routine, and in general only the 1st entry in the array is of interest.- * This method is exposed so that you can identify the "interesting words" in a document.- * For an easier method to call see {@link #retrieveInterestingTerms retrieveInterestingTerms()}.- *- * @param r the reader that has the content of the document- * @return the most interesting words in the document ordered by score, with the highest scoring, or best entry, first- *- * @see #retrieveInterestingTerms- */- public PriorityQueue retrieveTerms(Reader r) throws IOException {- Map words = new HashMap();- for (int i = 0; i < fieldNames.length; i++) {- String fieldName = fieldNames[i];- addTermFrequencies(r, words, fieldName);- }- return createQueue(words);- }-- /**- * @see #retrieveInterestingTerms(java.io.Reader)- */- public String [] retrieveInterestingTerms(int docNum) throws IOException{- ArrayList al = new ArrayList( maxQueryTerms);- PriorityQueue pq = retrieveTerms(docNum);- Object cur;- int lim = maxQueryTerms; // have to be careful, retrieveTerms returns all words but that's probably not useful to our caller...- // we just want to return the top words- while (((cur = pq.pop()) != null) && lim-- > 0) {- Object[] ar = (Object[]) cur;- al.add( ar[ 0]); // the 1st entry is the interesting word- }- String[] res = new String[ al.size()];- return (String[]) al.toArray( res);- }-- /**- * Convenience routine to make it easy to return the most interesting words in a document.- * More advanced users will call {@link #retrieveTerms(java.io.Reader) retrieveTerms()} directly.- * @param r the source document- * @return the most interesting words in the document- *- * @see #retrieveTerms(java.io.Reader)- * @see #setMaxQueryTerms- */- public String[] retrieveInterestingTerms( Reader r) throws IOException {- ArrayList al = new ArrayList( maxQueryTerms);- PriorityQueue pq = retrieveTerms( r);- Object cur;- int lim = maxQueryTerms; // have to be careful, retrieveTerms returns all words but that's probably not useful to our caller...- // we just want to return the top words- while (((cur = pq.pop()) != null) && lim-- > 0) {- Object[] ar = (Object[]) cur;- al.add( ar[ 0]); // the 1st entry is the interesting word- }- String[] res = new String[ al.size()];- return (String[]) al.toArray( res);- }-- /**- * PriorityQueue that orders words by score.- */- private static class FreqQ extends PriorityQueue {- FreqQ (int s) {- initialize(s);- }-- protected boolean lessThan(Object a, Object b) {- Object[] aa = (Object[]) a;- Object[] bb = (Object[]) b;- Float fa = (Float) aa[2];- Float fb = (Float) bb[2];- return fa.floatValue() > fb.floatValue();- }- }-- /**- * Use for frequencies and to avoid renewing Integers.- */- private static class Int {- int x;-- Int() {- x = 1;- }- }---}+/**+ * Copyright 2004-2005 The Apache Software Foundation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.lucene.search.similar;++import org.apache.lucene.util.PriorityQueue;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermFreqVector;+import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.DefaultSimilarity;+import org.apache.lucene.search.Similarity;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.Hits;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Document;++import java.util.Set;+import java.util.HashMap;+import java.util.Map;+import java.util.Collection;+import java.util.Iterator;+import java.io.IOException;+import java.io.Reader;+import java.io.File;+import java.io.PrintStream;+import java.io.StringReader;+import java.io.FileReader;+import java.io.InputStreamReader;+import java.net.URL;+import java.util.ArrayList;+++/**+ * Generate "more like this" similarity queries.+ * Based on this mail:+ * <code><pre>+ * Lucene does let you access the document frequency of terms, with IndexReader.docFreq().+ * Term frequencies can be computed by re-tokenizing the text, which, for a single document,+ * is usually fast enough. But looking up the docFreq() of every term in the document is+ * probably too slow.+ *+ * You can use some heuristics to prune the set of terms, to avoid calling docFreq() too much,+ * or at all. Since you're trying to maximize a tf*idf score, you're probably most interested+ * in terms with a high tf. Choosing a tf threshold even as low as two or three will radically+ * reduce the number of terms under consideration. Another heuristic is that terms with a+ * high idf (i.e., a low df) tend to be longer. So you could threshold the terms by the+ * number of characters, not selecting anything less than, e.g., six or seven characters.+ * With these sorts of heuristics you can usually find small set of, e.g., ten or fewer terms+ * that do a pretty good job of characterizing a document.+ *+ * It all depends on what you're trying to do. If you're trying to eek out that last percent+ * of precision and recall regardless of computational difficulty so that you can win a TREC+ * competition, then the techniques I mention above are useless. But if you're trying to+ * provide a "more like this" button on a search results page that does a decent job and has+ * good performance, such techniques might be useful.+ *+ * An efficient, effective "more-like-this" query generator would be a great contribution, if+ * anyone's interested. I'd imagine that it would take a Reader or a String (the document's+ * text), analyzer Analyzer, and return a set of representative terms using heuristics like those+ * above. The frequency and length thresholds could be parameters, etc.+ *+ * Doug+ * </pre></code>+ *+ *+ * <p>+ * <h3>Initial Usage</h3>+ *+ * This class has lots of options to try to make it efficient and flexible.+ * See the body of {@link #main main()} below in the source for real code, or+ * if you want pseudo code, the simpliest possible usage is as follows. The bold+ * fragment is specific to this class.+ *+ * <code><pre>+ *+ * IndexReader ir = ...+ * IndexSearcher is = ...+ * <b>+ * MoreLikeThis mlt = new MoreLikeThis(ir);+ * Reader target = ... </b><em>// orig source of doc you want to find similarities to</em><b>+ * Query query = mlt.like( target);+ * </b>+ * Hits hits = is.search(query);+ * <em>// now the usual iteration thru 'hits' - the only thing to watch for is to make sure+ * you ignore the doc if it matches your 'target' document, as it should be similar to itself </em>+ *+ * </pre></code>+ *+ * Thus you:+ * <ol>+ * <li> do your normal, Lucene setup for searching,+ * <li> create a MoreLikeThis,+ * <li> get the text of the doc you want to find similaries to+ * <li> then call one of the like() calls to generate a similarity query+ * <li> call the searcher to find the similar docs+ * </ol>+ *+ * <h3>More Advanced Usage</h3>+ *+ * You may want to use {@link #setFieldNames setFieldNames(...)} so you can examine+ * multiple fields (e.g. body and title) for similarity.+ * <p>+ *+ * Depending on the size of your index and the size and makeup of your documents you+ * may want to call the other set methods to control how the similarity queries are+ * generated:+ * <ul>+ * <li> {@link #setMinTermFreq setMinTermFreq(...)}+ * <li> {@link #setMinDocFreq setMinDocFreq(...)}+ * <li> {@link #setMinWordLen setMinWordLen(...)}+ * <li> {@link #setMaxWordLen setMaxWordLen(...)}+ * <li> {@link #setMaxQueryTerms setMaxQueryTerms(...)}+ * <li> {@link #setMaxNumTokensParsed setMaxNumTokensParsed(...)}+ * <li> {@link #setStopWords setStopWord(...)}+ * </ul>+ *+ * <hr>+ * <pre>+ * Changes: Mark Harwood 29/02/04+ * Some bugfixing, some refactoring, some optimisation.+ * - bugfix: retrieveTerms(int docNum) was not working for indexes without a termvector -added missing code+ * - bugfix: No significant terms being created for fields with a termvector - because+ * was only counting one occurence per term/field pair in calculations(ie not including frequency info from TermVector)+ * - refactor: moved common code into isNoiseWord()+ * - optimise: when no termvector support available - used maxNumTermsParsed to limit amount of tokenization+ * </pre>+ *+ */+public final class MoreLikeThis {++ /**+ * Default maximum number of tokens to parse in each example doc field that is not stored with TermVector support.+ * @see #getMaxNumTokensParsed+ */+ public static final int DEFAULT_MAX_NUM_TOKENS_PARSED=5000;+++ /**+ * Default analyzer to parse source doc with.+ * @see #getAnalyzer+ */+ public static final Analyzer DEFAULT_ANALYZER = new StandardAnalyzer();++ /**+ * Ignore terms with less than this frequency in the source doc.+ * @see #getMinTermFreq+ * @see #setMinTermFreq+ */+ public static final int DEFAULT_MIN_TERM_FREQ = 2;++ /**+ * Ignore words which do not occur in at least this many docs.+ * @see #getMinDocFreq+ * @see #setMinDocFreq+ */+ public static final int DEFAULT_MIN_DOC_FREQ = 5;++ /**+ * Boost terms in query based on score.+ * @see #isBoost+ * @see #setBoost+ */+ public static final boolean DEFAULT_BOOST = false;++ /**+ * Default field names. Null is used to specify that the field names should be looked+ * up at runtime from the provided reader.+ */+ public static final String[] DEFAULT_FIELD_NAMES = new String[] { "contents"};++ /**+ * Ignore words less than this length or if 0 then this has no effect.+ * @see #getMinWordLen+ * @see #setMinWordLen+ */+ public static final int DEFAULT_MIN_WORD_LENGTH = 0;++ /**+ * Ignore words greater than this length or if 0 then this has no effect.+ * @see #getMaxWordLen+ * @see #setMaxWordLen+ */+ public static final int DEFAULT_MAX_WORD_LENGTH = 0;++ /**+ * Default set of stopwords.+ * If null means to allow stop words.+ *+ * @see #setStopWords+ * @see #getStopWords+ */+ public static final Set DEFAULT_STOP_WORDS = null;++ /**+ * Current set of stop words.+ */+ private Set stopWords = DEFAULT_STOP_WORDS;++ /**+ * Return a Query with no more than this many terms.+ *+ * @see BooleanQuery#getMaxClauseCount+ * @see #getMaxQueryTerms+ * @see #setMaxQueryTerms+ */+ public static final int DEFAULT_MAX_QUERY_TERMS = 25;++ /**+ * Analyzer that will be used to parse the doc.+ */+ private Analyzer analyzer = DEFAULT_ANALYZER;++ /**+ * Ignore words less freqent that this.+ */+ private int minTermFreq = DEFAULT_MIN_TERM_FREQ;++ /**+ * Ignore words which do not occur in at least this many docs.+ */+ private int minDocFreq = DEFAULT_MIN_DOC_FREQ;++ /**+ * Should we apply a boost to the Query based on the scores?+ */+ private boolean boost = DEFAULT_BOOST;++ /**+ * Field name we'll analyze.+ */+ private String[] fieldNames = DEFAULT_FIELD_NAMES;++ /**+ * The maximum number of tokens to parse in each example doc field that is not stored with TermVector support+ */+ private int maxNumTokensParsed=DEFAULT_MAX_NUM_TOKENS_PARSED;++++ /**+ * Ignore words if less than this len.+ */+ private int minWordLen = DEFAULT_MIN_WORD_LENGTH;++ /**+ * Ignore words if greater than this len.+ */+ private int maxWordLen = DEFAULT_MAX_WORD_LENGTH;++ /**+ * Don't return a query longer than this.+ */+ private int maxQueryTerms = DEFAULT_MAX_QUERY_TERMS;++ /**+ * For idf() calculations.+ */+ private Similarity similarity;// = new DefaultSimilarity();++ /**+ * IndexReader to use+ */+ private final IndexReader ir;++ /**+ * Constructor requiring an IndexReader.+ */+ public MoreLikeThis(IndexReader ir) {+ this(ir, new DefaultSimilarity());+ }++ public MoreLikeThis(IndexReader ir, Similarity sim){+ this.ir = ir;+ this.similarity = sim;+ }+++ public Similarity getSimilarity() {+ return similarity;+ }++ public void setSimilarity(Similarity similarity) {+ this.similarity = similarity;+ }++ /**+ * Returns an analyzer that will be used to parse source doc with. The default analyzer+ * is the {@link #DEFAULT_ANALYZER}.+ *+ * @return the analyzer that will be used to parse source doc with.+ * @see #DEFAULT_ANALYZER+ */+ public Analyzer getAnalyzer() {+ return analyzer;+ }++ /**+ * Sets the analyzer to use. An analyzer is not required for generating a query with the+ * {@link #like(int)} method, all other 'like' methods require an analyzer.+ *+ * @param analyzer the analyzer to use to tokenize text.+ */+ public void setAnalyzer(Analyzer analyzer) {+ this.analyzer = analyzer;+ }++ /**+ * Returns the frequency below which terms will be ignored in the source doc. The default+ * frequency is the {@link #DEFAULT_MIN_TERM_FREQ}.+ *+ * @return the frequency below which terms will be ignored in the source doc.+ */+ public int getMinTermFreq() {+ return minTermFreq;+ }++ /**+ * Sets the frequency below which terms will be ignored in the source doc.+ *+ * @param minTermFreq the frequency below which terms will be ignored in the source doc.+ */+ public void setMinTermFreq(int minTermFreq) {+ this.minTermFreq = minTermFreq;+ }++ /**+ * Returns the frequency at which words will be ignored which do not occur in at least this+ * many docs. The default frequency is {@link #DEFAULT_MIN_DOC_FREQ}.+ *+ * @return the frequency at which words will be ignored which do not occur in at least this+ * many docs.+ */+ public int getMinDocFreq() {+ return minDocFreq;+ }++ /**+ * Sets the frequency at which words will be ignored which do not occur in at least this+ * many docs.+ *+ * @param minDocFreq the frequency at which words will be ignored which do not occur in at+ * least this many docs.+ */+ public void setMinDocFreq(int minDocFreq) {+ this.minDocFreq = minDocFreq;+ }++ /**+ * Returns whether to boost terms in query based on "score" or not. The default is+ * {@link #DEFAULT_BOOST}.+ *+ * @return whether to boost terms in query based on "score" or not.+ * @see #setBoost+ */+ public boolean isBoost() {+ return boost;+ }++ /**+ * Sets whether to boost terms in query based on "score" or not.+ *+ * @param boost true to boost terms in query based on "score", false otherwise.+ * @see #isBoost+ */+ public void setBoost(boolean boost) {+ this.boost = boost;+ }++ /**+ * Returns the field names that will be used when generating the 'More Like This' query.+ * The default field names that will be used is {@link #DEFAULT_FIELD_NAMES}.+ *+ * @return the field names that will be used when generating the 'More Like This' query.+ */+ public String[] getFieldNames() {+ return fieldNames;+ }++ /**+ * Sets the field names that will be used when generating the 'More Like This' query.+ * Set this to null for the field names to be determined at runtime from the IndexReader+ * provided in the constructor.+ *+ * @param fieldNames the field names that will be used when generating the 'More Like This'+ * query.+ */+ public void setFieldNames(String[] fieldNames) {+ this.fieldNames = fieldNames;+ }++ /**+ * Returns the minimum word length below which words will be ignored. Set this to 0 for no+ * minimum word length. The default is {@link #DEFAULT_MIN_WORD_LENGTH}.+ *+ * @return the minimum word length below which words will be ignored.+ */+ public int getMinWordLen() {+ return minWordLen;+ }++ /**+ * Sets the minimum word length below which words will be ignored.+ *+ * @param minWordLen the minimum word length below which words will be ignored.+ */+ public void setMinWordLen(int minWordLen) {+ this.minWordLen = minWordLen;+ }++ /**+ * Returns the maximum word length above which words will be ignored. Set this to 0 for no+ * maximum word length. The default is {@link #DEFAULT_MAX_WORD_LENGTH}.+ *+ * @return the maximum word length above which words will be ignored.+ */+ public int getMaxWordLen() {+ return maxWordLen;+ }++ /**+ * Sets the maximum word length above which words will be ignored.+ *+ * @param maxWordLen the maximum word length above which words will be ignored.+ */+ public void setMaxWordLen(int maxWordLen) {+ this.maxWordLen = maxWordLen;+ }++ /**+ * Set the set of stopwords.+ * Any word in this set is considered "uninteresting" and ignored.+ * Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as+ * for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".+ *+ * @param stopWords set of stopwords, if null it means to allow stop words+ *+ * @see org.apache.lucene.analysis.StopFilter#makeStopSet StopFilter.makeStopSet()+ * @see #getStopWords+ */+ public void setStopWords(Set stopWords) {+ this.stopWords = stopWords;+ }++ /**+ * Get the current stop words being used.+ * @see #setStopWords+ */+ public Set getStopWords() {+ return stopWords;+ }+++ /**+ * Returns the maximum number of query terms that will be included in any generated query.+ * The default is {@link #DEFAULT_MAX_QUERY_TERMS}.+ *+ * @return the maximum number of query terms that will be included in any generated query.+ */+ public int getMaxQueryTerms() {+ return maxQueryTerms;+ }++ /**+ * Sets the maximum number of query terms that will be included in any generated query.+ *+ * @param maxQueryTerms the maximum number of query terms that will be included in any+ * generated query.+ */+ public void setMaxQueryTerms(int maxQueryTerms) {+ this.maxQueryTerms = maxQueryTerms;+ }++ /**+ * @return The maximum number of tokens to parse in each example doc field that is not stored with TermVector support+ * @see #DEFAULT_MAX_NUM_TOKENS_PARSED+ */+ public int getMaxNumTokensParsed()+ {+ return maxNumTokensParsed;+ }++ /**+ * @param i The maximum number of tokens to parse in each example doc field that is not stored with TermVector support+ */+ public void setMaxNumTokensParsed(int i)+ {+ maxNumTokensParsed = i;+ }+++++ /**+ * Return a query that will return docs like the passed lucene document ID.+ *+ * @param docNum the documentID of the lucene doc to generate the 'More Like This" query for.+ * @return a query that will return docs like the passed lucene document ID.+ */+ public Query like(int docNum) throws IOException {+ if (fieldNames == null) {+ // gather list of valid fields from lucene+ Collection fields = ir.getFieldNames( IndexReader.FieldOption.INDEXED);+ fieldNames = (String[]) fields.toArray(new String[fields.size()]);+ }++ return createQuery(retrieveTerms(docNum));+ }++ /**+ * Return a query that will return docs like the passed file.+ *+ * @return a query that will return docs like the passed file.+ */+ public Query like(File f) throws IOException {+ if (fieldNames == null) {+ // gather list of valid fields from lucene+ Collection fields = ir.getFieldNames( IndexReader.FieldOption.INDEXED);+ fieldNames = (String[]) fields.toArray(new String[fields.size()]);+ }++ return like(new FileReader(f));+ }++ /**+ * Return a query that will return docs like the passed URL.+ *+ * @return a query that will return docs like the passed URL.+ */+ public Query like(URL u) throws IOException {+ return like(new InputStreamReader(u.openConnection().getInputStream()));+ }++ /**+ * Return a query that will return docs like the passed stream.+ *+ * @return a query that will return docs like the passed stream.+ */+ public Query like(java.io.InputStream is) throws IOException {+ return like(new InputStreamReader(is));+ }++ /**+ * Return a query that will return docs like the passed Reader.+ *+ * @return a query that will return docs like the passed Reader.+ */+ public Query like(Reader r) throws IOException {+ return createQuery(retrieveTerms(r));+ }++ /**+ * Create the More like query from a PriorityQueue+ */+ private Query createQuery(PriorityQueue q) {+ BooleanQuery query = new BooleanQuery();+ Object cur;+ int qterms = 0;+ float bestScore = 0;++ while (((cur = q.pop()) != null)) {+ Object[] ar = (Object[]) cur;+ TermQuery tq = new TermQuery(new Term((String) ar[1], (String) ar[0]));++ if (boost) {+ if (qterms == 0) {+ bestScore = ((Float) ar[2]).floatValue();+ }+ float myScore = ((Float) ar[2]).floatValue();++ tq.setBoost(myScore / bestScore);+ }++ try {+ query.add(tq, BooleanClause.Occur.SHOULD);+ }+ catch (BooleanQuery.TooManyClauses ignore) {+ break;+ }++ qterms++;+ if (maxQueryTerms > 0 && qterms >= maxQueryTerms) {+ break;+ }+ }++ return query;+ }++ /**+ * Create a PriorityQueue from a word->tf map.+ *+ * @param words a map of words keyed on the word(String) with Int objects as the values.+ */+ private PriorityQueue createQueue(Map words) throws IOException {+ // have collected all words in doc and their freqs+ int numDocs = ir.numDocs();+ FreqQ res = new FreqQ(words.size()); // will order words by score++ Iterator it = words.keySet().iterator();+ while (it.hasNext()) { // for every word+ String word = (String) it.next();++ int tf = ((Int) words.get(word)).x; // term freq in the source doc+ if (minTermFreq > 0 && tf < minTermFreq) {+ continue; // filter out words that don't occur enough times in the source+ }++ // go through all the fields and find the largest document frequency+ String topField = fieldNames[0];+ int docFreq = 0;+ for (int i = 0; i < fieldNames.length; i++) {+ int freq = ir.docFreq(new Term(fieldNames[i], word));+ topField = (freq > docFreq) ? fieldNames[i] : topField;+ docFreq = (freq > docFreq) ? freq : docFreq;+ }++ if (minDocFreq > 0 && docFreq < minDocFreq) {+ continue; // filter out words that don't occur in enough docs+ }++ if (docFreq == 0) {+ continue; // index update problem?+ }++ float idf = similarity.idf(docFreq, numDocs);+ float score = tf * idf;++ // only really need 1st 3 entries, other ones are for troubleshooting+ res.insert(new Object[]{word, // the word+ topField, // the top field+ new Float(score), // overall score+ new Float(idf), // idf+ new Integer(docFreq), // freq in all docs+ new Integer(tf)+ });+ }+ return res;+ }++ /**+ * Describe the parameters that control how the "more like this" query is formed.+ */+ public String describeParams() {+ StringBuffer sb = new StringBuffer();+ sb.append("\t" + "maxQueryTerms : " + maxQueryTerms + "\n");+ sb.append("\t" + "minWordLen : " + minWordLen + "\n");+ sb.append("\t" + "maxWordLen : " + maxWordLen + "\n");+ sb.append("\t" + "fieldNames : ");+ String delim = "";+ for (int i = 0; i < fieldNames.length; i++) {+ String fieldName = fieldNames[i];+ sb.append(delim).append(fieldName);+ delim = ", ";+ }+ sb.append("\n");+ sb.append("\t" + "boost : " + boost + "\n");+ sb.append("\t" + "minTermFreq : " + minTermFreq + "\n");+ sb.append("\t" + "minDocFreq : " + minDocFreq + "\n");+ return sb.toString();+ }++ /**+ * Test driver.+ * Pass in "-i INDEX" and then either "-fn FILE" or "-url URL".+ */+ public static void main(String[] a) throws Throwable {+ String indexName = "localhost_index";+ String fn = "c:/Program Files/Apache Group/Apache/htdocs/manual/vhosts/index.html.en";+ URL url = null;+ for (int i = 0; i < a.length; i++) {+ if (a[i].equals("-i")) {+ indexName = a[++i];+ }+ else if (a[i].equals("-f")) {+ fn = a[++i];+ }+ else if (a[i].equals("-url")) {+ url = new URL(a[++i]);+ }+ }++ PrintStream o = System.out;+ IndexReader r = IndexReader.open(indexName);+ o.println("Open index " + indexName + " which has " + r.numDocs() + " docs");++ MoreLikeThis mlt = new MoreLikeThis(r);++ o.println("Query generation parameters:");+ o.println(mlt.describeParams());+ o.println();++ Query query = null;+ if (url != null) {+ o.println("Parsing URL: " + url);+ query = mlt.like(url);+ }+ else if (fn != null) {+ o.println("Parsing file: " + fn);+ query = mlt.like(new File(fn));+ }++ o.println("q: " + query);+ o.println();+ IndexSearcher searcher = new IndexSearcher(indexName);++ Hits hits = searcher.search(query);+ int len = hits.length();+ o.println("found: " + len + " documents matching");+ o.println();+ for (int i = 0; i < Math.min(25, len); i++) {+ Document d = hits.doc(i);+ String summary = d.get( "summary");+ o.println("score : " + hits.score(i));+ o.println("url : " + d.get("url"));+ o.println("\ttitle : " + d.get("title"));+ if ( summary != null)+ o.println("\tsummary: " + d.get("summary"));+ o.println();+ }+ }++ /**+ * Find words for a more-like-this query former.+ *+ * @param docNum the id of the lucene document from which to find terms+ */+ public PriorityQueue retrieveTerms(int docNum) throws IOException {+ Map termFreqMap = new HashMap();+ for (int i = 0; i < fieldNames.length; i++) {+ String fieldName = fieldNames[i];+ TermFreqVector vector = ir.getTermFreqVector(docNum, fieldName);++ // field does not store term vector info+ if (vector == null) {+ Document d=ir.document(docNum);+ String text[]=d.getValues(fieldName);+ if(text!=null)+ {+ for (int j = 0; j < text.length; j++) {+ addTermFrequencies(new StringReader(text[j]), termFreqMap, fieldName);+ }+ }+ }+ else {+ addTermFrequencies(termFreqMap, vector);+ }++ }++ return createQueue(termFreqMap);+ }++ /**+ * Adds terms and frequencies found in vector into the Map termFreqMap+ * @param termFreqMap a Map of terms and their frequencies+ * @param vector List of terms and their frequencies for a doc/field+ */+ private void addTermFrequencies(Map termFreqMap, TermFreqVector vector)+ {+ String[] terms = vector.getTerms();+ int freqs[]=vector.getTermFrequencies();+ for (int j = 0; j < terms.length; j++) {+ String term = terms[j];++ if(isNoiseWord(term)){+ continue;+ }+ // increment frequency+ Int cnt = (Int) termFreqMap.get(term);+ if (cnt == null) {+ cnt=new Int();+ termFreqMap.put(term, cnt);+ cnt.x=freqs[j];+ }+ else {+ cnt.x+=freqs[j];+ }+ }+ }+ /**+ * Adds term frequencies found by tokenizing text from reader into the Map words+ * @param r a source of text to be tokenized+ * @param termFreqMap a Map of terms and their frequencies+ * @param fieldName Used by analyzer for any special per-field analysis+ */+ private void addTermFrequencies(Reader r, Map termFreqMap, String fieldName)+ throws IOException+ {+ TokenStream ts = analyzer.tokenStream(fieldName, r);+ int tokenCount=0;+ // for every token+ final Token reusableToken = new Token();+ for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {+ String word = nextToken.term();+ tokenCount++;+ if(tokenCount>maxNumTokensParsed)+ {+ break;+ }+ if(isNoiseWord(word)){+ continue;+ }++ // increment frequency+ Int cnt = (Int) termFreqMap.get(word);+ if (cnt == null) {+ termFreqMap.put(word, new Int());+ }+ else {+ cnt.x++;+ }+ }+ }+++ /** determines if the passed term is likely to be of interest in "more like" comparisons+ *+ * @param term The word being considered+ * @return true if should be ignored, false if should be used in further analysis+ */+ private boolean isNoiseWord(String term)+ {+ int len = term.length();+ if (minWordLen > 0 && len < minWordLen) {+ return true;+ }+ if (maxWordLen > 0 && len > maxWordLen) {+ return true;+ }+ if (stopWords != null && stopWords.contains( term)) {+ return true;+ }+ return false;+ }+++ /**+ * Find words for a more-like-this query former.+ * The result is a priority queue of arrays with one entry for <b>every word</b> in the document.+ * Each array has 6 elements.+ * The elements are:+ * <ol>+ * <li> The word (String)+ * <li> The top field that this word comes from (String)+ * <li> The score for this word (Float)+ * <li> The IDF value (Float)+ * <li> The frequency of this word in the index (Integer)+ * <li> The frequency of this word in the source document (Integer)+ * </ol>+ * This is a somewhat "advanced" routine, and in general only the 1st entry in the array is of interest.+ * This method is exposed so that you can identify the "interesting words" in a document.+ * For an easier method to call see {@link #retrieveInterestingTerms retrieveInterestingTerms()}.+ *+ * @param r the reader that has the content of the document+ * @return the most interesting words in the document ordered by score, with the highest scoring, or best entry, first+ *+ * @see #retrieveInterestingTerms+ */+ public PriorityQueue retrieveTerms(Reader r) throws IOException {+ Map words = new HashMap();+ for (int i = 0; i < fieldNames.length; i++) {+ String fieldName = fieldNames[i];+ addTermFrequencies(r, words, fieldName);+ }+ return createQueue(words);+ }++ /**+ * @see #retrieveInterestingTerms(java.io.Reader)+ */+ public String [] retrieveInterestingTerms(int docNum) throws IOException{+ ArrayList al = new ArrayList( maxQueryTerms);+ PriorityQueue pq = retrieveTerms(docNum);+ Object cur;+ int lim = maxQueryTerms; // have to be careful, retrieveTerms returns all words but that's probably not useful to our caller...+ // we just want to return the top words+ while (((cur = pq.pop()) != null) && lim-- > 0) {+ Object[] ar = (Object[]) cur;+ al.add( ar[ 0]); // the 1st entry is the interesting word+ }+ String[] res = new String[ al.size()];+ return (String[]) al.toArray( res);+ }++ /**+ * Convenience routine to make it easy to return the most interesting words in a document.+ * More advanced users will call {@link #retrieveTerms(java.io.Reader) retrieveTerms()} directly.+ * @param r the source document+ * @return the most interesting words in the document+ *+ * @see #retrieveTerms(java.io.Reader)+ * @see #setMaxQueryTerms+ */+ public String[] retrieveInterestingTerms( Reader r) throws IOException {+ ArrayList al = new ArrayList( maxQueryTerms);+ PriorityQueue pq = retrieveTerms( r);+ Object cur;+ int lim = maxQueryTerms; // have to be careful, retrieveTerms returns all words but that's probably not useful to our caller...+ // we just want to return the top words+ while (((cur = pq.pop()) != null) && lim-- > 0) {+ Object[] ar = (Object[]) cur;+ al.add( ar[ 0]); // the 1st entry is the interesting word+ }+ String[] res = new String[ al.size()];+ return (String[]) al.toArray( res);+ }++ /**+ * PriorityQueue that orders words by score.+ */+ private static class FreqQ extends PriorityQueue {+ FreqQ (int s) {+ initialize(s);+ }++ protected boolean lessThan(Object a, Object b) {+ Object[] aa = (Object[]) a;+ Object[] bb = (Object[]) b;+ Float fa = (Float) aa[2];+ Float fb = (Float) bb[2];+ return fa.floatValue() > fb.floatValue();+ }+ }++ /**+ * Use for frequencies and to avoid renewing Integers.+ */+ private static class Int {+ int x;++ Int() {+ x = 1;+ }+ }+++}diff --git a/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThisQuery.java b/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThisQuery.javaindex 6bb80b09a43..126c4978295 100644--- a/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThisQuery.java+++ b/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThisQuery.java@@ -1,164 +1,164 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.search.similar;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.util.Set;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.similar.MoreLikeThis;--/**- * A simple wrapper for MoreLikeThis for use in scenarios where a Query object is required eg- * in custom QueryParser extensions. At query.rewrite() time the reader is used to construct the- * actual MoreLikeThis object and obtain the real Query object.- */-public class MoreLikeThisQuery extends Query-{--- private String likeText;- private String[] moreLikeFields;- private Analyzer analyzer;- float percentTermsToMatch=0.3f;- int minTermFrequency=1;- int maxQueryTerms=5;- Set stopWords=null;- int minDocFreq=-1;--- /**- * @param moreLikeFields- */- public MoreLikeThisQuery(String likeText, String[] moreLikeFields, Analyzer analyzer)- {- this.likeText=likeText;- this.moreLikeFields=moreLikeFields;- this.analyzer=analyzer;- }-- public Query rewrite(IndexReader reader) throws IOException- {- MoreLikeThis mlt=new MoreLikeThis(reader);-- mlt.setFieldNames(moreLikeFields);- mlt.setAnalyzer(analyzer);- mlt.setMinTermFreq(minTermFrequency);- if(minDocFreq>=0)- {- mlt.setMinDocFreq(minDocFreq);- }- mlt.setMaxQueryTerms(maxQueryTerms);- mlt.setStopWords(stopWords);- BooleanQuery bq= (BooleanQuery) mlt.like(new ByteArrayInputStream(likeText.getBytes()));- BooleanClause[] clauses = bq.getClauses();- //make at least half the terms match- bq.setMinimumNumberShouldMatch((int)(clauses.length*percentTermsToMatch));- return bq;- }- /* (non-Javadoc)- * @see org.apache.lucene.search.Query#toString(java.lang.String)- */- public String toString(String field)- {- return "like:"+likeText;- }-- public float getPercentTermsToMatch() {- return percentTermsToMatch;- }- public void setPercentTermsToMatch(float percentTermsToMatch) {- this.percentTermsToMatch = percentTermsToMatch;- }-- public Analyzer getAnalyzer()- {- return analyzer;- }-- public void setAnalyzer(Analyzer analyzer)- {- this.analyzer = analyzer;- }-- public String getLikeText()- {- return likeText;- }-- public void setLikeText(String likeText)- {- this.likeText = likeText;- }-- public int getMaxQueryTerms()- {- return maxQueryTerms;- }-- public void setMaxQueryTerms(int maxQueryTerms)- {- this.maxQueryTerms = maxQueryTerms;- }-- public int getMinTermFrequency()- {- return minTermFrequency;- }-- public void setMinTermFrequency(int minTermFrequency)- {- this.minTermFrequency = minTermFrequency;- }-- public String[] getMoreLikeFields()- {- return moreLikeFields;- }-- public void setMoreLikeFields(String[] moreLikeFields)- {- this.moreLikeFields = moreLikeFields;- }- public Set getStopWords()- {- return stopWords;- }- public void setStopWords(Set stopWords)- {- this.stopWords = stopWords;- }-- public int getMinDocFreq()- {- return minDocFreq;- }-- public void setMinDocFreq(int minDocFreq)- {- this.minDocFreq = minDocFreq;- }-}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.search.similar;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.util.Set;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.similar.MoreLikeThis;++/**+ * A simple wrapper for MoreLikeThis for use in scenarios where a Query object is required eg+ * in custom QueryParser extensions. At query.rewrite() time the reader is used to construct the+ * actual MoreLikeThis object and obtain the real Query object.+ */+public class MoreLikeThisQuery extends Query+{+++ private String likeText;+ private String[] moreLikeFields;+ private Analyzer analyzer;+ float percentTermsToMatch=0.3f;+ int minTermFrequency=1;+ int maxQueryTerms=5;+ Set stopWords=null;+ int minDocFreq=-1;+++ /**+ * @param moreLikeFields+ */+ public MoreLikeThisQuery(String likeText, String[] moreLikeFields, Analyzer analyzer)+ {+ this.likeText=likeText;+ this.moreLikeFields=moreLikeFields;+ this.analyzer=analyzer;+ }++ public Query rewrite(IndexReader reader) throws IOException+ {+ MoreLikeThis mlt=new MoreLikeThis(reader);++ mlt.setFieldNames(moreLikeFields);+ mlt.setAnalyzer(analyzer);+ mlt.setMinTermFreq(minTermFrequency);+ if(minDocFreq>=0)+ {+ mlt.setMinDocFreq(minDocFreq);+ }+ mlt.setMaxQueryTerms(maxQueryTerms);+ mlt.setStopWords(stopWords);+ BooleanQuery bq= (BooleanQuery) mlt.like(new ByteArrayInputStream(likeText.getBytes()));+ BooleanClause[] clauses = bq.getClauses();+ //make at least half the terms match+ bq.setMinimumNumberShouldMatch((int)(clauses.length*percentTermsToMatch));+ return bq;+ }+ /* (non-Javadoc)+ * @see org.apache.lucene.search.Query#toString(java.lang.String)+ */+ public String toString(String field)+ {+ return "like:"+likeText;+ }++ public float getPercentTermsToMatch() {+ return percentTermsToMatch;+ }+ public void setPercentTermsToMatch(float percentTermsToMatch) {+ this.percentTermsToMatch = percentTermsToMatch;+ }++ public Analyzer getAnalyzer()+ {+ return analyzer;+ }++ public void setAnalyzer(Analyzer analyzer)+ {+ this.analyzer = analyzer;+ }++ public String getLikeText()+ {+ return likeText;+ }++ public void setLikeText(String likeText)+ {+ this.likeText = likeText;+ }++ public int getMaxQueryTerms()+ {+ return maxQueryTerms;+ }++ public void setMaxQueryTerms(int maxQueryTerms)+ {+ this.maxQueryTerms = maxQueryTerms;+ }++ public int getMinTermFrequency()+ {+ return minTermFrequency;+ }++ public void setMinTermFrequency(int minTermFrequency)+ {+ this.minTermFrequency = minTermFrequency;+ }++ public String[] getMoreLikeFields()+ {+ return moreLikeFields;+ }++ public void setMoreLikeFields(String[] moreLikeFields)+ {+ this.moreLikeFields = moreLikeFields;+ }+ public Set getStopWords()+ {+ return stopWords;+ }+ public void setStopWords(Set stopWords)+ {+ this.stopWords = stopWords;+ }++ public int getMinDocFreq()+ {+ return minDocFreq;+ }++ public void setMinDocFreq(int minDocFreq)+ {+ this.minDocFreq = minDocFreq;+ }+}diff --git a/contrib/queries/src/java/org/apache/lucene/search/similar/SimilarityQueries.java b/contrib/queries/src/java/org/apache/lucene/search/similar/SimilarityQueries.javaindex a3bd8a22323..e3cea76d034 100644--- a/contrib/queries/src/java/org/apache/lucene/search/similar/SimilarityQueries.java+++ b/contrib/queries/src/java/org/apache/lucene/search/similar/SimilarityQueries.java@@ -1,113 +1,113 @@-/**- * Copyright 2004 The Apache Software Foundation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.lucene.search.similar;--import java.io.IOException;-import java.io.StringReader;-import java.util.HashSet;-import java.util.Set;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.TermQuery;--/**- * Simple similarity measures.- *- * @see MoreLikeThis- */-public final class SimilarityQueries-{- /**- *- */- private SimilarityQueries()- {- }-- /**- * Simple similarity query generators.- * Takes every unique word and forms a boolean query where all words are optional.- * After you get this you'll use to to query your {@link IndexSearcher} for similar docs.- * The only caveat is the first hit returned <b>should be</b> your source document - you'll- * need to then ignore that.- *- * <p>- * So, if you have a code fragment like this:- * <br>- * <code>- * Query q = formSimilaryQuery( "I use Lucene to search fast. Fast searchers are good", new StandardAnalyzer(), "contents", null);- * </code>- *- * <p>- * The query returned, in string form, will be <code>'(i use lucene to search fast searchers are good')</code>.- *- * <p>- * The philosophy behind this method is "two documents are similar if they share lots of words".- * Note that behind the scenes, Lucenes scoring algorithm will tend to give two documents a higher similarity score if the share more uncommon words.- *- * <P>- * This method is fail-safe in that if a long 'body' is passed in and- * {@link BooleanQuery#add BooleanQuery.add()} (used internally)- * throws- * {@link org.apache.lucene.search.BooleanQuery.TooManyClauses BooleanQuery.TooManyClauses}, the- * query as it is will be returned.- *- * @param body the body of the document you want to find similar documents to- * @param a the analyzer to use to parse the body- * @param field the field you want to search on, probably something like "contents" or "body"- * @param stop optional set of stop words to ignore- * @return a query with all unique words in 'body'- * @throws IOException this can't happen...- */- public static Query formSimilarQuery( String body,- Analyzer a,- String field,- Set stop)- throws IOException- {- TokenStream ts = a.tokenStream( field, new StringReader( body));- BooleanQuery tmp = new BooleanQuery();- Set already = new HashSet(); // ignore dups- final Token reusableToken = new Token();- for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {- String word = nextToken.term();- // ignore opt stop words- if ( stop != null &&- stop.contains( word)) continue;- // ignore dups- if ( ! already.add( word)) continue;- // add to query- TermQuery tq = new TermQuery( new Term( field, word));- try- {- tmp.add( tq, BooleanClause.Occur.SHOULD);- }- catch( BooleanQuery.TooManyClauses too)- {- // fail-safe, just return what we have, not the end of the world- break;- }- }- return tmp;- }-}+/**+ * Copyright 2004 The Apache Software Foundation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.lucene.search.similar;++import java.io.IOException;+import java.io.StringReader;+import java.util.HashSet;+import java.util.Set;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.TermQuery;++/**+ * Simple similarity measures.+ *+ * @see MoreLikeThis+ */+public final class SimilarityQueries+{+ /**+ *+ */+ private SimilarityQueries()+ {+ }++ /**+ * Simple similarity query generators.+ * Takes every unique word and forms a boolean query where all words are optional.+ * After you get this you'll use to to query your {@link IndexSearcher} for similar docs.+ * The only caveat is the first hit returned <b>should be</b> your source document - you'll+ * need to then ignore that.+ *+ * <p>+ * So, if you have a code fragment like this:+ * <br>+ * <code>+ * Query q = formSimilaryQuery( "I use Lucene to search fast. Fast searchers are good", new StandardAnalyzer(), "contents", null);+ * </code>+ *+ * <p>+ * The query returned, in string form, will be <code>'(i use lucene to search fast searchers are good')</code>.+ *+ * <p>+ * The philosophy behind this method is "two documents are similar if they share lots of words".+ * Note that behind the scenes, Lucenes scoring algorithm will tend to give two documents a higher similarity score if the share more uncommon words.+ *+ * <P>+ * This method is fail-safe in that if a long 'body' is passed in and+ * {@link BooleanQuery#add BooleanQuery.add()} (used internally)+ * throws+ * {@link org.apache.lucene.search.BooleanQuery.TooManyClauses BooleanQuery.TooManyClauses}, the+ * query as it is will be returned.+ *+ * @param body the body of the document you want to find similar documents to+ * @param a the analyzer to use to parse the body+ * @param field the field you want to search on, probably something like "contents" or "body"+ * @param stop optional set of stop words to ignore+ * @return a query with all unique words in 'body'+ * @throws IOException this can't happen...+ */+ public static Query formSimilarQuery( String body,+ Analyzer a,+ String field,+ Set stop)+ throws IOException+ {+ TokenStream ts = a.tokenStream( field, new StringReader( body));+ BooleanQuery tmp = new BooleanQuery();+ Set already = new HashSet(); // ignore dups+ final Token reusableToken = new Token();+ for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {+ String word = nextToken.term();+ // ignore opt stop words+ if ( stop != null &&+ stop.contains( word)) continue;+ // ignore dups+ if ( ! already.add( word)) continue;+ // add to query+ TermQuery tq = new TermQuery( new Term( field, word));+ try+ {+ tmp.add( tq, BooleanClause.Occur.SHOULD);+ }+ catch( BooleanQuery.TooManyClauses too)+ {+ // fail-safe, just return what we have, not the end of the world+ break;+ }+ }+ return tmp;+ }+}diff --git a/contrib/queries/src/test/org/apache/lucene/search/FuzzyLikeThisQueryTest.java b/contrib/queries/src/test/org/apache/lucene/search/FuzzyLikeThisQueryTest.javaindex ae12e2e7bcd..c608cd71cc3 100644--- a/contrib/queries/src/test/org/apache/lucene/search/FuzzyLikeThisQueryTest.java+++ b/contrib/queries/src/test/org/apache/lucene/search/FuzzyLikeThisQueryTest.java@@ -1,114 +1,114 @@-package org.apache.lucene.search;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.io.IOException;-import java.util.HashSet;--import junit.framework.TestCase;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.WhitespaceAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.IndexWriter.MaxFieldLength;-import org.apache.lucene.store.RAMDirectory;--public class FuzzyLikeThisQueryTest extends TestCase-{- private RAMDirectory directory;- private IndexSearcher searcher;- private Analyzer analyzer=new WhitespaceAnalyzer();-- protected void setUp() throws Exception- {- directory = new RAMDirectory();- IndexWriter writer = new IndexWriter(directory, analyzer,true, MaxFieldLength.UNLIMITED);-- //Add series of docs with misspelt names- addDoc(writer, "jonathon smythe","1");- addDoc(writer, "jonathan smith","2");- addDoc(writer, "johnathon smyth","3");- addDoc(writer, "johnny smith","4" );- addDoc(writer, "jonny smith","5" );- addDoc(writer, "johnathon smythe","6");-- writer.close();- searcher=new IndexSearcher(directory);- }-- private void addDoc(IndexWriter writer, String name, String id) throws IOException- {- Document doc=new Document();- doc.add(new Field("name",name,Field.Store.YES,Field.Index.ANALYZED));- doc.add(new Field("id",id,Field.Store.YES,Field.Index.ANALYZED));- writer.addDocument(doc);- }--- //Tests that idf ranking is not favouring rare mis-spellings over a strong edit-distance match- public void testClosestEditDistanceMatchComesFirst() throws Throwable- {- FuzzyLikeThisQuery flt=new FuzzyLikeThisQuery(10,analyzer);- flt.addTerms("smith", "name", 0.3f, 1);- Query q=flt.rewrite(searcher.getIndexReader());- HashSet queryTerms=new HashSet();- q.extractTerms(queryTerms);- assertTrue("Should have variant smythe",queryTerms.contains(new Term("name","smythe")));- assertTrue("Should have variant smith",queryTerms.contains(new Term("name","smith")));- assertTrue("Should have variant smyth",queryTerms.contains(new Term("name","smyth")));- TopDocs topDocs = searcher.search(flt, 1);- ScoreDoc[] sd = topDocs.scoreDocs;- assertTrue("score docs must match 1 doc", (sd!=null)&&(sd.length>0));- Document doc=searcher.doc(sd[0].doc);- assertEquals("Should match most similar not most rare variant", "2",doc.get("id"));- }- //Test multiple input words are having variants produced- public void testMultiWord() throws Throwable- {- FuzzyLikeThisQuery flt=new FuzzyLikeThisQuery(10,analyzer);- flt.addTerms("jonathin smoth", "name", 0.3f, 1);- Query q=flt.rewrite(searcher.getIndexReader());- HashSet queryTerms=new HashSet();- q.extractTerms(queryTerms);- assertTrue("Should have variant jonathan",queryTerms.contains(new Term("name","jonathan")));- assertTrue("Should have variant smith",queryTerms.contains(new Term("name","smith")));- TopDocs topDocs = searcher.search(flt, 1);- ScoreDoc[] sd = topDocs.scoreDocs;- assertTrue("score docs must match 1 doc", (sd!=null)&&(sd.length>0));- Document doc=searcher.doc(sd[0].doc);- assertEquals("Should match most similar when using 2 words", "2",doc.get("id"));- }- //Test bug found when first query word does not match anything- public void testNoMatchFirstWordBug() throws Throwable- {- FuzzyLikeThisQuery flt=new FuzzyLikeThisQuery(10,analyzer);- flt.addTerms("fernando smith", "name", 0.3f, 1);- Query q=flt.rewrite(searcher.getIndexReader());- HashSet queryTerms=new HashSet();- q.extractTerms(queryTerms);- assertTrue("Should have variant smith",queryTerms.contains(new Term("name","smith")));- TopDocs topDocs = searcher.search(flt, 1);- ScoreDoc[] sd = topDocs.scoreDocs;- assertTrue("score docs must match 1 doc", (sd!=null)&&(sd.length>0));- Document doc=searcher.doc(sd[0].doc);- assertEquals("Should match most similar when using 2 words", "2",doc.get("id"));- }-}+package org.apache.lucene.search;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.HashSet;++import junit.framework.TestCase;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.WhitespaceAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.IndexWriter.MaxFieldLength;+import org.apache.lucene.store.RAMDirectory;++public class FuzzyLikeThisQueryTest extends TestCase+{+ private RAMDirectory directory;+ private IndexSearcher searcher;+ private Analyzer analyzer=new WhitespaceAnalyzer();++ protected void setUp() throws Exception+ {+ directory = new RAMDirectory();+ IndexWriter writer = new IndexWriter(directory, analyzer,true, MaxFieldLength.UNLIMITED);++ //Add series of docs with misspelt names+ addDoc(writer, "jonathon smythe","1");+ addDoc(writer, "jonathan smith","2");+ addDoc(writer, "johnathon smyth","3");+ addDoc(writer, "johnny smith","4" );+ addDoc(writer, "jonny smith","5" );+ addDoc(writer, "johnathon smythe","6");++ writer.close();+ searcher=new IndexSearcher(directory);+ }++ private void addDoc(IndexWriter writer, String name, String id) throws IOException+ {+ Document doc=new Document();+ doc.add(new Field("name",name,Field.Store.YES,Field.Index.ANALYZED));+ doc.add(new Field("id",id,Field.Store.YES,Field.Index.ANALYZED));+ writer.addDocument(doc);+ }+++ //Tests that idf ranking is not favouring rare mis-spellings over a strong edit-distance match+ public void testClosestEditDistanceMatchComesFirst() throws Throwable+ {+ FuzzyLikeThisQuery flt=new FuzzyLikeThisQuery(10,analyzer);+ flt.addTerms("smith", "name", 0.3f, 1);+ Query q=flt.rewrite(searcher.getIndexReader());+ HashSet queryTerms=new HashSet();+ q.extractTerms(queryTerms);+ assertTrue("Should have variant smythe",queryTerms.contains(new Term("name","smythe")));+ assertTrue("Should have variant smith",queryTerms.contains(new Term("name","smith")));+ assertTrue("Should have variant smyth",queryTerms.contains(new Term("name","smyth")));+ TopDocs topDocs = searcher.search(flt, 1);+ ScoreDoc[] sd = topDocs.scoreDocs;+ assertTrue("score docs must match 1 doc", (sd!=null)&&(sd.length>0));+ Document doc=searcher.doc(sd[0].doc);+ assertEquals("Should match most similar not most rare variant", "2",doc.get("id"));+ }+ //Test multiple input words are having variants produced+ public void testMultiWord() throws Throwable+ {+ FuzzyLikeThisQuery flt=new FuzzyLikeThisQuery(10,analyzer);+ flt.addTerms("jonathin smoth", "name", 0.3f, 1);+ Query q=flt.rewrite(searcher.getIndexReader());+ HashSet queryTerms=new HashSet();+ q.extractTerms(queryTerms);+ assertTrue("Should have variant jonathan",queryTerms.contains(new Term("name","jonathan")));+ assertTrue("Should have variant smith",queryTerms.contains(new Term("name","smith")));+ TopDocs topDocs = searcher.search(flt, 1);+ ScoreDoc[] sd = topDocs.scoreDocs;+ assertTrue("score docs must match 1 doc", (sd!=null)&&(sd.length>0));+ Document doc=searcher.doc(sd[0].doc);+ assertEquals("Should match most similar when using 2 words", "2",doc.get("id"));+ }+ //Test bug found when first query word does not match anything+ public void testNoMatchFirstWordBug() throws Throwable+ {+ FuzzyLikeThisQuery flt=new FuzzyLikeThisQuery(10,analyzer);+ flt.addTerms("fernando smith", "name", 0.3f, 1);+ Query q=flt.rewrite(searcher.getIndexReader());+ HashSet queryTerms=new HashSet();+ q.extractTerms(queryTerms);+ assertTrue("Should have variant smith",queryTerms.contains(new Term("name","smith")));+ TopDocs topDocs = searcher.search(flt, 1);+ ScoreDoc[] sd = topDocs.scoreDocs;+ assertTrue("score docs must match 1 doc", (sd!=null)&&(sd.length>0));+ Document doc=searcher.doc(sd[0].doc);+ assertEquals("Should match most similar when using 2 words", "2",doc.get("id"));+ }+}diff --git a/contrib/swing/src/java/org/apache/lucene/swing/models/ListSearcher.java b/contrib/swing/src/java/org/apache/lucene/swing/models/ListSearcher.javaindex 93eea77fa78..ac87a178148 100644--- a/contrib/swing/src/java/org/apache/lucene/swing/models/ListSearcher.java+++ b/contrib/swing/src/java/org/apache/lucene/swing/models/ListSearcher.java@@ -1,280 +1,280 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.store.RAMDirectory;-import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.WhitespaceAnalyzer;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.document.Fieldable;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.Hits;-import org.apache.lucene.queryParser.MultiFieldQueryParser;--import javax.swing.*;-import javax.swing.event.ListDataListener;-import javax.swing.event.ListDataEvent;-import java.util.ArrayList;--/**- * See table searcher explanation.- *- */-public class ListSearcher extends AbstractListModel {- private ListModel listModel;-- /**- * The reference links between the decorated ListModel- * and this list model based on search criteria- */- private ArrayList rowToModelIndex = new ArrayList();-- /**- * In memory lucene index- */- private RAMDirectory directory;-- /**- * Cached lucene analyzer- */- private Analyzer analyzer;-- /**- * Links between this list model and the decorated list model- * are maintained through links based on row number. This is a- * key constant to denote "row number" for indexing- */- private static final String ROW_NUMBER = "ROW_NUMBER";-- /**- * Since we only have one field, unlike lists with multiple- * fields -- we are just using a constant to denote field name.- * This is most likely unnecessary and should be removed at- * a later date- */- private static final String FIELD_NAME = "FIELD_NAME";-- /**- * Cache the current search String. Also used internally to- * key whether there is an active search running or not. i.e. if- * searchString is null, there is no active search.- */- private String searchString = null;- private ListDataListener listModelListener;-- public ListSearcher(ListModel newModel) {- analyzer = new WhitespaceAnalyzer();- setListModel(newModel);- listModelListener = new ListModelHandler();- newModel.addListDataListener(listModelListener);- clearSearchingState();- }-- private void setListModel(ListModel newModel) {- //remove listeners if there...- if (newModel != null) {- newModel.removeListDataListener(listModelListener);- }-- listModel = newModel;- if (listModel != null) {- listModel.addListDataListener(listModelListener);- }-- //recalculate the links between this list model and- //the inner list model since the decorated model just changed- reindex();-- // let all listeners know the list has changed- fireContentsChanged(this, 0, getSize());- }-- private void reindex() {- try {- // recreate the RAMDirectory- directory = new RAMDirectory();- IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);-- // iterate through all rows- for (int row=0; row < listModel.getSize(); row++){-- //for each row make a new document- Document document = new Document();- //add the row number of this row in the decorated list model- //this will allow us to retrive the results later- //and map this list model's row to a row in the decorated- //list model- document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));- //add the string representation of the row to the index- document.add(new Field(FIELD_NAME, String.valueOf(listModel.getElementAt(row)).toLowerCase(), Field.Store.YES, Field.Index.ANALYZED));- writer.addDocument(document);- }- writer.optimize();- writer.close();- } catch (Exception e){- e.printStackTrace();- }- }-- /**- * Run a new search.- *- * @param searchString Any valid lucene search string- */- public void search(String searchString){-- //if search string is null or empty, clear the search == search all- if (searchString == null || searchString.equals("")){- clearSearchingState();- fireContentsChanged(this, 0, getSize());- return;- }--- try {- //cache search String- this.searchString = searchString;-- //make a new index searcher with the in memory (RAM) index.- IndexSearcher is = new IndexSearcher(directory);-- //make an array of fields - one for each column- String[] fields = {FIELD_NAME};-- //build a query based on the fields, searchString and cached analyzer- //NOTE: This is an area for improvement since the MultiFieldQueryParser- // has some weirdness.- MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);- Query query =parser.parse(searchString);- //run the search- Hits hits = is.search(query);- //reset this list model with the new results- resetSearchResults(hits);- } catch (Exception e){- e.printStackTrace();- }-- //notify all listeners that the list has been changed- fireContentsChanged(this, 0, getSize());- }-- /**- *- * @param hits The new result set to set this list to.- */- private void resetSearchResults(Hits hits) {- try {- //clear our index mapping this list model rows to- //the decorated inner list model- rowToModelIndex.clear();- //iterate through the hits- //get the row number stored at the index- //that number is the row number of the decorated- //tabble model row that we are mapping to- for (int t=0; t<hits.length(); t++){- Document document = hits.doc(t);- Fieldable field = document.getField(ROW_NUMBER);- rowToModelIndex.add(new Integer(field.stringValue()));- }- } catch (Exception e){- e.printStackTrace();- }- }-- /**- * @return The current lucene analyzer- */- public Analyzer getAnalyzer() {- return analyzer;- }-- /**- * @param analyzer The new analyzer to use- */- public void setAnalyzer(Analyzer analyzer) {- this.analyzer = analyzer;- //reindex from the model with the new analyzer- reindex();-- //rerun the search if there is an active search- if (isSearching()){- search(searchString);- }- }-- private boolean isSearching() {- return searchString != null;- }-- private void clearSearchingState() {- searchString = null;- rowToModelIndex.clear();- for (int t=0; t<listModel.getSize(); t++){- rowToModelIndex.add(new Integer(t));- }- }-- private int getModelRow(int row){- return ((Integer) rowToModelIndex.get(row)).intValue();- }-- public int getSize() {- return (listModel == null) ? 0 : rowToModelIndex.size();- }-- public Object getElementAt(int index) {- return listModel.getElementAt(getModelRow(index));- }--- class ListModelHandler implements ListDataListener {-- public void contentsChanged(ListDataEvent e) {- somethingChanged();- }-- public void intervalAdded(ListDataEvent e) {- somethingChanged();- }-- public void intervalRemoved(ListDataEvent e) {- somethingChanged();- }-- private void somethingChanged(){- // If we're not searching, just pass the event along.- if (!isSearching()) {- clearSearchingState();- reindex();- fireContentsChanged(ListSearcher.this, 0, getSize());- return;- }-- // Something has happened to the data that may have invalidated the search.- reindex();- search(searchString);- fireContentsChanged(ListSearcher.this, 0, getSize());- return;- }-- }---}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.WhitespaceAnalyzer;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.Hits;+import org.apache.lucene.queryParser.MultiFieldQueryParser;++import javax.swing.*;+import javax.swing.event.ListDataListener;+import javax.swing.event.ListDataEvent;+import java.util.ArrayList;++/**+ * See table searcher explanation.+ *+ */+public class ListSearcher extends AbstractListModel {+ private ListModel listModel;++ /**+ * The reference links between the decorated ListModel+ * and this list model based on search criteria+ */+ private ArrayList rowToModelIndex = new ArrayList();++ /**+ * In memory lucene index+ */+ private RAMDirectory directory;++ /**+ * Cached lucene analyzer+ */+ private Analyzer analyzer;++ /**+ * Links between this list model and the decorated list model+ * are maintained through links based on row number. This is a+ * key constant to denote "row number" for indexing+ */+ private static final String ROW_NUMBER = "ROW_NUMBER";++ /**+ * Since we only have one field, unlike lists with multiple+ * fields -- we are just using a constant to denote field name.+ * This is most likely unnecessary and should be removed at+ * a later date+ */+ private static final String FIELD_NAME = "FIELD_NAME";++ /**+ * Cache the current search String. Also used internally to+ * key whether there is an active search running or not. i.e. if+ * searchString is null, there is no active search.+ */+ private String searchString = null;+ private ListDataListener listModelListener;++ public ListSearcher(ListModel newModel) {+ analyzer = new WhitespaceAnalyzer();+ setListModel(newModel);+ listModelListener = new ListModelHandler();+ newModel.addListDataListener(listModelListener);+ clearSearchingState();+ }++ private void setListModel(ListModel newModel) {+ //remove listeners if there...+ if (newModel != null) {+ newModel.removeListDataListener(listModelListener);+ }++ listModel = newModel;+ if (listModel != null) {+ listModel.addListDataListener(listModelListener);+ }++ //recalculate the links between this list model and+ //the inner list model since the decorated model just changed+ reindex();++ // let all listeners know the list has changed+ fireContentsChanged(this, 0, getSize());+ }++ private void reindex() {+ try {+ // recreate the RAMDirectory+ directory = new RAMDirectory();+ IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);++ // iterate through all rows+ for (int row=0; row < listModel.getSize(); row++){++ //for each row make a new document+ Document document = new Document();+ //add the row number of this row in the decorated list model+ //this will allow us to retrive the results later+ //and map this list model's row to a row in the decorated+ //list model+ document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));+ //add the string representation of the row to the index+ document.add(new Field(FIELD_NAME, String.valueOf(listModel.getElementAt(row)).toLowerCase(), Field.Store.YES, Field.Index.ANALYZED));+ writer.addDocument(document);+ }+ writer.optimize();+ writer.close();+ } catch (Exception e){+ e.printStackTrace();+ }+ }++ /**+ * Run a new search.+ *+ * @param searchString Any valid lucene search string+ */+ public void search(String searchString){++ //if search string is null or empty, clear the search == search all+ if (searchString == null || searchString.equals("")){+ clearSearchingState();+ fireContentsChanged(this, 0, getSize());+ return;+ }+++ try {+ //cache search String+ this.searchString = searchString;++ //make a new index searcher with the in memory (RAM) index.+ IndexSearcher is = new IndexSearcher(directory);++ //make an array of fields - one for each column+ String[] fields = {FIELD_NAME};++ //build a query based on the fields, searchString and cached analyzer+ //NOTE: This is an area for improvement since the MultiFieldQueryParser+ // has some weirdness.+ MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);+ Query query =parser.parse(searchString);+ //run the search+ Hits hits = is.search(query);+ //reset this list model with the new results+ resetSearchResults(hits);+ } catch (Exception e){+ e.printStackTrace();+ }++ //notify all listeners that the list has been changed+ fireContentsChanged(this, 0, getSize());+ }++ /**+ *+ * @param hits The new result set to set this list to.+ */+ private void resetSearchResults(Hits hits) {+ try {+ //clear our index mapping this list model rows to+ //the decorated inner list model+ rowToModelIndex.clear();+ //iterate through the hits+ //get the row number stored at the index+ //that number is the row number of the decorated+ //tabble model row that we are mapping to+ for (int t=0; t<hits.length(); t++){+ Document document = hits.doc(t);+ Fieldable field = document.getField(ROW_NUMBER);+ rowToModelIndex.add(new Integer(field.stringValue()));+ }+ } catch (Exception e){+ e.printStackTrace();+ }+ }++ /**+ * @return The current lucene analyzer+ */+ public Analyzer getAnalyzer() {+ return analyzer;+ }++ /**+ * @param analyzer The new analyzer to use+ */+ public void setAnalyzer(Analyzer analyzer) {+ this.analyzer = analyzer;+ //reindex from the model with the new analyzer+ reindex();++ //rerun the search if there is an active search+ if (isSearching()){+ search(searchString);+ }+ }++ private boolean isSearching() {+ return searchString != null;+ }++ private void clearSearchingState() {+ searchString = null;+ rowToModelIndex.clear();+ for (int t=0; t<listModel.getSize(); t++){+ rowToModelIndex.add(new Integer(t));+ }+ }++ private int getModelRow(int row){+ return ((Integer) rowToModelIndex.get(row)).intValue();+ }++ public int getSize() {+ return (listModel == null) ? 0 : rowToModelIndex.size();+ }++ public Object getElementAt(int index) {+ return listModel.getElementAt(getModelRow(index));+ }+++ class ListModelHandler implements ListDataListener {++ public void contentsChanged(ListDataEvent e) {+ somethingChanged();+ }++ public void intervalAdded(ListDataEvent e) {+ somethingChanged();+ }++ public void intervalRemoved(ListDataEvent e) {+ somethingChanged();+ }++ private void somethingChanged(){+ // If we're not searching, just pass the event along.+ if (!isSearching()) {+ clearSearchingState();+ reindex();+ fireContentsChanged(ListSearcher.this, 0, getSize());+ return;+ }++ // Something has happened to the data that may have invalidated the search.+ reindex();+ search(searchString);+ fireContentsChanged(ListSearcher.this, 0, getSize());+ return;+ }++ }+++}diff --git a/contrib/swing/src/java/org/apache/lucene/swing/models/TableSearcher.java b/contrib/swing/src/java/org/apache/lucene/swing/models/TableSearcher.javaindex f233e6e5a87..bd915bbe6ef 100644--- a/contrib/swing/src/java/org/apache/lucene/swing/models/TableSearcher.java+++ b/contrib/swing/src/java/org/apache/lucene/swing/models/TableSearcher.java@@ -1,351 +1,351 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.WhitespaceAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.document.Fieldable;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.queryParser.MultiFieldQueryParser;-import org.apache.lucene.search.Hits;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.store.RAMDirectory;--import javax.swing.event.TableModelEvent;-import javax.swing.event.TableModelListener;-import javax.swing.table.AbstractTableModel;-import javax.swing.table.TableModel;-import java.util.ArrayList;---/**- * This is a TableModel that encapsulates Lucene- * search logic within a TableModel implementation.- * It is implemented as a TableModel decorator,- * similar to the TableSorter demo from Sun that decorates- * a TableModel and provides sorting functionality. The benefit- * of this architecture is that you can decorate any TableModel- * implementation with this searching table model -- making it- * easy to add searching functionaliy to existing JTables -- or- * making new search capable table lucene.- *- * <p>This decorator works by holding a reference to a decorated ot inner- * TableModel. All data is stored within that table model, not this- * table model. Rather, this table model simply manages links to- * data in the inner table model according to the search. All methods on- * TableSearcher forward to the inner table model with subtle filtering- * or alteration according to the search criteria.- *- * <p>Using the table model:- *- * Pass the TableModel you want to decorate in at the constructor. When- * the TableModel initializes, it displays all search results. Call- * the search method with any valid Lucene search String and the data- * will be filtered by the search string. Users can always clear the search- * at any time by searching with an empty string. Additionally, you can- * add a button calling the clearSearch() method.- *- */-public class TableSearcher extends AbstractTableModel {-- /**- * The inner table model we are decorating- */- protected TableModel tableModel;-- /**- * This listener is used to register this class as a listener to- * the decorated table model for update events- */- private TableModelListener tableModelListener;-- /**- * these keeps reference to the decorated table model for data- * only rows that match the search criteria are linked- */- private ArrayList rowToModelIndex = new ArrayList();--- //Lucene stuff.-- /**- * In memory lucene index- */- private RAMDirectory directory;-- /**- * Cached lucene analyzer- */- private Analyzer analyzer;-- /**- * Links between this table model and the decorated table model- * are maintained through links based on row number. This is a- * key constant to denote "row number" for indexing- */- private static final String ROW_NUMBER = "ROW_NUMBER";-- /**- * Cache the current search String. Also used internally to- * key whether there is an active search running or not. i.e. if- * searchString is null, there is no active search.- */- private String searchString = null;-- /**- * @param tableModel The table model to decorate- */- public TableSearcher(TableModel tableModel) {- analyzer = new WhitespaceAnalyzer();- tableModelListener = new TableModelHandler();- setTableModel(tableModel);- tableModel.addTableModelListener(tableModelListener);- clearSearchingState();- }-- /**- *- * @return The inner table model this table model is decorating- */- public TableModel getTableModel() {- return tableModel;- }-- /**- * Set the table model used by this table model- * @param tableModel The new table model to decorate- */- public void setTableModel(TableModel tableModel) {-- //remove listeners if there...- if (this.tableModel != null) {- this.tableModel.removeTableModelListener(tableModelListener);- }-- this.tableModel = tableModel;- if (this.tableModel != null) {- this.tableModel.addTableModelListener(tableModelListener);- }-- //recalculate the links between this table model and- //the inner table model since the decorated model just changed- reindex();-- // let all listeners know the table has changed- fireTableStructureChanged();- }--- /**- * Reset the search results and links to the decorated (inner) table- * model from this table model.- */- private void reindex() {- try {- // recreate the RAMDirectory- directory = new RAMDirectory();- IndexWriter writer = new IndexWriter(directory, analyzer, true);-- // iterate through all rows- for (int row=0; row < tableModel.getRowCount(); row++){-- //for each row make a new document- Document document = new Document();- //add the row number of this row in the decorated table model- //this will allow us to retrive the results later- //and map this table model's row to a row in the decorated- //table model- document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));- //iterate through all columns- //index the value keyed by the column name- //NOTE: there could be a problem with using column names with spaces- for (int column=0; column < tableModel.getColumnCount(); column++){- String columnName = tableModel.getColumnName(column);- String columnValue = String.valueOf(tableModel.getValueAt(row, column)).toLowerCase();- document.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED));- }- writer.addDocument(document);- }- writer.optimize();- writer.close();- } catch (Exception e){- e.printStackTrace();- }- }-- /**- * @return The current lucene analyzer- */- public Analyzer getAnalyzer() {- return analyzer;- }-- /**- * @param analyzer The new analyzer to use- */- public void setAnalyzer(Analyzer analyzer) {- this.analyzer = analyzer;- //reindex from the model with the new analyzer- reindex();-- //rerun the search if there is an active search- if (isSearching()){- search(searchString);- }- }-- /**- * Run a new search.- *- * @param searchString Any valid lucene search string- */- public void search(String searchString){-- //if search string is null or empty, clear the search == search all- if (searchString == null || searchString.equals("")){- clearSearchingState();- fireTableDataChanged();- return;- }--- try {- //cache search String- this.searchString = searchString;-- //make a new index searcher with the in memory (RAM) index.- IndexSearcher is = new IndexSearcher(directory);-- //make an array of fields - one for each column- String[] fields = new String[tableModel.getColumnCount()];- for (int t=0; t<tableModel.getColumnCount(); t++){- fields[t]=tableModel.getColumnName(t);- }-- //build a query based on the fields, searchString and cached analyzer- //NOTE: This is an area for improvement since the MultiFieldQueryParser- // has some weirdness.- MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);- Query query = parser.parse(searchString);- //run the search- Hits hits = is.search(query);- //reset this table model with the new results- resetSearchResults(hits);- } catch (Exception e){- e.printStackTrace();- }-- //notify all listeners that the table has been changed- fireTableStructureChanged();- }-- /**- *- * @param hits The new result set to set this table to.- */- private void resetSearchResults(Hits hits) {- try {- //clear our index mapping this table model rows to- //the decorated inner table model- rowToModelIndex.clear();- //iterate through the hits- //get the row number stored at the index- //that number is the row number of the decorated- //tabble model row that we are mapping to- for (int t=0; t<hits.length(); t++){- Document document = hits.doc(t);- Fieldable field = document.getField(ROW_NUMBER);- rowToModelIndex.add(new Integer(field.stringValue()));- }- } catch (Exception e){- e.printStackTrace();- }- }-- private int getModelRow(int row){- return ((Integer) rowToModelIndex.get(row)).intValue();- }-- /**- * Clear the currently active search- * Resets the complete dataset of the decorated- * table model.- */- private void clearSearchingState(){- searchString = null;- rowToModelIndex.clear();- for (int t=0; t<tableModel.getRowCount(); t++){- rowToModelIndex.add(new Integer(t));- }- }-- // TableModel interface methods- public int getRowCount() {- return (tableModel == null) ? 0 : rowToModelIndex.size();- }-- public int getColumnCount() {- return (tableModel == null) ? 0 : tableModel.getColumnCount();- }-- public String getColumnName(int column) {- return tableModel.getColumnName(column);- }-- public Class getColumnClass(int column) {- return tableModel.getColumnClass(column);- }-- public boolean isCellEditable(int row, int column) {- return tableModel.isCellEditable(getModelRow(row), column);- }-- public Object getValueAt(int row, int column) {- return tableModel.getValueAt(getModelRow(row), column);- }-- public void setValueAt(Object aValue, int row, int column) {- tableModel.setValueAt(aValue, getModelRow(row), column);- }-- private boolean isSearching() {- return searchString != null;- }-- private class TableModelHandler implements TableModelListener {- public void tableChanged(TableModelEvent e) {- // If we're not searching, just pass the event along.- if (!isSearching()) {- clearSearchingState();- reindex();- fireTableChanged(e);- return;- }-- // Something has happened to the data that may have invalidated the search.- reindex();- search(searchString);- fireTableDataChanged();- return;- }-- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.WhitespaceAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.queryParser.MultiFieldQueryParser;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.store.RAMDirectory;++import javax.swing.event.TableModelEvent;+import javax.swing.event.TableModelListener;+import javax.swing.table.AbstractTableModel;+import javax.swing.table.TableModel;+import java.util.ArrayList;+++/**+ * This is a TableModel that encapsulates Lucene+ * search logic within a TableModel implementation.+ * It is implemented as a TableModel decorator,+ * similar to the TableSorter demo from Sun that decorates+ * a TableModel and provides sorting functionality. The benefit+ * of this architecture is that you can decorate any TableModel+ * implementation with this searching table model -- making it+ * easy to add searching functionaliy to existing JTables -- or+ * making new search capable table lucene.+ *+ * <p>This decorator works by holding a reference to a decorated ot inner+ * TableModel. All data is stored within that table model, not this+ * table model. Rather, this table model simply manages links to+ * data in the inner table model according to the search. All methods on+ * TableSearcher forward to the inner table model with subtle filtering+ * or alteration according to the search criteria.+ *+ * <p>Using the table model:+ *+ * Pass the TableModel you want to decorate in at the constructor. When+ * the TableModel initializes, it displays all search results. Call+ * the search method with any valid Lucene search String and the data+ * will be filtered by the search string. Users can always clear the search+ * at any time by searching with an empty string. Additionally, you can+ * add a button calling the clearSearch() method.+ *+ */+public class TableSearcher extends AbstractTableModel {++ /**+ * The inner table model we are decorating+ */+ protected TableModel tableModel;++ /**+ * This listener is used to register this class as a listener to+ * the decorated table model for update events+ */+ private TableModelListener tableModelListener;++ /**+ * these keeps reference to the decorated table model for data+ * only rows that match the search criteria are linked+ */+ private ArrayList rowToModelIndex = new ArrayList();+++ //Lucene stuff.++ /**+ * In memory lucene index+ */+ private RAMDirectory directory;++ /**+ * Cached lucene analyzer+ */+ private Analyzer analyzer;++ /**+ * Links between this table model and the decorated table model+ * are maintained through links based on row number. This is a+ * key constant to denote "row number" for indexing+ */+ private static final String ROW_NUMBER = "ROW_NUMBER";++ /**+ * Cache the current search String. Also used internally to+ * key whether there is an active search running or not. i.e. if+ * searchString is null, there is no active search.+ */+ private String searchString = null;++ /**+ * @param tableModel The table model to decorate+ */+ public TableSearcher(TableModel tableModel) {+ analyzer = new WhitespaceAnalyzer();+ tableModelListener = new TableModelHandler();+ setTableModel(tableModel);+ tableModel.addTableModelListener(tableModelListener);+ clearSearchingState();+ }++ /**+ *+ * @return The inner table model this table model is decorating+ */+ public TableModel getTableModel() {+ return tableModel;+ }++ /**+ * Set the table model used by this table model+ * @param tableModel The new table model to decorate+ */+ public void setTableModel(TableModel tableModel) {++ //remove listeners if there...+ if (this.tableModel != null) {+ this.tableModel.removeTableModelListener(tableModelListener);+ }++ this.tableModel = tableModel;+ if (this.tableModel != null) {+ this.tableModel.addTableModelListener(tableModelListener);+ }++ //recalculate the links between this table model and+ //the inner table model since the decorated model just changed+ reindex();++ // let all listeners know the table has changed+ fireTableStructureChanged();+ }+++ /**+ * Reset the search results and links to the decorated (inner) table+ * model from this table model.+ */+ private void reindex() {+ try {+ // recreate the RAMDirectory+ directory = new RAMDirectory();+ IndexWriter writer = new IndexWriter(directory, analyzer, true);++ // iterate through all rows+ for (int row=0; row < tableModel.getRowCount(); row++){++ //for each row make a new document+ Document document = new Document();+ //add the row number of this row in the decorated table model+ //this will allow us to retrive the results later+ //and map this table model's row to a row in the decorated+ //table model+ document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));+ //iterate through all columns+ //index the value keyed by the column name+ //NOTE: there could be a problem with using column names with spaces+ for (int column=0; column < tableModel.getColumnCount(); column++){+ String columnName = tableModel.getColumnName(column);+ String columnValue = String.valueOf(tableModel.getValueAt(row, column)).toLowerCase();+ document.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED));+ }+ writer.addDocument(document);+ }+ writer.optimize();+ writer.close();+ } catch (Exception e){+ e.printStackTrace();+ }+ }++ /**+ * @return The current lucene analyzer+ */+ public Analyzer getAnalyzer() {+ return analyzer;+ }++ /**+ * @param analyzer The new analyzer to use+ */+ public void setAnalyzer(Analyzer analyzer) {+ this.analyzer = analyzer;+ //reindex from the model with the new analyzer+ reindex();++ //rerun the search if there is an active search+ if (isSearching()){+ search(searchString);+ }+ }++ /**+ * Run a new search.+ *+ * @param searchString Any valid lucene search string+ */+ public void search(String searchString){++ //if search string is null or empty, clear the search == search all+ if (searchString == null || searchString.equals("")){+ clearSearchingState();+ fireTableDataChanged();+ return;+ }+++ try {+ //cache search String+ this.searchString = searchString;++ //make a new index searcher with the in memory (RAM) index.+ IndexSearcher is = new IndexSearcher(directory);++ //make an array of fields - one for each column+ String[] fields = new String[tableModel.getColumnCount()];+ for (int t=0; t<tableModel.getColumnCount(); t++){+ fields[t]=tableModel.getColumnName(t);+ }++ //build a query based on the fields, searchString and cached analyzer+ //NOTE: This is an area for improvement since the MultiFieldQueryParser+ // has some weirdness.+ MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);+ Query query = parser.parse(searchString);+ //run the search+ Hits hits = is.search(query);+ //reset this table model with the new results+ resetSearchResults(hits);+ } catch (Exception e){+ e.printStackTrace();+ }++ //notify all listeners that the table has been changed+ fireTableStructureChanged();+ }++ /**+ *+ * @param hits The new result set to set this table to.+ */+ private void resetSearchResults(Hits hits) {+ try {+ //clear our index mapping this table model rows to+ //the decorated inner table model+ rowToModelIndex.clear();+ //iterate through the hits+ //get the row number stored at the index+ //that number is the row number of the decorated+ //tabble model row that we are mapping to+ for (int t=0; t<hits.length(); t++){+ Document document = hits.doc(t);+ Fieldable field = document.getField(ROW_NUMBER);+ rowToModelIndex.add(new Integer(field.stringValue()));+ }+ } catch (Exception e){+ e.printStackTrace();+ }+ }++ private int getModelRow(int row){+ return ((Integer) rowToModelIndex.get(row)).intValue();+ }++ /**+ * Clear the currently active search+ * Resets the complete dataset of the decorated+ * table model.+ */+ private void clearSearchingState(){+ searchString = null;+ rowToModelIndex.clear();+ for (int t=0; t<tableModel.getRowCount(); t++){+ rowToModelIndex.add(new Integer(t));+ }+ }++ // TableModel interface methods+ public int getRowCount() {+ return (tableModel == null) ? 0 : rowToModelIndex.size();+ }++ public int getColumnCount() {+ return (tableModel == null) ? 0 : tableModel.getColumnCount();+ }++ public String getColumnName(int column) {+ return tableModel.getColumnName(column);+ }++ public Class getColumnClass(int column) {+ return tableModel.getColumnClass(column);+ }++ public boolean isCellEditable(int row, int column) {+ return tableModel.isCellEditable(getModelRow(row), column);+ }++ public Object getValueAt(int row, int column) {+ return tableModel.getValueAt(getModelRow(row), column);+ }++ public void setValueAt(Object aValue, int row, int column) {+ tableModel.setValueAt(aValue, getModelRow(row), column);+ }++ private boolean isSearching() {+ return searchString != null;+ }++ private class TableModelHandler implements TableModelListener {+ public void tableChanged(TableModelEvent e) {+ // If we're not searching, just pass the event along.+ if (!isSearching()) {+ clearSearchingState();+ reindex();+ fireTableChanged(e);+ return;+ }++ // Something has happened to the data that may have invalidated the search.+ reindex();+ search(searchString);+ fireTableDataChanged();+ return;+ }++ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/BaseListModel.java b/contrib/swing/src/test/org/apache/lucene/swing/models/BaseListModel.javaindex a7f183754aa..6eb16ff9f42 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/BaseListModel.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/BaseListModel.java@@ -1,55 +1,55 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.util.ArrayList;-import java.util.Iterator;-import java.util.List;--import javax.swing.AbstractListModel;---public class BaseListModel extends AbstractListModel {- private List data = new ArrayList();-- public BaseListModel(Iterator iterator) {- while (iterator.hasNext()) {- data.add(iterator.next());- }- }-- public int getSize() {- return data.size();- }-- public Object getElementAt(int index) {- return data.get(index);- }-- public void addRow(Object toAdd) {- data.add(toAdd);- fireContentsChanged(this, 0, getSize());- }-- public void removeRow(Object toRemove) {- data.remove(toRemove);- fireContentsChanged(this, 0, getSize());- }----}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.ArrayList;+import java.util.Iterator;+import java.util.List;++import javax.swing.AbstractListModel;+++public class BaseListModel extends AbstractListModel {+ private List data = new ArrayList();++ public BaseListModel(Iterator iterator) {+ while (iterator.hasNext()) {+ data.add(iterator.next());+ }+ }++ public int getSize() {+ return data.size();+ }++ public Object getElementAt(int index) {+ return data.get(index);+ }++ public void addRow(Object toAdd) {+ data.add(toAdd);+ fireContentsChanged(this, 0, getSize());+ }++ public void removeRow(Object toRemove) {+ data.remove(toRemove);+ fireContentsChanged(this, 0, getSize());+ }++++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/BaseTableModel.java b/contrib/swing/src/test/org/apache/lucene/swing/models/BaseTableModel.javaindex f42b896e8f3..6e87c5b43c1 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/BaseTableModel.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/BaseTableModel.java@@ -1,100 +1,100 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.util.ArrayList;-import java.util.Iterator;-import java.util.List;--import javax.swing.table.AbstractTableModel;---public class BaseTableModel extends AbstractTableModel {- private List columnNames = new ArrayList();- private List rows = new ArrayList();-- public BaseTableModel(Iterator data) {- columnNames.add("Name");- columnNames.add("Type");- columnNames.add("Phone");- columnNames.add("Street");- columnNames.add("City");- columnNames.add("State");- columnNames.add("Zip");-- while (data.hasNext()) {- Object nextRow = (Object) data.next();- rows.add(nextRow);- }- }-- public int getColumnCount() {- return columnNames.size();- }-- public int getRowCount() {- return rows.size();- }-- public void addRow(RestaurantInfo info){- rows.add(info);- fireTableDataChanged();- }-- public void removeRow(RestaurantInfo info){- rows.remove(info);- fireTableDataChanged();- }-- public boolean isCellEditable(int rowIndex, int columnIndex) {- return false;- }-- public Class getColumnClass(int columnIndex) {- return String.class;- }-- public Object getValueAt(int rowIndex, int columnIndex) {- RestaurantInfo restaurantInfo = (RestaurantInfo) rows.get(rowIndex);- if (columnIndex == 0){ // name- return restaurantInfo.getName();- } else if (columnIndex == 1){ // category- return restaurantInfo.getType();- } else if (columnIndex == 2){ // phone- return restaurantInfo.getPhone();- } else if (columnIndex == 3){ // street- return restaurantInfo.getStreet();- } else if (columnIndex == 4){ // city- return restaurantInfo.getCity();- } else if (columnIndex == 5){ // state- return restaurantInfo.getState();- } else if (columnIndex == 6){ // zip- return restaurantInfo.getZip();- } else {- return "";- }- }-- public void setValueAt(Object aValue, int rowIndex, int columnIndex) {- //no op- }-- public String getColumnName(int columnIndex) {- return columnNames.get(columnIndex).toString();- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.ArrayList;+import java.util.Iterator;+import java.util.List;++import javax.swing.table.AbstractTableModel;+++public class BaseTableModel extends AbstractTableModel {+ private List columnNames = new ArrayList();+ private List rows = new ArrayList();++ public BaseTableModel(Iterator data) {+ columnNames.add("Name");+ columnNames.add("Type");+ columnNames.add("Phone");+ columnNames.add("Street");+ columnNames.add("City");+ columnNames.add("State");+ columnNames.add("Zip");++ while (data.hasNext()) {+ Object nextRow = (Object) data.next();+ rows.add(nextRow);+ }+ }++ public int getColumnCount() {+ return columnNames.size();+ }++ public int getRowCount() {+ return rows.size();+ }++ public void addRow(RestaurantInfo info){+ rows.add(info);+ fireTableDataChanged();+ }++ public void removeRow(RestaurantInfo info){+ rows.remove(info);+ fireTableDataChanged();+ }++ public boolean isCellEditable(int rowIndex, int columnIndex) {+ return false;+ }++ public Class getColumnClass(int columnIndex) {+ return String.class;+ }++ public Object getValueAt(int rowIndex, int columnIndex) {+ RestaurantInfo restaurantInfo = (RestaurantInfo) rows.get(rowIndex);+ if (columnIndex == 0){ // name+ return restaurantInfo.getName();+ } else if (columnIndex == 1){ // category+ return restaurantInfo.getType();+ } else if (columnIndex == 2){ // phone+ return restaurantInfo.getPhone();+ } else if (columnIndex == 3){ // street+ return restaurantInfo.getStreet();+ } else if (columnIndex == 4){ // city+ return restaurantInfo.getCity();+ } else if (columnIndex == 5){ // state+ return restaurantInfo.getState();+ } else if (columnIndex == 6){ // zip+ return restaurantInfo.getZip();+ } else {+ return "";+ }+ }++ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {+ //no op+ }++ public String getColumnName(int columnIndex) {+ return columnNames.get(columnIndex).toString();+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/DataStore.java b/contrib/swing/src/test/org/apache/lucene/swing/models/DataStore.javaindex fc86345b213..8c19db7f1c4 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/DataStore.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/DataStore.java@@ -1,202 +1,202 @@-package org.apache.lucene.swing.models;---/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---import java.util.ArrayList;-import java.util.Collection;-import java.util.Iterator;---public class DataStore {-- private static final String ITALIAN_CATEGORY = "Italian";- private static final String CUBAN_CATEGORY = "Cuban";- private static final String STEAK_CATEGORY = "Steak";- private static int id = 0;-- static Collection restaurants = new ArrayList();- static RestaurantInfo pinos = new RestaurantInfo();- static RestaurantInfo canolis = new RestaurantInfo();- static RestaurantInfo picadillo = new RestaurantInfo();- static RestaurantInfo versailles = new RestaurantInfo();- static RestaurantInfo laCaretta = new RestaurantInfo();- static RestaurantInfo laCaretta2 = new RestaurantInfo();- static RestaurantInfo laCaretta3 = new RestaurantInfo();- static RestaurantInfo ranchaLuna = new RestaurantInfo();- static RestaurantInfo leMerais = new RestaurantInfo();- static RestaurantInfo chris = new RestaurantInfo();- static RestaurantInfo outback = new RestaurantInfo();- static RestaurantInfo outback2 = new RestaurantInfo();- static RestaurantInfo outback3 = new RestaurantInfo();- static RestaurantInfo outback4 = new RestaurantInfo();--- public static Iterator getRestaurants(){- return restaurants.iterator();- }-- static {- pinos.setId(getNextId());- pinos.setType(ITALIAN_CATEGORY);- pinos.setName("Pino's");- pinos.setPhone("(305) 111-2222");- pinos.setStreet("12115 105th Street ");- pinos.setCity("Miami");- pinos.setState("FL");- pinos.setZip("33176");- restaurants.add(pinos);-- canolis.setId(getNextId());- canolis.setType(ITALIAN_CATEGORY);- canolis.setName("Canoli's");- canolis.setPhone("(305) 234-5543");- canolis.setStreet("12123 85th Street ");- canolis.setCity("Miami");- canolis.setState("FL");- canolis.setZip("33176");- restaurants.add(canolis);-- picadillo.setId(getNextId());- picadillo.setType(CUBAN_CATEGORY);- picadillo.setName("Picadillo");- picadillo.setPhone("(305) 746-7865");- picadillo.setStreet("109 12th Street ");- picadillo.setCity("Miami");- picadillo.setState("FL");- picadillo.setZip("33176");- restaurants.add(picadillo);-- versailles.setId(getNextId());- versailles.setType(CUBAN_CATEGORY);- versailles.setName("Cafe Versailles");- versailles.setPhone("(305) 201-5438");- versailles.setStreet("312 8th Street ");- versailles.setCity("Miami");- versailles.setState("FL");- versailles.setZip("33176");- restaurants.add(versailles);-- laCaretta.setId(getNextId());- laCaretta.setType(CUBAN_CATEGORY);- laCaretta.setName("La Carretta");- laCaretta.setPhone("(305) 342-9876");- laCaretta.setStreet("348 8th Street ");- laCaretta.setCity("Miami");- laCaretta.setState("FL");- laCaretta.setZip("33176");- restaurants.add(laCaretta);-- laCaretta2.setId(getNextId());- laCaretta2.setType(CUBAN_CATEGORY);- laCaretta2.setName("La Carretta");- laCaretta2.setPhone("(305) 556-9876");- laCaretta2.setStreet("31224 23rd Street ");- laCaretta2.setCity("Miami");- laCaretta2.setState("FL");- laCaretta2.setZip("33176");- restaurants.add(laCaretta2);-- laCaretta3.setId(getNextId());- laCaretta3.setType(CUBAN_CATEGORY);- laCaretta3.setName("La Carretta");- laCaretta3.setPhone("(305) 682-9876");- laCaretta3.setStreet("23543 107th Street ");- laCaretta3.setCity("Miami");- laCaretta3.setState("FL");- laCaretta3.setZip("33176");- restaurants.add(laCaretta3);-- ranchaLuna.setId(getNextId());- ranchaLuna.setType(CUBAN_CATEGORY);- ranchaLuna.setName("Rancha Luna");- ranchaLuna.setPhone("(305) 777-4384");- ranchaLuna.setStreet("110 23rd Street ");- ranchaLuna.setCity("Miami");- ranchaLuna.setState("FL");- ranchaLuna.setZip("33176");- restaurants.add(ranchaLuna);-- leMerais.setId(getNextId());- leMerais.setType(STEAK_CATEGORY);- leMerais.setName("Le Merais");- leMerais.setPhone("(212) 654-9187");- leMerais.setStreet("11 West 46th Street");- leMerais.setCity("New York");- leMerais.setState("NY");- leMerais.setZip("10018");- restaurants.add(leMerais);-- chris.setId(getNextId());- chris.setType(STEAK_CATEGORY);- chris.setName("Ruth's Chris Seakhouse");- chris.setPhone("(305) 354-8885");- chris.setStreet("12365 203rd Street ");- chris.setCity("Miami");- chris.setState("FL");- chris.setZip("33176");- restaurants.add(chris);-- outback.setId(getNextId());- outback.setType(STEAK_CATEGORY);- outback.setName("Outback");- outback.setPhone("(305) 244-7623");- outback.setStreet("348 136th Street ");- outback.setCity("Miami");- outback.setState("FL");- outback.setZip("33176");- restaurants.add(outback);-- outback2.setId(getNextId());- outback2.setType(STEAK_CATEGORY);- outback2.setName("Outback");- outback2.setPhone("(305) 533-6522");- outback2.setStreet("21 207th Street ");- outback2.setCity("Miami");- outback2.setState("FL");- outback2.setZip("33176");- restaurants.add(outback2);-- outback3.setId(getNextId());- outback3.setType(STEAK_CATEGORY);- outback3.setName("Outback");- outback3.setPhone("(305) 244-7623");- outback3.setStreet("10117 107th Street ");- outback3.setCity("Miami");- outback3.setState("FL");- outback3.setZip("33176");- restaurants.add(outback3);-- outback4.setId(getNextId());- outback4.setType(STEAK_CATEGORY);- outback4.setName("Outback");- outback4.setPhone("(954) 221-3312");- outback4.setStreet("10 11th Street ");- outback4.setCity("Aventura");- outback4.setState("FL");- outback4.setZip("32154");- restaurants.add(outback4);-- }-- private static int getNextId(){- id++;- return id;- }--}+package org.apache.lucene.swing.models;+++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++import java.util.ArrayList;+import java.util.Collection;+import java.util.Iterator;+++public class DataStore {++ private static final String ITALIAN_CATEGORY = "Italian";+ private static final String CUBAN_CATEGORY = "Cuban";+ private static final String STEAK_CATEGORY = "Steak";+ private static int id = 0;++ static Collection restaurants = new ArrayList();+ static RestaurantInfo pinos = new RestaurantInfo();+ static RestaurantInfo canolis = new RestaurantInfo();+ static RestaurantInfo picadillo = new RestaurantInfo();+ static RestaurantInfo versailles = new RestaurantInfo();+ static RestaurantInfo laCaretta = new RestaurantInfo();+ static RestaurantInfo laCaretta2 = new RestaurantInfo();+ static RestaurantInfo laCaretta3 = new RestaurantInfo();+ static RestaurantInfo ranchaLuna = new RestaurantInfo();+ static RestaurantInfo leMerais = new RestaurantInfo();+ static RestaurantInfo chris = new RestaurantInfo();+ static RestaurantInfo outback = new RestaurantInfo();+ static RestaurantInfo outback2 = new RestaurantInfo();+ static RestaurantInfo outback3 = new RestaurantInfo();+ static RestaurantInfo outback4 = new RestaurantInfo();+++ public static Iterator getRestaurants(){+ return restaurants.iterator();+ }++ static {+ pinos.setId(getNextId());+ pinos.setType(ITALIAN_CATEGORY);+ pinos.setName("Pino's");+ pinos.setPhone("(305) 111-2222");+ pinos.setStreet("12115 105th Street ");+ pinos.setCity("Miami");+ pinos.setState("FL");+ pinos.setZip("33176");+ restaurants.add(pinos);++ canolis.setId(getNextId());+ canolis.setType(ITALIAN_CATEGORY);+ canolis.setName("Canoli's");+ canolis.setPhone("(305) 234-5543");+ canolis.setStreet("12123 85th Street ");+ canolis.setCity("Miami");+ canolis.setState("FL");+ canolis.setZip("33176");+ restaurants.add(canolis);++ picadillo.setId(getNextId());+ picadillo.setType(CUBAN_CATEGORY);+ picadillo.setName("Picadillo");+ picadillo.setPhone("(305) 746-7865");+ picadillo.setStreet("109 12th Street ");+ picadillo.setCity("Miami");+ picadillo.setState("FL");+ picadillo.setZip("33176");+ restaurants.add(picadillo);++ versailles.setId(getNextId());+ versailles.setType(CUBAN_CATEGORY);+ versailles.setName("Cafe Versailles");+ versailles.setPhone("(305) 201-5438");+ versailles.setStreet("312 8th Street ");+ versailles.setCity("Miami");+ versailles.setState("FL");+ versailles.setZip("33176");+ restaurants.add(versailles);++ laCaretta.setId(getNextId());+ laCaretta.setType(CUBAN_CATEGORY);+ laCaretta.setName("La Carretta");+ laCaretta.setPhone("(305) 342-9876");+ laCaretta.setStreet("348 8th Street ");+ laCaretta.setCity("Miami");+ laCaretta.setState("FL");+ laCaretta.setZip("33176");+ restaurants.add(laCaretta);++ laCaretta2.setId(getNextId());+ laCaretta2.setType(CUBAN_CATEGORY);+ laCaretta2.setName("La Carretta");+ laCaretta2.setPhone("(305) 556-9876");+ laCaretta2.setStreet("31224 23rd Street ");+ laCaretta2.setCity("Miami");+ laCaretta2.setState("FL");+ laCaretta2.setZip("33176");+ restaurants.add(laCaretta2);++ laCaretta3.setId(getNextId());+ laCaretta3.setType(CUBAN_CATEGORY);+ laCaretta3.setName("La Carretta");+ laCaretta3.setPhone("(305) 682-9876");+ laCaretta3.setStreet("23543 107th Street ");+ laCaretta3.setCity("Miami");+ laCaretta3.setState("FL");+ laCaretta3.setZip("33176");+ restaurants.add(laCaretta3);++ ranchaLuna.setId(getNextId());+ ranchaLuna.setType(CUBAN_CATEGORY);+ ranchaLuna.setName("Rancha Luna");+ ranchaLuna.setPhone("(305) 777-4384");+ ranchaLuna.setStreet("110 23rd Street ");+ ranchaLuna.setCity("Miami");+ ranchaLuna.setState("FL");+ ranchaLuna.setZip("33176");+ restaurants.add(ranchaLuna);++ leMerais.setId(getNextId());+ leMerais.setType(STEAK_CATEGORY);+ leMerais.setName("Le Merais");+ leMerais.setPhone("(212) 654-9187");+ leMerais.setStreet("11 West 46th Street");+ leMerais.setCity("New York");+ leMerais.setState("NY");+ leMerais.setZip("10018");+ restaurants.add(leMerais);++ chris.setId(getNextId());+ chris.setType(STEAK_CATEGORY);+ chris.setName("Ruth's Chris Seakhouse");+ chris.setPhone("(305) 354-8885");+ chris.setStreet("12365 203rd Street ");+ chris.setCity("Miami");+ chris.setState("FL");+ chris.setZip("33176");+ restaurants.add(chris);++ outback.setId(getNextId());+ outback.setType(STEAK_CATEGORY);+ outback.setName("Outback");+ outback.setPhone("(305) 244-7623");+ outback.setStreet("348 136th Street ");+ outback.setCity("Miami");+ outback.setState("FL");+ outback.setZip("33176");+ restaurants.add(outback);++ outback2.setId(getNextId());+ outback2.setType(STEAK_CATEGORY);+ outback2.setName("Outback");+ outback2.setPhone("(305) 533-6522");+ outback2.setStreet("21 207th Street ");+ outback2.setCity("Miami");+ outback2.setState("FL");+ outback2.setZip("33176");+ restaurants.add(outback2);++ outback3.setId(getNextId());+ outback3.setType(STEAK_CATEGORY);+ outback3.setName("Outback");+ outback3.setPhone("(305) 244-7623");+ outback3.setStreet("10117 107th Street ");+ outback3.setCity("Miami");+ outback3.setState("FL");+ outback3.setZip("33176");+ restaurants.add(outback3);++ outback4.setId(getNextId());+ outback4.setType(STEAK_CATEGORY);+ outback4.setName("Outback");+ outback4.setPhone("(954) 221-3312");+ outback4.setStreet("10 11th Street ");+ outback4.setCity("Aventura");+ outback4.setState("FL");+ outback4.setZip("32154");+ restaurants.add(outback4);++ }++ private static int getNextId(){+ id++;+ return id;+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/ListSearcherSimulator.java b/contrib/swing/src/test/org/apache/lucene/swing/models/ListSearcherSimulator.javaindex 5ccd6db6a58..25531ee7dc1 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/ListSearcherSimulator.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/ListSearcherSimulator.java@@ -1,88 +1,88 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.awt.BorderLayout;--import javax.swing.JFrame;-import javax.swing.JLabel;-import javax.swing.JList;-import javax.swing.JPanel;-import javax.swing.JScrollPane;-import javax.swing.JTextField;-import javax.swing.event.DocumentEvent;-import javax.swing.event.DocumentListener;---public class ListSearcherSimulator {-- public ListSearcherSimulator() {- JFrame frame = new JFrame();- frame.setBounds(200,200, 400,250);-- JList list = new JList();- JScrollPane scrollPane = new JScrollPane(list);-- final BaseListModel listModel = new BaseListModel(DataStore.getRestaurants());- final ListSearcher listSearcher = new ListSearcher(listModel);-- list.setModel(listSearcher);-- final JTextField searchField = new JTextField();- searchField.getDocument().addDocumentListener(- new DocumentListener(){- public void changedUpdate(DocumentEvent e) {- listSearcher.search(searchField.getText().trim().toLowerCase());- }-- public void insertUpdate(DocumentEvent e) {- listSearcher.search(searchField.getText().trim().toLowerCase());- }-- public void removeUpdate(DocumentEvent e) {- listSearcher.search(searchField.getText().trim().toLowerCase());- }- }- );-- frame.getContentPane().setLayout(new BorderLayout());- frame.getContentPane().add(scrollPane, BorderLayout.CENTER);-- JPanel searchPanel = new JPanel();- searchPanel.setLayout(new BorderLayout(10,10));- searchPanel.add(searchField, BorderLayout.CENTER);- searchPanel.add(new JLabel("Search: "), BorderLayout.WEST);-- JPanel topPanel = new JPanel(new BorderLayout());- topPanel.add(searchPanel, BorderLayout.CENTER);- topPanel.add(new JPanel(), BorderLayout.EAST);- topPanel.add(new JPanel(), BorderLayout.WEST);- topPanel.add(new JPanel(), BorderLayout.NORTH);- topPanel.add(new JPanel(), BorderLayout.SOUTH);-- frame.getContentPane().add(topPanel, BorderLayout.NORTH);-- frame.setTitle("Lucene powered table searching");- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);- frame.show();- }-- public static void main(String[] args) {- new ListSearcherSimulator();- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.awt.BorderLayout;++import javax.swing.JFrame;+import javax.swing.JLabel;+import javax.swing.JList;+import javax.swing.JPanel;+import javax.swing.JScrollPane;+import javax.swing.JTextField;+import javax.swing.event.DocumentEvent;+import javax.swing.event.DocumentListener;+++public class ListSearcherSimulator {++ public ListSearcherSimulator() {+ JFrame frame = new JFrame();+ frame.setBounds(200,200, 400,250);++ JList list = new JList();+ JScrollPane scrollPane = new JScrollPane(list);++ final BaseListModel listModel = new BaseListModel(DataStore.getRestaurants());+ final ListSearcher listSearcher = new ListSearcher(listModel);++ list.setModel(listSearcher);++ final JTextField searchField = new JTextField();+ searchField.getDocument().addDocumentListener(+ new DocumentListener(){+ public void changedUpdate(DocumentEvent e) {+ listSearcher.search(searchField.getText().trim().toLowerCase());+ }++ public void insertUpdate(DocumentEvent e) {+ listSearcher.search(searchField.getText().trim().toLowerCase());+ }++ public void removeUpdate(DocumentEvent e) {+ listSearcher.search(searchField.getText().trim().toLowerCase());+ }+ }+ );++ frame.getContentPane().setLayout(new BorderLayout());+ frame.getContentPane().add(scrollPane, BorderLayout.CENTER);++ JPanel searchPanel = new JPanel();+ searchPanel.setLayout(new BorderLayout(10,10));+ searchPanel.add(searchField, BorderLayout.CENTER);+ searchPanel.add(new JLabel("Search: "), BorderLayout.WEST);++ JPanel topPanel = new JPanel(new BorderLayout());+ topPanel.add(searchPanel, BorderLayout.CENTER);+ topPanel.add(new JPanel(), BorderLayout.EAST);+ topPanel.add(new JPanel(), BorderLayout.WEST);+ topPanel.add(new JPanel(), BorderLayout.NORTH);+ topPanel.add(new JPanel(), BorderLayout.SOUTH);++ frame.getContentPane().add(topPanel, BorderLayout.NORTH);++ frame.setTitle("Lucene powered table searching");+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);+ frame.show();+ }++ public static void main(String[] args) {+ new ListSearcherSimulator();+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/RestaurantInfo.java b/contrib/swing/src/test/org/apache/lucene/swing/models/RestaurantInfo.javaindex 4e19afe9e9a..6dad564d34d 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/RestaurantInfo.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/RestaurantInfo.java@@ -1,100 +1,100 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---public class RestaurantInfo {- private int id;- private String name;-- private String type;-- private String phone;- private String street;- private String city;- private String state;- private String zip;-- public int getId() {- return id;- }-- public void setId(int id) {- this.id = id;- }-- public String getName() {- return name;- }-- public void setName(String name) {- this.name = name;- }-- public String getPhone() {- return phone;- }-- public void setPhone(String phone) {- this.phone = phone;- }-- public String getStreet() {- return street;- }-- public void setStreet(String street) {- this.street = street;- }-- public String getCity() {- return city;- }-- public void setCity(String city) {- this.city = city;- }-- public String getState() {- return state;- }-- public void setState(String state) {- this.state = state;- }-- public String getZip() {- return zip;- }-- public void setZip(String zip) {- this.zip = zip;- }-- public String getType() {- return type;- }-- public void setType(String type) {- this.type = type;- }-- public String toString() {- return getName() + " - " + getPhone();- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++public class RestaurantInfo {+ private int id;+ private String name;++ private String type;++ private String phone;+ private String street;+ private String city;+ private String state;+ private String zip;++ public int getId() {+ return id;+ }++ public void setId(int id) {+ this.id = id;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getPhone() {+ return phone;+ }++ public void setPhone(String phone) {+ this.phone = phone;+ }++ public String getStreet() {+ return street;+ }++ public void setStreet(String street) {+ this.street = street;+ }++ public String getCity() {+ return city;+ }++ public void setCity(String city) {+ this.city = city;+ }++ public String getState() {+ return state;+ }++ public void setState(String state) {+ this.state = state;+ }++ public String getZip() {+ return zip;+ }++ public void setZip(String zip) {+ this.zip = zip;+ }++ public String getType() {+ return type;+ }++ public void setType(String type) {+ this.type = type;+ }++ public String toString() {+ return getName() + " - " + getPhone();+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TableSearcherSimulator.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TableSearcherSimulator.javaindex 5bfe6259e18..e170a3fb478 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TableSearcherSimulator.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TableSearcherSimulator.java@@ -1,81 +1,81 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import javax.swing.*;-import java.awt.*;-import java.awt.event.ActionListener;-import java.awt.event.ActionEvent;---public class TableSearcherSimulator {-- public TableSearcherSimulator() {- JFrame frame = new JFrame();- frame.setBounds(200,200, 400,250);-- JTable table = new JTable();- final BaseTableModel tableModel = new BaseTableModel(DataStore.getRestaurants());- final TableSearcher searchTableModel = new TableSearcher(tableModel);-- table.setModel(searchTableModel);- JScrollPane scrollPane = new JScrollPane(table);-- final JTextField searchField = new JTextField();- JButton searchButton = new JButton("Go");-- ActionListener searchListener = new ActionListener() {- public void actionPerformed(ActionEvent e) {- searchTableModel.search(searchField.getText().trim().toLowerCase());- searchField.requestFocus();- }- };-- searchButton.addActionListener(searchListener);- searchField.addActionListener(searchListener);---- frame.getContentPane().setLayout(new BorderLayout());- frame.getContentPane().add(scrollPane, BorderLayout.CENTER);-- JPanel searchPanel = new JPanel();- searchPanel.setLayout(new BorderLayout(10,10));- searchPanel.add(searchField, BorderLayout.CENTER);- searchPanel.add(searchButton, BorderLayout.EAST);-- JPanel topPanel = new JPanel(new BorderLayout());- topPanel.add(searchPanel, BorderLayout.CENTER);- topPanel.add(new JPanel(), BorderLayout.EAST);- topPanel.add(new JPanel(), BorderLayout.WEST);- topPanel.add(new JPanel(), BorderLayout.NORTH);- topPanel.add(new JPanel(), BorderLayout.SOUTH);-- frame.getContentPane().add(topPanel, BorderLayout.NORTH);-- frame.setTitle("Lucene powered table searching");- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);- frame.show();-- }--- public static void main(String[] args) {- new TableSearcherSimulator();- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import javax.swing.*;+import java.awt.*;+import java.awt.event.ActionListener;+import java.awt.event.ActionEvent;+++public class TableSearcherSimulator {++ public TableSearcherSimulator() {+ JFrame frame = new JFrame();+ frame.setBounds(200,200, 400,250);++ JTable table = new JTable();+ final BaseTableModel tableModel = new BaseTableModel(DataStore.getRestaurants());+ final TableSearcher searchTableModel = new TableSearcher(tableModel);++ table.setModel(searchTableModel);+ JScrollPane scrollPane = new JScrollPane(table);++ final JTextField searchField = new JTextField();+ JButton searchButton = new JButton("Go");++ ActionListener searchListener = new ActionListener() {+ public void actionPerformed(ActionEvent e) {+ searchTableModel.search(searchField.getText().trim().toLowerCase());+ searchField.requestFocus();+ }+ };++ searchButton.addActionListener(searchListener);+ searchField.addActionListener(searchListener);++++ frame.getContentPane().setLayout(new BorderLayout());+ frame.getContentPane().add(scrollPane, BorderLayout.CENTER);++ JPanel searchPanel = new JPanel();+ searchPanel.setLayout(new BorderLayout(10,10));+ searchPanel.add(searchField, BorderLayout.CENTER);+ searchPanel.add(searchButton, BorderLayout.EAST);++ JPanel topPanel = new JPanel(new BorderLayout());+ topPanel.add(searchPanel, BorderLayout.CENTER);+ topPanel.add(new JPanel(), BorderLayout.EAST);+ topPanel.add(new JPanel(), BorderLayout.WEST);+ topPanel.add(new JPanel(), BorderLayout.NORTH);+ topPanel.add(new JPanel(), BorderLayout.SOUTH);++ frame.getContentPane().add(topPanel, BorderLayout.NORTH);++ frame.setTitle("Lucene powered table searching");+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);+ frame.show();++ }+++ public static void main(String[] args) {+ new TableSearcherSimulator();+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicList.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicList.javaindex b628c8d9446..ac19c21db7a 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicList.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicList.java@@ -1,52 +1,52 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.util.ArrayList;-import java.util.List;--import javax.swing.ListModel;--import junit.framework.TestCase;--/**- **/-public class TestBasicList extends TestCase {- private ListModel baseListModel;- private ListSearcher listSearcher;- private List list;-- protected void setUp() throws Exception {- list = new ArrayList();- list.add(DataStore.canolis);- list.add(DataStore.chris);-- baseListModel = new BaseListModel(list.iterator());- listSearcher = new ListSearcher(baseListModel);- }--- public void testRows(){- assertEquals(list.size(), listSearcher.getSize());- }-- public void testValueAt(){- assertEquals(baseListModel.getElementAt(0), listSearcher.getElementAt(0));- assertNotSame(baseListModel.getElementAt(1), listSearcher.getElementAt(0));- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.ArrayList;+import java.util.List;++import javax.swing.ListModel;++import junit.framework.TestCase;++/**+ **/+public class TestBasicList extends TestCase {+ private ListModel baseListModel;+ private ListSearcher listSearcher;+ private List list;++ protected void setUp() throws Exception {+ list = new ArrayList();+ list.add(DataStore.canolis);+ list.add(DataStore.chris);++ baseListModel = new BaseListModel(list.iterator());+ listSearcher = new ListSearcher(baseListModel);+ }+++ public void testRows(){+ assertEquals(list.size(), listSearcher.getSize());+ }++ public void testValueAt(){+ assertEquals(baseListModel.getElementAt(0), listSearcher.getElementAt(0));+ assertNotSame(baseListModel.getElementAt(1), listSearcher.getElementAt(0));+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicTable.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicTable.javaindex 57a498eac28..603bb84151a 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicTable.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TestBasicTable.java@@ -1,58 +1,58 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.util.ArrayList;-import java.util.List;--import javax.swing.table.TableModel;--import junit.framework.TestCase;---public class TestBasicTable extends TestCase {- private TableModel baseTableModel;- private TableSearcher tableSearcher;- private List list;-- protected void setUp() throws Exception {- list = new ArrayList();- list.add(DataStore.canolis);- list.add(DataStore.chris);-- baseTableModel = new BaseTableModel(list.iterator());- tableSearcher = new TableSearcher(baseTableModel);- }-- public void testColumns(){-- assertEquals(baseTableModel.getColumnCount(), tableSearcher.getColumnCount());- assertEquals(baseTableModel.getColumnName(0), tableSearcher.getColumnName(0));- assertNotSame(baseTableModel.getColumnName(0), tableSearcher.getColumnName(1));- assertEquals(baseTableModel.getColumnClass(0), tableSearcher.getColumnClass(0));- }-- public void testRows(){- assertEquals(list.size(), tableSearcher.getRowCount());- }-- public void testValueAt(){- assertEquals(baseTableModel.getValueAt(0,0), tableSearcher.getValueAt(0,0));- assertEquals(baseTableModel.getValueAt(0,3), tableSearcher.getValueAt(0,3));- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.ArrayList;+import java.util.List;++import javax.swing.table.TableModel;++import junit.framework.TestCase;+++public class TestBasicTable extends TestCase {+ private TableModel baseTableModel;+ private TableSearcher tableSearcher;+ private List list;++ protected void setUp() throws Exception {+ list = new ArrayList();+ list.add(DataStore.canolis);+ list.add(DataStore.chris);++ baseTableModel = new BaseTableModel(list.iterator());+ tableSearcher = new TableSearcher(baseTableModel);+ }++ public void testColumns(){++ assertEquals(baseTableModel.getColumnCount(), tableSearcher.getColumnCount());+ assertEquals(baseTableModel.getColumnName(0), tableSearcher.getColumnName(0));+ assertNotSame(baseTableModel.getColumnName(0), tableSearcher.getColumnName(1));+ assertEquals(baseTableModel.getColumnClass(0), tableSearcher.getColumnClass(0));+ }++ public void testRows(){+ assertEquals(list.size(), tableSearcher.getRowCount());+ }++ public void testValueAt(){+ assertEquals(baseTableModel.getValueAt(0,0), tableSearcher.getValueAt(0,0));+ assertEquals(baseTableModel.getValueAt(0,3), tableSearcher.getValueAt(0,3));+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingList.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingList.javaindex 3305a0bf2bc..6f74a20cd99 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingList.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingList.java@@ -1,45 +1,45 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import javax.swing.ListModel;--import junit.framework.TestCase;----public class TestSearchingList extends TestCase {- private ListModel baseListModel;- private ListSearcher listSearcher;-- protected void setUp() throws Exception {- baseListModel = new BaseListModel(DataStore.getRestaurants());- listSearcher = new ListSearcher(baseListModel);- }-- public void testSearch(){- //make sure data is there- assertEquals(baseListModel.getSize(), listSearcher.getSize());- //search for pino's- listSearcher.search("pino's");- assertEquals(1, listSearcher.getSize());- //clear search and check that- listSearcher.search(null);- assertEquals(baseListModel.getSize(), listSearcher.getSize());- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import javax.swing.ListModel;++import junit.framework.TestCase;++++public class TestSearchingList extends TestCase {+ private ListModel baseListModel;+ private ListSearcher listSearcher;++ protected void setUp() throws Exception {+ baseListModel = new BaseListModel(DataStore.getRestaurants());+ listSearcher = new ListSearcher(baseListModel);+ }++ public void testSearch(){+ //make sure data is there+ assertEquals(baseListModel.getSize(), listSearcher.getSize());+ //search for pino's+ listSearcher.search("pino's");+ assertEquals(1, listSearcher.getSize());+ //clear search and check that+ listSearcher.search(null);+ assertEquals(baseListModel.getSize(), listSearcher.getSize());+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingTable.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingTable.javaindex a6ec1fa0ac8..6f9108034f5 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingTable.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TestSearchingTable.java@@ -1,44 +1,44 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import junit.framework.TestCase;--import javax.swing.table.TableModel;---public class TestSearchingTable extends TestCase {- private TableModel baseTableModel;- private TableSearcher tableSearcher;-- protected void setUp() throws Exception {- baseTableModel = new BaseTableModel(DataStore.getRestaurants());- tableSearcher = new TableSearcher(baseTableModel);- }-- public void testSearch(){- //make sure data is there- assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());- //search for pino's- tableSearcher.search("pino's");- assertEquals(1, tableSearcher.getRowCount());- //clear search and check that- tableSearcher.search(null);- assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());- }--}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import junit.framework.TestCase;++import javax.swing.table.TableModel;+++public class TestSearchingTable extends TestCase {+ private TableModel baseTableModel;+ private TableSearcher tableSearcher;++ protected void setUp() throws Exception {+ baseTableModel = new BaseTableModel(DataStore.getRestaurants());+ tableSearcher = new TableSearcher(baseTableModel);+ }++ public void testSearch(){+ //make sure data is there+ assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());+ //search for pino's+ tableSearcher.search("pino's");+ assertEquals(1, tableSearcher.getRowCount());+ //clear search and check that+ tableSearcher.search(null);+ assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());+ }++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingList.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingList.javaindex 0292f5ae0db..7334f10e76c 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingList.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingList.java@@ -1,77 +1,77 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import junit.framework.TestCase;---public class TestUpdatingList extends TestCase {- private BaseListModel baseListModel;- private ListSearcher listSearcher;-- RestaurantInfo infoToAdd1, infoToAdd2;-- protected void setUp() throws Exception {- baseListModel = new BaseListModel(DataStore.getRestaurants());- listSearcher = new ListSearcher(baseListModel);-- infoToAdd1 = new RestaurantInfo();- infoToAdd1.setName("Pino's");-- infoToAdd2 = new RestaurantInfo();- infoToAdd2.setName("Pino's");- infoToAdd2.setType("Italian");- }-- public void testAddWithoutSearch(){- assertEquals(baseListModel.getSize(), listSearcher.getSize());- int count = listSearcher.getSize();- baseListModel.addRow(infoToAdd1);- count++;- assertEquals(count, listSearcher.getSize());- }-- public void testRemoveWithoutSearch(){- assertEquals(baseListModel.getSize(), listSearcher.getSize());- baseListModel.addRow(infoToAdd1);- int count = listSearcher.getSize();- baseListModel.removeRow(infoToAdd1);- count--;- assertEquals(count, listSearcher.getSize());- }-- public void testAddWithSearch(){- assertEquals(baseListModel.getSize(), listSearcher.getSize());- listSearcher.search("pino's");- int count = listSearcher.getSize();- baseListModel.addRow(infoToAdd2);- count++;- assertEquals(count, listSearcher.getSize());- }-- public void testRemoveWithSearch(){- assertEquals(baseListModel.getSize(), listSearcher.getSize());- baseListModel.addRow(infoToAdd1);- listSearcher.search("pino's");- int count = listSearcher.getSize();- baseListModel.removeRow(infoToAdd1);- count--;- assertEquals(count, listSearcher.getSize());- }---}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import junit.framework.TestCase;+++public class TestUpdatingList extends TestCase {+ private BaseListModel baseListModel;+ private ListSearcher listSearcher;++ RestaurantInfo infoToAdd1, infoToAdd2;++ protected void setUp() throws Exception {+ baseListModel = new BaseListModel(DataStore.getRestaurants());+ listSearcher = new ListSearcher(baseListModel);++ infoToAdd1 = new RestaurantInfo();+ infoToAdd1.setName("Pino's");++ infoToAdd2 = new RestaurantInfo();+ infoToAdd2.setName("Pino's");+ infoToAdd2.setType("Italian");+ }++ public void testAddWithoutSearch(){+ assertEquals(baseListModel.getSize(), listSearcher.getSize());+ int count = listSearcher.getSize();+ baseListModel.addRow(infoToAdd1);+ count++;+ assertEquals(count, listSearcher.getSize());+ }++ public void testRemoveWithoutSearch(){+ assertEquals(baseListModel.getSize(), listSearcher.getSize());+ baseListModel.addRow(infoToAdd1);+ int count = listSearcher.getSize();+ baseListModel.removeRow(infoToAdd1);+ count--;+ assertEquals(count, listSearcher.getSize());+ }++ public void testAddWithSearch(){+ assertEquals(baseListModel.getSize(), listSearcher.getSize());+ listSearcher.search("pino's");+ int count = listSearcher.getSize();+ baseListModel.addRow(infoToAdd2);+ count++;+ assertEquals(count, listSearcher.getSize());+ }++ public void testRemoveWithSearch(){+ assertEquals(baseListModel.getSize(), listSearcher.getSize());+ baseListModel.addRow(infoToAdd1);+ listSearcher.search("pino's");+ int count = listSearcher.getSize();+ baseListModel.removeRow(infoToAdd1);+ count--;+ assertEquals(count, listSearcher.getSize());+ }+++}diff --git a/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.java b/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.javaindex 40118e705ae..17d1b908224 100644--- a/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.java+++ b/contrib/swing/src/test/org/apache/lucene/swing/models/TestUpdatingTable.java@@ -1,77 +1,77 @@-package org.apache.lucene.swing.models;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import junit.framework.TestCase;---public class TestUpdatingTable extends TestCase {- private BaseTableModel baseTableModel;- private TableSearcher tableSearcher;-- RestaurantInfo infoToAdd1, infoToAdd2;-- protected void setUp() throws Exception {- baseTableModel = new BaseTableModel(DataStore.getRestaurants());- tableSearcher = new TableSearcher(baseTableModel);-- infoToAdd1 = new RestaurantInfo();- infoToAdd1.setName("Pino's");- infoToAdd1.setType("Italian");-- infoToAdd2 = new RestaurantInfo();- infoToAdd2.setName("Pino's");- infoToAdd2.setType("Italian");- }-- public void testAddWithoutSearch(){- assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());- int count = tableSearcher.getRowCount();- baseTableModel.addRow(infoToAdd1);- count++;- assertEquals(count, tableSearcher.getRowCount());- }-- public void testRemoveWithoutSearch(){- assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());- int count = tableSearcher.getRowCount();- baseTableModel.addRow(infoToAdd1);- baseTableModel.removeRow(infoToAdd1);- assertEquals(count, tableSearcher.getRowCount());- }-- public void testAddWithSearch(){- assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());- tableSearcher.search("pino's");- int count = tableSearcher.getRowCount();- baseTableModel.addRow(infoToAdd2);- count++;- assertEquals(count, tableSearcher.getRowCount());- }-- public void testRemoveWithSearch(){- assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());- baseTableModel.addRow(infoToAdd1);- tableSearcher.search("pino's");- int count = tableSearcher.getRowCount();- baseTableModel.removeRow(infoToAdd1);- count--;- assertEquals(count, tableSearcher.getRowCount());- }---}+package org.apache.lucene.swing.models;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import junit.framework.TestCase;+++public class TestUpdatingTable extends TestCase {+ private BaseTableModel baseTableModel;+ private TableSearcher tableSearcher;++ RestaurantInfo infoToAdd1, infoToAdd2;++ protected void setUp() throws Exception {+ baseTableModel = new BaseTableModel(DataStore.getRestaurants());+ tableSearcher = new TableSearcher(baseTableModel);++ infoToAdd1 = new RestaurantInfo();+ infoToAdd1.setName("Pino's");+ infoToAdd1.setType("Italian");++ infoToAdd2 = new RestaurantInfo();+ infoToAdd2.setName("Pino's");+ infoToAdd2.setType("Italian");+ }++ public void testAddWithoutSearch(){+ assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());+ int count = tableSearcher.getRowCount();+ baseTableModel.addRow(infoToAdd1);+ count++;+ assertEquals(count, tableSearcher.getRowCount());+ }++ public void testRemoveWithoutSearch(){+ assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());+ int count = tableSearcher.getRowCount();+ baseTableModel.addRow(infoToAdd1);+ baseTableModel.removeRow(infoToAdd1);+ assertEquals(count, tableSearcher.getRowCount());+ }++ public void testAddWithSearch(){+ assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());+ tableSearcher.search("pino's");+ int count = tableSearcher.getRowCount();+ baseTableModel.addRow(infoToAdd2);+ count++;+ assertEquals(count, tableSearcher.getRowCount());+ }++ public void testRemoveWithSearch(){+ assertEquals(baseTableModel.getRowCount(), tableSearcher.getRowCount());+ baseTableModel.addRow(infoToAdd1);+ tableSearcher.search("pino's");+ int count = tableSearcher.getRowCount();+ baseTableModel.removeRow(infoToAdd1);+ count--;+ assertEquals(count, tableSearcher.getRowCount());+ }+++}diff --git a/contrib/xml-query-parser/src/demo/java/org/apache/lucene/xmlparser/webdemo/FormBasedXmlQueryDemo.java b/contrib/xml-query-parser/src/demo/java/org/apache/lucene/xmlparser/webdemo/FormBasedXmlQueryDemo.javaindex f8233db38bb..38e89ae8352 100644--- a/contrib/xml-query-parser/src/demo/java/org/apache/lucene/xmlparser/webdemo/FormBasedXmlQueryDemo.java+++ b/contrib/xml-query-parser/src/demo/java/org/apache/lucene/xmlparser/webdemo/FormBasedXmlQueryDemo.java@@ -1,133 +1,133 @@-package org.apache.lucene.xmlparser.webdemo;--import java.io.BufferedReader;-import java.io.IOException;-import java.io.InputStream;-import java.io.InputStreamReader;-import java.util.Enumeration;-import java.util.Properties;-import java.util.StringTokenizer;--import javax.servlet.RequestDispatcher;-import javax.servlet.ServletConfig;-import javax.servlet.ServletException;-import javax.servlet.http.HttpServlet;-import javax.servlet.http.HttpServletRequest;-import javax.servlet.http.HttpServletResponse;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.standard.StandardAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.CorruptIndexException;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.ScoreDoc;-import org.apache.lucene.search.TopDocs;-import org.apache.lucene.store.RAMDirectory;-import org.apache.lucene.xmlparser.CorePlusExtensionsParser;-import org.apache.lucene.xmlparser.QueryTemplateManager;--public class FormBasedXmlQueryDemo extends HttpServlet {-- private QueryTemplateManager queryTemplateManager;- private CorePlusExtensionsParser xmlParser;- private IndexSearcher searcher;- private Analyzer analyzer=new StandardAnalyzer();-- public void init(ServletConfig config) throws ServletException {- super.init(config);- try {- openExampleIndex();-- //load servlet configuration settings- String xslFile=config.getInitParameter("xslFile");- String defaultStandardQueryParserField = config.getInitParameter("defaultStandardQueryParserField");--- //Load and cache choice of XSL query template using QueryTemplateManager- queryTemplateManager=new QueryTemplateManager(- getServletContext().getResourceAsStream("/WEB-INF/"+xslFile));-- //initialize an XML Query Parser for use by all threads- xmlParser=new CorePlusExtensionsParser(defaultStandardQueryParserField,analyzer);- } catch (Exception e) {- throw new ServletException("Error loading query template",e);- }- }-- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {- //Take all completed form fields and add to a Properties object- Properties completedFormFields=new Properties();- Enumeration pNames = request.getParameterNames();- while(pNames.hasMoreElements()){- String propName=(String) pNames.nextElement();- String value=request.getParameter(propName);- if((value!=null)&&(value.trim().length()>0)){- completedFormFields.setProperty(propName, value);- }- }-- try{-- //Create an XML query by populating template with given user criteria- org.w3c.dom.Document xmlQuery=queryTemplateManager.getQueryAsDOM(completedFormFields);-- //Parse the XML to produce a Lucene query- Query query=xmlParser.getQuery(xmlQuery.getDocumentElement());-- //Run the query- TopDocs topDocs = searcher.search(query,10);-- //and package the results and forward to JSP- if(topDocs!=null) {- ScoreDoc[] sd = topDocs.scoreDocs;- Document[] results=new Document[sd.length];- for (int i = 0; i < results.length; i++) {- results[i]=searcher.doc(sd[i].doc);- request.setAttribute("results", results);- }- }- RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");- dispatcher.forward(request,response);- }- catch(Exception e){- throw new ServletException("Error processing query",e);- }- }-- private void openExampleIndex() throws CorruptIndexException, IOException {-- //Create a RAM-based index from our test data file- RAMDirectory rd=new RAMDirectory();- IndexWriter writer=new IndexWriter (rd,analyzer,IndexWriter.MaxFieldLength.LIMITED);- InputStream dataIn=getServletContext().getResourceAsStream("/WEB-INF/data.tsv");- BufferedReader br = new BufferedReader(new InputStreamReader(dataIn));- String line = br.readLine();- while(line!=null)- {- line=line.trim();- if(line.length()>0)- {- //parse row and create a document- StringTokenizer st=new StringTokenizer(line,"\t");- Document doc=new Document();- doc.add(new Field("location",st.nextToken(),Field.Store.YES,- Field.Index.ANALYZED_NO_NORMS));- doc.add(new Field("salary",st.nextToken(),Field.Store.YES,- Field.Index.ANALYZED_NO_NORMS));- doc.add(new Field("type",st.nextToken(),Field.Store.YES,- Field.Index.ANALYZED_NO_NORMS));- doc.add(new Field("description",st.nextToken(),Field.Store.YES,- Field.Index.ANALYZED));- writer.addDocument(doc);- }- line=br.readLine();- }- writer.close();-- //open searcher- searcher=new IndexSearcher(rd);- }-}+package org.apache.lucene.xmlparser.webdemo;++import java.io.BufferedReader;+import java.io.IOException;+import java.io.InputStream;+import java.io.InputStreamReader;+import java.util.Enumeration;+import java.util.Properties;+import java.util.StringTokenizer;++import javax.servlet.RequestDispatcher;+import javax.servlet.ServletConfig;+import javax.servlet.ServletException;+import javax.servlet.http.HttpServlet;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.CorruptIndexException;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.ScoreDoc;+import org.apache.lucene.search.TopDocs;+import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.xmlparser.CorePlusExtensionsParser;+import org.apache.lucene.xmlparser.QueryTemplateManager;++public class FormBasedXmlQueryDemo extends HttpServlet {++ private QueryTemplateManager queryTemplateManager;+ private CorePlusExtensionsParser xmlParser;+ private IndexSearcher searcher;+ private Analyzer analyzer=new StandardAnalyzer();++ public void init(ServletConfig config) throws ServletException {+ super.init(config);+ try {+ openExampleIndex();++ //load servlet configuration settings+ String xslFile=config.getInitParameter("xslFile");+ String defaultStandardQueryParserField = config.getInitParameter("defaultStandardQueryParserField");+++ //Load and cache choice of XSL query template using QueryTemplateManager+ queryTemplateManager=new QueryTemplateManager(+ getServletContext().getResourceAsStream("/WEB-INF/"+xslFile));++ //initialize an XML Query Parser for use by all threads+ xmlParser=new CorePlusExtensionsParser(defaultStandardQueryParserField,analyzer);+ } catch (Exception e) {+ throw new ServletException("Error loading query template",e);+ }+ }++ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {+ //Take all completed form fields and add to a Properties object+ Properties completedFormFields=new Properties();+ Enumeration pNames = request.getParameterNames();+ while(pNames.hasMoreElements()){+ String propName=(String) pNames.nextElement();+ String value=request.getParameter(propName);+ if((value!=null)&&(value.trim().length()>0)){+ completedFormFields.setProperty(propName, value);+ }+ }++ try{++ //Create an XML query by populating template with given user criteria+ org.w3c.dom.Document xmlQuery=queryTemplateManager.getQueryAsDOM(completedFormFields);++ //Parse the XML to produce a Lucene query+ Query query=xmlParser.getQuery(xmlQuery.getDocumentElement());++ //Run the query+ TopDocs topDocs = searcher.search(query,10);++ //and package the results and forward to JSP+ if(topDocs!=null) {+ ScoreDoc[] sd = topDocs.scoreDocs;+ Document[] results=new Document[sd.length];+ for (int i = 0; i < results.length; i++) {+ results[i]=searcher.doc(sd[i].doc);+ request.setAttribute("results", results);+ }+ }+ RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");+ dispatcher.forward(request,response);+ }+ catch(Exception e){+ throw new ServletException("Error processing query",e);+ }+ }++ private void openExampleIndex() throws CorruptIndexException, IOException {++ //Create a RAM-based index from our test data file+ RAMDirectory rd=new RAMDirectory();+ IndexWriter writer=new IndexWriter (rd,analyzer,IndexWriter.MaxFieldLength.LIMITED);+ InputStream dataIn=getServletContext().getResourceAsStream("/WEB-INF/data.tsv");+ BufferedReader br = new BufferedReader(new InputStreamReader(dataIn));+ String line = br.readLine();+ while(line!=null)+ {+ line=line.trim();+ if(line.length()>0)+ {+ //parse row and create a document+ StringTokenizer st=new StringTokenizer(line,"\t");+ Document doc=new Document();+ doc.add(new Field("location",st.nextToken(),Field.Store.YES,+ Field.Index.ANALYZED_NO_NORMS));+ doc.add(new Field("salary",st.nextToken(),Field.Store.YES,+ Field.Index.ANALYZED_NO_NORMS));+ doc.add(new Field("type",st.nextToken(),Field.Store.YES,+ Field.Index.ANALYZED_NO_NORMS));+ doc.add(new Field("description",st.nextToken(),Field.Store.YES,+ Field.Index.ANALYZED));+ writer.addDocument(doc);+ }+ line=br.readLine();+ }+ writer.close();++ //open searcher+ searcher=new IndexSearcher(rd);+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CoreParser.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CoreParser.javaindex da537f98e14..b0fba5f3a68 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CoreParser.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CoreParser.java@@ -1,180 +1,180 @@-package org.apache.lucene.xmlparser;--import java.io.InputStream;--import javax.xml.parsers.DocumentBuilder;-import javax.xml.parsers.DocumentBuilderFactory;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.queryParser.QueryParser;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.builders.BooleanQueryBuilder;-import org.apache.lucene.xmlparser.builders.ConstantScoreQueryBuilder;-import org.apache.lucene.xmlparser.builders.FilteredQueryBuilder;-import org.apache.lucene.xmlparser.builders.MatchAllDocsQueryBuilder;-import org.apache.lucene.xmlparser.builders.CachedFilterBuilder;-import org.apache.lucene.xmlparser.builders.RangeFilterBuilder;-import org.apache.lucene.xmlparser.builders.SpanFirstBuilder;-import org.apache.lucene.xmlparser.builders.SpanNearBuilder;-import org.apache.lucene.xmlparser.builders.SpanNotBuilder;-import org.apache.lucene.xmlparser.builders.SpanOrBuilder;-import org.apache.lucene.xmlparser.builders.SpanOrTermsBuilder;-import org.apache.lucene.xmlparser.builders.SpanQueryBuilderFactory;-import org.apache.lucene.xmlparser.builders.SpanTermBuilder;-import org.apache.lucene.xmlparser.builders.TermQueryBuilder;-import org.apache.lucene.xmlparser.builders.TermsQueryBuilder;-import org.apache.lucene.xmlparser.builders.UserInputQueryBuilder;-import org.w3c.dom.Document;-import org.w3c.dom.Element;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-/**- * Assembles a QueryBuilder which uses only core Lucene Query objects- *- */-public class CoreParser implements QueryBuilder-{-- protected Analyzer analyzer;- protected QueryParser parser;- protected QueryBuilderFactory queryFactory;- protected FilterBuilderFactory filterFactory;- //Controls the max size of the LRU cache used for QueryFilter objects parsed.- public static int maxNumCachedFilters=20;--- /**- * Construct an XML parser that uses a single instance QueryParser for handling- * UserQuery tags - all parse operations are synchronised on this parser- * @param analyzer- * @param parser A QueryParser which will be synchronized on during parse calls.- */- public CoreParser(Analyzer analyzer, QueryParser parser)- {- this(null,analyzer,parser);- }-- /**- * Constructs an XML parser that creates a QueryParser for each UserQuery request.- * @param defaultField The default field name used by QueryParsers constructed for UserQuery tags- * @param analyzer- */- public CoreParser(String defaultField, Analyzer analyzer)- {- this(defaultField,analyzer,null);- }-- protected CoreParser(String defaultField,Analyzer analyzer, QueryParser parser)- {- this.analyzer=analyzer;- this.parser=parser;- filterFactory = new FilterBuilderFactory();- filterFactory.addBuilder("RangeFilter",new RangeFilterBuilder());--- queryFactory = new QueryBuilderFactory();- queryFactory.addBuilder("TermQuery",new TermQueryBuilder());- queryFactory.addBuilder("TermsQuery",new TermsQueryBuilder(analyzer));- queryFactory.addBuilder("MatchAllDocsQuery",new MatchAllDocsQueryBuilder());- queryFactory.addBuilder("BooleanQuery",new BooleanQueryBuilder(queryFactory));- if(parser!=null)- {- queryFactory.addBuilder("UserQuery",new UserInputQueryBuilder(parser));- }- else- {- queryFactory.addBuilder("UserQuery",new UserInputQueryBuilder(defaultField,analyzer));- }- queryFactory.addBuilder("FilteredQuery",new FilteredQueryBuilder(filterFactory,queryFactory));- queryFactory.addBuilder("ConstantScoreQuery",new ConstantScoreQueryBuilder(filterFactory));-- filterFactory.addBuilder("CachedFilter",new CachedFilterBuilder(queryFactory,- filterFactory, maxNumCachedFilters));--- SpanQueryBuilderFactory sqof=new SpanQueryBuilderFactory();-- SpanNearBuilder snb=new SpanNearBuilder(sqof);- sqof.addBuilder("SpanNear",snb);- queryFactory.addBuilder("SpanNear",snb);-- SpanTermBuilder snt=new SpanTermBuilder();- sqof.addBuilder("SpanTerm",snt);- queryFactory.addBuilder("SpanTerm",snt);-- SpanOrBuilder sot=new SpanOrBuilder(sqof);- sqof.addBuilder("SpanOr",sot);- queryFactory.addBuilder("SpanOr",sot);-- SpanOrTermsBuilder sots=new SpanOrTermsBuilder(analyzer);- sqof.addBuilder("SpanOrTerms",sots);- queryFactory.addBuilder("SpanOrTerms",sots);-- SpanFirstBuilder sft=new SpanFirstBuilder(sqof);- sqof.addBuilder("SpanFirst",sft);- queryFactory.addBuilder("SpanFirst",sft);-- SpanNotBuilder snot=new SpanNotBuilder(sqof);- sqof.addBuilder("SpanNot",snot);- queryFactory.addBuilder("SpanNot",snot);- }-- public Query parse(InputStream xmlStream) throws ParserException- {- return getQuery(parseXML(xmlStream).getDocumentElement());- }-- public void addQueryBuilder(String nodeName,QueryBuilder builder)- {- queryFactory.addBuilder(nodeName,builder);- }- public void addFilterBuilder(String nodeName,FilterBuilder builder)- {- filterFactory.addBuilder(nodeName,builder);- }-- private static Document parseXML(InputStream pXmlFile) throws ParserException- {- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();- DocumentBuilder db = null;- try- {- db = dbf.newDocumentBuilder();- }- catch (Exception se)- {- throw new ParserException("XML Parser configuration error", se);- }- org.w3c.dom.Document doc = null;- try- {- doc = db.parse(pXmlFile);- }- catch (Exception se)- {- throw new ParserException("Error parsing XML stream:" + se, se);- }- return doc;- }--- public Query getQuery(Element e) throws ParserException- {- return queryFactory.getQuery(e);- }-}+package org.apache.lucene.xmlparser;++import java.io.InputStream;++import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.builders.BooleanQueryBuilder;+import org.apache.lucene.xmlparser.builders.ConstantScoreQueryBuilder;+import org.apache.lucene.xmlparser.builders.FilteredQueryBuilder;+import org.apache.lucene.xmlparser.builders.MatchAllDocsQueryBuilder;+import org.apache.lucene.xmlparser.builders.CachedFilterBuilder;+import org.apache.lucene.xmlparser.builders.RangeFilterBuilder;+import org.apache.lucene.xmlparser.builders.SpanFirstBuilder;+import org.apache.lucene.xmlparser.builders.SpanNearBuilder;+import org.apache.lucene.xmlparser.builders.SpanNotBuilder;+import org.apache.lucene.xmlparser.builders.SpanOrBuilder;+import org.apache.lucene.xmlparser.builders.SpanOrTermsBuilder;+import org.apache.lucene.xmlparser.builders.SpanQueryBuilderFactory;+import org.apache.lucene.xmlparser.builders.SpanTermBuilder;+import org.apache.lucene.xmlparser.builders.TermQueryBuilder;+import org.apache.lucene.xmlparser.builders.TermsQueryBuilder;+import org.apache.lucene.xmlparser.builders.UserInputQueryBuilder;+import org.w3c.dom.Document;+import org.w3c.dom.Element;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+/**+ * Assembles a QueryBuilder which uses only core Lucene Query objects+ *+ */+public class CoreParser implements QueryBuilder+{++ protected Analyzer analyzer;+ protected QueryParser parser;+ protected QueryBuilderFactory queryFactory;+ protected FilterBuilderFactory filterFactory;+ //Controls the max size of the LRU cache used for QueryFilter objects parsed.+ public static int maxNumCachedFilters=20;+++ /**+ * Construct an XML parser that uses a single instance QueryParser for handling+ * UserQuery tags - all parse operations are synchronised on this parser+ * @param analyzer+ * @param parser A QueryParser which will be synchronized on during parse calls.+ */+ public CoreParser(Analyzer analyzer, QueryParser parser)+ {+ this(null,analyzer,parser);+ }++ /**+ * Constructs an XML parser that creates a QueryParser for each UserQuery request.+ * @param defaultField The default field name used by QueryParsers constructed for UserQuery tags+ * @param analyzer+ */+ public CoreParser(String defaultField, Analyzer analyzer)+ {+ this(defaultField,analyzer,null);+ }++ protected CoreParser(String defaultField,Analyzer analyzer, QueryParser parser)+ {+ this.analyzer=analyzer;+ this.parser=parser;+ filterFactory = new FilterBuilderFactory();+ filterFactory.addBuilder("RangeFilter",new RangeFilterBuilder());+++ queryFactory = new QueryBuilderFactory();+ queryFactory.addBuilder("TermQuery",new TermQueryBuilder());+ queryFactory.addBuilder("TermsQuery",new TermsQueryBuilder(analyzer));+ queryFactory.addBuilder("MatchAllDocsQuery",new MatchAllDocsQueryBuilder());+ queryFactory.addBuilder("BooleanQuery",new BooleanQueryBuilder(queryFactory));+ if(parser!=null)+ {+ queryFactory.addBuilder("UserQuery",new UserInputQueryBuilder(parser));+ }+ else+ {+ queryFactory.addBuilder("UserQuery",new UserInputQueryBuilder(defaultField,analyzer));+ }+ queryFactory.addBuilder("FilteredQuery",new FilteredQueryBuilder(filterFactory,queryFactory));+ queryFactory.addBuilder("ConstantScoreQuery",new ConstantScoreQueryBuilder(filterFactory));++ filterFactory.addBuilder("CachedFilter",new CachedFilterBuilder(queryFactory,+ filterFactory, maxNumCachedFilters));+++ SpanQueryBuilderFactory sqof=new SpanQueryBuilderFactory();++ SpanNearBuilder snb=new SpanNearBuilder(sqof);+ sqof.addBuilder("SpanNear",snb);+ queryFactory.addBuilder("SpanNear",snb);++ SpanTermBuilder snt=new SpanTermBuilder();+ sqof.addBuilder("SpanTerm",snt);+ queryFactory.addBuilder("SpanTerm",snt);++ SpanOrBuilder sot=new SpanOrBuilder(sqof);+ sqof.addBuilder("SpanOr",sot);+ queryFactory.addBuilder("SpanOr",sot);++ SpanOrTermsBuilder sots=new SpanOrTermsBuilder(analyzer);+ sqof.addBuilder("SpanOrTerms",sots);+ queryFactory.addBuilder("SpanOrTerms",sots);++ SpanFirstBuilder sft=new SpanFirstBuilder(sqof);+ sqof.addBuilder("SpanFirst",sft);+ queryFactory.addBuilder("SpanFirst",sft);++ SpanNotBuilder snot=new SpanNotBuilder(sqof);+ sqof.addBuilder("SpanNot",snot);+ queryFactory.addBuilder("SpanNot",snot);+ }++ public Query parse(InputStream xmlStream) throws ParserException+ {+ return getQuery(parseXML(xmlStream).getDocumentElement());+ }++ public void addQueryBuilder(String nodeName,QueryBuilder builder)+ {+ queryFactory.addBuilder(nodeName,builder);+ }+ public void addFilterBuilder(String nodeName,FilterBuilder builder)+ {+ filterFactory.addBuilder(nodeName,builder);+ }++ private static Document parseXML(InputStream pXmlFile) throws ParserException+ {+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();+ DocumentBuilder db = null;+ try+ {+ db = dbf.newDocumentBuilder();+ }+ catch (Exception se)+ {+ throw new ParserException("XML Parser configuration error", se);+ }+ org.w3c.dom.Document doc = null;+ try+ {+ doc = db.parse(pXmlFile);+ }+ catch (Exception se)+ {+ throw new ParserException("Error parsing XML stream:" + se, se);+ }+ return doc;+ }+++ public Query getQuery(Element e) throws ParserException+ {+ return queryFactory.getQuery(e);+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CorePlusExtensionsParser.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CorePlusExtensionsParser.javaindex 8b2036da383..fe4c8bc6e2e 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CorePlusExtensionsParser.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/CorePlusExtensionsParser.java@@ -1,62 +1,62 @@-package org.apache.lucene.xmlparser;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.queryParser.QueryParser;-import org.apache.lucene.xmlparser.builders.BooleanFilterBuilder;-import org.apache.lucene.xmlparser.builders.BoostingQueryBuilder;-import org.apache.lucene.xmlparser.builders.DuplicateFilterBuilder;-import org.apache.lucene.xmlparser.builders.FuzzyLikeThisQueryBuilder;-import org.apache.lucene.xmlparser.builders.LikeThisQueryBuilder;-import org.apache.lucene.xmlparser.builders.TermsFilterBuilder;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class CorePlusExtensionsParser extends CoreParser-{-- /**- * Construct an XML parser that uses a single instance QueryParser for handling- * UserQuery tags - all parse operations are synchronised on this parser- * @param analyzer- * @param parser A QueryParser which will be synchronized on during parse calls.- */- public CorePlusExtensionsParser(Analyzer analyzer, QueryParser parser)- {- this(null,analyzer, parser);- }- /**- * Constructs an XML parser that creates a QueryParser for each UserQuery request.- * @param defaultField The default field name used by QueryParsers constructed for UserQuery tags- * @param analyzer- */- public CorePlusExtensionsParser(String defaultField,Analyzer analyzer)- {- this(defaultField,analyzer, null);- }-- private CorePlusExtensionsParser(String defaultField,Analyzer analyzer, QueryParser parser)- {- super(defaultField,analyzer, parser);- filterFactory.addBuilder("TermsFilter",new TermsFilterBuilder(analyzer));- filterFactory.addBuilder("BooleanFilter",new BooleanFilterBuilder(filterFactory));- filterFactory.addBuilder("DuplicateFilter",new DuplicateFilterBuilder());- String fields[]={"contents"};- queryFactory.addBuilder("LikeThisQuery",new LikeThisQueryBuilder(analyzer,fields));- queryFactory.addBuilder("BoostingQuery", new BoostingQueryBuilder(queryFactory));- queryFactory.addBuilder("FuzzyLikeThisQuery", new FuzzyLikeThisQueryBuilder(analyzer));-- }-}+package org.apache.lucene.xmlparser;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.xmlparser.builders.BooleanFilterBuilder;+import org.apache.lucene.xmlparser.builders.BoostingQueryBuilder;+import org.apache.lucene.xmlparser.builders.DuplicateFilterBuilder;+import org.apache.lucene.xmlparser.builders.FuzzyLikeThisQueryBuilder;+import org.apache.lucene.xmlparser.builders.LikeThisQueryBuilder;+import org.apache.lucene.xmlparser.builders.TermsFilterBuilder;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class CorePlusExtensionsParser extends CoreParser+{++ /**+ * Construct an XML parser that uses a single instance QueryParser for handling+ * UserQuery tags - all parse operations are synchronised on this parser+ * @param analyzer+ * @param parser A QueryParser which will be synchronized on during parse calls.+ */+ public CorePlusExtensionsParser(Analyzer analyzer, QueryParser parser)+ {+ this(null,analyzer, parser);+ }+ /**+ * Constructs an XML parser that creates a QueryParser for each UserQuery request.+ * @param defaultField The default field name used by QueryParsers constructed for UserQuery tags+ * @param analyzer+ */+ public CorePlusExtensionsParser(String defaultField,Analyzer analyzer)+ {+ this(defaultField,analyzer, null);+ }++ private CorePlusExtensionsParser(String defaultField,Analyzer analyzer, QueryParser parser)+ {+ super(defaultField,analyzer, parser);+ filterFactory.addBuilder("TermsFilter",new TermsFilterBuilder(analyzer));+ filterFactory.addBuilder("BooleanFilter",new BooleanFilterBuilder(filterFactory));+ filterFactory.addBuilder("DuplicateFilter",new DuplicateFilterBuilder());+ String fields[]={"contents"};+ queryFactory.addBuilder("LikeThisQuery",new LikeThisQueryBuilder(analyzer,fields));+ queryFactory.addBuilder("BoostingQuery", new BoostingQueryBuilder(queryFactory));+ queryFactory.addBuilder("FuzzyLikeThisQuery", new FuzzyLikeThisQueryBuilder(analyzer));++ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/DOMUtils.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/DOMUtils.javaindex c1289d4ca2f..2f67d886e69 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/DOMUtils.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/DOMUtils.java@@ -1,276 +1,276 @@-package org.apache.lucene.xmlparser;-import java.io.Reader;--import javax.xml.parsers.DocumentBuilder;-import javax.xml.parsers.DocumentBuilderFactory;--import org.w3c.dom.Document;-import org.w3c.dom.Element;-import org.w3c.dom.Node;-import org.xml.sax.InputSource;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class DOMUtils-{- public static Element getChildByTagOrFail(Element e, String name) throws ParserException- {- Element kid = getChildByTagName(e, name);- if (null == kid)- {- throw new ParserException(e.getTagName() + " missing \"" + name- + "\" child element");- }- return kid;- }-- public static Element getFirstChildOrFail(Element e) throws ParserException- {- Element kid = getFirstChildElement(e);- if (null == kid)- {- throw new ParserException(e.getTagName()- + " does not contain a child element");- }- return kid;- }-- public static String getAttributeOrFail(Element e, String name) throws ParserException- {- String v = e.getAttribute(name);- if (null == v)- {- throw new ParserException(e.getTagName() + " missing \"" + name- + "\" attribute");- }- return v;- }- public static String getAttributeWithInheritanceOrFail(Element e, String name) throws ParserException- {- String v = getAttributeWithInheritance(e, name);- if (null == v)- {- throw new ParserException(e.getTagName() + " missing \"" + name- + "\" attribute");- }- return v;- }- public static String getNonBlankTextOrFail(Element e) throws ParserException- {- String v = getText(e);- if (null != v)- v = v.trim();- if (null == v || 0 == v.length())- {- throw new ParserException(e.getTagName() + " has no text");- }- return v;- }------- /* Convenience method where there is only one child Element of a given name */- public static Element getChildByTagName(Element e, String name)- {- for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())- {- if( (kid.getNodeType()==Node.ELEMENT_NODE) && (name.equals(kid.getNodeName())) )- {- return (Element)kid;- }- }- return null;- }-- /**- * Returns an attribute value from this node, or first parent node with this attribute defined- * @param element- * @param attributeName- * @return A non-zero-length value if defined, otherwise null- */- public static String getAttributeWithInheritance(Element element, String attributeName)- {- String result=element.getAttribute(attributeName);- if( (result==null)|| ("".equals(result) ) )- {- Node n=element.getParentNode();- if((n==element)||(n==null))- {- return null;- }- if(n instanceof Element)- {- Element parent=(Element) n;- return getAttributeWithInheritance(parent,attributeName);- }- return null; //we reached the top level of the document without finding attribute- }- return result;- }---- /* Convenience method where there is only one child Element of a given name */- public static String getChildTextByTagName(Element e, String tagName)- {- Element child=getChildByTagName(e,tagName);- if(child!=null)- {- return getText(child);- }- return null;- }-- /* Convenience method to append a new child with text*/- public static Element insertChild(Element parent, String tagName, String text)- {- Element child = parent.getOwnerDocument().createElement(tagName);- parent.appendChild(child);- if(text!=null)- {- child.appendChild(child.getOwnerDocument().createTextNode(text));- }- return child;- }-- public static String getAttribute(Element element, String attributeName, String deflt)- {- String result=element.getAttribute(attributeName);- if( (result==null)|| ("".equals(result) ) )- {- return deflt;- }- return result;- }- public static float getAttribute(Element element, String attributeName, float deflt)- {- String result=element.getAttribute(attributeName);- if( (result==null)|| ("".equals(result) ) )- {- return deflt;- }- return Float.parseFloat(result);- }-- public static int getAttribute(Element element, String attributeName, int deflt)- {- String result=element.getAttribute(attributeName);- if( (result==null)|| ("".equals(result) ) )- {- return deflt;- }- return Integer.parseInt(result);- }-- public static boolean getAttribute(Element element, String attributeName,- boolean deflt)- {- String result = element.getAttribute(attributeName);- if ((result == null) || ("".equals(result)))- {- return deflt;- }- return Boolean.valueOf(result).booleanValue();- }-- /* Returns text of node and all child nodes - without markup */- //MH changed to Node from Element 25/11/2005- public static String getText(Node e)- {- StringBuffer sb=new StringBuffer();- getTextBuffer(e, sb);- return sb.toString();- }-- public static Element getFirstChildElement(Element element)- {- for (Node kid = element.getFirstChild(); kid != null; kid = kid- .getNextSibling())- {- if (kid.getNodeType() == Node.ELEMENT_NODE)- {- return (Element) kid;- }- }- return null;- }-- private static void getTextBuffer(Node e, StringBuffer sb)- {- for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())- {- switch(kid.getNodeType())- {- case Node.TEXT_NODE:- {- sb.append(kid.getNodeValue());- break;- }- case Node.ELEMENT_NODE:- {- getTextBuffer(kid, sb);- break;- }- case Node.ENTITY_REFERENCE_NODE:- {- getTextBuffer(kid, sb);- break;- }- }- }- }-- /**- * Helper method to parse an XML file into a DOM tree, given a reader.- * @param is reader of the XML file to be parsed- * @return an org.w3c.dom.Document object- */- public static Document loadXML(Reader is)- {-- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();- DocumentBuilder db = null;-- try- {- db = dbf.newDocumentBuilder();- }- catch (Exception se)- {- throw new RuntimeException("Parser configuration error", se);- }-- // Step 3: parse the input file- org.w3c.dom.Document doc = null;- try- {- doc = db.parse(new InputSource(is));- //doc = db.parse(is);- }- catch (Exception se)- {- throw new RuntimeException("Error parsing file:" + se, se);- }-- return doc;- }-}---+package org.apache.lucene.xmlparser;+import java.io.Reader;++import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;++import org.w3c.dom.Document;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+import org.xml.sax.InputSource;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class DOMUtils+{+ public static Element getChildByTagOrFail(Element e, String name) throws ParserException+ {+ Element kid = getChildByTagName(e, name);+ if (null == kid)+ {+ throw new ParserException(e.getTagName() + " missing \"" + name+ + "\" child element");+ }+ return kid;+ }++ public static Element getFirstChildOrFail(Element e) throws ParserException+ {+ Element kid = getFirstChildElement(e);+ if (null == kid)+ {+ throw new ParserException(e.getTagName()+ + " does not contain a child element");+ }+ return kid;+ }++ public static String getAttributeOrFail(Element e, String name) throws ParserException+ {+ String v = e.getAttribute(name);+ if (null == v)+ {+ throw new ParserException(e.getTagName() + " missing \"" + name+ + "\" attribute");+ }+ return v;+ }+ public static String getAttributeWithInheritanceOrFail(Element e, String name) throws ParserException+ {+ String v = getAttributeWithInheritance(e, name);+ if (null == v)+ {+ throw new ParserException(e.getTagName() + " missing \"" + name+ + "\" attribute");+ }+ return v;+ }+ public static String getNonBlankTextOrFail(Element e) throws ParserException+ {+ String v = getText(e);+ if (null != v)+ v = v.trim();+ if (null == v || 0 == v.length())+ {+ throw new ParserException(e.getTagName() + " has no text");+ }+ return v;+ }+++++++ /* Convenience method where there is only one child Element of a given name */+ public static Element getChildByTagName(Element e, String name)+ {+ for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())+ {+ if( (kid.getNodeType()==Node.ELEMENT_NODE) && (name.equals(kid.getNodeName())) )+ {+ return (Element)kid;+ }+ }+ return null;+ }++ /**+ * Returns an attribute value from this node, or first parent node with this attribute defined+ * @param element+ * @param attributeName+ * @return A non-zero-length value if defined, otherwise null+ */+ public static String getAttributeWithInheritance(Element element, String attributeName)+ {+ String result=element.getAttribute(attributeName);+ if( (result==null)|| ("".equals(result) ) )+ {+ Node n=element.getParentNode();+ if((n==element)||(n==null))+ {+ return null;+ }+ if(n instanceof Element)+ {+ Element parent=(Element) n;+ return getAttributeWithInheritance(parent,attributeName);+ }+ return null; //we reached the top level of the document without finding attribute+ }+ return result;+ }++++ /* Convenience method where there is only one child Element of a given name */+ public static String getChildTextByTagName(Element e, String tagName)+ {+ Element child=getChildByTagName(e,tagName);+ if(child!=null)+ {+ return getText(child);+ }+ return null;+ }++ /* Convenience method to append a new child with text*/+ public static Element insertChild(Element parent, String tagName, String text)+ {+ Element child = parent.getOwnerDocument().createElement(tagName);+ parent.appendChild(child);+ if(text!=null)+ {+ child.appendChild(child.getOwnerDocument().createTextNode(text));+ }+ return child;+ }++ public static String getAttribute(Element element, String attributeName, String deflt)+ {+ String result=element.getAttribute(attributeName);+ if( (result==null)|| ("".equals(result) ) )+ {+ return deflt;+ }+ return result;+ }+ public static float getAttribute(Element element, String attributeName, float deflt)+ {+ String result=element.getAttribute(attributeName);+ if( (result==null)|| ("".equals(result) ) )+ {+ return deflt;+ }+ return Float.parseFloat(result);+ }++ public static int getAttribute(Element element, String attributeName, int deflt)+ {+ String result=element.getAttribute(attributeName);+ if( (result==null)|| ("".equals(result) ) )+ {+ return deflt;+ }+ return Integer.parseInt(result);+ }++ public static boolean getAttribute(Element element, String attributeName,+ boolean deflt)+ {+ String result = element.getAttribute(attributeName);+ if ((result == null) || ("".equals(result)))+ {+ return deflt;+ }+ return Boolean.valueOf(result).booleanValue();+ }++ /* Returns text of node and all child nodes - without markup */+ //MH changed to Node from Element 25/11/2005+ public static String getText(Node e)+ {+ StringBuffer sb=new StringBuffer();+ getTextBuffer(e, sb);+ return sb.toString();+ }++ public static Element getFirstChildElement(Element element)+ {+ for (Node kid = element.getFirstChild(); kid != null; kid = kid+ .getNextSibling())+ {+ if (kid.getNodeType() == Node.ELEMENT_NODE)+ {+ return (Element) kid;+ }+ }+ return null;+ }++ private static void getTextBuffer(Node e, StringBuffer sb)+ {+ for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())+ {+ switch(kid.getNodeType())+ {+ case Node.TEXT_NODE:+ {+ sb.append(kid.getNodeValue());+ break;+ }+ case Node.ELEMENT_NODE:+ {+ getTextBuffer(kid, sb);+ break;+ }+ case Node.ENTITY_REFERENCE_NODE:+ {+ getTextBuffer(kid, sb);+ break;+ }+ }+ }+ }++ /**+ * Helper method to parse an XML file into a DOM tree, given a reader.+ * @param is reader of the XML file to be parsed+ * @return an org.w3c.dom.Document object+ */+ public static Document loadXML(Reader is)+ {++ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();+ DocumentBuilder db = null;++ try+ {+ db = dbf.newDocumentBuilder();+ }+ catch (Exception se)+ {+ throw new RuntimeException("Parser configuration error", se);+ }++ // Step 3: parse the input file+ org.w3c.dom.Document doc = null;+ try+ {+ doc = db.parse(new InputSource(is));+ //doc = db.parse(is);+ }+ catch (Exception se)+ {+ throw new RuntimeException("Error parsing file:" + se, se);+ }++ return doc;+ }+}+++diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilder.javaindex 84deaf28cad..e36e371a145 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilder.java@@ -1,27 +1,27 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser;--import org.apache.lucene.search.Filter;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public interface FilterBuilder {- public Filter getFilter(Element e) throws ParserException;-}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser;++import org.apache.lucene.search.Filter;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public interface FilterBuilder {+ public Filter getFilter(Element e) throws ParserException;+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilderFactory.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilderFactory.javaindex c5a8b473229..04b2788f42e 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilderFactory.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/FilterBuilderFactory.java@@ -1,47 +1,47 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser;--import java.util.HashMap;--import org.apache.lucene.search.Filter;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class FilterBuilderFactory implements FilterBuilder {-- HashMap builders=new HashMap();-- public Filter getFilter(Element n) throws ParserException {- FilterBuilder builder=(FilterBuilder) builders.get(n.getNodeName());- if(builder==null)- {- throw new ParserException("No FilterBuilder defined for node "+n.getNodeName());- }- return builder.getFilter(n);- }- public void addBuilder(String nodeName,FilterBuilder builder)- {- builders.put(nodeName,builder);- }- public FilterBuilder getFilterBuilder(String nodeName)- {- return (FilterBuilder) builders.get(nodeName);- }-}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser;++import java.util.HashMap;++import org.apache.lucene.search.Filter;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class FilterBuilderFactory implements FilterBuilder {++ HashMap builders=new HashMap();++ public Filter getFilter(Element n) throws ParserException {+ FilterBuilder builder=(FilterBuilder) builders.get(n.getNodeName());+ if(builder==null)+ {+ throw new ParserException("No FilterBuilder defined for node "+n.getNodeName());+ }+ return builder.getFilter(n);+ }+ public void addBuilder(String nodeName,FilterBuilder builder)+ {+ builders.put(nodeName,builder);+ }+ public FilterBuilder getFilterBuilder(String nodeName)+ {+ return (FilterBuilder) builders.get(nodeName);+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/ParserException.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/ParserException.javaindex ce1b6954c01..49af7c3228b 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/ParserException.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/ParserException.java@@ -1,49 +1,49 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class ParserException extends Exception {-- /**- *- */- public ParserException() {- super();- }- /**- * @param message- */- public ParserException(String message) {- super(message);- }- /**- * @param message- * @param cause- */- public ParserException(String message, Throwable cause) {- super(message, cause);- }- /**- * @param cause- */- public ParserException(Throwable cause) {- super(cause);- }-}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class ParserException extends Exception {++ /**+ *+ */+ public ParserException() {+ super();+ }+ /**+ * @param message+ */+ public ParserException(String message) {+ super(message);+ }+ /**+ * @param message+ * @param cause+ */+ public ParserException(String message, Throwable cause) {+ super(message, cause);+ }+ /**+ * @param cause+ */+ public ParserException(Throwable cause) {+ super(cause);+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilder.javaindex 1feaa0bddff..4517f28cf74 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilder.java@@ -1,29 +1,29 @@-package org.apache.lucene.xmlparser;--import org.apache.lucene.search.Query;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-/**- * Implemented by objects that produce Lucene Query objects from XML streams. Implementations are- * expected to be thread-safe so that they can be used to simultaneously parse multiple XML documents.- */-public interface QueryBuilder {-- public Query getQuery(Element e) throws ParserException;--}+package org.apache.lucene.xmlparser;++import org.apache.lucene.search.Query;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+/**+ * Implemented by objects that produce Lucene Query objects from XML streams. Implementations are+ * expected to be thread-safe so that they can be used to simultaneously parse multiple XML documents.+ */+public interface QueryBuilder {++ public Query getQuery(Element e) throws ParserException;++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilderFactory.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilderFactory.javaindex b49088e73df..8c4ca17c9fd 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilderFactory.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryBuilderFactory.java@@ -1,48 +1,48 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser;--import java.util.HashMap;--import org.apache.lucene.search.Query;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class QueryBuilderFactory implements QueryBuilder {-- HashMap builders=new HashMap();-- public Query getQuery(Element n) throws ParserException {- QueryBuilder builder=(QueryBuilder) builders.get(n.getNodeName());- if(builder==null)- {- throw new ParserException("No QueryObjectBuilder defined for node "+n.getNodeName());- }- return builder.getQuery(n);- }- public void addBuilder(String nodeName,QueryBuilder builder)- {- builders.put(nodeName,builder);- }- public QueryBuilder getQueryBuilder(String nodeName)- {- return (QueryBuilder) builders.get(nodeName);- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser;++import java.util.HashMap;++import org.apache.lucene.search.Query;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class QueryBuilderFactory implements QueryBuilder {++ HashMap builders=new HashMap();++ public Query getQuery(Element n) throws ParserException {+ QueryBuilder builder=(QueryBuilder) builders.get(n.getNodeName());+ if(builder==null)+ {+ throw new ParserException("No QueryObjectBuilder defined for node "+n.getNodeName());+ }+ return builder.getQuery(n);+ }+ public void addBuilder(String nodeName,QueryBuilder builder)+ {+ builders.put(nodeName,builder);+ }+ public QueryBuilder getQueryBuilder(String nodeName)+ {+ return (QueryBuilder) builders.get(nodeName);+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryTemplateManager.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryTemplateManager.javaindex b8b050360b8..76f3a144c65 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryTemplateManager.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/QueryTemplateManager.java@@ -1,211 +1,211 @@-package org.apache.lucene.xmlparser;--import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.util.Enumeration;-import java.util.HashMap;-import java.util.Properties;--import javax.xml.parsers.DocumentBuilder;-import javax.xml.parsers.DocumentBuilderFactory;-import javax.xml.parsers.ParserConfigurationException;-import javax.xml.transform.Result;-import javax.xml.transform.Source;-import javax.xml.transform.Templates;-import javax.xml.transform.Transformer;-import javax.xml.transform.TransformerConfigurationException;-import javax.xml.transform.TransformerException;-import javax.xml.transform.TransformerFactory;-import javax.xml.transform.dom.DOMResult;-import javax.xml.transform.dom.DOMSource;-import javax.xml.transform.stream.StreamResult;--import org.w3c.dom.Document;-import org.w3c.dom.Element;-import org.xml.sax.SAXException;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-/**- * Provides utilities for turning query form input (such as from a web page or Swing gui) into- * Lucene XML queries by using XSL templates. This approach offers a convenient way of externalizing- * and changing how user input is turned into Lucene queries.- * Database applications often adopt similar practices by externalizing SQL in template files that can- * be easily changed/optimized by a DBA.- * The static methods can be used on their own or by creating an instance of this class you can store and- * re-use compiled stylesheets for fast use (e.g. in a server environment)- */-public class QueryTemplateManager-{- static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();- static TransformerFactory tFactory = TransformerFactory.newInstance();-- HashMap compiledTemplatesCache=new HashMap();- Templates defaultCompiledTemplates=null;--- public QueryTemplateManager()- {-- }- public QueryTemplateManager(InputStream xslIs) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException- {- addDefaultQueryTemplate(xslIs);- }- public void addDefaultQueryTemplate(InputStream xslIs) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException- {- defaultCompiledTemplates=getTemplates(xslIs);- }- public void addQueryTemplate(String name, InputStream xslIs) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException- {- compiledTemplatesCache.put(name,getTemplates(xslIs));- }- public String getQueryAsXmlString(Properties formProperties,String queryTemplateName) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- Templates ts=(Templates) compiledTemplatesCache.get(queryTemplateName);- return getQueryAsXmlString(formProperties, ts);- }-- public Document getQueryAsDOM(Properties formProperties,String queryTemplateName) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- Templates ts=(Templates) compiledTemplatesCache.get(queryTemplateName);- return getQueryAsDOM(formProperties, ts);- }- public String getQueryAsXmlString(Properties formProperties) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- return getQueryAsXmlString(formProperties, defaultCompiledTemplates);- }-- public Document getQueryAsDOM(Properties formProperties) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- return getQueryAsDOM(formProperties, defaultCompiledTemplates);- }--- /**- * Fast means of constructing query using a precompiled stylesheet- */- public static String getQueryAsXmlString(Properties formProperties, Templates template) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- ByteArrayOutputStream baos=new ByteArrayOutputStream();- StreamResult result=new StreamResult(baos);- transformCriteria(formProperties,template,result);- return baos.toString();- }-- /**- * Slow means of constructing query parsing a stylesheet from an input stream- */- public static String getQueryAsXmlString(Properties formProperties, InputStream xslIs) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- ByteArrayOutputStream baos=new ByteArrayOutputStream();- StreamResult result=new StreamResult(baos);- transformCriteria(formProperties,xslIs,result);- return baos.toString();- }--- /**- * Fast means of constructing query using a cached,precompiled stylesheet- */- public static Document getQueryAsDOM(Properties formProperties, Templates template) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- DOMResult result=new DOMResult();- transformCriteria(formProperties,template,result);- return (Document)result.getNode();- }--- /**- * Slow means of constructing query - parses stylesheet from input stream- */- public static Document getQueryAsDOM(Properties formProperties, InputStream xslIs) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- DOMResult result=new DOMResult();- transformCriteria(formProperties,xslIs,result);- return (Document)result.getNode();- }----- /**- * Slower transformation using an uncompiled stylesheet (suitable for development environment)- */- public static void transformCriteria(Properties formProperties, InputStream xslIs, Result result) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- dbf.setNamespaceAware(true);- DocumentBuilder builder = dbf.newDocumentBuilder();- org.w3c.dom.Document xslDoc = builder.parse(xslIs);- DOMSource ds = new DOMSource(xslDoc);-- Transformer transformer =null;- synchronized (tFactory)- {- transformer = tFactory.newTransformer(ds);- }- transformCriteria(formProperties,transformer,result);- }-- /**- * Fast transformation using a pre-compiled stylesheet (suitable for production environments)- */- public static void transformCriteria(Properties formProperties, Templates template, Result result) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- transformCriteria(formProperties,template.newTransformer(),result);- }---- public static void transformCriteria(Properties formProperties, Transformer transformer, Result result) throws SAXException, IOException, ParserConfigurationException, TransformerException- {- dbf.setNamespaceAware(true);-- //Create an XML document representing the search index document.- DocumentBuilder db = dbf.newDocumentBuilder ();- org.w3c.dom.Document doc = db.newDocument ();- Element root = doc.createElement ("Document");- doc.appendChild (root);-- Enumeration keysEnum = formProperties.keys();- while(keysEnum.hasMoreElements())- {- String propName=(String) keysEnum.nextElement();- String value=formProperties.getProperty(propName);- if((value!=null)&&(value.length()>0))- {- DOMUtils.insertChild(root,propName,value);- }- }- //Use XSLT to to transform into an XML query string using the queryTemplate- DOMSource xml=new DOMSource(doc);- transformer.transform(xml,result);- }-- /**- * Parses a query stylesheet for repeated use- */- public static Templates getTemplates(InputStream xslIs) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException- {- dbf.setNamespaceAware(true);- DocumentBuilder builder = dbf.newDocumentBuilder();- org.w3c.dom.Document xslDoc = builder.parse(xslIs);- DOMSource ds = new DOMSource(xslDoc);- return tFactory.newTemplates(ds);- }-}+package org.apache.lucene.xmlparser;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.util.Enumeration;+import java.util.HashMap;+import java.util.Properties;++import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;+import javax.xml.parsers.ParserConfigurationException;+import javax.xml.transform.Result;+import javax.xml.transform.Source;+import javax.xml.transform.Templates;+import javax.xml.transform.Transformer;+import javax.xml.transform.TransformerConfigurationException;+import javax.xml.transform.TransformerException;+import javax.xml.transform.TransformerFactory;+import javax.xml.transform.dom.DOMResult;+import javax.xml.transform.dom.DOMSource;+import javax.xml.transform.stream.StreamResult;++import org.w3c.dom.Document;+import org.w3c.dom.Element;+import org.xml.sax.SAXException;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+/**+ * Provides utilities for turning query form input (such as from a web page or Swing gui) into+ * Lucene XML queries by using XSL templates. This approach offers a convenient way of externalizing+ * and changing how user input is turned into Lucene queries.+ * Database applications often adopt similar practices by externalizing SQL in template files that can+ * be easily changed/optimized by a DBA.+ * The static methods can be used on their own or by creating an instance of this class you can store and+ * re-use compiled stylesheets for fast use (e.g. in a server environment)+ */+public class QueryTemplateManager+{+ static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();+ static TransformerFactory tFactory = TransformerFactory.newInstance();++ HashMap compiledTemplatesCache=new HashMap();+ Templates defaultCompiledTemplates=null;+++ public QueryTemplateManager()+ {++ }+ public QueryTemplateManager(InputStream xslIs) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException+ {+ addDefaultQueryTemplate(xslIs);+ }+ public void addDefaultQueryTemplate(InputStream xslIs) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException+ {+ defaultCompiledTemplates=getTemplates(xslIs);+ }+ public void addQueryTemplate(String name, InputStream xslIs) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException+ {+ compiledTemplatesCache.put(name,getTemplates(xslIs));+ }+ public String getQueryAsXmlString(Properties formProperties,String queryTemplateName) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ Templates ts=(Templates) compiledTemplatesCache.get(queryTemplateName);+ return getQueryAsXmlString(formProperties, ts);+ }++ public Document getQueryAsDOM(Properties formProperties,String queryTemplateName) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ Templates ts=(Templates) compiledTemplatesCache.get(queryTemplateName);+ return getQueryAsDOM(formProperties, ts);+ }+ public String getQueryAsXmlString(Properties formProperties) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ return getQueryAsXmlString(formProperties, defaultCompiledTemplates);+ }++ public Document getQueryAsDOM(Properties formProperties) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ return getQueryAsDOM(formProperties, defaultCompiledTemplates);+ }+++ /**+ * Fast means of constructing query using a precompiled stylesheet+ */+ public static String getQueryAsXmlString(Properties formProperties, Templates template) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ ByteArrayOutputStream baos=new ByteArrayOutputStream();+ StreamResult result=new StreamResult(baos);+ transformCriteria(formProperties,template,result);+ return baos.toString();+ }++ /**+ * Slow means of constructing query parsing a stylesheet from an input stream+ */+ public static String getQueryAsXmlString(Properties formProperties, InputStream xslIs) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ ByteArrayOutputStream baos=new ByteArrayOutputStream();+ StreamResult result=new StreamResult(baos);+ transformCriteria(formProperties,xslIs,result);+ return baos.toString();+ }+++ /**+ * Fast means of constructing query using a cached,precompiled stylesheet+ */+ public static Document getQueryAsDOM(Properties formProperties, Templates template) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ DOMResult result=new DOMResult();+ transformCriteria(formProperties,template,result);+ return (Document)result.getNode();+ }+++ /**+ * Slow means of constructing query - parses stylesheet from input stream+ */+ public static Document getQueryAsDOM(Properties formProperties, InputStream xslIs) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ DOMResult result=new DOMResult();+ transformCriteria(formProperties,xslIs,result);+ return (Document)result.getNode();+ }+++++ /**+ * Slower transformation using an uncompiled stylesheet (suitable for development environment)+ */+ public static void transformCriteria(Properties formProperties, InputStream xslIs, Result result) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ dbf.setNamespaceAware(true);+ DocumentBuilder builder = dbf.newDocumentBuilder();+ org.w3c.dom.Document xslDoc = builder.parse(xslIs);+ DOMSource ds = new DOMSource(xslDoc);++ Transformer transformer =null;+ synchronized (tFactory)+ {+ transformer = tFactory.newTransformer(ds);+ }+ transformCriteria(formProperties,transformer,result);+ }++ /**+ * Fast transformation using a pre-compiled stylesheet (suitable for production environments)+ */+ public static void transformCriteria(Properties formProperties, Templates template, Result result) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ transformCriteria(formProperties,template.newTransformer(),result);+ }++++ public static void transformCriteria(Properties formProperties, Transformer transformer, Result result) throws SAXException, IOException, ParserConfigurationException, TransformerException+ {+ dbf.setNamespaceAware(true);++ //Create an XML document representing the search index document.+ DocumentBuilder db = dbf.newDocumentBuilder ();+ org.w3c.dom.Document doc = db.newDocument ();+ Element root = doc.createElement ("Document");+ doc.appendChild (root);++ Enumeration keysEnum = formProperties.keys();+ while(keysEnum.hasMoreElements())+ {+ String propName=(String) keysEnum.nextElement();+ String value=formProperties.getProperty(propName);+ if((value!=null)&&(value.length()>0))+ {+ DOMUtils.insertChild(root,propName,value);+ }+ }+ //Use XSLT to to transform into an XML query string using the queryTemplate+ DOMSource xml=new DOMSource(doc);+ transformer.transform(xml,result);+ }++ /**+ * Parses a query stylesheet for repeated use+ */+ public static Templates getTemplates(InputStream xslIs) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException+ {+ dbf.setNamespaceAware(true);+ DocumentBuilder builder = dbf.newDocumentBuilder();+ org.w3c.dom.Document xslDoc = builder.parse(xslIs);+ DOMSource ds = new DOMSource(xslDoc);+ return tFactory.newTemplates(ds);+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanFilterBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanFilterBuilder.javaindex ebcd9bf0635..a5465fa39df 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanFilterBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanFilterBuilder.java@@ -1,64 +1,64 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanFilter;-import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilterClause;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilder;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-import org.w3c.dom.Node;-import org.w3c.dom.NodeList;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class BooleanFilterBuilder implements FilterBuilder {-- private FilterBuilder factory;-- public BooleanFilterBuilder(FilterBuilder factory)- {- this.factory=factory;- }-- public Filter getFilter(Element e) throws ParserException {- BooleanFilter bf=new BooleanFilter();- NodeList nl = e.getChildNodes();-- for(int i=0;i<nl.getLength();i++)- {- Node node = nl.item(i);- if(node.getNodeName().equals("Clause"))- {- Element clauseElem=(Element) node;- BooleanClause.Occur occurs=BooleanQueryBuilder.getOccursValue(clauseElem);-- Element clauseFilter=DOMUtils.getFirstChildOrFail(clauseElem);- Filter f=factory.getFilter(clauseFilter);- bf.add(new FilterClause(f,occurs));- }- }-- return bf;- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanFilter;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.FilterClause;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilder;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class BooleanFilterBuilder implements FilterBuilder {++ private FilterBuilder factory;++ public BooleanFilterBuilder(FilterBuilder factory)+ {+ this.factory=factory;+ }++ public Filter getFilter(Element e) throws ParserException {+ BooleanFilter bf=new BooleanFilter();+ NodeList nl = e.getChildNodes();++ for(int i=0;i<nl.getLength();i++)+ {+ Node node = nl.item(i);+ if(node.getNodeName().equals("Clause"))+ {+ Element clauseElem=(Element) node;+ BooleanClause.Occur occurs=BooleanQueryBuilder.getOccursValue(clauseElem);++ Element clauseFilter=DOMUtils.getFirstChildOrFail(clauseElem);+ Filter f=factory.getFilter(clauseFilter);+ bf.add(new FilterClause(f,occurs));+ }+ }++ return bf;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanQueryBuilder.javaindex 0eb88f0af6a..dffd3ad6298 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BooleanQueryBuilder.java@@ -1,100 +1,100 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-import org.w3c.dom.Node;-import org.w3c.dom.NodeList;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---public class BooleanQueryBuilder implements QueryBuilder {-- private QueryBuilder factory;-- public BooleanQueryBuilder(QueryBuilder factory)- {- this.factory=factory;- }-- /* (non-Javadoc)- * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)- */- public Query getQuery(Element e) throws ParserException {- BooleanQuery bq=new BooleanQuery(DOMUtils.getAttribute(e,"disableCoord",false));- bq.setMinimumNumberShouldMatch(DOMUtils.getAttribute(e,"minimumNumberShouldMatch",0));- bq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));-- NodeList nl = e.getChildNodes();- for(int i=0;i<nl.getLength();i++)- {- Node node = nl.item(i);- if(node.getNodeName().equals("Clause"))- {- Element clauseElem=(Element) node;- BooleanClause.Occur occurs=getOccursValue(clauseElem);-- Element clauseQuery=DOMUtils.getFirstChildOrFail(clauseElem);- Query q=factory.getQuery(clauseQuery);- bq.add(new BooleanClause(q,occurs));- }- }-- return bq;- }- static BooleanClause.Occur getOccursValue(Element clauseElem) throws ParserException- {- String occs=clauseElem.getAttribute("occurs");- BooleanClause.Occur occurs=BooleanClause.Occur.SHOULD;- if("must".equalsIgnoreCase(occs))- {- occurs=BooleanClause.Occur.MUST;- }- else- {- if("mustNot".equalsIgnoreCase(occs))- {- occurs=BooleanClause.Occur.MUST_NOT;- }- else- {- if(("should".equalsIgnoreCase(occs))||("".equals(occs)))- {- occurs=BooleanClause.Occur.SHOULD;- }- else- {- if(occs!=null)- {- throw new ParserException("Invalid value for \"occurs\" attribute of clause:"+occs);- }- }- }- }- return occurs;-- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++public class BooleanQueryBuilder implements QueryBuilder {++ private QueryBuilder factory;++ public BooleanQueryBuilder(QueryBuilder factory)+ {+ this.factory=factory;+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)+ */+ public Query getQuery(Element e) throws ParserException {+ BooleanQuery bq=new BooleanQuery(DOMUtils.getAttribute(e,"disableCoord",false));+ bq.setMinimumNumberShouldMatch(DOMUtils.getAttribute(e,"minimumNumberShouldMatch",0));+ bq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));++ NodeList nl = e.getChildNodes();+ for(int i=0;i<nl.getLength();i++)+ {+ Node node = nl.item(i);+ if(node.getNodeName().equals("Clause"))+ {+ Element clauseElem=(Element) node;+ BooleanClause.Occur occurs=getOccursValue(clauseElem);++ Element clauseQuery=DOMUtils.getFirstChildOrFail(clauseElem);+ Query q=factory.getQuery(clauseQuery);+ bq.add(new BooleanClause(q,occurs));+ }+ }++ return bq;+ }+ static BooleanClause.Occur getOccursValue(Element clauseElem) throws ParserException+ {+ String occs=clauseElem.getAttribute("occurs");+ BooleanClause.Occur occurs=BooleanClause.Occur.SHOULD;+ if("must".equalsIgnoreCase(occs))+ {+ occurs=BooleanClause.Occur.MUST;+ }+ else+ {+ if("mustNot".equalsIgnoreCase(occs))+ {+ occurs=BooleanClause.Occur.MUST_NOT;+ }+ else+ {+ if(("should".equalsIgnoreCase(occs))||("".equals(occs)))+ {+ occurs=BooleanClause.Occur.SHOULD;+ }+ else+ {+ if(occs!=null)+ {+ throw new ParserException("Invalid value for \"occurs\" attribute of clause:"+occs);+ }+ }+ }+ }+ return occurs;++ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BoostingQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BoostingQueryBuilder.javaindex ec83eddaf53..5ca17cbd5b0 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BoostingQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/BoostingQueryBuilder.java@@ -1,57 +1,57 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.BoostingQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class BoostingQueryBuilder implements QueryBuilder-{-- private QueryBuilder factory;- float defaultBoost=0.01f;-- public BoostingQueryBuilder (QueryBuilder factory)- {- this.factory=factory;- }-- public Query getQuery(Element e) throws ParserException- {-- Element mainQueryElem=DOMUtils.getChildByTagOrFail(e,"Query");- mainQueryElem=DOMUtils.getFirstChildOrFail(mainQueryElem);- Query mainQuery=factory.getQuery(mainQueryElem);-- Element boostQueryElem=DOMUtils.getChildByTagOrFail(e,"BoostQuery");- float boost=DOMUtils.getAttribute(boostQueryElem,"boost",defaultBoost);- boostQueryElem=DOMUtils.getFirstChildOrFail(boostQueryElem);- Query boostQuery=factory.getQuery(boostQueryElem);-- BoostingQuery bq = new BoostingQuery(mainQuery,boostQuery,boost);-- bq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return bq;-- }---}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.BoostingQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class BoostingQueryBuilder implements QueryBuilder+{++ private QueryBuilder factory;+ float defaultBoost=0.01f;++ public BoostingQueryBuilder (QueryBuilder factory)+ {+ this.factory=factory;+ }++ public Query getQuery(Element e) throws ParserException+ {++ Element mainQueryElem=DOMUtils.getChildByTagOrFail(e,"Query");+ mainQueryElem=DOMUtils.getFirstChildOrFail(mainQueryElem);+ Query mainQuery=factory.getQuery(mainQueryElem);++ Element boostQueryElem=DOMUtils.getChildByTagOrFail(e,"BoostQuery");+ float boost=DOMUtils.getAttribute(boostQueryElem,"boost",defaultBoost);+ boostQueryElem=DOMUtils.getFirstChildOrFail(boostQueryElem);+ Query boostQuery=factory.getQuery(boostQueryElem);++ BoostingQuery bq = new BoostingQuery(mainQuery,boostQuery,boost);++ bq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return bq;++ }+++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/CachedFilterBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/CachedFilterBuilder.javaindex 674f694efa6..8280a2c7579 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/CachedFilterBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/CachedFilterBuilder.java@@ -1,129 +1,129 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import java.util.Map.Entry;--import org.apache.lucene.search.CachingWrapperFilter;-import org.apache.lucene.search.Filter;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.QueryWrapperFilter;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilder;-import org.apache.lucene.xmlparser.FilterBuilderFactory;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.apache.lucene.xmlparser.QueryBuilderFactory;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-/**- * Filters are cached in an LRU Cache keyed on the contained query or filter object. Using this will- * speed up overall performance for repeated uses of the same expensive query/filter. The sorts of- * queries/filters likely to benefit from caching need not necessarily be complex - e.g. simple- * TermQuerys with a large DF (document frequency) can be expensive on large indexes.- * A good example of this might be a term query on a field with only 2 possible values -- * "true" or "false". In a large index, querying or filtering on this field requires reading- * millions of document ids from disk which can more usefully be cached as a filter bitset.- *- * For Queries/Filters to be cached and reused the object must implement hashcode and- * equals methods correctly so that duplicate queries/filters can be detected in the cache.- *- * The CoreParser.maxNumCachedFilters property can be used to control the size of the LRU- * Cache established during the construction of CoreParser instances.- *- */-public class CachedFilterBuilder implements FilterBuilder {-- private QueryBuilderFactory queryFactory;- private FilterBuilderFactory filterFactory;-- private LRUCache filterCache = null;-- private int cacheSize;-- public CachedFilterBuilder(QueryBuilderFactory queryFactory,- FilterBuilderFactory filterFactory,int cacheSize)- {- this.queryFactory=queryFactory;- this.filterFactory=filterFactory;- this.cacheSize=cacheSize;- }-- public synchronized Filter getFilter(Element e) throws ParserException- {-- Element childElement = DOMUtils.getFirstChildOrFail(e);-- if (filterCache == null)- {- filterCache = new LRUCache(cacheSize);- }-- // Test to see if child Element is a query or filter that needs to be- // cached- QueryBuilder qb = queryFactory.getQueryBuilder(childElement.getNodeName());- Object cacheKey = null;- Query q = null;- Filter f = null;- if (qb != null)- {- q = qb.getQuery(childElement);- cacheKey = q;- } else- {- f = filterFactory.getFilter(childElement);- cacheKey = f;- }- Filter cachedFilter = (Filter) filterCache.get(cacheKey);- if (cachedFilter != null)- {- return cachedFilter; // cache hit- }-- //cache miss- if (qb != null)- {- cachedFilter = new QueryWrapperFilter(q);- } else- {- cachedFilter = new CachingWrapperFilter(f);- }-- filterCache.put(cacheKey, cachedFilter);- return cachedFilter;- }-- static class LRUCache extends java.util.LinkedHashMap- {- public LRUCache(int maxsize)- {- super(maxsize * 4 / 3 + 1, 0.75f, true);- this.maxsize = maxsize;- }-- protected int maxsize;-- protected boolean removeEldestEntry(Entry eldest)- {- return size() > maxsize;- }-- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import java.util.Map.Entry;++import org.apache.lucene.search.CachingWrapperFilter;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.QueryWrapperFilter;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilder;+import org.apache.lucene.xmlparser.FilterBuilderFactory;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.apache.lucene.xmlparser.QueryBuilderFactory;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+/**+ * Filters are cached in an LRU Cache keyed on the contained query or filter object. Using this will+ * speed up overall performance for repeated uses of the same expensive query/filter. The sorts of+ * queries/filters likely to benefit from caching need not necessarily be complex - e.g. simple+ * TermQuerys with a large DF (document frequency) can be expensive on large indexes.+ * A good example of this might be a term query on a field with only 2 possible values -+ * "true" or "false". In a large index, querying or filtering on this field requires reading+ * millions of document ids from disk which can more usefully be cached as a filter bitset.+ *+ * For Queries/Filters to be cached and reused the object must implement hashcode and+ * equals methods correctly so that duplicate queries/filters can be detected in the cache.+ *+ * The CoreParser.maxNumCachedFilters property can be used to control the size of the LRU+ * Cache established during the construction of CoreParser instances.+ *+ */+public class CachedFilterBuilder implements FilterBuilder {++ private QueryBuilderFactory queryFactory;+ private FilterBuilderFactory filterFactory;++ private LRUCache filterCache = null;++ private int cacheSize;++ public CachedFilterBuilder(QueryBuilderFactory queryFactory,+ FilterBuilderFactory filterFactory,int cacheSize)+ {+ this.queryFactory=queryFactory;+ this.filterFactory=filterFactory;+ this.cacheSize=cacheSize;+ }++ public synchronized Filter getFilter(Element e) throws ParserException+ {++ Element childElement = DOMUtils.getFirstChildOrFail(e);++ if (filterCache == null)+ {+ filterCache = new LRUCache(cacheSize);+ }++ // Test to see if child Element is a query or filter that needs to be+ // cached+ QueryBuilder qb = queryFactory.getQueryBuilder(childElement.getNodeName());+ Object cacheKey = null;+ Query q = null;+ Filter f = null;+ if (qb != null)+ {+ q = qb.getQuery(childElement);+ cacheKey = q;+ } else+ {+ f = filterFactory.getFilter(childElement);+ cacheKey = f;+ }+ Filter cachedFilter = (Filter) filterCache.get(cacheKey);+ if (cachedFilter != null)+ {+ return cachedFilter; // cache hit+ }++ //cache miss+ if (qb != null)+ {+ cachedFilter = new QueryWrapperFilter(q);+ } else+ {+ cachedFilter = new CachingWrapperFilter(f);+ }++ filterCache.put(cacheKey, cachedFilter);+ return cachedFilter;+ }++ static class LRUCache extends java.util.LinkedHashMap+ {+ public LRUCache(int maxsize)+ {+ super(maxsize * 4 / 3 + 1, 0.75f, true);+ this.maxsize = maxsize;+ }++ protected int maxsize;++ protected boolean removeEldestEntry(Entry eldest)+ {+ return size() > maxsize;+ }++ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/ConstantScoreQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/ConstantScoreQueryBuilder.javaindex 55819459b80..c80ae569ac5 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/ConstantScoreQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/ConstantScoreQueryBuilder.java@@ -1,46 +1,46 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.ConstantScoreQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilderFactory;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class ConstantScoreQueryBuilder implements QueryBuilder-{- private FilterBuilderFactory filterFactory;-- public ConstantScoreQueryBuilder(FilterBuilderFactory filterFactory)- {- this.filterFactory=filterFactory;- }-- public Query getQuery(Element e) throws ParserException- {- Element filterElem=DOMUtils.getFirstChildOrFail(e);- Query q=new ConstantScoreQuery(filterFactory.getFilter(filterElem));-- q.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));-- return q;-- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.ConstantScoreQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilderFactory;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class ConstantScoreQueryBuilder implements QueryBuilder+{+ private FilterBuilderFactory filterFactory;++ public ConstantScoreQueryBuilder(FilterBuilderFactory filterFactory)+ {+ this.filterFactory=filterFactory;+ }++ public Query getQuery(Element e) throws ParserException+ {+ Element filterElem=DOMUtils.getFirstChildOrFail(e);+ Query q=new ConstantScoreQuery(filterFactory.getFilter(filterElem));++ q.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));++ return q;++ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/DuplicateFilterBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/DuplicateFilterBuilder.javaindex fdbd64372d7..fad8f2ee0d8 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/DuplicateFilterBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/DuplicateFilterBuilder.java@@ -1,73 +1,73 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanFilter;-import org.apache.lucene.search.DuplicateFilter;-import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilterClause;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilder;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-import org.w3c.dom.Node;-import org.w3c.dom.NodeList;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class DuplicateFilterBuilder implements FilterBuilder {--- public Filter getFilter(Element e) throws ParserException {- String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");- DuplicateFilter df=new DuplicateFilter(fieldName);- String keepMode=DOMUtils.getAttribute(e,"keepMode","first");- if(keepMode.equalsIgnoreCase("first"))- {- df.setKeepMode(DuplicateFilter.KM_USE_FIRST_OCCURRENCE);- }- else- if(keepMode.equalsIgnoreCase("last"))- {- df.setKeepMode(DuplicateFilter.KM_USE_LAST_OCCURRENCE);- }- else- {- throw new ParserException("Illegal keepMode attribute in DuplicateFilter:"+keepMode);- }- String processingMode=DOMUtils.getAttribute(e,"processingMode","full");- if(processingMode.equalsIgnoreCase("full"))- {- df.setProcessingMode(DuplicateFilter.PM_FULL_VALIDATION);- }- else- if(processingMode.equalsIgnoreCase("fast"))- {- df.setProcessingMode(DuplicateFilter.PM_FAST_INVALIDATION);- }- else- {- throw new ParserException("Illegal processingMode attribute in DuplicateFilter:"+processingMode);- }-- return df;- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanFilter;+import org.apache.lucene.search.DuplicateFilter;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.FilterClause;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilder;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class DuplicateFilterBuilder implements FilterBuilder {+++ public Filter getFilter(Element e) throws ParserException {+ String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");+ DuplicateFilter df=new DuplicateFilter(fieldName);+ String keepMode=DOMUtils.getAttribute(e,"keepMode","first");+ if(keepMode.equalsIgnoreCase("first"))+ {+ df.setKeepMode(DuplicateFilter.KM_USE_FIRST_OCCURRENCE);+ }+ else+ if(keepMode.equalsIgnoreCase("last"))+ {+ df.setKeepMode(DuplicateFilter.KM_USE_LAST_OCCURRENCE);+ }+ else+ {+ throw new ParserException("Illegal keepMode attribute in DuplicateFilter:"+keepMode);+ }+ String processingMode=DOMUtils.getAttribute(e,"processingMode","full");+ if(processingMode.equalsIgnoreCase("full"))+ {+ df.setProcessingMode(DuplicateFilter.PM_FULL_VALIDATION);+ }+ else+ if(processingMode.equalsIgnoreCase("fast"))+ {+ df.setProcessingMode(DuplicateFilter.PM_FAST_INVALIDATION);+ }+ else+ {+ throw new ParserException("Illegal processingMode attribute in DuplicateFilter:"+processingMode);+ }++ return df;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FilteredQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FilteredQueryBuilder.javaindex 6b08b7666ac..c68a59a11be 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FilteredQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FilteredQueryBuilder.java@@ -1,61 +1,61 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilder;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class FilteredQueryBuilder implements QueryBuilder {-- private FilterBuilder filterFactory;- private QueryBuilder queryFactory;-- public FilteredQueryBuilder(FilterBuilder filterFactory, QueryBuilder queryFactory)- {- this.filterFactory=filterFactory;- this.queryFactory=queryFactory;-- }-- /* (non-Javadoc)- * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)- */- public Query getQuery(Element e) throws ParserException {- Element filterElement=DOMUtils.getChildByTagOrFail(e,"Filter");- filterElement=DOMUtils.getFirstChildOrFail(filterElement);- Filter f=filterFactory.getFilter(filterElement);-- Element queryElement=DOMUtils.getChildByTagOrFail(e,"Query");- queryElement=DOMUtils.getFirstChildOrFail(queryElement);- Query q=queryFactory.getQuery(queryElement);-- FilteredQuery fq = new FilteredQuery(q,f);- fq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return fq;- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.Filter;+import org.apache.lucene.search.FilteredQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilder;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class FilteredQueryBuilder implements QueryBuilder {++ private FilterBuilder filterFactory;+ private QueryBuilder queryFactory;++ public FilteredQueryBuilder(FilterBuilder filterFactory, QueryBuilder queryFactory)+ {+ this.filterFactory=filterFactory;+ this.queryFactory=queryFactory;++ }++ /* (non-Javadoc)+ * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)+ */+ public Query getQuery(Element e) throws ParserException {+ Element filterElement=DOMUtils.getChildByTagOrFail(e,"Filter");+ filterElement=DOMUtils.getFirstChildOrFail(filterElement);+ Filter f=filterFactory.getFilter(filterElement);++ Element queryElement=DOMUtils.getChildByTagOrFail(e,"Query");+ queryElement=DOMUtils.getFirstChildOrFail(queryElement);+ Query q=queryFactory.getQuery(queryElement);++ FilteredQuery fq = new FilteredQuery(q,f);+ fq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return fq;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FuzzyLikeThisQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FuzzyLikeThisQueryBuilder.javaindex 2dbd305fe8d..4a8681f263c 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FuzzyLikeThisQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/FuzzyLikeThisQueryBuilder.java@@ -1,62 +1,62 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.search.FuzzyLikeThisQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-import org.w3c.dom.NodeList;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class FuzzyLikeThisQueryBuilder implements QueryBuilder-{- int defaultMaxNumTerms=50;- float defaultMinSimilarity=0.5f;- int defaultPrefixLength=1;- boolean defaultIgnoreTF=false;- private Analyzer analyzer;-- public FuzzyLikeThisQueryBuilder(Analyzer analyzer)- {- this.analyzer=analyzer;- }-- public Query getQuery(Element e) throws ParserException- {- NodeList nl = e.getElementsByTagName("Field");- int maxNumTerms=DOMUtils.getAttribute(e,"maxNumTerms",defaultMaxNumTerms);- FuzzyLikeThisQuery fbq=new FuzzyLikeThisQuery(maxNumTerms,analyzer);- fbq.setIgnoreTF(DOMUtils.getAttribute(e,"ignoreTF",defaultIgnoreTF));- for(int i=0;i<nl.getLength();i++)- {- Element fieldElem=(Element) nl.item(i);- float minSimilarity=DOMUtils.getAttribute(fieldElem,"minSimilarity",defaultMinSimilarity);- int prefixLength=DOMUtils.getAttribute(fieldElem,"prefixLength",defaultPrefixLength);- String fieldName=DOMUtils.getAttributeWithInheritance(fieldElem,"fieldName");-- String value=DOMUtils.getText(fieldElem);- fbq.addTerms(value,fieldName,minSimilarity,prefixLength);- }- fbq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));-- return fbq;- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.search.FuzzyLikeThisQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+import org.w3c.dom.NodeList;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class FuzzyLikeThisQueryBuilder implements QueryBuilder+{+ int defaultMaxNumTerms=50;+ float defaultMinSimilarity=0.5f;+ int defaultPrefixLength=1;+ boolean defaultIgnoreTF=false;+ private Analyzer analyzer;++ public FuzzyLikeThisQueryBuilder(Analyzer analyzer)+ {+ this.analyzer=analyzer;+ }++ public Query getQuery(Element e) throws ParserException+ {+ NodeList nl = e.getElementsByTagName("Field");+ int maxNumTerms=DOMUtils.getAttribute(e,"maxNumTerms",defaultMaxNumTerms);+ FuzzyLikeThisQuery fbq=new FuzzyLikeThisQuery(maxNumTerms,analyzer);+ fbq.setIgnoreTF(DOMUtils.getAttribute(e,"ignoreTF",defaultIgnoreTF));+ for(int i=0;i<nl.getLength();i++)+ {+ Element fieldElem=(Element) nl.item(i);+ float minSimilarity=DOMUtils.getAttribute(fieldElem,"minSimilarity",defaultMinSimilarity);+ int prefixLength=DOMUtils.getAttribute(fieldElem,"prefixLength",defaultPrefixLength);+ String fieldName=DOMUtils.getAttributeWithInheritance(fieldElem,"fieldName");++ String value=DOMUtils.getText(fieldElem);+ fbq.addTerms(value,fieldName,minSimilarity,prefixLength);+ }+ fbq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));++ return fbq;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/LikeThisQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/LikeThisQueryBuilder.javaindex 768bbba8df0..431c1d13b5d 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/LikeThisQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/LikeThisQueryBuilder.java@@ -1,112 +1,112 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import java.io.IOException;-import java.io.StringReader;-import java.util.HashSet;-import java.util.Set;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.search.similar.MoreLikeThisQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---public class LikeThisQueryBuilder implements QueryBuilder {-- private Analyzer analyzer;- String defaultFieldNames [];- int defaultMaxQueryTerms=20;- int defaultMinTermFrequency=1;- float defaultPercentTermsToMatch=30; //default is a 3rd of selected terms must match-- public LikeThisQueryBuilder(Analyzer analyzer,String [] defaultFieldNames)- {- this.analyzer=analyzer;- this.defaultFieldNames=defaultFieldNames;- }-- /* (non-Javadoc)- * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)- */- public Query getQuery(Element e) throws ParserException {- String fieldsList=e.getAttribute("fieldNames"); //a comma-delimited list of fields- String fields[]=defaultFieldNames;- if((fieldsList!=null)&&(fieldsList.trim().length()>0))- {- fields=fieldsList.trim().split(",");- //trim the fieldnames- for (int i = 0; i < fields.length; i++) {- fields[i]=fields[i].trim();- }- }-- //Parse any "stopWords" attribute- //TODO MoreLikeThis needs to ideally have per-field stopWords lists - until then- //I use all analyzers/fields to generate multi-field compatible stop list- String stopWords=e.getAttribute("stopWords");- Set stopWordsSet=null;- if((stopWords!=null)&&(fields!=null))- {- stopWordsSet=new HashSet();- final Token reusableToken = new Token();- for (int i = 0; i < fields.length; i++)- {- TokenStream ts = analyzer.tokenStream(fields[i],new StringReader(stopWords));- try- {- for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {- stopWordsSet.add(nextToken.term());- }- }- catch(IOException ioe)- {- throw new ParserException("IoException parsing stop words list in "- +getClass().getName()+":"+ioe.getLocalizedMessage());- }- }- }--- MoreLikeThisQuery mlt=new MoreLikeThisQuery(DOMUtils.getText(e),fields,analyzer);- mlt.setMaxQueryTerms(DOMUtils.getAttribute(e,"maxQueryTerms",defaultMaxQueryTerms));- mlt.setMinTermFrequency(DOMUtils.getAttribute(e,"minTermFrequency",defaultMinTermFrequency));- mlt.setPercentTermsToMatch(DOMUtils.getAttribute(e,"percentTermsToMatch",defaultPercentTermsToMatch)/100);- mlt.setStopWords(stopWordsSet);- int minDocFreq=DOMUtils.getAttribute(e,"minDocFreq",-1);- if(minDocFreq>=0)- {- mlt.setMinDocFreq(minDocFreq);- }-- mlt.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));-- return mlt;- }----}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import java.io.IOException;+import java.io.StringReader;+import java.util.HashSet;+import java.util.Set;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.search.similar.MoreLikeThisQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++public class LikeThisQueryBuilder implements QueryBuilder {++ private Analyzer analyzer;+ String defaultFieldNames [];+ int defaultMaxQueryTerms=20;+ int defaultMinTermFrequency=1;+ float defaultPercentTermsToMatch=30; //default is a 3rd of selected terms must match++ public LikeThisQueryBuilder(Analyzer analyzer,String [] defaultFieldNames)+ {+ this.analyzer=analyzer;+ this.defaultFieldNames=defaultFieldNames;+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)+ */+ public Query getQuery(Element e) throws ParserException {+ String fieldsList=e.getAttribute("fieldNames"); //a comma-delimited list of fields+ String fields[]=defaultFieldNames;+ if((fieldsList!=null)&&(fieldsList.trim().length()>0))+ {+ fields=fieldsList.trim().split(",");+ //trim the fieldnames+ for (int i = 0; i < fields.length; i++) {+ fields[i]=fields[i].trim();+ }+ }++ //Parse any "stopWords" attribute+ //TODO MoreLikeThis needs to ideally have per-field stopWords lists - until then+ //I use all analyzers/fields to generate multi-field compatible stop list+ String stopWords=e.getAttribute("stopWords");+ Set stopWordsSet=null;+ if((stopWords!=null)&&(fields!=null))+ {+ stopWordsSet=new HashSet();+ final Token reusableToken = new Token();+ for (int i = 0; i < fields.length; i++)+ {+ TokenStream ts = analyzer.tokenStream(fields[i],new StringReader(stopWords));+ try+ {+ for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {+ stopWordsSet.add(nextToken.term());+ }+ }+ catch(IOException ioe)+ {+ throw new ParserException("IoException parsing stop words list in "+ +getClass().getName()+":"+ioe.getLocalizedMessage());+ }+ }+ }+++ MoreLikeThisQuery mlt=new MoreLikeThisQuery(DOMUtils.getText(e),fields,analyzer);+ mlt.setMaxQueryTerms(DOMUtils.getAttribute(e,"maxQueryTerms",defaultMaxQueryTerms));+ mlt.setMinTermFrequency(DOMUtils.getAttribute(e,"minTermFrequency",defaultMinTermFrequency));+ mlt.setPercentTermsToMatch(DOMUtils.getAttribute(e,"percentTermsToMatch",defaultPercentTermsToMatch)/100);+ mlt.setStopWords(stopWordsSet);+ int minDocFreq=DOMUtils.getAttribute(e,"minDocFreq",-1);+ if(minDocFreq>=0)+ {+ mlt.setMinDocFreq(minDocFreq);+ }++ mlt.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));++ return mlt;+ }++++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/MatchAllDocsQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/MatchAllDocsQueryBuilder.javaindex 59e74d9e2eb..01aec2ecad1 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/MatchAllDocsQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/MatchAllDocsQueryBuilder.java@@ -1,30 +1,30 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.MatchAllDocsQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class MatchAllDocsQueryBuilder implements QueryBuilder-{- public Query getQuery(Element e) throws ParserException- {- return new MatchAllDocsQuery();- }-}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.MatchAllDocsQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class MatchAllDocsQueryBuilder implements QueryBuilder+{+ public Query getQuery(Element e) throws ParserException+ {+ return new MatchAllDocsQuery();+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/RangeFilterBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/RangeFilterBuilder.javaindex 5b62448226f..389af5d9b8e 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/RangeFilterBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/RangeFilterBuilder.java@@ -1,45 +1,45 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.Filter;-import org.apache.lucene.search.RangeFilter;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilder;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */----public class RangeFilterBuilder implements FilterBuilder {--- public Filter getFilter(Element e) throws ParserException {-- String fieldName=DOMUtils.getAttributeWithInheritance(e,"fieldName");-- String lowerTerm=e.getAttribute("lowerTerm");- String upperTerm=e.getAttribute("upperTerm");- boolean includeLower=DOMUtils.getAttribute(e,"includeLower",true);- boolean includeUpper=DOMUtils.getAttribute(e,"includeUpper",true);- return new RangeFilter(fieldName,lowerTerm,upperTerm,includeLower,includeUpper);- }--}+/*+ * Created on 25-Jan-2006+ */+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.Filter;+import org.apache.lucene.search.RangeFilter;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilder;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++++public class RangeFilterBuilder implements FilterBuilder {+++ public Filter getFilter(Element e) throws ParserException {++ String fieldName=DOMUtils.getAttributeWithInheritance(e,"fieldName");++ String lowerTerm=e.getAttribute("lowerTerm");+ String upperTerm=e.getAttribute("upperTerm");+ boolean includeLower=DOMUtils.getAttribute(e,"includeLower",true);+ boolean includeUpper=DOMUtils.getAttribute(e,"includeUpper",true);+ return new RangeFilter(fieldName,lowerTerm,upperTerm,includeLower,includeUpper);+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanBuilderBase.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanBuilderBase.javaindex 387617c0095..e7fde616d8b 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanBuilderBase.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanBuilderBase.java@@ -1,29 +1,29 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public abstract class SpanBuilderBase implements SpanQueryBuilder-{- public Query getQuery(Element e) throws ParserException- {- return getSpanQuery(e);- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public abstract class SpanBuilderBase implements SpanQueryBuilder+{+ public Query getQuery(Element e) throws ParserException+ {+ return getSpanQuery(e);+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanFirstBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanFirstBuilder.javaindex 2fc91716172..79c95f1cba6 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanFirstBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanFirstBuilder.java@@ -1,46 +1,46 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.spans.SpanFirstQuery;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class SpanFirstBuilder extends SpanBuilderBase-{- SpanQueryBuilder factory;-- public SpanFirstBuilder(SpanQueryBuilder factory)- {- super();- this.factory = factory;- }-- public SpanQuery getSpanQuery(Element e) throws ParserException- {- int end=DOMUtils.getAttribute(e,"end",1);- Element child=DOMUtils.getFirstChildElement(e);- SpanQuery q=factory.getSpanQuery(child);-- SpanFirstQuery sfq = new SpanFirstQuery(q,end);-- sfq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return sfq;- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.spans.SpanFirstQuery;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class SpanFirstBuilder extends SpanBuilderBase+{+ SpanQueryBuilder factory;++ public SpanFirstBuilder(SpanQueryBuilder factory)+ {+ super();+ this.factory = factory;+ }++ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ int end=DOMUtils.getAttribute(e,"end",1);+ Element child=DOMUtils.getFirstChildElement(e);+ SpanQuery q=factory.getSpanQuery(child);++ SpanFirstQuery sfq = new SpanFirstQuery(q,end);++ sfq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return sfq;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNearBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNearBuilder.javaindex b7e7c83a81b..b9bd7500d4f 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNearBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNearBuilder.java@@ -1,53 +1,53 @@-package org.apache.lucene.xmlparser.builders;--import java.util.ArrayList;--import org.apache.lucene.search.spans.SpanNearQuery;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-import org.w3c.dom.Node;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class SpanNearBuilder extends SpanBuilderBase-{- SpanQueryBuilder factory;- public SpanNearBuilder(SpanQueryBuilder factory)- {- this.factory=factory;- }-- public SpanQuery getSpanQuery(Element e) throws ParserException- {- String slopString=DOMUtils.getAttributeOrFail(e,"slop");- int slop=Integer.parseInt(slopString);- boolean inOrder=DOMUtils.getAttribute(e,"inOrder",false);- ArrayList spans=new ArrayList();- for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())- {- if (kid.getNodeType() == Node.ELEMENT_NODE)- {- spans.add(factory.getSpanQuery((Element) kid));- }- }- SpanQuery[] spanQueries=(SpanQuery[]) spans.toArray(new SpanQuery[spans.size()]);- SpanNearQuery snq=new SpanNearQuery(spanQueries,slop,inOrder);- return snq;- }--}+package org.apache.lucene.xmlparser.builders;++import java.util.ArrayList;++import org.apache.lucene.search.spans.SpanNearQuery;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class SpanNearBuilder extends SpanBuilderBase+{+ SpanQueryBuilder factory;+ public SpanNearBuilder(SpanQueryBuilder factory)+ {+ this.factory=factory;+ }++ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ String slopString=DOMUtils.getAttributeOrFail(e,"slop");+ int slop=Integer.parseInt(slopString);+ boolean inOrder=DOMUtils.getAttribute(e,"inOrder",false);+ ArrayList spans=new ArrayList();+ for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())+ {+ if (kid.getNodeType() == Node.ELEMENT_NODE)+ {+ spans.add(factory.getSpanQuery((Element) kid));+ }+ }+ SpanQuery[] spanQueries=(SpanQuery[]) spans.toArray(new SpanQuery[spans.size()]);+ SpanNearQuery snq=new SpanNearQuery(spanQueries,slop,inOrder);+ return snq;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNotBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNotBuilder.javaindex 98059a9660f..5092eaf215d 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNotBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNotBuilder.java@@ -1,54 +1,54 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.search.spans.SpanNotQuery;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class SpanNotBuilder extends SpanBuilderBase-{-- SpanQueryBuilder factory;-- /**- * @param factory- */- public SpanNotBuilder(SpanQueryBuilder factory)- {- super();- this.factory = factory;- }- public SpanQuery getSpanQuery(Element e) throws ParserException- {- Element includeElem=DOMUtils.getChildByTagOrFail(e,"Include");- includeElem=DOMUtils.getFirstChildOrFail(includeElem);-- Element excludeElem=DOMUtils.getChildByTagOrFail(e,"Exclude");- excludeElem=DOMUtils.getFirstChildOrFail(excludeElem);-- SpanQuery include=factory.getSpanQuery(includeElem);- SpanQuery exclude=factory.getSpanQuery(excludeElem);-- SpanNotQuery snq = new SpanNotQuery(include,exclude);-- snq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return snq;- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.search.spans.SpanNotQuery;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class SpanNotBuilder extends SpanBuilderBase+{++ SpanQueryBuilder factory;++ /**+ * @param factory+ */+ public SpanNotBuilder(SpanQueryBuilder factory)+ {+ super();+ this.factory = factory;+ }+ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ Element includeElem=DOMUtils.getChildByTagOrFail(e,"Include");+ includeElem=DOMUtils.getFirstChildOrFail(includeElem);++ Element excludeElem=DOMUtils.getChildByTagOrFail(e,"Exclude");+ excludeElem=DOMUtils.getFirstChildOrFail(excludeElem);++ SpanQuery include=factory.getSpanQuery(includeElem);+ SpanQuery exclude=factory.getSpanQuery(excludeElem);++ SpanNotQuery snq = new SpanNotQuery(include,exclude);++ snq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return snq;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrBuilder.javaindex 7cc7f28dcae..f284aaa6c5d 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrBuilder.java@@ -1,55 +1,55 @@-package org.apache.lucene.xmlparser.builders;--import java.util.ArrayList;--import org.apache.lucene.search.spans.SpanOrQuery;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-import org.w3c.dom.Node;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class SpanOrBuilder extends SpanBuilderBase-{-- SpanQueryBuilder factory;-- public SpanOrBuilder(SpanQueryBuilder factory)- {- super();- this.factory = factory;- }-- public SpanQuery getSpanQuery(Element e) throws ParserException- {- ArrayList clausesList=new ArrayList();- for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())- {- if (kid.getNodeType() == Node.ELEMENT_NODE)- {- SpanQuery clause=factory.getSpanQuery((Element) kid);- clausesList.add(clause);- }- }- SpanQuery[] clauses=(SpanQuery[]) clausesList.toArray(new SpanQuery[clausesList.size()]);- SpanOrQuery soq = new SpanOrQuery(clauses);- soq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return soq;- }--}+package org.apache.lucene.xmlparser.builders;++import java.util.ArrayList;++import org.apache.lucene.search.spans.SpanOrQuery;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class SpanOrBuilder extends SpanBuilderBase+{++ SpanQueryBuilder factory;++ public SpanOrBuilder(SpanQueryBuilder factory)+ {+ super();+ this.factory = factory;+ }++ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ ArrayList clausesList=new ArrayList();+ for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling())+ {+ if (kid.getNodeType() == Node.ELEMENT_NODE)+ {+ SpanQuery clause=factory.getSpanQuery((Element) kid);+ clausesList.add(clause);+ }+ }+ SpanQuery[] clauses=(SpanQuery[]) clausesList.toArray(new SpanQuery[clausesList.size()]);+ SpanOrQuery soq = new SpanOrQuery(clauses);+ soq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return soq;+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrTermsBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrTermsBuilder.javaindex 603d1245ab9..c8ed5665b9f 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrTermsBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanOrTermsBuilder.java@@ -1,70 +1,70 @@-package org.apache.lucene.xmlparser.builders;--import java.io.IOException;-import java.io.StringReader;-import java.util.ArrayList;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.spans.SpanOrQuery;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.search.spans.SpanTermQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class SpanOrTermsBuilder extends SpanBuilderBase-{- Analyzer analyzer;--- /**- * @param analyzer- */- public SpanOrTermsBuilder(Analyzer analyzer)- {- super();- this.analyzer = analyzer;- }- public SpanQuery getSpanQuery(Element e) throws ParserException- {- String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");- String value=DOMUtils.getNonBlankTextOrFail(e);-- try- {- ArrayList clausesList=new ArrayList();- TokenStream ts=analyzer.tokenStream(fieldName,new StringReader(value));- final Token reusableToken = new Token();- for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {- SpanTermQuery stq=new SpanTermQuery(new Term(fieldName,nextToken.term()));- clausesList.add(stq);- }- SpanOrQuery soq=new SpanOrQuery((SpanQuery[]) clausesList.toArray(new SpanQuery[clausesList.size()]));- soq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return soq;- }- catch(IOException ioe)- {- throw new ParserException("IOException parsing value:"+value);- }- }--}+package org.apache.lucene.xmlparser.builders;++import java.io.IOException;+import java.io.StringReader;+import java.util.ArrayList;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.spans.SpanOrQuery;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.search.spans.SpanTermQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class SpanOrTermsBuilder extends SpanBuilderBase+{+ Analyzer analyzer;+++ /**+ * @param analyzer+ */+ public SpanOrTermsBuilder(Analyzer analyzer)+ {+ super();+ this.analyzer = analyzer;+ }+ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");+ String value=DOMUtils.getNonBlankTextOrFail(e);++ try+ {+ ArrayList clausesList=new ArrayList();+ TokenStream ts=analyzer.tokenStream(fieldName,new StringReader(value));+ final Token reusableToken = new Token();+ for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {+ SpanTermQuery stq=new SpanTermQuery(new Term(fieldName,nextToken.term()));+ clausesList.add(stq);+ }+ SpanOrQuery soq=new SpanOrQuery((SpanQuery[]) clausesList.toArray(new SpanQuery[clausesList.size()]));+ soq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return soq;+ }+ catch(IOException ioe)+ {+ throw new ParserException("IOException parsing value:"+value);+ }+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilder.javaindex 35a5c8632cc..baa679bde65 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilder.java@@ -1,28 +1,28 @@-package org.apache.lucene.xmlparser.builders;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;---public interface SpanQueryBuilder extends QueryBuilder{-- public SpanQuery getSpanQuery(Element e) throws ParserException;--}+package org.apache.lucene.xmlparser.builders;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+++public interface SpanQueryBuilder extends QueryBuilder{++ public SpanQuery getSpanQuery(Element e) throws ParserException;++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilderFactory.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilderFactory.javaindex fba68e5344f..e2723689e56 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilderFactory.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanQueryBuilderFactory.java@@ -1,47 +1,47 @@-package org.apache.lucene.xmlparser.builders;--import java.util.HashMap;--import org.apache.lucene.search.Query;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class SpanQueryBuilderFactory implements SpanQueryBuilder {-- HashMap builders=new HashMap();-- public Query getQuery(Element e) throws ParserException {- return getSpanQuery(e);- }- public void addBuilder(String nodeName,SpanQueryBuilder builder)- {- builders.put(nodeName,builder);- }- public SpanQuery getSpanQuery(Element e) throws ParserException- {- SpanQueryBuilder builder=(SpanQueryBuilder) builders.get(e.getNodeName());- if(builder==null)- {- throw new ParserException("No SpanQueryObjectBuilder defined for node "+e.getNodeName());- }- return builder.getSpanQuery(e);- }--}+package org.apache.lucene.xmlparser.builders;++import java.util.HashMap;++import org.apache.lucene.search.Query;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class SpanQueryBuilderFactory implements SpanQueryBuilder {++ HashMap builders=new HashMap();++ public Query getQuery(Element e) throws ParserException {+ return getSpanQuery(e);+ }+ public void addBuilder(String nodeName,SpanQueryBuilder builder)+ {+ builders.put(nodeName,builder);+ }+ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ SpanQueryBuilder builder=(SpanQueryBuilder) builders.get(e.getNodeName());+ if(builder==null)+ {+ throw new ParserException("No SpanQueryObjectBuilder defined for node "+e.getNodeName());+ }+ return builder.getSpanQuery(e);+ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanTermBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanTermBuilder.javaindex fbaad1bbc65..3a31d8f9970 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanTermBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanTermBuilder.java@@ -1,39 +1,39 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.index.Term;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.search.spans.SpanTermQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-public class SpanTermBuilder extends SpanBuilderBase-{-- public SpanQuery getSpanQuery(Element e) throws ParserException- {- String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");- String value=DOMUtils.getNonBlankTextOrFail(e);- SpanTermQuery stq = new SpanTermQuery(new Term(fieldName,value));-- stq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return stq;-- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.index.Term;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.search.spans.SpanTermQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+public class SpanTermBuilder extends SpanBuilderBase+{++ public SpanQuery getSpanQuery(Element e) throws ParserException+ {+ String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");+ String value=DOMUtils.getNonBlankTextOrFail(e);+ SpanTermQuery stq = new SpanTermQuery(new Term(fieldName,value));++ stq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return stq;++ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermQueryBuilder.javaindex 680f2266ce3..37df3752f6d 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermQueryBuilder.java@@ -1,41 +1,41 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.index.Term;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.TermQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---public class TermQueryBuilder implements QueryBuilder {-- public Query getQuery(Element e) throws ParserException {-- String field=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");- String value=DOMUtils.getNonBlankTextOrFail(e);- TermQuery tq = new TermQuery(new Term(field,value));- tq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));-- return tq;-- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.index.Term;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++public class TermQueryBuilder implements QueryBuilder {++ public Query getQuery(Element e) throws ParserException {++ String field=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");+ String value=DOMUtils.getNonBlankTextOrFail(e);+ TermQuery tq = new TermQuery(new Term(field,value));+ tq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));++ return tq;++ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsFilterBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsFilterBuilder.javaindex b632ea24687..52091dccb92 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsFilterBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsFilterBuilder.java@@ -1,81 +1,81 @@-package org.apache.lucene.xmlparser.builders;--import java.io.IOException;-import java.io.StringReader;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.Filter;-import org.apache.lucene.search.TermsFilter;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.FilterBuilder;-import org.apache.lucene.xmlparser.ParserException;-import org.w3c.dom.Element;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class TermsFilterBuilder implements FilterBuilder-{- Analyzer analyzer;-- /**- * @param analyzer- */- public TermsFilterBuilder(Analyzer analyzer)- {- this.analyzer = analyzer;- }-- /*- * (non-Javadoc)- *- * @see org.apache.lucene.xmlparser.FilterBuilder#process(org.w3c.dom.Element)- */- public Filter getFilter(Element e) throws ParserException- {- TermsFilter tf = new TermsFilter();- String text = DOMUtils.getNonBlankTextOrFail(e);- String fieldName = DOMUtils.getAttributeWithInheritanceOrFail(e, "fieldName");- TokenStream ts = analyzer.tokenStream(fieldName, new StringReader(text));-- try- {- final Token reusableToken = new Token();- Term term = null;- for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {- if (term == null)- {- term = new Term(fieldName, nextToken.term());- } else- {-// create from previous to save fieldName.intern overhead- term = term.createTerm(nextToken.term());- }- tf.addTerm(term);- }- }- catch (IOException ioe)- {- throw new RuntimeException("Error constructing terms from index:"- + ioe);- }- return tf;- }-}+package org.apache.lucene.xmlparser.builders;++import java.io.IOException;+import java.io.StringReader;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.TermsFilter;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.FilterBuilder;+import org.apache.lucene.xmlparser.ParserException;+import org.w3c.dom.Element;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class TermsFilterBuilder implements FilterBuilder+{+ Analyzer analyzer;++ /**+ * @param analyzer+ */+ public TermsFilterBuilder(Analyzer analyzer)+ {+ this.analyzer = analyzer;+ }++ /*+ * (non-Javadoc)+ *+ * @see org.apache.lucene.xmlparser.FilterBuilder#process(org.w3c.dom.Element)+ */+ public Filter getFilter(Element e) throws ParserException+ {+ TermsFilter tf = new TermsFilter();+ String text = DOMUtils.getNonBlankTextOrFail(e);+ String fieldName = DOMUtils.getAttributeWithInheritanceOrFail(e, "fieldName");+ TokenStream ts = analyzer.tokenStream(fieldName, new StringReader(text));++ try+ {+ final Token reusableToken = new Token();+ Term term = null;+ for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {+ if (term == null)+ {+ term = new Term(fieldName, nextToken.term());+ } else+ {+// create from previous to save fieldName.intern overhead+ term = term.createTerm(nextToken.term());+ }+ tf.addTerm(term);+ }+ }+ catch (IOException ioe)+ {+ throw new RuntimeException("Error constructing terms from index:"+ + ioe);+ }+ return tf;+ }+}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsQueryBuilder.javaindex d33996d3de0..40e1c2ca035 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/TermsQueryBuilder.java@@ -1,85 +1,85 @@-package org.apache.lucene.xmlparser.builders;--import java.io.IOException;-import java.io.StringReader;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.Token;-import org.apache.lucene.analysis.TokenStream;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.TermQuery;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-/**- * Builds a BooleanQuery from all of the terms found in the XML element using the choice of analyzer- */-public class TermsQueryBuilder implements QueryBuilder {-- Analyzer analyzer;--- public TermsQueryBuilder(Analyzer analyzer)- {- this.analyzer = analyzer;- }---- public Query getQuery(Element e) throws ParserException {-- String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");- String text=DOMUtils.getNonBlankTextOrFail(e);-- BooleanQuery bq=new BooleanQuery(DOMUtils.getAttribute(e,"disableCoord",false));- bq.setMinimumNumberShouldMatch(DOMUtils.getAttribute(e,"minimumNumberShouldMatch",0));- TokenStream ts = analyzer.tokenStream(fieldName, new StringReader(text));- try- {- final Token reusableToken = new Token();- Term term = null;- for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {- if (term == null)- {- term = new Term(fieldName, nextToken.term());- } else- {-// create from previous to save fieldName.intern overhead- term = term.createTerm(nextToken.term());- }- bq.add(new BooleanClause(new TermQuery(term),BooleanClause.Occur.SHOULD));- }- }- catch (IOException ioe)- {- throw new RuntimeException("Error constructing terms from index:"- + ioe);- }- bq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));-- return bq;-- }--}+package org.apache.lucene.xmlparser.builders;++import java.io.IOException;+import java.io.StringReader;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+/**+ * Builds a BooleanQuery from all of the terms found in the XML element using the choice of analyzer+ */+public class TermsQueryBuilder implements QueryBuilder {++ Analyzer analyzer;+++ public TermsQueryBuilder(Analyzer analyzer)+ {+ this.analyzer = analyzer;+ }++++ public Query getQuery(Element e) throws ParserException {++ String fieldName=DOMUtils.getAttributeWithInheritanceOrFail(e,"fieldName");+ String text=DOMUtils.getNonBlankTextOrFail(e);++ BooleanQuery bq=new BooleanQuery(DOMUtils.getAttribute(e,"disableCoord",false));+ bq.setMinimumNumberShouldMatch(DOMUtils.getAttribute(e,"minimumNumberShouldMatch",0));+ TokenStream ts = analyzer.tokenStream(fieldName, new StringReader(text));+ try+ {+ final Token reusableToken = new Token();+ Term term = null;+ for (Token nextToken = ts.next(reusableToken); nextToken != null; nextToken = ts.next(reusableToken)) {+ if (term == null)+ {+ term = new Term(fieldName, nextToken.term());+ } else+ {+// create from previous to save fieldName.intern overhead+ term = term.createTerm(nextToken.term());+ }+ bq.add(new BooleanClause(new TermQuery(term),BooleanClause.Occur.SHOULD));+ }+ }+ catch (IOException ioe)+ {+ throw new RuntimeException("Error constructing terms from index:"+ + ioe);+ }+ bq.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));++ return bq;++ }++}diff --git a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/UserInputQueryBuilder.java b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/UserInputQueryBuilder.javaindex b611ef25963..ffd82771473 100644--- a/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/UserInputQueryBuilder.java+++ b/contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/UserInputQueryBuilder.java@@ -1,94 +1,94 @@-package org.apache.lucene.xmlparser.builders;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.queryParser.ParseException;-import org.apache.lucene.queryParser.QueryParser;-import org.apache.lucene.search.Query;-import org.apache.lucene.xmlparser.DOMUtils;-import org.apache.lucene.xmlparser.ParserException;-import org.apache.lucene.xmlparser.QueryBuilder;-import org.w3c.dom.Element;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--/**- * UserInputQueryBuilder uses 1 of 2 strategies for thread-safe parsing:- * 1) Synchronizing access to "parse" calls on a previously supplied QueryParser- * or..- * 2) creating a new QueryParser object for each parse request- */-public class UserInputQueryBuilder implements QueryBuilder {-- QueryParser unSafeParser;- private Analyzer analyzer;- private String defaultField;-- /**- * This constructor has the disadvantage of not being able to change choice of default field name- * @param parser thread un-safe query parser- */- public UserInputQueryBuilder(QueryParser parser) {- this.unSafeParser = parser;- }-- public UserInputQueryBuilder(String defaultField, Analyzer analyzer) {- this.analyzer = analyzer;- this.defaultField = defaultField;- }-- /* (non-Javadoc)- * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)- */- public Query getQuery(Element e) throws ParserException {- String text=DOMUtils.getText(e);- try {- Query q = null;- if(unSafeParser!=null)- {- //synchronize on unsafe parser- synchronized (unSafeParser)- {- q = unSafeParser.parse(text);- }- }- else- {- String fieldName=DOMUtils.getAttribute(e, "fieldName", defaultField);- //Create new parser- QueryParser parser=createQueryParser(fieldName, analyzer);- q = parser.parse(text);- }- q.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));- return q;- } catch (ParseException e1) {- throw new ParserException(e1.getMessage());- }- }-- /**- * Method to create a QueryParser - designed to be overridden- * @param fieldName- * @param analyzer- * @return- */- protected QueryParser createQueryParser(String fieldName, Analyzer analyzer)- {- return new QueryParser(fieldName,analyzer);- }--}+package org.apache.lucene.xmlparser.builders;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.queryParser.ParseException;+import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.search.Query;+import org.apache.lucene.xmlparser.DOMUtils;+import org.apache.lucene.xmlparser.ParserException;+import org.apache.lucene.xmlparser.QueryBuilder;+import org.w3c.dom.Element;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * UserInputQueryBuilder uses 1 of 2 strategies for thread-safe parsing:+ * 1) Synchronizing access to "parse" calls on a previously supplied QueryParser+ * or..+ * 2) creating a new QueryParser object for each parse request+ */+public class UserInputQueryBuilder implements QueryBuilder {++ QueryParser unSafeParser;+ private Analyzer analyzer;+ private String defaultField;++ /**+ * This constructor has the disadvantage of not being able to change choice of default field name+ * @param parser thread un-safe query parser+ */+ public UserInputQueryBuilder(QueryParser parser) {+ this.unSafeParser = parser;+ }++ public UserInputQueryBuilder(String defaultField, Analyzer analyzer) {+ this.analyzer = analyzer;+ this.defaultField = defaultField;+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)+ */+ public Query getQuery(Element e) throws ParserException {+ String text=DOMUtils.getText(e);+ try {+ Query q = null;+ if(unSafeParser!=null)+ {+ //synchronize on unsafe parser+ synchronized (unSafeParser)+ {+ q = unSafeParser.parse(text);+ }+ }+ else+ {+ String fieldName=DOMUtils.getAttribute(e, "fieldName", defaultField);+ //Create new parser+ QueryParser parser=createQueryParser(fieldName, analyzer);+ q = parser.parse(text);+ }+ q.setBoost(DOMUtils.getAttribute(e,"boost",1.0f));+ return q;+ } catch (ParseException e1) {+ throw new ParserException(e1.getMessage());+ }+ }++ /**+ * Method to create a QueryParser - designed to be overridden+ * @param fieldName+ * @param analyzer+ * @return+ */+ protected QueryParser createQueryParser(String fieldName, Analyzer analyzer)+ {+ return new QueryParser(fieldName,analyzer);+ }++}diff --git a/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestParser.java b/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestParser.javaindex 7e291a64419..87c9679e24b 100644--- a/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestParser.java+++ b/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestParser.java@@ -1,215 +1,215 @@-package org.apache.lucene.xmlparser;--import java.io.BufferedReader;-import java.io.IOException;-import java.io.InputStream;-import java.io.InputStreamReader;--import junit.framework.TestCase;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.standard.StandardAnalyzer;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.search.Hits;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.store.Directory;-import org.apache.lucene.store.RAMDirectory;-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--public class TestParser extends TestCase {-- CoreParser builder;- static Directory dir;- Analyzer analyzer=new StandardAnalyzer();- IndexReader reader;- private IndexSearcher searcher;-- //CHANGE THIS TO SEE OUTPUT- boolean printResults=false;--- /*- * @see TestCase#setUp()- */- protected void setUp() throws Exception {- super.setUp();-- //initialize the parser- builder=new CorePlusExtensionsParser("contents",analyzer);-- //initialize the index (done once, then cached in static data for use with ALL tests)- if(dir==null)- {- BufferedReader d = new BufferedReader(new InputStreamReader(TestParser.class.getResourceAsStream("reuters21578.txt")));- dir=new RAMDirectory();- IndexWriter writer=new IndexWriter(dir,analyzer,true);- String line = d.readLine();- while(line!=null)- {- int endOfDate=line.indexOf('\t');- String date=line.substring(0,endOfDate).trim();- String content=line.substring(endOfDate).trim();- org.apache.lucene.document.Document doc =new org.apache.lucene.document.Document();- doc.add(new Field("date",date,Field.Store.YES,Field.Index.ANALYZED));- doc.add(new Field("contents",content,Field.Store.YES,Field.Index.ANALYZED));- writer.addDocument(doc);- line=d.readLine();- }- d.close();- writer.close();- }- reader=IndexReader.open(dir);- searcher=new IndexSearcher(reader);-- }----- protected void tearDown() throws Exception {- reader.close();- searcher.close();-// dir.close();-- }- public void testSimpleXML() throws ParserException, IOException- {- Query q=parse("TermQuery.xml");- dumpResults("TermQuery", q, 5);- }- public void testSimpleTermsQueryXML() throws ParserException, IOException- {- Query q=parse("TermsQuery.xml");- dumpResults("TermsQuery", q, 5);- }- public void testBooleanQueryXML() throws ParserException, IOException- {- Query q=parse("BooleanQuery.xml");- dumpResults("BooleanQuery", q, 5);- }- public void testRangeFilterQueryXML() throws ParserException, IOException- {- Query q=parse("RangeFilterQuery.xml");- dumpResults("RangeFilter", q, 5);- }- public void testUserQueryXML() throws ParserException, IOException- {- Query q=parse("UserInputQuery.xml");- dumpResults("UserInput with Filter", q, 5);- }-- public void testCustomFieldUserQueryXML() throws ParserException, IOException- {- Query q=parse("UserInputQueryCustomField.xml");- Hits h = searcher.search(q);- assertEquals("UserInputQueryCustomField should produce 0 result ", 0,h.length());- }-- public void testLikeThisQueryXML() throws Exception- {- Query q=parse("LikeThisQuery.xml");- dumpResults("like this", q, 5);- }- public void testBoostingQueryXML() throws Exception- {- Query q=parse("BoostingQuery.xml");- dumpResults("boosting ",q, 5);- }- public void testFuzzyLikeThisQueryXML() throws Exception- {- Query q=parse("FuzzyLikeThisQuery.xml");- //show rewritten fuzzyLikeThisQuery - see what is being matched on- if(printResults)- {- System.out.println(q.rewrite(reader));- }- dumpResults("FuzzyLikeThis", q, 5);- }- public void testTermsFilterXML() throws Exception- {- Query q=parse("TermsFilterQuery.xml");- dumpResults("Terms Filter",q, 5);- }- public void testSpanTermXML() throws Exception- {- Query q=parse("SpanQuery.xml");- dumpResults("Span Query",q, 5);- }- public void testConstantScoreQueryXML() throws Exception- {- Query q=parse("ConstantScoreQuery.xml");- dumpResults("ConstantScoreQuery",q, 5);- }- public void testMatchAllDocsPlusFilterXML() throws ParserException, IOException- {- Query q=parse("MatchAllDocsQuery.xml");- dumpResults("MatchAllDocsQuery with range filter", q, 5);- }- public void testBooleanFilterXML() throws ParserException, IOException- {- Query q=parse("BooleanFilter.xml");- dumpResults("Boolean filter", q, 5);- }- public void testNestedBooleanQuery() throws ParserException, IOException- {- Query q=parse("NestedBooleanQuery.xml");- dumpResults("Nested Boolean query", q, 5);- }- public void testCachedFilterXML() throws ParserException, IOException- {- Query q=parse("CachedFilter.xml");- dumpResults("Cached filter", q, 5);- }- public void testDuplicateFilterQueryXML() throws ParserException, IOException- {- Query q=parse("DuplicateFilterQuery.xml");- Hits h = searcher.search(q);- assertEquals("DuplicateFilterQuery should produce 1 result ", 1,h.length());- }---- //================= Helper methods ===================================- private Query parse(String xmlFileName) throws ParserException, IOException- {- InputStream xmlStream=TestParser.class.getResourceAsStream(xmlFileName);- Query result=builder.parse(xmlStream);- xmlStream.close();- return result;- }- private void dumpResults(String qType,Query q, int numDocs) throws IOException- {- Hits h = searcher.search(q);- assertTrue(qType +" should produce results ", h.length()>0);- if(printResults)- {- System.out.println("========="+qType+"============");- for(int i=0;i<Math.min(numDocs,h.length());i++)- {- org.apache.lucene.document.Document ldoc=h.doc(i);- System.out.println("["+ldoc.get("date")+"]"+ldoc.get("contents"));- }- System.out.println();- }- }---}+package org.apache.lucene.xmlparser;++import java.io.BufferedReader;+import java.io.IOException;+import java.io.InputStream;+import java.io.InputStreamReader;++import junit.framework.TestCase;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.RAMDirectory;+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class TestParser extends TestCase {++ CoreParser builder;+ static Directory dir;+ Analyzer analyzer=new StandardAnalyzer();+ IndexReader reader;+ private IndexSearcher searcher;++ //CHANGE THIS TO SEE OUTPUT+ boolean printResults=false;+++ /*+ * @see TestCase#setUp()+ */+ protected void setUp() throws Exception {+ super.setUp();++ //initialize the parser+ builder=new CorePlusExtensionsParser("contents",analyzer);++ //initialize the index (done once, then cached in static data for use with ALL tests)+ if(dir==null)+ {+ BufferedReader d = new BufferedReader(new InputStreamReader(TestParser.class.getResourceAsStream("reuters21578.txt")));+ dir=new RAMDirectory();+ IndexWriter writer=new IndexWriter(dir,analyzer,true);+ String line = d.readLine();+ while(line!=null)+ {+ int endOfDate=line.indexOf('\t');+ String date=line.substring(0,endOfDate).trim();+ String content=line.substring(endOfDate).trim();+ org.apache.lucene.document.Document doc =new org.apache.lucene.document.Document();+ doc.add(new Field("date",date,Field.Store.YES,Field.Index.ANALYZED));+ doc.add(new Field("contents",content,Field.Store.YES,Field.Index.ANALYZED));+ writer.addDocument(doc);+ line=d.readLine();+ }+ d.close();+ writer.close();+ }+ reader=IndexReader.open(dir);+ searcher=new IndexSearcher(reader);++ }+++++ protected void tearDown() throws Exception {+ reader.close();+ searcher.close();+// dir.close();++ }+ public void testSimpleXML() throws ParserException, IOException+ {+ Query q=parse("TermQuery.xml");+ dumpResults("TermQuery", q, 5);+ }+ public void testSimpleTermsQueryXML() throws ParserException, IOException+ {+ Query q=parse("TermsQuery.xml");+ dumpResults("TermsQuery", q, 5);+ }+ public void testBooleanQueryXML() throws ParserException, IOException+ {+ Query q=parse("BooleanQuery.xml");+ dumpResults("BooleanQuery", q, 5);+ }+ public void testRangeFilterQueryXML() throws ParserException, IOException+ {+ Query q=parse("RangeFilterQuery.xml");+ dumpResults("RangeFilter", q, 5);+ }+ public void testUserQueryXML() throws ParserException, IOException+ {+ Query q=parse("UserInputQuery.xml");+ dumpResults("UserInput with Filter", q, 5);+ }++ public void testCustomFieldUserQueryXML() throws ParserException, IOException+ {+ Query q=parse("UserInputQueryCustomField.xml");+ Hits h = searcher.search(q);+ assertEquals("UserInputQueryCustomField should produce 0 result ", 0,h.length());+ }++ public void testLikeThisQueryXML() throws Exception+ {+ Query q=parse("LikeThisQuery.xml");+ dumpResults("like this", q, 5);+ }+ public void testBoostingQueryXML() throws Exception+ {+ Query q=parse("BoostingQuery.xml");+ dumpResults("boosting ",q, 5);+ }+ public void testFuzzyLikeThisQueryXML() throws Exception+ {+ Query q=parse("FuzzyLikeThisQuery.xml");+ //show rewritten fuzzyLikeThisQuery - see what is being matched on+ if(printResults)+ {+ System.out.println(q.rewrite(reader));+ }+ dumpResults("FuzzyLikeThis", q, 5);+ }+ public void testTermsFilterXML() throws Exception+ {+ Query q=parse("TermsFilterQuery.xml");+ dumpResults("Terms Filter",q, 5);+ }+ public void testSpanTermXML() throws Exception+ {+ Query q=parse("SpanQuery.xml");+ dumpResults("Span Query",q, 5);+ }+ public void testConstantScoreQueryXML() throws Exception+ {+ Query q=parse("ConstantScoreQuery.xml");+ dumpResults("ConstantScoreQuery",q, 5);+ }+ public void testMatchAllDocsPlusFilterXML() throws ParserException, IOException+ {+ Query q=parse("MatchAllDocsQuery.xml");+ dumpResults("MatchAllDocsQuery with range filter", q, 5);+ }+ public void testBooleanFilterXML() throws ParserException, IOException+ {+ Query q=parse("BooleanFilter.xml");+ dumpResults("Boolean filter", q, 5);+ }+ public void testNestedBooleanQuery() throws ParserException, IOException+ {+ Query q=parse("NestedBooleanQuery.xml");+ dumpResults("Nested Boolean query", q, 5);+ }+ public void testCachedFilterXML() throws ParserException, IOException+ {+ Query q=parse("CachedFilter.xml");+ dumpResults("Cached filter", q, 5);+ }+ public void testDuplicateFilterQueryXML() throws ParserException, IOException+ {+ Query q=parse("DuplicateFilterQuery.xml");+ Hits h = searcher.search(q);+ assertEquals("DuplicateFilterQuery should produce 1 result ", 1,h.length());+ }++++ //================= Helper methods ===================================+ private Query parse(String xmlFileName) throws ParserException, IOException+ {+ InputStream xmlStream=TestParser.class.getResourceAsStream(xmlFileName);+ Query result=builder.parse(xmlStream);+ xmlStream.close();+ return result;+ }+ private void dumpResults(String qType,Query q, int numDocs) throws IOException+ {+ Hits h = searcher.search(q);+ assertTrue(qType +" should produce results ", h.length()>0);+ if(printResults)+ {+ System.out.println("========="+qType+"============");+ for(int i=0;i<Math.min(numDocs,h.length());i++)+ {+ org.apache.lucene.document.Document ldoc=h.doc(i);+ System.out.println("["+ldoc.get("date")+"]"+ldoc.get("contents"));+ }+ System.out.println();+ }+ }+++}diff --git a/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestQueryTemplateManager.java b/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestQueryTemplateManager.javaindex 142b26bde6a..101e977c07a 100644--- a/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestQueryTemplateManager.java+++ b/contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestQueryTemplateManager.java@@ -1,163 +1,163 @@-package org.apache.lucene.xmlparser;--import java.io.IOException;-import java.util.Properties;-import java.util.StringTokenizer;--import javax.xml.parsers.ParserConfigurationException;-import javax.xml.transform.TransformerException;--import junit.framework.TestCase;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.analysis.standard.StandardAnalyzer;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.search.Hits;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.store.RAMDirectory;-import org.w3c.dom.Document;-import org.xml.sax.SAXException;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-/**- * This class illustrates how form input (such as from a web page or Swing gui) can be- * turned into Lucene queries using a choice of XSL templates for different styles of queries.- */-public class TestQueryTemplateManager extends TestCase {-- CoreParser builder;- Analyzer analyzer=new StandardAnalyzer();- private IndexSearcher searcher;-- //A collection of documents' field values for use in our tests- String docFieldValues []=- {- "artist=Jeff Buckley \talbum=Grace \treleaseDate=1999 \tgenre=rock",- "artist=Fugazi \talbum=Repeater \treleaseDate=1990 \tgenre=alternative",- "artist=Fugazi \talbum=Red Medicine \treleaseDate=1995 \tgenre=alternative",- "artist=Peeping Tom \talbum=Peeping Tom \treleaseDate=2006 \tgenre=rock",- "artist=Red Snapper \talbum=Prince Blimey \treleaseDate=1996 \tgenre=electronic"- };-- //A collection of example queries, consisting of name/value pairs representing form content plus- // a choice of query style template to use in the test, with expected number of hits- String queryForms[]=- {- "artist=Fugazi \texpectedMatches=2 \ttemplate=albumBooleanQuery",- "artist=Fugazi \treleaseDate=1990 \texpectedMatches=1 \ttemplate=albumBooleanQuery",- "artist=Buckley \tgenre=rock \texpectedMatches=1 \ttemplate=albumFilteredQuery",- "artist=Buckley \tgenre=electronic \texpectedMatches=0 \ttemplate=albumFilteredQuery",- "queryString=artist:buckly~ NOT genre:electronic \texpectedMatches=1 \ttemplate=albumLuceneClassicQuery"- };--- public void testFormTransforms() throws SAXException, IOException, ParserConfigurationException, TransformerException, ParserException- {- //Cache all the query templates we will be referring to.- QueryTemplateManager qtm=new QueryTemplateManager();- qtm.addQueryTemplate("albumBooleanQuery", getClass().getResourceAsStream("albumBooleanQuery.xsl"));- qtm.addQueryTemplate("albumFilteredQuery", getClass().getResourceAsStream("albumFilteredQuery.xsl"));- qtm.addQueryTemplate("albumLuceneClassicQuery", getClass().getResourceAsStream("albumLuceneClassicQuery.xsl"));- //Run all of our test queries- for (int i = 0; i < queryForms.length; i++)- {- Properties queryFormProperties=getPropsFromString(queryForms[i]);-- //Get the required query XSL template for this test-// Templates template=getTemplate(queryFormProperties.getProperty("template"));-- //Transform the queryFormProperties into a Lucene XML query- Document doc=qtm.getQueryAsDOM(queryFormProperties,queryFormProperties.getProperty("template"));-- //Parse the XML query using the XML parser- Query q=builder.getQuery(doc.getDocumentElement());-- //Run the query- Hits h=searcher.search(q);-- //Check we have the expected number of results- int expectedHits=Integer.parseInt(queryFormProperties.getProperty("expectedMatches"));- assertEquals("Number of results should match for query "+queryForms[i],expectedHits,h.length());-- }- }-- //Helper method to construct Lucene query forms used in our test- Properties getPropsFromString(String nameValuePairs)- {- Properties result=new Properties();- StringTokenizer st=new StringTokenizer(nameValuePairs,"\t=");- while(st.hasMoreTokens())- {- String name=st.nextToken().trim();- if(st.hasMoreTokens())- {- String value=st.nextToken().trim();- result.setProperty(name,value);- }- }- return result;- }-- //Helper method to construct Lucene documents used in our tests- org.apache.lucene.document.Document getDocumentFromString(String nameValuePairs)- {- org.apache.lucene.document.Document result=new org.apache.lucene.document.Document();- StringTokenizer st=new StringTokenizer(nameValuePairs,"\t=");- while(st.hasMoreTokens())- {- String name=st.nextToken().trim();- if(st.hasMoreTokens())- {- String value=st.nextToken().trim();- result.add(new Field(name,value,Field.Store.YES,Field.Index.ANALYZED));- }- }- return result;- }-- /*- * @see TestCase#setUp()- */- protected void setUp() throws Exception {- super.setUp();--- //Create an index- RAMDirectory dir=new RAMDirectory();- IndexWriter w=new IndexWriter(dir,analyzer,true);- for (int i = 0; i < docFieldValues.length; i++)- {- w.addDocument(getDocumentFromString(docFieldValues[i]));- }- w.optimize();- w.close();- searcher=new IndexSearcher(dir);-- //initialize the parser- builder=new CorePlusExtensionsParser("artist", analyzer);-- }--- protected void tearDown() throws Exception {- searcher.close();- }-}+package org.apache.lucene.xmlparser;++import java.io.IOException;+import java.util.Properties;+import java.util.StringTokenizer;++import javax.xml.parsers.ParserConfigurationException;+import javax.xml.transform.TransformerException;++import junit.framework.TestCase;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.store.RAMDirectory;+import org.w3c.dom.Document;+import org.xml.sax.SAXException;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+/**+ * This class illustrates how form input (such as from a web page or Swing gui) can be+ * turned into Lucene queries using a choice of XSL templates for different styles of queries.+ */+public class TestQueryTemplateManager extends TestCase {++ CoreParser builder;+ Analyzer analyzer=new StandardAnalyzer();+ private IndexSearcher searcher;++ //A collection of documents' field values for use in our tests+ String docFieldValues []=+ {+ "artist=Jeff Buckley \talbum=Grace \treleaseDate=1999 \tgenre=rock",+ "artist=Fugazi \talbum=Repeater \treleaseDate=1990 \tgenre=alternative",+ "artist=Fugazi \talbum=Red Medicine \treleaseDate=1995 \tgenre=alternative",+ "artist=Peeping Tom \talbum=Peeping Tom \treleaseDate=2006 \tgenre=rock",+ "artist=Red Snapper \talbum=Prince Blimey \treleaseDate=1996 \tgenre=electronic"+ };++ //A collection of example queries, consisting of name/value pairs representing form content plus+ // a choice of query style template to use in the test, with expected number of hits+ String queryForms[]=+ {+ "artist=Fugazi \texpectedMatches=2 \ttemplate=albumBooleanQuery",+ "artist=Fugazi \treleaseDate=1990 \texpectedMatches=1 \ttemplate=albumBooleanQuery",+ "artist=Buckley \tgenre=rock \texpectedMatches=1 \ttemplate=albumFilteredQuery",+ "artist=Buckley \tgenre=electronic \texpectedMatches=0 \ttemplate=albumFilteredQuery",+ "queryString=artist:buckly~ NOT genre:electronic \texpectedMatches=1 \ttemplate=albumLuceneClassicQuery"+ };+++ public void testFormTransforms() throws SAXException, IOException, ParserConfigurationException, TransformerException, ParserException+ {+ //Cache all the query templates we will be referring to.+ QueryTemplateManager qtm=new QueryTemplateManager();+ qtm.addQueryTemplate("albumBooleanQuery", getClass().getResourceAsStream("albumBooleanQuery.xsl"));+ qtm.addQueryTemplate("albumFilteredQuery", getClass().getResourceAsStream("albumFilteredQuery.xsl"));+ qtm.addQueryTemplate("albumLuceneClassicQuery", getClass().getResourceAsStream("albumLuceneClassicQuery.xsl"));+ //Run all of our test queries+ for (int i = 0; i < queryForms.length; i++)+ {+ Properties queryFormProperties=getPropsFromString(queryForms[i]);++ //Get the required query XSL template for this test+// Templates template=getTemplate(queryFormProperties.getProperty("template"));++ //Transform the queryFormProperties into a Lucene XML query+ Document doc=qtm.getQueryAsDOM(queryFormProperties,queryFormProperties.getProperty("template"));++ //Parse the XML query using the XML parser+ Query q=builder.getQuery(doc.getDocumentElement());++ //Run the query+ Hits h=searcher.search(q);++ //Check we have the expected number of results+ int expectedHits=Integer.parseInt(queryFormProperties.getProperty("expectedMatches"));+ assertEquals("Number of results should match for query "+queryForms[i],expectedHits,h.length());++ }+ }++ //Helper method to construct Lucene query forms used in our test+ Properties getPropsFromString(String nameValuePairs)+ {+ Properties result=new Properties();+ StringTokenizer st=new StringTokenizer(nameValuePairs,"\t=");+ while(st.hasMoreTokens())+ {+ String name=st.nextToken().trim();+ if(st.hasMoreTokens())+ {+ String value=st.nextToken().trim();+ result.setProperty(name,value);+ }+ }+ return result;+ }++ //Helper method to construct Lucene documents used in our tests+ org.apache.lucene.document.Document getDocumentFromString(String nameValuePairs)+ {+ org.apache.lucene.document.Document result=new org.apache.lucene.document.Document();+ StringTokenizer st=new StringTokenizer(nameValuePairs,"\t=");+ while(st.hasMoreTokens())+ {+ String name=st.nextToken().trim();+ if(st.hasMoreTokens())+ {+ String value=st.nextToken().trim();+ result.add(new Field(name,value,Field.Store.YES,Field.Index.ANALYZED));+ }+ }+ return result;+ }++ /*+ * @see TestCase#setUp()+ */+ protected void setUp() throws Exception {+ super.setUp();+++ //Create an index+ RAMDirectory dir=new RAMDirectory();+ IndexWriter w=new IndexWriter(dir,analyzer,true);+ for (int i = 0; i < docFieldValues.length; i++)+ {+ w.addDocument(getDocumentFromString(docFieldValues[i]));+ }+ w.optimize();+ w.close();+ searcher=new IndexSearcher(dir);++ //initialize the parser+ builder=new CorePlusExtensionsParser("artist", analyzer);++ }+++ protected void tearDown() throws Exception {+ searcher.close();+ }+}diff --git a/src/java/org/apache/lucene/util/cache/Cache.java b/src/java/org/apache/lucene/util/cache/Cache.javaindex 820d46cc11b..c82d1a9bf19 100644--- a/src/java/org/apache/lucene/util/cache/Cache.java+++ b/src/java/org/apache/lucene/util/cache/Cache.java@@ -1,105 +1,105 @@-package org.apache.lucene.util.cache;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */---/**- * Base class for cache implementations.- */-public abstract class Cache {-- /**- * Simple Cache wrapper that synchronizes all- * calls that access the cache.- */- static class SynchronizedCache extends Cache {- Object mutex;- Cache cache;-- SynchronizedCache(Cache cache) {- this.cache = cache;- this.mutex = this;- }-- SynchronizedCache(Cache cache, Object mutex) {- this.cache = cache;- this.mutex = mutex;- }-- public void put(Object key, Object value) {- synchronized(mutex) {cache.put(key, value);}- }-- public Object get(Object key) {- synchronized(mutex) {return cache.get(key);}- }-- public boolean containsKey(Object key) {- synchronized(mutex) {return cache.containsKey(key);}- }-- public void close() {- synchronized(mutex) {cache.close();}- }-- Cache getSynchronizedCache() {- return this;- }- }-- /**- * Returns a thread-safe cache backed by the specified cache.- * In order to guarantee thread-safety, all access to the backed cache must- * be accomplished through the returned cache.- */- public static Cache synchronizedCache(Cache cache) {- return cache.getSynchronizedCache();- }-- /**- * Called by {@link #synchronizedCache(Cache)}. This method- * returns a {@link SynchronizedCache} instance that wraps- * this instance by default and can be overridden to return- * e. g. subclasses of {@link SynchronizedCache} or this- * in case this cache is already synchronized.- */- Cache getSynchronizedCache() {- return new SynchronizedCache(this);- }-- /**- * Puts a (key, value)-pair into the cache.- */- public abstract void put(Object key, Object value);-- /**- * Returns the value for the given key.- */- public abstract Object get(Object key);-- /**- * Returns whether the given key is in this cache.- */- public abstract boolean containsKey(Object key);-- /**- * Closes the cache.- */- public abstract void close();--}+package org.apache.lucene.util.cache;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+++/**+ * Base class for cache implementations.+ */+public abstract class Cache {++ /**+ * Simple Cache wrapper that synchronizes all+ * calls that access the cache.+ */+ static class SynchronizedCache extends Cache {+ Object mutex;+ Cache cache;++ SynchronizedCache(Cache cache) {+ this.cache = cache;+ this.mutex = this;+ }++ SynchronizedCache(Cache cache, Object mutex) {+ this.cache = cache;+ this.mutex = mutex;+ }++ public void put(Object key, Object value) {+ synchronized(mutex) {cache.put(key, value);}+ }++ public Object get(Object key) {+ synchronized(mutex) {return cache.get(key);}+ }++ public boolean containsKey(Object key) {+ synchronized(mutex) {return cache.containsKey(key);}+ }++ public void close() {+ synchronized(mutex) {cache.close();}+ }++ Cache getSynchronizedCache() {+ return this;+ }+ }++ /**+ * Returns a thread-safe cache backed by the specified cache.+ * In order to guarantee thread-safety, all access to the backed cache must+ * be accomplished through the returned cache.+ */+ public static Cache synchronizedCache(Cache cache) {+ return cache.getSynchronizedCache();+ }++ /**+ * Called by {@link #synchronizedCache(Cache)}. This method+ * returns a {@link SynchronizedCache} instance that wraps+ * this instance by default and can be overridden to return+ * e. g. subclasses of {@link SynchronizedCache} or this+ * in case this cache is already synchronized.+ */+ Cache getSynchronizedCache() {+ return new SynchronizedCache(this);+ }++ /**+ * Puts a (key, value)-pair into the cache.+ */+ public abstract void put(Object key, Object value);++ /**+ * Returns the value for the given key.+ */+ public abstract Object get(Object key);++ /**+ * Returns whether the given key is in this cache.+ */+ public abstract boolean containsKey(Object key);++ /**+ * Closes the cache.+ */+ public abstract void close();++}diff --git a/src/java/org/apache/lucene/util/cache/SimpleLRUCache.java b/src/java/org/apache/lucene/util/cache/SimpleLRUCache.javaindex 53646c8cc40..74e6267eeb1 100644--- a/src/java/org/apache/lucene/util/cache/SimpleLRUCache.java+++ b/src/java/org/apache/lucene/util/cache/SimpleLRUCache.java@@ -1,49 +1,49 @@-package org.apache.lucene.util.cache;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.util.LinkedHashMap;-import java.util.Map;--/**- * Simple LRU cache implementation that uses a LinkedHashMap.- * This cache is not synchronized, use {@link Cache#synchronizedCache(Cache)}- * if needed.- *- */-public class SimpleLRUCache extends SimpleMapCache {- private final static float LOADFACTOR = 0.75f;-- private int cacheSize;-- /**- * Creates a last-recently-used cache with the specified size.- */- public SimpleLRUCache(int cacheSize) {- super(null);- this.cacheSize = cacheSize;- int capacity = (int) Math.ceil(cacheSize / LOADFACTOR) + 1;-- super.map = new LinkedHashMap(capacity, LOADFACTOR, true) {- protected boolean removeEldestEntry(Map.Entry eldest) {- return size() > SimpleLRUCache.this.cacheSize;- }- };- }--}+package org.apache.lucene.util.cache;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.LinkedHashMap;+import java.util.Map;++/**+ * Simple LRU cache implementation that uses a LinkedHashMap.+ * This cache is not synchronized, use {@link Cache#synchronizedCache(Cache)}+ * if needed.+ *+ */+public class SimpleLRUCache extends SimpleMapCache {+ private final static float LOADFACTOR = 0.75f;++ private int cacheSize;++ /**+ * Creates a last-recently-used cache with the specified size.+ */+ public SimpleLRUCache(int cacheSize) {+ super(null);+ this.cacheSize = cacheSize;+ int capacity = (int) Math.ceil(cacheSize / LOADFACTOR) + 1;++ super.map = new LinkedHashMap(capacity, LOADFACTOR, true) {+ protected boolean removeEldestEntry(Map.Entry eldest) {+ return size() > SimpleLRUCache.this.cacheSize;+ }+ };+ }++}diff --git a/src/java/org/apache/lucene/util/cache/SimpleMapCache.java b/src/java/org/apache/lucene/util/cache/SimpleMapCache.javaindex be0bafdc0d9..8440a692bf4 100644--- a/src/java/org/apache/lucene/util/cache/SimpleMapCache.java+++ b/src/java/org/apache/lucene/util/cache/SimpleMapCache.java@@ -1,100 +1,100 @@-package org.apache.lucene.util.cache;--/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import java.util.HashMap;-import java.util.Map;-import java.util.Set;--/**- * Simple cache implementation that uses a HashMap to store (key, value) pairs.- * This cache is not synchronized, use {@link Cache#synchronizedCache(Cache)}- * if needed.- */-public class SimpleMapCache extends Cache {- Map map;-- public SimpleMapCache() {- this(new HashMap());- }-- public SimpleMapCache(Map map) {- this.map = map;- }-- public Object get(Object key) {- return map.get(key);- }-- public void put(Object key, Object value) {- map.put(key, value);- }-- public void close() {- // NOOP- }-- public boolean containsKey(Object key) {- return map.containsKey(key);- }-- /**- * Returns a Set containing all keys in this cache.- */- public Set keySet() {- return map.keySet();- }-- Cache getSynchronizedCache() {- return new SynchronizedSimpleMapCache(this);- }-- private static class SynchronizedSimpleMapCache extends SimpleMapCache {- Object mutex;- SimpleMapCache cache;-- SynchronizedSimpleMapCache(SimpleMapCache cache) {- this.cache = cache;- this.mutex = this;- }-- public void put(Object key, Object value) {- synchronized(mutex) {cache.put(key, value);}- }-- public Object get(Object key) {- synchronized(mutex) {return cache.get(key);}- }-- public boolean containsKey(Object key) {- synchronized(mutex) {return cache.containsKey(key);}- }-- public void close() {- synchronized(mutex) {cache.close();}- }-- public Set keySet() {- synchronized(mutex) {return cache.keySet();}- }-- Cache getSynchronizedCache() {- return this;- }- }-}+package org.apache.lucene.util.cache;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.HashMap;+import java.util.Map;+import java.util.Set;++/**+ * Simple cache implementation that uses a HashMap to store (key, value) pairs.+ * This cache is not synchronized, use {@link Cache#synchronizedCache(Cache)}+ * if needed.+ */+public class SimpleMapCache extends Cache {+ Map map;++ public SimpleMapCache() {+ this(new HashMap());+ }++ public SimpleMapCache(Map map) {+ this.map = map;+ }++ public Object get(Object key) {+ return map.get(key);+ }++ public void put(Object key, Object value) {+ map.put(key, value);+ }++ public void close() {+ // NOOP+ }++ public boolean containsKey(Object key) {+ return map.containsKey(key);+ }++ /**+ * Returns a Set containing all keys in this cache.+ */+ public Set keySet() {+ return map.keySet();+ }++ Cache getSynchronizedCache() {+ return new SynchronizedSimpleMapCache(this);+ }++ private static class SynchronizedSimpleMapCache extends SimpleMapCache {+ Object mutex;+ SimpleMapCache cache;++ SynchronizedSimpleMapCache(SimpleMapCache cache) {+ this.cache = cache;+ this.mutex = this;+ }++ public void put(Object key, Object value) {+ synchronized(mutex) {cache.put(key, value);}+ }++ public Object get(Object key) {+ synchronized(mutex) {return cache.get(key);}+ }++ public boolean containsKey(Object key) {+ synchronized(mutex) {return cache.containsKey(key);}+ }++ public void close() {+ synchronized(mutex) {cache.close();}+ }++ public Set keySet() {+ synchronized(mutex) {return cache.keySet();}+ }++ Cache getSynchronizedCache() {+ return this;+ }+ }+}diff --git a/src/test/org/apache/lucene/util/TestSmallFloat.java b/src/test/org/apache/lucene/util/TestSmallFloat.javaindex a44c2de2319..5a4608e5704 100644--- a/src/test/org/apache/lucene/util/TestSmallFloat.java+++ b/src/test/org/apache/lucene/util/TestSmallFloat.java@@ -1,113 +1,113 @@-package org.apache.lucene.util;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.lucene.util.LuceneTestCase;-import java.util.Random;--/**- * @version $Id$- */-public class TestSmallFloat extends LuceneTestCase {-- // original lucene byteToFloat- static float orig_byteToFloat(byte b) {- if (b == 0) // zero is a special case- return 0.0f;- int mantissa = b & 7;- int exponent = (b >> 3) & 31;- int bits = ((exponent+(63-15)) << 24) | (mantissa << 21);- return Float.intBitsToFloat(bits);- }-- // original lucene floatToByte- static byte orig_floatToByte(float f) {- if (f < 0.0f) // round negatives up to zero- f = 0.0f;-- if (f == 0.0f) // zero is a special case- return 0;-- int bits = Float.floatToIntBits(f); // parse float into parts- int mantissa = (bits & 0xffffff) >> 21;- int exponent = (((bits >> 24) & 0x7f) - 63) + 15;-- if (exponent > 31) { // overflow: use max value- exponent = 31;- mantissa = 7;- }-- if (exponent < 0) { // underflow: use min value- exponent = 0;- mantissa = 1;- }-- return (byte)((exponent << 3) | mantissa); // pack into a byte- }-- public void testByteToFloat() {- for (int i=0; i<256; i++) {- float f1 = orig_byteToFloat((byte)i);- float f2 = SmallFloat.byteToFloat((byte)i, 3,15);- float f3 = SmallFloat.byte315ToFloat((byte)i);- assertEquals(f1,f2,0.0);- assertEquals(f2,f3,0.0);-- float f4 = SmallFloat.byteToFloat((byte)i,5,2);- float f5 = SmallFloat.byte52ToFloat((byte)i);- assertEquals(f4,f5,0.0);- }- }-- public void testFloatToByte() {- Random rand = new Random(0);- // up iterations for more exhaustive test after changing something- for (int i=0; i<100000; i++) {- float f = Float.intBitsToFloat(rand.nextInt());- if (f!=f) continue; // skip NaN- byte b1 = orig_floatToByte(f);- byte b2 = SmallFloat.floatToByte(f,3,15);- byte b3 = SmallFloat.floatToByte315(f);- assertEquals(b1,b2);- assertEquals(b2,b3);-- byte b4 = SmallFloat.floatToByte(f,5,2);- byte b5 = SmallFloat.floatToByte52(f);- assertEquals(b4,b5);- }- }-- /***- // Do an exhaustive test of all possible floating point values- // for the 315 float against the original norm encoding in Similarity.- // Takes 75 seconds on my Pentium4 3GHz, with Java5 -server- public void testAllFloats() {- for(int i = Integer.MIN_VALUE;;i++) {- float f = Float.intBitsToFloat(i);- if (f==f) { // skip non-numbers- byte b1 = orig_floatToByte(f);- byte b2 = SmallFloat.floatToByte315(f);- if (b1!=b2) {- TestCase.fail("Failed floatToByte315 for float " + f);- }- }- if (i==Integer.MAX_VALUE) break;- }- }- ***/--}+package org.apache.lucene.util;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.util.LuceneTestCase;+import java.util.Random;++/**+ * @version $Id$+ */+public class TestSmallFloat extends LuceneTestCase {++ // original lucene byteToFloat+ static float orig_byteToFloat(byte b) {+ if (b == 0) // zero is a special case+ return 0.0f;+ int mantissa = b & 7;+ int exponent = (b >> 3) & 31;+ int bits = ((exponent+(63-15)) << 24) | (mantissa << 21);+ return Float.intBitsToFloat(bits);+ }++ // original lucene floatToByte+ static byte orig_floatToByte(float f) {+ if (f < 0.0f) // round negatives up to zero+ f = 0.0f;++ if (f == 0.0f) // zero is a special case+ return 0;++ int bits = Float.floatToIntBits(f); // parse float into parts+ int mantissa = (bits & 0xffffff) >> 21;+ int exponent = (((bits >> 24) & 0x7f) - 63) + 15;++ if (exponent > 31) { // overflow: use max value+ exponent = 31;+ mantissa = 7;+ }++ if (exponent < 0) { // underflow: use min value+ exponent = 0;+ mantissa = 1;+ }++ return (byte)((exponent << 3) | mantissa); // pack into a byte+ }++ public void testByteToFloat() {+ for (int i=0; i<256; i++) {+ float f1 = orig_byteToFloat((byte)i);+ float f2 = SmallFloat.byteToFloat((byte)i, 3,15);+ float f3 = SmallFloat.byte315ToFloat((byte)i);+ assertEquals(f1,f2,0.0);+ assertEquals(f2,f3,0.0);++ float f4 = SmallFloat.byteToFloat((byte)i,5,2);+ float f5 = SmallFloat.byte52ToFloat((byte)i);+ assertEquals(f4,f5,0.0);+ }+ }++ public void testFloatToByte() {+ Random rand = new Random(0);+ // up iterations for more exhaustive test after changing something+ for (int i=0; i<100000; i++) {+ float f = Float.intBitsToFloat(rand.nextInt());+ if (f!=f) continue; // skip NaN+ byte b1 = orig_floatToByte(f);+ byte b2 = SmallFloat.floatToByte(f,3,15);+ byte b3 = SmallFloat.floatToByte315(f);+ assertEquals(b1,b2);+ assertEquals(b2,b3);++ byte b4 = SmallFloat.floatToByte(f,5,2);+ byte b5 = SmallFloat.floatToByte52(f);+ assertEquals(b4,b5);+ }+ }++ /***+ // Do an exhaustive test of all possible floating point values+ // for the 315 float against the original norm encoding in Similarity.+ // Takes 75 seconds on my Pentium4 3GHz, with Java5 -server+ public void testAllFloats() {+ for(int i = Integer.MIN_VALUE;;i++) {+ float f = Float.intBitsToFloat(i);+ if (f==f) { // skip non-numbers+ byte b1 = orig_floatToByte(f);+ byte b2 = SmallFloat.floatToByte315(f);+ if (b1!=b2) {+ TestCase.fail("Failed floatToByte315 for float " + f);+ }+ }+ if (i==Integer.MAX_VALUE) break;+ }+ }+ ***/++}diff --git a/src/test/org/apache/lucene/util/cache/TestSimpleLRUCache.java b/src/test/org/apache/lucene/util/cache/TestSimpleLRUCache.javaindex ed6aff5a207..03a8545bd75 100644--- a/src/test/org/apache/lucene/util/cache/TestSimpleLRUCache.java+++ b/src/test/org/apache/lucene/util/cache/TestSimpleLRUCache.java@@ -1,63 +1,63 @@-package org.apache.lucene.util.cache;--/**-* Licensed to the Apache Software Foundation (ASF) under one or more-* contributor license agreements. See the NOTICE file distributed with-* this work for additional information regarding copyright ownership.-* The ASF licenses this file to You under the Apache License, Version 2.0-* (the "License"); you may not use this file except in compliance with-* the License. You may obtain a copy of the License at-*-* http://www.apache.org/licenses/LICENSE-2.0-*-* Unless required by applicable law or agreed to in writing, software-* distributed under the License is distributed on an "AS IS" BASIS,-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-* See the License for the specific language governing permissions and-* limitations under the License.-*/--import junit.framework.TestCase;--public class TestSimpleLRUCache extends TestCase {-- public void testLRUCache() throws Exception {- final int n = 100;- Object dummy = new Object();-- Cache cache = new SimpleLRUCache(n);-- for (int i = 0; i < n; i++) {- cache.put(new Integer(i), dummy);- }-- // access every 2nd item in cache- for (int i = 0; i < n; i+=2) {- assertNotNull(cache.get(new Integer(i)));- }-- // add n/2 elements to cache, the ones that weren't- // touched in the previous loop should now be thrown away- for (int i = n; i < n + (n / 2); i++) {- cache.put(new Integer(i), dummy);- }-- // access every 4th item in cache- for (int i = 0; i < n; i+=4) {- assertNotNull(cache.get(new Integer(i)));- }-- // add 3/4n elements to cache, the ones that weren't- // touched in the previous loops should now be thrown away- for (int i = n; i < n + (n * 3 / 4); i++) {- cache.put(new Integer(i), dummy);- }-- // access every 4th item in cache- for (int i = 0; i < n; i+=4) {- assertNotNull(cache.get(new Integer(i)));- }-- }--}+package org.apache.lucene.util.cache;++/**+* Licensed to the Apache Software Foundation (ASF) under one or more+* contributor license agreements. See the NOTICE file distributed with+* this work for additional information regarding copyright ownership.+* The ASF licenses this file to You under the Apache License, Version 2.0+* (the "License"); you may not use this file except in compliance with+* the License. You may obtain a copy of the License at+*+* http://www.apache.org/licenses/LICENSE-2.0+*+* Unless required by applicable law or agreed to in writing, software+* distributed under the License is distributed on an "AS IS" BASIS,+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+* See the License for the specific language governing permissions and+* limitations under the License.+*/++import junit.framework.TestCase;++public class TestSimpleLRUCache extends TestCase {++ public void testLRUCache() throws Exception {+ final int n = 100;+ Object dummy = new Object();++ Cache cache = new SimpleLRUCache(n);++ for (int i = 0; i < n; i++) {+ cache.put(new Integer(i), dummy);+ }++ // access every 2nd item in cache+ for (int i = 0; i < n; i+=2) {+ assertNotNull(cache.get(new Integer(i)));+ }++ // add n/2 elements to cache, the ones that weren't+ // touched in the previous loop should now be thrown away+ for (int i = n; i < n + (n / 2); i++) {+ cache.put(new Integer(i), dummy);+ }++ // access every 4th item in cache+ for (int i = 0; i < n; i+=4) {+ assertNotNull(cache.get(new Integer(i)));+ }++ // add 3/4n elements to cache, the ones that weren't+ // touched in the previous loops should now be thrown away+ for (int i = n; i < n + (n * 3 / 4); i++) {+ cache.put(new Integer(i), dummy);+ }++ // access every 4th item in cache+ for (int i = 0; i < n; i+=4) {+ assertNotNull(cache.get(new Integer(i)));+ }++ }++}