Apache Lucene open-source search software
initial version
Yonik Seeley148b4dbc923c
diff --git a/README b/README.txtsimilarity index 100%rename from READMErename to README.txtdiff --git a/src/apps/SolarTest/cachetest.txt b/src/apps/SolarTest/cachetest.txtnew file mode 100644index 00000000000..4e8f10fbe2c--- /dev/null+++ b/src/apps/SolarTest/cachetest.txt@@ -0,0 +1,24 @@++#change the query cache size to 3 and the autowarm size to 2 for this test+<commit/>+val_s:A+val_s:B+val_s:C+val_s:D+#B,C,D should be in cache+val_s:A+#miss, now C,D,A should be in cache+<commit/>+#should see old{lookups=5, hits=0, size=3}, new{size=2}+#now D,A should be autowarmed in new++val_s:C+#miss, now cache=D,A,C+<commit/>+#should see old{lookups,1 hits=0, size=3}, new{size=2}+#now A,C should be autowarmed in new++val_s:A+val_s:C+<commit/>+#should see old{lookups=2, hits=2, size=0}diff --git a/src/apps/SolarTest/commit.bat b/src/apps/SolarTest/commit.batnew file mode 100644index 00000000000..50715f6b348--- /dev/null+++ b/src/apps/SolarTest/commit.bat@@ -0,0 +1,4 @@++PATH=c:/cygwin/bin+c:/cygwin/bin/bash.exe -c "echo handler called... cwd=`pwd` MYVAR=%MYVAR% > commit.outfile"+exit 33diff --git a/src/apps/SolarTest/dict.txt b/src/apps/SolarTest/dict.txtnew file mode 100644index 00000000000..6d7d0f168e0--- /dev/null+++ b/src/apps/SolarTest/dict.txt@@ -0,0 +1 @@+userName:Alex;startDate top 2;diff --git a/src/apps/SolarTest/newtest.txt b/src/apps/SolarTest/newtest.txtnew file mode 100644index 00000000000..b01f6f39a81--- /dev/null+++ b/src/apps/SolarTest/newtest.txt@@ -0,0 +1,540 @@+#compact the index, keep things from getting out of hand+<optimize/>++#test query+qlkciyopsbgzyvkylsjhchghjrdf %//result[@numFound="0"]++#test escaping of ";"+<delete><id>42</id></delete>+<add><doc><field name="id">42</field><field name="val_s">aa;bb</field></doc></add>+<commit/>+id:42 AND val_s:aa\;bb %//*[@numFound="1"]+id:42 AND val_s:"aa;bb" %//*[@numFound="1"]+id:42 AND val_s:"aa" %//*[@numFound="0"]++++#test allowDups default of false+<delete><id>42</id></delete>+<add><doc><field name="id">42</field><field name="val_s">AAA</field></doc></add>+<add><doc><field name="id">42</field><field name="val_s">BBB</field></doc></add>+<commit/>+id:42 %//*[@numFound="1"] %//str[.="BBB"]+<add><doc><field name="id">42</field><field name="val_s">CCC</field></doc></add>+<add><doc><field name="id">42</field><field name="val_s">DDD</field></doc></add>+<commit/>+id:42 %//*[@numFound="1"] %//str[.="DDD"]+<delete><id>42</id></delete>++#test deletes+<delete><query>id:[100 TO 110]</query></delete>+<add allowDups="false"><doc><field name="id">101</field></doc></add>+<add allowDups="false"><doc><field name="id">101</field></doc></add>+<add allowDups="true"><doc><field name="id">105</field></doc></add>+<add allowDups="false"><doc><field name="id">102</field></doc></add>+<add allowDups="true"><doc><field name="id">103</field></doc></add>+<add allowDups="false"><doc><field name="id">101</field></doc></add>+<commit/>+id:[100 TO 110] %//*[@numFound="4"]+<delete><id>102</id></delete>+<commit/>+id:[100 TO 110] %//*[@numFound="3"]+<delete><query>id:105</query></delete>+<commit/>+id:[100 TO 110] %//*[@numFound="2"]+<delete><query>id:[100 TO 110]</query></delete>+<commit/>+id:[100 TO 110] %//*[@numFound="0"]++#test range+<delete><id>44</id></delete>+<add allowDups="true"><doc><field name="id">44</field><field name="val_s">apple</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="val_s">banana</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="val_s">pear</field></doc></add>+<commit/>+val_s:[a TO z] %//*[@numFound="3"] %*[count(//doc)=3] %//*[@start="0"]+val_s:[a TO z] %%start=2&limit=5 %//*[@numFound="3"] %*[count(//doc)=1] %*//doc[1]/str[.="pear"] %//*[@start="2"]+val_s:[a TO z] %%start=3&limit=5 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z] %%start=4&limit=5 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z] %%start=25&limit=5 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z] %%start=0&limit=1 %//*[@numFound="3"] %*[count(//doc)=1] %*//doc[1]/str[.="apple"]+val_s:[a TO z] %%start=0&limit=2 %//*[@numFound="3"] %*[count(//doc)=2] %*//doc[2]/str[.="banana"]+val_s:[a TO z] %%start=1&limit=1 %//*[@numFound="3"] %*[count(//doc)=1] %*//doc[1]/str[.="banana"]+val_s:[a TO z] %%start=3&limit=1 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z] %%start=4&limit=1 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z] %%start=1&limit=0 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z] %%start=0&limit=0 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z];val_s asc %%start=0&limit=0 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO z];val_s desc %%start=0&limit=0 %//*[@numFound="3"] %*[count(//doc)=0]+val_s:[a TO b] %//*[@numFound="1"]+val_s:[a TO cat] %//*[@numFound="2"]+val_s:[a TO *] %//*[@numFound="3"]+val_s:[* TO z] %//*[@numFound="3"]+val_s:[* TO *] %//*[@numFound="3"]+val_s:[apple TO pear] %//*[@numFound="3"]+val_s:[bear TO boar] %//*[@numFound="0"]+val_s:[a TO a] %//*[@numFound="0"]+val_s:[apple TO apple] %//*[@numFound="1"]+val_s:{apple TO pear} %//*[@numFound="1"]+val_s:{a TO z} %//*[@numFound="3"]+val_s:{* TO *} %//*[@numFound="3"]+#test rangequery within a boolean query+id:44 AND val_s:[a TO z] %//*[@numFound="3"]+id:44 OR val_s:[a TO z] %//*[@numFound="3"]+val_s:[a TO b] OR val_s:[b TO z] %//*[@numFound="3"]++val_s:[a TO b] -val_s:[b TO z] %//*[@numFound="1"]+-val_s:[a TO b] +val_s:[b TO z] %//*[@numFound="2"]+val_s:[a TO c] AND val_s:[apple TO z] %//*[@numFound="2"]+val_s:[a TO c] AND val_s:[a TO apple] %//*[@numFound="1"]+id:44 AND (val_s:[a TO c] AND val_s:[a TO apple]) %//*[@numFound="1"]+(val_s:[apple TO apple] OR val_s:[a TO c]) AND (val_s:[b TO c] OR val_s:[b TO b]) %//*[@numFound="1"] %//str[.="banana"]+(val_s:[apple TO apple] AND val_s:[a TO c]) OR (val_s:[p TO z] AND val_s:[a TO z]) %//*[@numFound="2"] %//str[.="apple"] %//str[.="pear"]++#check for docs that appear more than once in a range+<add allowDups="true"><doc><field name="id">44</field><field name="val_s">apple</field><field name="val_s">banana</field></doc></add>+<commit/>+val_s:[* TO *] OR val_s:[* TO *] %//*[@numFound="4"]+val_s:[* TO *] AND val_s:[* TO *] %//*[@numFound="4"]+val_s:[* TO *] %//*[@numFound="4"]+++#<delete><id>44</id></delete>+<add overwritePending="true" overwriteCommitted="true"><doc><field name="id">44</field><field name="text">red riding hood</field></doc></add>+<commit/>+id:44 AND red %//@numFound[.="1"] %*[count(//doc)=1]+id:44 AND ride %//@numFound[.="1"]+id:44 AND blue %//@numFound[.="0"]++#allow duplicates+<delete><id>44</id></delete>+<add allowDups="true" overwriteCommitted="false" overwritePending="false"><doc><field name="id">44</field><field name="text">red riding hood</field></doc></add>+<add allowDups="true" overwriteCommitted="false" overwritePending="false"><doc><field name="id">44</field><field name="text">big bad wolf</field></doc></add>+<commit/>+id:44 %//@numFound[.="2"]+id:44 AND red %//@numFound[.="1"] %*[count(//doc)=1]+id:44 AND wolf %//@numFound[.="1"] %*[count(//doc)=1]++id:44 red wolf %//@numFound[.="2"]++#test removal of multiples w/o adding anything else+<delete><id>44</id></delete>+<commit/>+id:44 %//@numFound[.="0"]++#untokenized string type+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="ssto">and a 10.4 ?</field></doc></add>+<commit/>+id:44 %//str[.="and a 10.4 ?"]+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="sind">abc123</field></doc></add>+<commit/>+#TODO: how to search for something with spaces....+sind:abc123 %//@numFound[.="1"] %*[count(//@name[.="sind"])=0] %*[count(//@name[.="id"])=1]++<delete><id>44</id></delete>+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="sindsto">abc123</field></doc></add>+<commit/>+#TODO: how to search for something with spaces....+sindsto:abc123 %//str[.="abc123"]++#test output of multivalued fields+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="title">yonik3</field><field name="title" boost="2">yonik4</field></doc></add>+<commit></commit>+id:44 %//arr[@name="title"][./str="yonik3" and ./str="yonik4"] %*[count(//@name[.="title"])=1]+title:yonik3 %//@numFound[.>"0"]+title:yonik4 %//@numFound[.>"0"]+title:yonik5 %//@numFound[.="0"]+<delete><query>title:yonik4</query></delete>+<commit/>+id:44 %//@numFound[.="0"]+++#not visible until commit+<delete><id>44</id></delete>+<commit/>+<add><doc><field name="id">44</field></doc></add>+id:44 %//@numFound[.="0"]+<commit/>+id:44 %//@numFound[.="1"]++#test configurable stop words+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="teststop">world stopworda view</field></doc></add>+<commit/>++id:44 +teststop:world %//@numFound[.="1"]+teststop:stopworda %//@numFound[.="0"]++#test ignoreCase stop words+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="stopfilt">world AnD view</field></doc></add>+<commit/>++id:44 +stopfilt:world %//@numFound[.="1"]+stopfilt:"and" %//@numFound[.="0"]+stopfilt:"AND" %//@numFound[.="0"]+stopfilt:"AnD" %//@numFound[.="0"]++#test dynamic field types+<delete fromPending="true" fromCommitted="true"><id>44</id></delete>+<add><doc><field name="id">44</field><field name="gack_i">51778</field><field name="t_name">cats</field></doc></add>+<commit/>+#test if the dyn fields got added+id:44 %*[count(//doc/*)>=3] %//int[@name="gack_i"][.="51778"] %//str[@name="t_name"][.="cats"]+#now test if we can query by a dynamic field (requires analyzer support)+t_name:cat %//str[@name="t_name" and .="cats"]+#check that deleteByQuery works for dynamic fields+<delete><query>t_name:cat</query></delete>+<commit/>+t_name:cat %//@numFound[.="0"]++#test that longest dynamic field match happens first+<add><doc><field name="id">44</field><field name="xaa">mystr</field><field name="xaaa">12321</field></doc></add>+<commit/>+id:44 %//str[@name="xaa"][.="mystr"] %//int[@name="xaaa"][.="12321"]+++#test integer ranges and sorting+<delete><id>44</id></delete>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">1234567890</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">10</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">2</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">15</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">-1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">-987654321</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">2147483647</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">-2147483648</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_i">0</field></doc></add>+<commit/>+id:44 %*[count(//doc)=10]+num_i:2147483647 %//@numFound[.="1"] %//int[.="2147483647"]+num_i:"-2147483648" %//@numFound[.="1"] %//int[.="-2147483648"]+id:44;num_i asc; %//doc[1]/int[.="-2147483648"] %//doc[last()]/int[.="2147483647"]+id:44;num_i desc; %//doc[1]/int[.="2147483647"] %//doc[last()]/int[.="-2147483648"]+num_i:[0 TO 9] %*[count(//doc)=3]+num_i:[-2147483648 TO 2147483647] %*[count(//doc)=10]+num_i:[-10 TO -1] %*[count(//doc)=1]++#test long ranges and sorting+<delete><id>44</id></delete>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">1234567890</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">10</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">2</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">15</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">-1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">-987654321</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">9223372036854775807</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">-9223372036854775808</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_l">0</field></doc></add>+<commit/>+id:44 %*[count(//doc)=10]+num_l:9223372036854775807 %//@numFound[.="1"] %//long[.="9223372036854775807"]+num_l:"-9223372036854775808" %//@numFound[.="1"] %//long[.="-9223372036854775808"]+id:44;num_l asc; %//doc[1]/long[.="-9223372036854775808"] %//doc[last()]/long[.="9223372036854775807"]+id:44;num_l desc; %//doc[1]/long[.="9223372036854775807"] %//doc[last()]/long[.="-9223372036854775808"]+num_l:[-1 TO 9] %*[count(//doc)=4]+num_l:[-9223372036854775808 TO 9223372036854775807] %*[count(//doc)=10]+num_l:[-10 TO -1] %*[count(//doc)=1]++#test binary float ranges and sorting+<delete><id>44</id></delete>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">1.4142135</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">Infinity</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">-Infinity</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">NaN</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">2</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">-1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">-987654321</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">-999999.99</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">-1e20</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_f">0</field></doc></add>+<commit/>+id:44 %*[count(//doc)=10]+num_f:Infinity %//@numFound[.="1"] %//float[.="Infinity"]+num_f:"-Infinity" %//@numFound[.="1"] %//float[.="-Infinity"]+num_f:"NaN" %//@numFound[.="1"] %//float[.="NaN"]+num_f:"-1e20" %//@numFound[.="1"]+id:44;num_f asc; %//doc[1]/float[.="-Infinity"] %//doc[last()]/float[.="NaN"]+id:44;num_f desc; %//doc[1]/float[.="NaN"] %//doc[last()]/float[.="-Infinity"]+num_f:[-1 TO 2] %*[count(//doc)=4]+num_f:[-Infinity TO Infinity] %*[count(//doc)=9]++++#test binary double ranges and sorting+<delete><id>44</id></delete>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">1.4142135</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">Infinity</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">-Infinity</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">NaN</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">2</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">-1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">1e-100</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">-999999.99</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">-1e100</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="num_d">0</field></doc></add>+<commit/>+id:44 %*[count(//doc)=10]+num_d:Infinity %//@numFound[.="1"] %//double[.="Infinity"]+num_d:"-Infinity" %//@numFound[.="1"] %//double[.="-Infinity"]+num_d:"NaN" %//@numFound[.="1"] %//double[.="NaN"]+num_d:"-1e100" %//@numFound[.="1"]+num_d:"1e-100" %//@numFound[.="1"]+id:44;num_d asc; %//doc[1]/double[.="-Infinity"] %//doc[last()]/double[.="NaN"]+id:44;num_d desc; %//doc[1]/double[.="NaN"] %//doc[last()]/double[.="-Infinity"]+num_d:[-1 TO 2] %*[count(//doc)=5]+num_d:[-Infinity TO Infinity] %*[count(//doc)=9]+++#test sorting on multiple fields+<delete><id>44</id></delete>+<add allowDups="true"><doc><field name="id">44</field><field name="a_i">10</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="a_i">1</field><field name="b_i">100</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="a_i">-1</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="a_i">15</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="a_i">1</field><field name="b_i">50</field></doc></add>+<add allowDups="true"><doc><field name="id">44</field><field name="a_i">0</field></doc></add>+<commit/>+id:44 %*[count(//doc)=6]++id:44; a_i asc,b_i desc %*[count(//doc)=6] %//doc[3]/int[.="100"] %//doc[4]/int[.="50"]+id:44;a_i asc , b_i asc; %*[count(//doc)=6] %//doc[3]/int[.="50"] %//doc[4]/int[.="100"]+id:44;a_i asc; %*[count(//doc)=6] %//doc[1]/int[.="-1"] %//doc[last()]/int[.="15"]+id:44;a_i asc , score top; %*[count(//doc)=6] %//doc[1]/int[.="-1"] %//doc[last()]/int[.="15"]+id:44; score top , a_i top, b_i bottom ; %*[count(//doc)=6] %//doc[last()]/int[.="-1"] %//doc[1]/int[.="15"] %//doc[3]/int[.="50"] %//doc[4]/int[.="100"]+++#test sorting with some docs missing the sort field+<delete><query>id_i:[1000 TO 1010]</query></delete>+<add allowDups="true"><doc><field name="id_i">1000</field><field name="a_i">1</field></doc></add>+<add allowDups="true"><doc><field name="id_i">1001</field><field name="a_i">10</field></doc></add>+<add allowDups="true"><doc><field name="id_i">1002</field><field name="a_i">1</field><field name="b_i">100</field></doc></add>+<add allowDups="true"><doc><field name="id_i">1003</field><field name="a_i">-1</field></doc></add>+<add allowDups="true"><doc><field name="id_i">1004</field><field name="a_i">15</field></doc></add>+<add allowDups="true"><doc><field name="id_i">1005</field><field name="a_i">1</field><field name="b_i">50</field></doc></add>+<add allowDups="true"><doc><field name="id_i">1006</field><field name="a_i">0</field></doc></add>+<commit/>+id_i:[1000 TO 1010] %*[count(//doc)=7]+id_i:[1000 TO 1010]; b_i asc %*[count(//doc)=7] %//doc[1]/int[.="50"] %//doc[2]/int[.="100"]+id_i:[1000 TO 1010]; b_i desc %*[count(//doc)=7] %//doc[1]/int[.="100"] %//doc[2]/int[.="50"]+id_i:[1000 TO 1010]; a_i asc,b_i desc %*[count(//doc)=7] %//doc[3]/int[.="100"] %//doc[4]/int[.="50"] %//doc[5]/int[.="1000"]+id_i:[1000 TO 1010]; a_i asc,b_i asc %*[count(//doc)=7] %//doc[3]/int[.="50"] %//doc[4]/int[.="100"] %//doc[5]/int[.="1000"]+++#test prefix query+<delete><query>val_s:[* TO *]</query></delete>+<add><doc><field name="id">100</field><field name="val_s">apple</field></doc></add>+<add><doc><field name="id">101</field><field name="val_s">banana</field></doc></add>+<add><doc><field name="id">102</field><field name="val_s">apple</field></doc></add>+<add><doc><field name="id">103</field><field name="val_s">pearing</field></doc></add>+<add><doc><field name="id">104</field><field name="val_s">pear</field></doc></add>+<add><doc><field name="id">105</field><field name="val_s">appalling</field></doc></add>+<add><doc><field name="id">106</field><field name="val_s">pearson</field></doc></add>+<add><doc><field name="id">107</field><field name="val_s">port</field></doc></add>+<commit/>++val_s:a* %//*[@numFound="3"]+val_s:p* %//*[@numFound="4"]+#val_s:* %//*[@numFound="8"]++<delete><query>id:[100 TO 110]</query></delete>++#test copyField functionality+<add><doc><field name="id">42</field><field name="title">How Now4 brown Cows</field></doc></add>+<commit/>+id:42 AND title:Now %*[count(//doc)=0]+id:42 AND title_lettertok:Now %*[count(//doc)=1]+id:42 AND title:cow %*[count(//doc)=0]+id:42 AND title_stemmed:cow %*[count(//doc)=1]+id:42 AND text:cow %*[count(//doc)=1]++#test slop+<add><doc><field name="id">42</field><field name="text">foo bar</field></doc></add>+<commit/>+id:42 AND text:"foo bar" %*[count(//doc)=1]+id:42 AND text:"foo" %*[count(//doc)=1]+id:42 AND text:"bar" %*[count(//doc)=1]+id:42 AND text:"bar foo" %*[count(//doc)=0]+id:42 AND text:"bar foo"~2 %*[count(//doc)=1]+++#intra-word delimiter testing (WordDelimiterFilter)+<add><doc><field name="id">42</field><field name="subword">foo bar</field></doc></add>+<commit/>+id:42 AND subword:"foo bar" %*[count(//doc)=1]+id:42 AND subword:"foo" %*[count(//doc)=1]+id:42 AND subword:"bar" %*[count(//doc)=1]+id:42 AND subword:"bar foo" %*[count(//doc)=0]+id:42 AND subword:"bar foo"~2 %*[count(//doc)=1]+id:42 AND subword:"foo/bar" %*[count(//doc)=1]+id:42 AND subword:"foobar" %*[count(//doc)=0]++<add><doc><field name="id">42</field><field name="subword">foo-bar</field></doc></add>+<commit/>+id:42 AND subword:"foo bar" %*[count(//doc)=1]+id:42 AND subword:"foo" %*[count(//doc)=1]+id:42 AND subword:"bar" %*[count(//doc)=1]+id:42 AND subword:"bar foo" %*[count(//doc)=0]+id:42 AND subword:"bar foo"~2 %*[count(//doc)=1]+id:42 AND subword:"foo/bar" %*[count(//doc)=1]+id:42 AND subword:foobar %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">Canon PowerShot SD500 7MP</field></doc></add>+<commit/>+id:42 AND subword:"power-shot" %*[count(//doc)=1]+id:42 AND subword:"power shot sd 500" %*[count(//doc)=1]+id:42 AND subword:"powershot" %*[count(//doc)=1]+id:42 AND subword:"SD-500" %*[count(//doc)=1]+id:42 AND subword:"SD500" %*[count(//doc)=1]+id:42 AND subword:"SD500-7MP" %*[count(//doc)=1]+id:42 AND subword:"PowerShotSD500-7MP" %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">Wi-Fi</field></doc></add>+<commit/>+id:42 AND subword:wifi %*[count(//doc)=1]+id:42 AND subword:wi+=fi %*[count(//doc)=1]+id:42 AND subword:wi+=fi %*[count(//doc)=1]+id:42 AND subword:WiFi %*[count(//doc)=1]+id:42 AND subword:"wi fi" %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">'I.B.M' A's,B's,C's</field></doc></add>+<commit/>+id:42 AND subword:"'I.B.M.'" %*[count(//doc)=1]+id:42 AND subword:I.B.M %*[count(//doc)=1]+id:42 AND subword:IBM %*[count(//doc)=1]+id:42 AND subword:I--B--M %*[count(//doc)=1]+id:42 AND subword:"I B M" %*[count(//doc)=1]+id:42 AND subword:IBM's %*[count(//doc)=1]+id:42 AND subword:IBM'sx %*[count(//doc)=0]++#this one fails since IBM and ABC are separated by two tokens+#id:42 AND subword:IBM's-ABC's %*[count(//doc)=1]+id:42 AND subword:"IBM's-ABC's"~2 %*[count(//doc)=1]++id:42 AND subword:"A's B's-C's" %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">Sony KDF-E50A10</field></doc></add>+<commit/>++#check for exact match:+# Sony KDF E/KDFE 50 A 10 (this is how it's indexed)+# Sony KDF E 50 A 10 (and how it's queried)+id:42 AND subword:"Sony KDF-E50A10" %*[count(//doc)=1]+id:42 AND subword:10 %*[count(//doc)=1]+id:42 AND subword:Sony %*[count(//doc)=1]++#this one fails without slop since Sony and KDFE have a token inbetween+#id:42 AND subword:SonyKDFE50A10 %*[count(//doc)=1]+id:42 AND subword:"SonyKDFE50A10"~10 %*[count(//doc)=1]++id:42 AND subword:"Sony KDF E-50-A-10" %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">http://www.yahoo.com</field></doc></add>+<commit/>+id:42 AND subword:yahoo %*[count(//doc)=1]+id:42 AND subword:www.yahoo.com %*[count(//doc)=1]+id:42 AND subword:http://www.yahoo.com %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">--Q 1-- W2 E-3 Ok xY 4R 5-T *6-Y- 7-8-- 10A-B</field></doc></add>+<commit/>+id:42 AND subword:Q %*[count(//doc)=1]+id:42 AND subword:1 %*[count(//doc)=1]+id:42 AND subword:"w 2" %*[count(//doc)=1]+id:42 AND subword:"e 3" %*[count(//doc)=1]+id:42 AND subword:"o k" %*[count(//doc)=0]+id:42 AND subword:"ok" %*[count(//doc)=1]+id:42 AND subword:"x y" %*[count(//doc)=1]+id:42 AND subword:"xy" %*[count(//doc)=1]+id:42 AND subword:"4 r" %*[count(//doc)=1]+id:42 AND subword:"5 t" %*[count(//doc)=1]+id:42 AND subword:"5 t" %*[count(//doc)=1]+id:42 AND subword:"6 y" %*[count(//doc)=1]+id:42 AND subword:"7 8" %*[count(//doc)=1]+id:42 AND subword:"78" %*[count(//doc)=1]+id:42 AND subword:"10 A+B" %*[count(//doc)=1]++<add><doc><field name="id">42</field><field name="subword">FooBarBaz</field></doc></add>+<add><doc><field name="id">42</field><field name="subword">FooBar10</field></doc></add>+<add><doc><field name="id">42</field><field name="subword">10FooBar</field></doc></add>+<add><doc><field name="id">42</field><field name="subword">BAZ</field></doc></add>+<add><doc><field name="id">42</field><field name="subword">10</field></doc></add>+<add><doc><field name="id">42</field><field name="subword">Mark, I found what's the problem! It turns to be from the latest schema. I found tons of exceptions in the resin.stdout that prevented the builder from performing. It's all coming from the WordDelimiterFilter which was just added to the latest schema: [2005-08-29 15:11:38.375] java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 673804 [2005-08-29 15:11:38.375] at java.util.ArrayList.RangeCheck(ArrayList.java:547) 673805 [2005-08-29 15:11:38.375] at java.util.ArrayList.get(ArrayList.java:322) 673806 [2005-08-29 15:11:38.375] at solar.analysis.WordDelimiterFilter.addCombos(WordDelimiterFilter.java:349) 673807 [2005-08-29 15:11:38.375] at solar.analysis.WordDelimiterFilter.next(WordDelimiterFilter.java:325) 673808 [2005-08-29 15:11:38.375] at org.apache.lucene.analysis.LowerCaseFilter.next(LowerCaseFilter.java:32) 673809 [2005-08-29 15:11:38.375] at org.apache.lucene.analysis.StopFilter.next(StopFilter.java:98) 673810 [2005-08-29 15:11:38.375] at solar.EnglishPorterFilter.next(TokenizerFactory.java:163) 673811 [2005-08-29 15:11:38.375] at org.apache.lucene.index.DocumentWriter.invertDocument(DocumentWriter.java:143) 673812 [2005-08-29 15:11:38.375] at org.apache.lucene.index.DocumentWriter.addDocument(DocumentWriter.java:81) 673813 [2005-08-29 15:11:38.375] at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:307) 673814 [2005-08-29 15:11:38.375] at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:294) 673815 [2005-08-29 15:11:38.375] at solar.DirectUpdateHandler2.doAdd(DirectUpdateHandler2.java:170) 673816 [2005-08-29 15:11:38.375] at solar.DirectUpdateHandler2.overwriteBoth(DirectUpdateHandler2.java:317) 673817 [2005-08-29 15:11:38.375] at solar.DirectUpdateHandler2.addDoc(DirectUpdateHandler2.java:191) 673818 [2005-08-29 15:11:38.375] at solar.SolarCore.update(SolarCore.java:795) 673819 [2005-08-29 15:11:38.375] at solarserver.SolarServlet.doPost(SolarServlet.java:71) 673820 [2005-08-29 15:11:38.375] at javax.servlet.http.HttpServlet.service(HttpServlet.java:154) 673821 [2005-08-29 15:11:38.375] at javax.servlet.http.HttpServlet.service(HttpServlet.java:92) 673822 [2005-08-29 15:11:38.375] at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterChain.java:99) 673823 [2005-08-29 15:11:38.375] at com.caucho.server.cache.CacheFilterChain.doFilter(CacheFilterChain.java:188) 673824 [2005-08-29 15:11:38.375] at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain.java:163) 673825 [2005-08-29 15:11:38.375] at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocation.java:208) 673826 [2005-08-29 15:11:38.375] at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:259) 673827 [2005-08-29 15:11:38.375] at com.caucho.server.port.TcpConnection.run(TcpConnection.java:363) 673828 [2005-08-29 15:11:38.375] at com.caucho.util.ThreadPool.runTasks(ThreadPool.java:490) 673829 [2005-08-29 15:11:38.375] at com.caucho.util.ThreadPool.run(ThreadPool.java:423) 673830 [2005-08-29 15:11:38.375] at java.lang.Thread.run(Thread.java:595) With the previous schema I'm able to perform a successful full build: http://c12-ssa-dev40-so-mas1.cnet.com:5078/select/?stylesheet=q=docTypeversion=2.0start=0rows=10indent=on Do you want to rollback to the previous schema version</field></doc></add>+++#+<delete fromPending="true" fromCommitted="true"><id>44</id></delete>+<add><doc><field name="id">44</field><field name="fname_s">Yonik</field><field name="here_b">true</field><field name="iq_l">10000000000</field><field name="description_t">software engineer</field><field name="ego_d">1e100</field><field name="pi_f">3.1415962</field><field name="when_dt">2005-03-18T01:14:34Z</field><field name="arr_f">1.414213562</field><field name="arr_f">.999</field></doc></add>+<commit/>+id:44+id:44 %%fl=fname_s,arr_f %//str[.="Yonik"] %//float[.="1.4142135"]+id:44 %%fl= %//str[.="Yonik"] %//float[.="1.4142135"]++#test addition of score field+id:44 %%fl=score %//str[.="Yonik"] %//float[.="1.4142135"] %//float[@name="score"] %*[count(//doc/*)=10]+id:44 %%fl=*,score %//str[.="Yonik"] %//float[.="1.4142135"] %//float[@name="score"] %*[count(//doc/*)=10]+id:44 %%fl=* %//str[.="Yonik"] %//float[.="1.4142135"] %*[count(//doc/*)>=9]++#test maxScore+id:44 %%fl=score %//result[@maxScore>0]+id:44;id desc; %%fl=score %//result[@maxScore>0]+id:44; %%fl=score %//@maxScore = //doc/float[@name="score"]+id:44;id desc; %%fl=score %//@maxScore = //doc/float[@name="score"]+id:44;id desc; %%fl=score&limit=0 %//result[@maxScore>0]+++# test schema field attribute inheritance and overriding+<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="shouldbestored">hi</field></doc></add>+<commit/>+id:44 %//*[@name="shouldbestored"]++id:44 +shouldbestored:hi %//*[@numFound="1"]++<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="shouldbeunstored">hi</field></doc></add>+<commit/>+id:44 %not(//*[@name="shouldbeunstored"])++id:44 +shouldbeunstored:hi %//*[@numFound="1"]++<delete><id>44</id></delete>+<add><doc><field name="id">44</field><field name="shouldbeunindexed">hi</field></doc></add>+<commit/>+id:44 %//*[@name="shouldbeunindexed"]+# this should result in an error... how to check for that?+#+id:44 +shouldbeunindexed:hi %//*[@numFound="0"]++#test spaces between XML elements because that can introduce extra XML events that+#can mess up parsing (and it has in the past)+ <delete> <id>44</id> </delete>+ <add> <doc> <field name="id">44</field> <field name="shouldbestored">hi</field> </doc> </add>+ <commit />++#test adding multiple docs per add command+<delete><query>id:[0 TO 99]</query></delete>+<add><doc><field name="id">1</field></doc><doc><field name="id">2</field></doc></add>+<commit/>+id:[0 TO 99] %//*[@numFound="2"]++#test synonym filter+<delete><query>id:[10 TO 100]</query></delete>+<add><doc><field name="id">10</field><field name="syn">a</field></doc></add>+<add><doc><field name="id">11</field><field name="syn">b</field></doc></add>+<add><doc><field name="id">12</field><field name="syn">c</field></doc></add>+<add><doc><field name="id">13</field><field name="syn">foo</field></doc></add>+<commit/>+id:10 AND syn:a %//*[@numFound="1"]+id:10 AND syn:aa %//*[@numFound="1"]+id:11 AND syn:b %//*[@numFound="1"]+id:11 AND syn:b1 %//*[@numFound="1"]+id:11 AND syn:b2 %//*[@numFound="1"]+id:12 AND syn:c %//*[@numFound="1"]+id:12 AND syn:c1 %//*[@numFound="1"]+id:12 AND syn:c2 %//*[@numFound="1"]+id:13 AND syn:foo %//*[@numFound="1"]+id:13 AND syn:bar %//*[@numFound="1"]+id:13 AND syn:baz %//*[@numFound="1"]++#trigger output of custom value test+values %%qt=test+diff --git a/src/apps/SolarTest/protwords.txt b/src/apps/SolarTest/protwords.txtnew file mode 100644index 00000000000..f668c1c0e35--- /dev/null+++ b/src/apps/SolarTest/protwords.txt@@ -0,0 +1,5 @@+#use a protected word file to avoid stemming two+#unrelated words to the same base word.+#to test, we will use words that would normally obviously be stemmed.+cats+ridding\ No newline at end of filediff --git a/src/apps/SolarTest/run b/src/apps/SolarTest/runnew file mode 100755index 00000000000..639600fa881--- /dev/null+++ b/src/apps/SolarTest/run@@ -0,0 +1 @@+java -cp "../solar/classes;classes;../../lucene/lucene-1.4.3.jar" SolarPerf -schema test_schema.xml -index F:/root/index -verbose -test newtest.txtdiff --git a/src/apps/SolarTest/schema.xml b/src/apps/SolarTest/schema.xmlnew file mode 100644index 00000000000..694ad922559--- /dev/null+++ b/src/apps/SolarTest/schema.xml@@ -0,0 +1,334 @@+<?xml version="1.0" ?>+<!-- The Solar schema file. This file should be named "schema.xml" and+ should be located where the classloader for the Solar webapp can find it.++ $Id: schema.xml,v 1.1 2005/06/09 03:01:13 yonik Exp $+ $Source: /cvs/main/searching/solar-configs/test/WEB-INF/classes/schema.xml,v $+ $Name: $+ -->++<schema name="test" version="1.0">+ <types>++ <!-- field type definitions... note that the "name" attribute is+ just a label to be used by field definitions. The "class"+ attribute and any other attributes determine the real type and+ behavior of the fieldtype.+ -->++ <!-- numeric field types that store and index the text+ value verbatim (and hence don't sort correctly or support range queries.)+ These are provided more for backward compatability, allowing one+ to create a schema that matches an existing lucene index.+ -->+ <fieldtype name="integer" class="solar.IntField"/>+ <fieldtype name="long" class="solar.LongField"/>+ <fieldtype name="float" class="solar.FloatField"/>+ <fieldtype name="double" class="solar.DoubleField"/>++ <!-- numeric field types that manipulate the value into+ a string value that isn't human readable in it's internal form,+ but sorts correctly and supports range queries.++ If sortMissingLast="true" then a sort on this field will cause documents+ without the field to come after documents with the field,+ regardless of the requested sort order.+ If sortMissingFirst="true" then a sort on this field will cause documents+ without the field to come before documents with the field,+ regardless of the requested sort order.+ If sortMissingLast="false" and sortMissingFirst="false" (the default),+ then default lucene sorting will be used which places docs without the field+ first in an ascending sort and last in a descending sort.+ -->+ <fieldtype name="sint" class="solar.SortableIntField" sortMissingLast="true"/>+ <fieldtype name="slong" class="solar.SortableLongField" sortMissingLast="true"/>+ <fieldtype name="sfloat" class="solar.SortableFloatField" sortMissingLast="true"/>+ <fieldtype name="sdouble" class="solar.SortableDoubleField" sortMissingLast="true"/>++ <!-- bcd versions of sortable numeric type may provide smaller+ storage space and support very large numbers.+ -->+ <fieldtype name="bcdint" class="solar.BCDIntField" sortMissingLast="true"/>+ <fieldtype name="bcdlong" class="solar.BCDLongField" sortMissingLast="true"/>+ <fieldtype name="bcdstr" class="solar.BCDStrField" sortMissingLast="true"/>+++ <fieldtype name="boolean" class="solar.BoolField" sortMissingLast="true"/>+ <fieldtype name="string" class="solar.StrField" sortMissingLast="true"/>++ <!-- format for date is 1995-12-31T23:59:59.999Z and only the fractional+ seconds part (.999) is optional.+ -->+ <fieldtype name="date" class="solar.DateField" sortMissingLast="true"/>++ <!-- solar.TextField allows the specification of custom+ text analyzers specified as a tokenizer and a list+ of token filters.+ -->+ <fieldtype name="text" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.StandardTokenizerFactory"/>+ <filter class="solar.StandardFilterFactory"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ <filter class="solar.StopFilterFactory"/>+ <!-- lucene PorterStemFilterFactory deprecated+ <filter class="solar.PorterStemFilterFactory"/>+ -->+ <filter class="solar.EnglishPorterFilterFactory"/>+ </analyzer>+ </fieldtype>+++ <fieldtype name="nametext" class="solar.TextField">+ <analyzer class="org.apache.lucene.analysis.WhitespaceAnalyzer"/>+ </fieldtype>++ <fieldtype name="teststop" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.LowerCaseTokenizerFactory"/>+ <filter class="solar.StandardFilterFactory"/>+ <filter class="solar.StopFilterFactory" words="stopwords.txt"/>+ </analyzer>+ </fieldtype>++ <!-- fieldtypes in this section isolate tokenizers and tokenfilters for testing -->+ <fieldtype name="lowertok" class="solar.TextField">+ <analyzer><tokenizer class="solar.LowerCaseTokenizerFactory"/></analyzer>+ </fieldtype>+ <fieldtype name="standardtok" class="solar.TextField">+ <analyzer><tokenizer class="solar.StandardTokenizerFactory"/></analyzer>+ </fieldtype>+ <fieldtype name="lettertok" class="solar.TextField">+ <analyzer><tokenizer class="solar.LetterTokenizerFactory"/></analyzer>+ </fieldtype>+ <fieldtype name="whitetok" class="solar.TextField">+ <analyzer><tokenizer class="solar.WhitespaceTokenizerFactory"/></analyzer>+ </fieldtype>+ <fieldtype name="HTMLstandardtok" class="solar.TextField">+ <analyzer><tokenizer class="solar.HTMLStripStandardTokenizerFactory"/></analyzer>+ </fieldtype>+ <fieldtype name="HTMLwhitetok" class="solar.TextField">+ <analyzer><tokenizer class="solar.HTMLStripWhitespaceTokenizerFactory"/></analyzer>+ </fieldtype>+ <fieldtype name="standardtokfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.StandardTokenizerFactory"/>+ <filter class="solar.StandardFilterFactory"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="standardfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.StandardFilterFactory"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="lowerfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="porterfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.PorterStemFilterFactory"/>+ </analyzer>+ </fieldtype>+ <!-- fieldtype name="snowballfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.SnowballPorterFilterFactory"/>+ </analyzer>+ </fieldtype -->+ <fieldtype name="engporterfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.EnglishPorterFilterFactory"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="custengporterfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.EnglishPorterFilterFactory" protected="protwords.txt"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="stopfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.StopFilterFactory" ignoreCase="true"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="custstopfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.StopFilterFactory" words="stopwords.txt"/>+ </analyzer>+ </fieldtype>+ <fieldtype name="lengthfilt" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.LengthFilterFactory" min="2" max="5"/>+ </analyzer>+ </fieldtype>++ <fieldtype name="subword" class="solar.TextField">+ <analyzer type="index">+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ <filter class="solar.StopFilterFactory"/>+ <filter class="solar.EnglishPorterFilterFactory"/>+ </analyzer>+ <analyzer type="query">+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ <filter class="solar.StopFilterFactory"/>+ <filter class="solar.EnglishPorterFilterFactory"/>+ </analyzer>+ </fieldtype>++ <!-- more flexible in matching skus, but more chance of a false match -->+ <fieldtype name="skutype1" class="solar.TextField">+ <analyzer type="index">+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ </analyzer>+ <analyzer type="query">+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.WordDelimiterFilterFactory" generateWordParts="0" generateNumberParts="0" catenateWords="1" catenateNumbers="1" catenateAll="0"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ </analyzer>+ </fieldtype>++ <!-- less flexible in matching skus, but less chance of a false match -->+ <fieldtype name="skutype2" class="solar.TextField">+ <analyzer type="index">+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.WordDelimiterFilterFactory" generateWordParts="0" generateNumberParts="0" catenateWords="1" catenateNumbers="1" catenateAll="0"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ </analyzer>+ <analyzer type="query">+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter class="solar.WordDelimiterFilterFactory" generateWordParts="0" generateNumberParts="0" catenateWords="1" catenateNumbers="1" catenateAll="0"/>+ <filter class="solar.LowerCaseFilterFactory"/>+ </analyzer>+ </fieldtype>++ <!-- less flexible in matching skus, but less chance of a false match -->+ <fieldtype name="syn" class="solar.TextField">+ <analyzer>+ <tokenizer class="solar.WhitespaceTokenizerFactory"/>+ <filter name="syn" class="solar.SynonymFilterFactory" synonyms="synonyms.txt"/>+ </analyzer>+ </fieldtype>++ <fieldtype name="unstored" class="solar.StrField" indexed="true" stored="false"/>+ </types>+++ <fields>+ <field name="id" type="integer" indexed="true" stored="true"/>+ <field name="name" type="nametext" indexed="true" stored="true"/>+ <field name="text" type="text" indexed="true" stored="false"/>+ <field name="subject" type="text" indexed="true" stored="true"/>+ <field name="title" type="nametext" indexed="true" stored="true"/>+ <field name="weight" type="float" indexed="true" stored="true"/>+ <field name="bday" type="date" indexed="true" stored="true"/>++ <field name="title_stemmed" type="text" indexed="true" stored="false"/>+ <field name="title_lettertok" type="lettertok" indexed="true" stored="false"/>++ <field name="syn" type="syn" indexed="true" stored="true"/>++ <!-- to test property inheritance and overriding -->+ <field name="shouldbeunstored" type="unstored" />+ <field name="shouldbestored" type="unstored" stored="true"/>+ <field name="shouldbeunindexed" type="unstored" indexed="false" stored="true"/>+++ <!-- test different combinations of indexed and stored -->+ <field name="bind" type="boolean" indexed="true" stored="false"/>+ <field name="bsto" type="boolean" indexed="false" stored="true"/>+ <field name="bindsto" type="boolean" indexed="true" stored="true"/>+ <field name="isto" type="integer" indexed="false" stored="true"/>+ <field name="iind" type="integer" indexed="true" stored="false"/>+ <field name="ssto" type="string" indexed="false" stored="true"/>+ <field name="sind" type="string" indexed="true" stored="false"/>+ <field name="sindsto" type="string" indexed="true" stored="true"/>++ <!-- fields to test individual tokenizers and tokenfilters -->+ <field name="teststop" type="teststop" indexed="true" stored="true"/>+ <field name="lowertok" type="lowertok" indexed="true" stored="true"/>+ <field name="standardtok" type="standardtok" indexed="true" stored="true"/>+ <field name="HTMLstandardtok" type="HTMLstandardtok" indexed="true" stored="true"/>+ <field name="lettertok" type="lettertok" indexed="true" stored="true"/>+ <field name="whitetok" type="whitetok" indexed="true" stored="true"/>+ <field name="HTMLwhitetok" type="HTMLwhitetok" indexed="true" stored="true"/>+ <field name="standardtokfilt" type="standardtokfilt" indexed="true" stored="true"/>+ <field name="standardfilt" type="standardfilt" indexed="true" stored="true"/>+ <field name="lowerfilt" type="lowerfilt" indexed="true" stored="true"/>+ <field name="porterfilt" type="porterfilt" indexed="true" stored="true"/>+ <field name="engporterfilt" type="engporterfilt" indexed="true" stored="true"/>+ <field name="custengporterfilt" type="custengporterfilt" indexed="true" stored="true"/>+ <field name="stopfilt" type="stopfilt" indexed="true" stored="true"/>+ <field name="custstopfilt" type="custstopfilt" indexed="true" stored="true"/>+ <field name="lengthfilt" type="lengthfilt" indexed="true" stored="true"/>+++ <field name="subword" type="subword" indexed="true" stored="true"/>+ <field name="sku1" type="skutype1" indexed="true" stored="true"/>+ <field name="sku2" type="skutype2" indexed="true" stored="true"/>++ <!-- Dynamic field definitions. If a field name is not found, dynamicFields+ will be used if the name matches any of the patterns.+ RESTRICTION: the glob-like pattern in the name attribute must have+ a "*" only at the start or the end.+ EXAMPLE: name="*_i" will match any field ending in _i (like myid_i, z_i)+ Longer patterns will be matched first. if equal size patterns+ both match, the first appearing in the schema will be used.+ -->+ <dynamicField name="*_i" type="sint" indexed="true" stored="true"/>+ <dynamicField name="*_s" type="string" indexed="true" stored="true"/>+ <dynamicField name="*_l" type="slong" indexed="true" stored="true"/>+ <dynamicField name="*_t" type="text" indexed="true" stored="true"/>+ <dynamicField name="*_b" type="boolean" indexed="true" stored="true"/>+ <dynamicField name="*_f" type="sfloat" indexed="true" stored="true"/>+ <dynamicField name="*_d" type="sdouble" indexed="true" stored="true"/>+ <dynamicField name="*_dt" type="date" indexed="true" stored="true"/>+ <dynamicField name="*_bcd" type="bcdstr" indexed="true" stored="true"/>++ <dynamicField name="*_sI" type="string" indexed="true" stored="false"/>+ <dynamicField name="*_sS" type="string" indexed="false" stored="true"/>+ <dynamicField name="t_*" type="text" indexed="true" stored="true"/>+++ <!-- for testing to ensure that longer patterns are matched first -->+ <dynamicField name="*aa" type="string" indexed="true" stored="true"/>+ <dynamicField name="*aaa" type="integer" indexed="false" stored="true"/>+++ </fields>++ <defaultSearchField>text</defaultSearchField>+ <uniqueKey>id</uniqueKey>++ <!-- copyField commands copy one field to another at the time a document+ is added to the index. It's used either to index the same field different+ ways, or to add multiple fields to the same field for easier/faster searching.+ -->+ <copyField source="title" dest="title_stemmed"/>+ <copyField source="title" dest="title_lettertok"/>++ <copyField source="title" dest="text"/>+ <copyField source="subject" dest="text"/>+++ <!-- Similarity is the scoring routine for each document vs a query.+ A custom similarity may be specified here, but the default is fine+ for most applications.+ -->+ <!-- <similarity class="org.apache.lucene.search.DefaultSimilarity"/> -->++</schema>diff --git a/src/apps/SolarTest/solrconfig.xml b/src/apps/SolarTest/solrconfig.xmlnew file mode 100644index 00000000000..f1d96f92c2d--- /dev/null+++ b/src/apps/SolarTest/solrconfig.xml@@ -0,0 +1,191 @@+<?xml version="1.0" ?>++<!-- $Id$+ $Source$+ $Name$+ -->++<config>++ <!-- Used to specify an alternate directory to hold all index data.+ It defaults to "index" if not present, and should probably+ not be changed if replication is in use. -->+ <!--+ <indexDir>index</indexDir>+ -->++ <indexDefaults>+ <!-- Values here affect all index writers and act as a default+ unless overridden. -->+ <useCompoundFile>false</useCompoundFile>+ <mergeFactor>10</mergeFactor>+ <maxBufferedDocs>1000</maxBufferedDocs>+ <maxMergeDocs>2147483647</maxMergeDocs>+ <maxFieldLength>10000</maxFieldLength>++ <!-- these are global... can't currently override per index -->+ <writeLockTimeout>1000</writeLockTimeout>+ <commitLockTimeout>10000</commitLockTimeout>++ </indexDefaults>++ <mainIndex>+ <!-- lucene options specific to the main on-disk lucene index -->+ <useCompoundFile>false</useCompoundFile>+ <mergeFactor>10</mergeFactor>+ <maxBufferedDocs>1000</maxBufferedDocs>+ <maxMergeDocs>2147483647</maxMergeDocs>+ <maxFieldLength>10000</maxFieldLength>++ <unlockOnStartup>true</unlockOnStartup>+ </mainIndex>++ <updateHandler class="solar.DirectUpdateHandler2">++ <!-- autocommit pending docs if certain criteria are met -->+ <autocommit> <!-- NOTE: autocommit not implemented yet -->+ <maxDocs>10000</maxDocs>+ <maxSec>3600</maxSec>+ </autocommit>++ <!-- represents a lower bound on the frequency that commits may+ occur (in seconds). NOTE: not yet implemented+ -->+ <commitIntervalLowerBound>0</commitIntervalLowerBound>++ <!-- The RunExecutableListener executes an external command.+ exe - the name of the executable to run+ dir - dir to use as the current working directory. default="."+ wait - the calling thread waits until the executable returns. default="true"+ args - the arguments to pass to the program. default=nothing+ env - environment variables to set. default=nothing+ -->+ <!-- A postCommit event is fired after every commit+ <listener event="postCommit" class="solar.RunExecutableListener">+ <str name="exe">/var/opt/resin3/__PORT__/scripts/solar/snapshooter</str>+ <str name="dir">/var/opt/resin3/__PORT__</str>+ <bool name="wait">true</bool>+ <arr name="args"> <str>arg1</str> <str>arg2</str> </arr>+ <arr name="env"> <str>MYVAR=val1</str> </arr>+ </listener>+ -->+++ </updateHandler>+++ <query>+ <!-- Maximum number of clauses in a boolean query... can affect+ range or wildcard queries that expand to big boolean+ queries. An exception is thrown if exceeded.+ -->+ <maxBooleanClauses>1024</maxBooleanClauses>+++ <!-- Cache specification for Filters or DocSets - unordered set of *all* documents+ that match a particular query.+ -->+ <filterCache+ class="solar.search.LRUCache"+ size="512"+ initialSize="512"+ autowarmCount="256"/>++ <queryResultCache+ class="solar.search.LRUCache"+ size="512"+ initialSize="512"+ autowarmCount="1024"/>++ <documentCache+ class="solar.search.LRUCache"+ size="512"+ initialSize="512"+ autowarmCount="0"/>++ <!--+ <cache name="myUserCache"+ class="solar.search.LRUCache"+ size="4096"+ initialSize="1024"+ autowarmCount="1024"+ regenerator="MyRegenerator"+ />+ -->+++ <useFilterForSortedQuery>true</useFilterForSortedQuery>++ <queryResultWindowSize>10</queryResultWindowSize>++ <HashDocSet maxSize="3000" loadFactor="0.75"/>+++ <!-- boolToFilterOptimizer converts boolean clauses with zero boost+ into cached filters if the number of docs selected by the clause exceeds+ the threshold (represented as a fraction of the total index)+ -->+ <boolTofilterOptimizer enabled="true" cacheSize="32" threshold=".05"/>+++ <!-- a newSearcher event is fired whenever a new searcher is being prepared+ and there is a current searcher handling requests (aka registered). -->+ <!-- QuerySenderListener takes an array of NamedList and executes a+ local query request for each NamedList in sequence. -->+ <!--+ <listener event="newSearcher" class="solar.QuerySenderListener">+ <arr name="queries">+ <lst> <str name="q">solar</str> <str name="start">0</str> <str name="rows">10</str> </lst>+ <lst> <str name="q">rocks</str> <str name="start">0</str> <str name="rows">10</str> </lst>+ </arr>+ </listener>+ -->++ <!-- a firstSearcher event is fired whenever a new searcher is being+ prepared but there is no current registered searcher to handle+ requests or to gain prewarming data from. -->+ <!--+ <listener event="firstSearcher" class="solar.QuerySenderListener">+ <arr name="queries">+ <lst> <str name="q">fast_warm</str> <str name="start">0</str> <str name="rows">10</str> </lst>+ </arr>+ </listener>+ -->+++ </query>+++ <!-- An alternate set representation that uses an integer hash to store filters (sets of docids).+ If the set cardinality <= maxSize elements, then HashDocSet will be used instead of the bitset+ based HashBitset. -->++ <!-- requestHandler plugins... incoming queries will be dispatched to the+ correct handler based on the qt (query type) param matching the+ name of registered handlers.+ The "standard" request handler is the default and will be used if qt+ is not specified in the request.+ -->+ <requestHandler name="standard" class="solar.StandardRequestHandler" />+ <requestHandler name="old" class="solar.tst.OldRequestHandler" >+ <int name="myparam">1000</int>+ <float name="ratio">1.4142135</float>+ <arr name="myarr"><int>1</int><int>2</int></arr>+ <str>foo</str>+ </requestHandler>+ <requestHandler name="oldagain" class="solar.tst.OldRequestHandler" >+ <lst name="lst1"> <str name="op">sqrt</str> <int name="val">2</int> </lst>+ <lst name="lst2"> <str name="op">log</str> <float name="val">10</float> </lst>+ </requestHandler>++ <requestHandler name="test" class="solar.tst.TestRequestHandler" />+++ <admin>+ <defaultQuery>solar</defaultQuery>+ <gettableFiles>solarconfig.xml conf/solar/WEB-INF/web.external.xml conf/resin.conf </gettableFiles>+ </admin>++++</config>diff --git a/src/apps/SolarTest/src/SolrTest.java b/src/apps/SolarTest/src/SolrTest.javanew file mode 100644index 00000000000..837555ff608--- /dev/null+++ b/src/apps/SolarTest/src/SolrTest.java@@ -0,0 +1,367 @@+/**+ * 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 org.apache.solr.core.SolrCore;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.request.*;+++import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;+import javax.xml.parsers.ParserConfigurationException;+import javax.xml.xpath.XPath;+import javax.xml.xpath.XPathFactory;+import javax.xml.xpath.XPathConstants;+import java.io.*;+import java.util.*;+import java.util.logging.Logger;+import java.util.logging.Level;+import java.util.logging.Handler;+import java.util.logging.ConsoleHandler;++import org.w3c.dom.Document;+++/**+ * User: Yonik Seeley+ * Date: Aug 16, 2004+ */+public class SolrTest extends Thread {+ static SolrCore core;++ static String[] requestDict;+ static String[] updateDict;+ static String[] testDict;+ static List<Integer> testDictLineno;++ static List<Integer> lineno;+ public static String[] readDict(String filename) throws IOException {+ BufferedReader br = new BufferedReader(new FileReader(filename));+ ArrayList lst = new ArrayList(1024);+ lineno = new ArrayList<Integer>(1024);+ String line;+ int lineNum=0;+ while ((line = br.readLine())!=null) {+ lineNum++;+ if (line.length() <= 1) continue;+ lst.add(line);+ lineno.add(lineNum);+ }+ br.close();+ return (String[]) lst.toArray(new String[lst.size()]);+ }+++ public static boolean verbose=false;+ static boolean doValidate=true;++ static int countdown;+ static synchronized boolean runAgain() {+ return countdown-- > 0;+ }+++ // statistics per client+ int numReq=0;+ int numErr=0;+ int numBodyChars=0;++ boolean isWriter=false;+ boolean sequenceTest=false;++ public void run() {+ if (sequenceTest) {+ for (int i=0; i<testDict.length; i++) {+ String s = testDict[i];+ int lineno = testDictLineno.get(i);+ String req;+ String test=null;+ String params=null;+ char[] resp;+ if (s.length()<2 || s.startsWith("#")) continue; // comment+ System.out.println("LINE=" + lineno + " EXECUTING " + s);++ int endQuery = s.length();+ int startParams = s.indexOf("%%");+ int endParams = s.length();+ int endTests = s.length();+ if (startParams > 0) {+ endQuery = startParams;+ endParams = s.length();+ }+ int startTests = s.indexOf('%', startParams+2);+ if (startTests > 0) {+ if (endQuery == s.length()) endQuery = startTests;+ endParams = startTests;+ }++ req = s.substring(0,endQuery).trim();+ if (startParams > 0) params = s.substring(startParams+2,endParams).trim();+ if (startTests > 0) test = s.substring(startTests+1,endTests).trim();++ System.out.println("###req=" + req);+ System.out.println("###params=" + params);+ System.out.println("###tests=" + test);++ if (req.startsWith("<")) {+ resp = doUpdate(req);+ } else {+ resp = doReq(req,params);+ }+ if (doValidate) {+ validate(req,test,resp);+ } else {+ System.out.println("#### no validation performed");+ }+ }+ System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> SUCCESS <<<<<<<<<<<<<<<<<<<<<<<<<<");+ }++ else {+ while(runAgain()) {+ if (isWriter) doUpdate(updateDict[(int)(Math.random()*updateDict.length)]);+ else doReq(requestDict[(int)(Math.random()*requestDict.length)], null);+ }+ }+ }++ private DocumentBuilder builder;+ private XPath xpath = XPathFactory.newInstance().newXPath();+ {+ try {+ builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();+ } catch (ParserConfigurationException e) {+ e.printStackTrace();+ }+ }++ private void validate(String req, String test, char[] resp) {+ if (test==null || test.length()==0) return;+ Document document=null;+ try {+ // the resp[] contains a declaration that it is UTF-8, so we+ // need to change it to that for the XML parser.++ document = builder.parse(new ByteArrayInputStream(new String(resp).getBytes("UTF-8")));+ // document = builder.parse(new String(resp));+ } catch (Exception e) {+ System.out.println("ERROR parsing '" + new String(resp) + "'");+ throw new RuntimeException(e);+ }++ String[] tests = test.split("%");+ for (String xp : tests) {+ Boolean bool=false;+ xp=xp.trim();+ try {+ bool = (Boolean) xpath.evaluate(xp, document, XPathConstants.BOOLEAN);+ } catch (Exception e) {+ System.out.println("##################ERROR EVALUATING XPATH '" + xp + "'");+ throw new RuntimeException(e);+ }+ if (!bool) {+ System.out.println("##################ERROR");+ System.out.println("req="+req);+ System.out.println("xp="+xp);+ throw new RuntimeException("test failed.");+ }+ }++ }+++ public char[] doUpdate(String req) {+ try {+ // String lucene=updateDict[(int)(Math.random()*updateDict.length)];+ String lucene=req;+ StringReader ureq = new StringReader(lucene);+ CharArrayWriter writer = new CharArrayWriter(32000);+ core.update(ureq, writer);+ if (verbose) System.out.println("UPDATE RESPONSE:'" + writer + "'");+ // if (verbose) System.out.println("BODY chars read:" + writer.size());+ this.numBodyChars+=writer.size();+ this.numReq++;+ return writer.toCharArray();+ } catch (Exception e) {+ this.numErr++;+ e.printStackTrace();+ }+ return null;+ }+++ static XMLResponseWriter xmlwriter = new XMLResponseWriter();+ static SolrRequestHandler handler =+ // new OldRequestHandler();+ new StandardRequestHandler();++ public char[] doReq(String req, String params) {+ int start=0;+ int limit=10;+ String handler="standard";+ //handler="test";+++ Map args = new HashMap();+ args.put("indent", "on");+ args.put("debugQuery", "on");+ args.put("fl", "score");+ args.put("version", "2.0");++ if (params != null) {+ String[] plist = params.split("&");+ for (String decl : plist) {+ String[] nv = decl.split("=");+ if (nv.length==1) {+ nv = new String[] { nv[0], "" };+ }+ if (nv[0].equals("start")) {+ start=Integer.parseInt(nv[1]);+ }+ else if (nv[0].equals("limit")) {+ limit=Integer.parseInt(nv[1]);+ }+ else if (nv[0].equals("qt")) {+ handler = nv[1];+ } else {+ args.put(nv[0], nv[1]);+ }+ }+ }++ try {+ // String lucene=requestDict[(int)(Math.random()*requestDict.length)];+ String lucene=req;+ CharArrayWriter writer = new CharArrayWriter(32000);++ System.out.println("start="+start+" limit="+limit+" handler="+handler);+ LocalSolrQueryRequest qreq = new LocalSolrQueryRequest(core,lucene,handler,start,limit,args);+ SolrQueryResponse qrsp = new SolrQueryResponse();+ try {+ core.execute(qreq,qrsp);+ if (qrsp.getException() != null) throw qrsp.getException();+ // handler.handleRequest(qreq,qrsp);+ xmlwriter.write(writer,qreq,qrsp);+ } finally {+ qreq.close();+ }+ if (verbose) System.out.println("GOT:'" + writer + "'");+ if (verbose) System.out.println("BODY chars read:" + writer.size());+ this.numBodyChars+=writer.size();+ this.numReq++;+ return writer.toCharArray();+ } catch (Exception e) {+ this.numErr++;+ e.printStackTrace();+ }+ return null;+ }++++ public static void main(String[] args) throws Exception {+ int readers=1;+ int requests=1;+ int writers=0;++ Logger log = Logger.getLogger("solar");+ log.setUseParentHandlers(false);+ log.setLevel(Level.FINEST);+ Handler handler = new ConsoleHandler();+ handler.setLevel(Level.FINEST);+ log.addHandler(handler);++ String filename="dict.txt";+ String updateFilename="update_dict.txt";+ String luceneDir=null;+ String schemaFile="schema.xml";+ String testFile=null;++ boolean b_numUpdates=false; boolean b_writers=false;++ int i=0; String arg;+ while (i < args.length && args[i].startsWith("-")) {+ arg = args[i++];+ if (arg.equals("-verbose")) {+ verbose=true;+ } else if (arg.equals("-dict")) {+ filename=args[i++];+ } else if (arg.equals("-index")) {+ luceneDir=args[i++];+ } else if (arg.equals("-readers")) {+ readers=Integer.parseInt(args[i++]);+ } else if (arg.equals("-numRequests")) {+ requests=Integer.parseInt(args[i++]);+ } else if (arg.equals("-writers")) {+ writers=Integer.parseInt(args[i++]);+ b_writers=true;+ } else if (arg.equals("-schema")) {+ schemaFile=args[i++];+ } else if (arg.equals("-test")) {+ testFile=args[i++];+ } else if (arg.equals("-noValidate")) {+ doValidate=false;+ } else {+ System.out.println("Unknown option: " + arg);+ return;+ }+ }++ try {++ IndexSchema schema = new IndexSchema(schemaFile);+ countdown = requests;+ core=new SolrCore(luceneDir,schema);++ try {+ if (readers > 0) requestDict = readDict(filename);+ if (writers > 0) updateDict = readDict(updateFilename);+ if (testFile != null) {+ testDict = readDict(testFile);+ testDictLineno = lineno;+ }+ } catch (IOException e) {+ e.printStackTrace();+ System.out.println("Can't read "+filename);+ return;+ }++ SolrTest[] clients = new SolrTest[readers+writers];+ for (i=0; i<readers; i++) {+ clients[i] = new SolrTest();+ if (testFile != null) clients[i].sequenceTest=true;+ clients[i].start();+ }+ for (i=readers; i<readers+writers; i++) {+ clients[i] = new SolrTest();+ clients[i].isWriter = true;+ clients[i].start();+ }++ for (i=0; i<readers; i++) {+ clients[i].join();+ }+ for (i=readers; i<readers+writers; i++) {+ clients[i].join();+ }++ } finally {+ if (core != null) core.close();+ }++ }++}diff --git a/src/apps/SolarTest/stopwords.txt b/src/apps/SolarTest/stopwords.txtnew file mode 100644index 00000000000..5401d99f9fb--- /dev/null+++ b/src/apps/SolarTest/stopwords.txt@@ -0,0 +1,2 @@+stopworda+stopwordbdiff --git a/src/apps/SolarTest/synonyms.txt b/src/apps/SolarTest/synonyms.txtnew file mode 100644index 00000000000..d56bc23f14e--- /dev/null+++ b/src/apps/SolarTest/synonyms.txt@@ -0,0 +1,6 @@+a => aa+b => b1 b2+c => c1,c2+a\=>a => b\=>b+a\,a => b\,b+foo,bar,baz\ No newline at end of filediff --git a/src/apps/SolarTest/test_func.txt b/src/apps/SolarTest/test_func.txtnew file mode 100644index 00000000000..156f7435559--- /dev/null+++ b/src/apps/SolarTest/test_func.txt@@ -0,0 +1,51 @@+<delete><query>id:[* TO *]</query></delete>+<optimize/>++<delete><query>id[0 TO 9]</query></delete>+<commit/>++<add><doc><field name="id">3</field></doc></add>+<add><doc><field name="id">1</field></doc></add>+<add><doc><field name="id">7</field></doc></add>+<add><doc><field name="id">0</field></doc></add>+<add><doc><field name="id">5</field></doc></add>+<commit/>++_val_:"linear(id,2,3)"++id:[ 0 TO 5 ] +_val_:"linear(id,2,3)"^0.1++id:[ 0 TO 5 ] +_val_:"linear(rord(id),2,3)"^0.1++id:[ 0 TO 5 ] +_val_:"recip(rord(id),2,3,4)"^0.1++id:[ 0 TO 5 ] +_val_:"linear(linear(rord(id),6,5),2,3)"^0.1++#<delete><query>id:[0 TO 9]</query></delete>+#<commit/>++<delete><query>weight:[* TO *]</query></delete>+<commit/>++<add><doc><field name="id">10</field><field name="weight">3</field></doc></add>+<add><doc><field name="id">11</field><field name="weight">1</field></doc></add>+<add><doc><field name="id">12</field><field name="weight">7</field></doc></add>+<add><doc><field name="id">13</field><field name="weight">0</field></doc></add>+<add><doc><field name="id">14</field><field name="weight">5</field></doc></add>+<commit/>+++id:[10 TO 14] +_val_:weight^2++id:[10 TO 14] +_val_:"ord(weight)"^2++id:[10 TO 14] +_val_:"rord(weight)"^2++#+id:[10 TO 14] +weight:_int_^2+#+id:[10 TO 14] +weight:_ord_^2+#+id:[10 TO 14] +weight:_rord_^2++<add><doc><field name="id">10</field><field name="q_i">2</field></doc></add>+<add><doc><field name="id">11</field><field name="q_f">3.14159</field></doc></add>+<add><doc><field name="id">12</field><field name="q_l">900</field></doc></add>+<add><doc><field name="id">13</field><field name="q_d">.1</field></doc></add>+<add><doc><field name="id">14</field><field name="q_dt">2005-01-01T01:01:01Z</field></doc></add>+<commit/>+_val_:q_i %%fl=score %//@maxScore = //doc/float[@name="score"] %//doc/float[@name="score"] = "2.0"+_val_:q_f %%fl=score %//@maxScore = //doc/float[@name="score"] %//doc/float[@name="score"] = "3.14159"+_val_:q_l %%fl=score %//@maxScore = //doc/float[@name="score"] %//doc/float[@name="score"] = "900.0"+_val_:q_d %%fl=score %//@maxScore = //doc/float[@name="score"] %//doc/float[@name="score"] = "0.1"+_val_:q_dt %%fl=score %//@maxScore = //doc/float[@name="score"] %//doc/float[@name="score"] = "1.0"diff --git a/src/java/org/apache/solr/analysis/BaseTokenFilterFactory.java b/src/java/org/apache/solr/analysis/BaseTokenFilterFactory.javanew file mode 100644index 00000000000..14d0e3d3854--- /dev/null+++ b/src/java/org/apache/solr/analysis/BaseTokenFilterFactory.java@@ -0,0 +1,68 @@+/**+ * 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.+ */++package org.apache.solr.analysis;+++import java.util.Map;++/**+ * @author yonik+ * @version $Id: BaseTokenFilterFactory.java,v 1.5 2005/12/06 04:16:16 yonik Exp $+ */+public abstract class BaseTokenFilterFactory implements TokenFilterFactory {+ protected Map<String,String> args;+ public void init(Map<String,String> args) {+ this.args=args;+ }++ public Map<String,String> getArgs() {+ return args;+ }++ // TODO: move these somewhere that tokenizers and others+ // can also use them...+ protected int getInt(String name) {+ return getInt(name,-1,false);+ }++ protected int getInt(String name, int defaultVal) {+ return getInt(name,defaultVal,true);+ }++ protected int getInt(String name, int defaultVal, boolean useDefault) {+ String s = args.get(name);+ if (s==null) {+ if (useDefault) return defaultVal;+ throw new RuntimeException("Configuration Error: missing parameter '" + name + "'");+ }+ return Integer.parseInt(s);+ }++ protected boolean getBoolean(String name, boolean defaultVal) {+ return getBoolean(name,defaultVal,true);+ }++ protected boolean getBoolean(String name, boolean defaultVal, boolean useDefault) {+ String s = args.get(name);+ if (s==null) {+ if (useDefault) return defaultVal;+ throw new RuntimeException("Configuration Error: missing parameter '" + name + "'");+ }+ return Boolean.parseBoolean(s);+ }++}diff --git a/src/java/org/apache/solr/analysis/BaseTokenizerFactory.java b/src/java/org/apache/solr/analysis/BaseTokenizerFactory.javanew file mode 100644index 00000000000..191f116a1ea--- /dev/null+++ b/src/java/org/apache/solr/analysis/BaseTokenizerFactory.java@@ -0,0 +1,34 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import java.util.Map;++/**+ * @author yonik+ * @version $Id: BaseTokenizerFactory.java,v 1.3 2005/09/20 04:57:50 yonik Exp $+ */+public abstract class BaseTokenizerFactory implements TokenizerFactory {+ protected Map<String,String> args;+ public void init(Map<String,String> args) {+ this.args=args;+ }++ public Map<String,String> getArgs() {+ return args;+ }+}diff --git a/src/java/org/apache/solr/analysis/EnglishPorterFilterFactory.java b/src/java/org/apache/solr/analysis/EnglishPorterFilterFactory.javanew file mode 100644index 00000000000..3bc4fd35a44--- /dev/null+++ b/src/java/org/apache/solr/analysis/EnglishPorterFilterFactory.java@@ -0,0 +1,111 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.solr.core.Config;+import org.apache.lucene.analysis.StopFilter;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.TokenFilter;+import org.apache.lucene.analysis.Token;++import java.util.Map;+import java.util.List;+import java.util.Set;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id$+ */+public class EnglishPorterFilterFactory extends BaseTokenFilterFactory {+ public void init(Map<String, String> args) {+ super.init(args);+ String wordFile = args.get("protected");+ if (wordFile != null) {+ try {+ List<String> wlist = Config.getLines(wordFile);+ protectedWords = StopFilter.makeStopSet((String[])wlist.toArray(new String[0]));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ }++ private Set protectedWords = null;++ public TokenStream create(TokenStream input) {+ return new EnglishPorterFilter(input,protectedWords);+ }+}+++/** English Porter2 filter that doesn't use reflection to+/* adapt lucene to the snowball stemmer code.+ */+class EnglishPorterFilter extends TokenFilter {+ private final Set protWords;+ private net.sf.snowball.ext.EnglishStemmer stemmer;++ public EnglishPorterFilter(TokenStream source, Set protWords) {+ super(source);+ this.protWords=protWords;+ stemmer = new net.sf.snowball.ext.EnglishStemmer();+ }+++ /** the original code from lucene sandbox+ public final Token next() throws IOException {+ Token token = input.next();+ if (token == null)+ return null;+ stemmer.setCurrent(token.termText());+ try {+ stemMethod.invoke(stemmer, EMPTY_ARGS);+ } catch (Exception e) {+ throw new RuntimeException(e.toString());+ }+ return new Token(stemmer.getCurrent(),+ token.startOffset(), token.endOffset(), token.type());+ }+ **/++ public Token next() throws IOException {+ Token tok = input.next();+ if (tok==null) return null;+ String tokstr = tok.termText();++ // if protected, don't stem. use this to avoid stemming collisions.+ if (protWords != null && protWords.contains(tokstr)) {+ return tok;+ }++ stemmer.setCurrent(tokstr);+ stemmer.stem();+ String newstr = stemmer.getCurrent();+ if (tokstr.equals(newstr)) {+ return tok;+ } else {+ // TODO: it would be nice if I could just set termText directly like+ // lucene packages can.+ Token newtok = new Token(newstr, tok.startOffset(), tok.endOffset(), tok.type());+ newtok.setPositionIncrement(tok.getPositionIncrement());+ return newtok;+ }++ }+}+diff --git a/src/java/org/apache/solr/analysis/HTMLStripReader.java b/src/java/org/apache/solr/analysis/HTMLStripReader.javanew file mode 100644index 00000000000..d2f817e5295--- /dev/null+++ b/src/java/org/apache/solr/analysis/HTMLStripReader.java@@ -0,0 +1,1318 @@+/**+ * 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.+ */++package org.apache.solr.analysis;+++import java.io.Reader;+import java.io.BufferedReader;+import java.io.IOException;+import java.io.InputStreamReader;+import java.util.HashMap;++/**+ * A Reader that wraps another reader and attempts to strip out HTML constructs.+ *+ *+ * @author yonik+ * @version $Id: HTMLStripReader.java,v 1.2 2005/08/30 15:31:42 yonik Exp $+ */++public class HTMLStripReader extends Reader {+ private final Reader in;+ private final int READAHEAD=4096;++ // pushback buffer+ private final StringBuilder pushed = new StringBuilder();++ private static final int EOF=-1;+ private static final int MISMATCH=-2;+ private static final int MATCH=-3;++ // temporary buffer+ private final StringBuilder sb = new StringBuilder();+++ public static void main(String[] args) throws IOException {+ Reader in = new HTMLStripReader(+ new InputStreamReader(System.in));+ int ch;+ while ( (ch=in.read()) != -1 ) System.out.print((char)ch);+ }++ public HTMLStripReader(Reader source) {+ super();+ this.in=source.markSupported() ? source : new BufferedReader(source);+ }+++ private int next() throws IOException {+ int len = pushed.length();+ if (len>0) {+ int ch = pushed.charAt(len-1);+ pushed.setLength(len-1);+ return ch;+ }+ return in.read();+ }++ private int nextSkipWS() throws IOException {+ int ch=next();+ while(isSpace(ch)) ch=next();+ return ch;+ }++ private int peek() throws IOException {+ int len = pushed.length();+ if (len>0) {+ return pushed.charAt(len-1);+ }+ int ch = in.read();+ push(ch);+ return ch;+ }++ private void push(int ch) {+ pushed.append((char)ch);+ }+++ private boolean isSpace(int ch) {+ switch (ch) {+ case ' ':+ case '\n':+ case '\r':+ case '\t': return true;+ default: return false;+ }+ }++ private boolean isHex(int ch) {+ return (ch>='0' && ch<='9') ||+ (ch>='A' && ch<='Z') ||+ (ch>='a' && ch<='z');+ }++ private boolean isAlpha(int ch) {+ return ch>='a' && ch<='z' || ch>='A' && ch<='Z';+ }++ private boolean isDigit(int ch) {+ return ch>='0' && ch<='9';+ }++/*** From HTML 4.0+[4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender+[5] Name ::= (Letter | '_' | ':') (NameChar)*+[6] Names ::= Name (#x20 Name)*+[7] Nmtoken ::= (NameChar)++[8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*+***/++ // should I include all id chars allowable by HTML/XML here?+ // including accented chars, ':', etc?+ private boolean isIdChar(int ch) {+ // return Character.isUnicodeIdentifierPart(ch);+ // isUnicodeIdentiferPart doesn't include '-'... shoudl I still+ // use it and add in '-',':',etc?+ return isAlpha(ch) || isDigit(ch) || ch=='.' ||+ ch=='-' || ch=='_' || ch==':'+ || Character.isLetter(ch);++ }++ private boolean isFirstIdChar(int ch) {+ return Character.isUnicodeIdentifierStart(ch);+ // return isAlpha(ch) || ch=='_' || Character.isLetter(ch);+ }++ private void saveState() throws IOException {+ in.mark(READAHEAD);+ }++ private void restoreState() throws IOException {+ in.reset();+ pushed.setLength(0);+ }++ private int readNumericEntity() throws IOException {+ // "&#" has already been read at this point++ // is this decimal, hex, or nothing at all.+ int ch = next();+ int base=10;+ boolean invalid=false;+ sb.setLength(0);++ if (isDigit(ch)) {+ // decimal character entity+ sb.append((char)ch);+ for (int i=0; i<10; i++) {+ ch = next();+ if (isDigit(ch)) {+ sb.append((char)ch);+ } else {+ break;+ }+ }+ } else if (ch=='x') {+ // hex character entity+ base=16;+ sb.setLength(0);+ for (int i=0; i<10; i++) {+ ch = next();+ if (isHex(ch)) {+ sb.append((char)ch);+ } else {+ break;+ }+ }+ } else {+ return MISMATCH;+ }+++ // In older HTML, an entity may not have always been terminated+ // with a semicolon. We'll also treat EOF or whitespace as terminating+ // the entity.+ if (ch==';' || ch==-1) {+ return Integer.parseInt(sb.toString(), base);+ }++ // if whitespace terminated the entity, we need to return+ // that whitespace on the next call to read().+ if (isSpace(ch)) {+ push(ch);+ return Integer.parseInt(sb.toString(), base);+ }++ // Not an entity...+ return MISMATCH;+ }++ private int readEntity() throws IOException {+ int ch = next();+ if (ch=='#') return readNumericEntity();++ //read an entity reference++ // for an entity reference, require the ';' for safety.+ // otherwise we may try and convert part of some company+ // names to an entity. "Alpha&Beta Corp" for instance.+ //+ // TODO: perhaps I should special case some of the+ // more common ones like & to make the ';' optional...++ sb.setLength(0);+ sb.append((char)ch);++ for (int i=0; i<READAHEAD; i++) {+ ch=next();+ if (Character.isLetter(ch)) {+ sb.append((char)ch);+ } else {+ break;+ }+ }++ if (ch==';') {+ String entity=sb.toString();+ Character entityChar = entityTable.get(entity);+ if (entityChar!=null) {+ return entityChar.charValue();+ }+ }++ return MISMATCH;+ }++ /*** valid comments according to HTML specs+ <!-- Hello -->+ <!-- Hello -- -- Hello-->+ <!---->+ <!------ Hello -->+ <!>+ <!------> Hello -->++ #comments inside of an entity decl:+ <!ENTITY amp CDATA "&" -- ampersand, U+0026 ISOnum -->++ Turns out, IE & mozilla don't parse comments correctly.+ Since this is meant to be a practical stripper, I'll just+ try and duplicate what the browsers do.++ <!-- (stuff_including_markup)* -->+ <!FOO (stuff, not including markup) >+ <! (stuff, not including markup)* >+++ ***/++ private int readBang(boolean inScript) throws IOException {+ // at this point, "<!" has been read++ int ret = readComment(inScript);+ if (ret==MATCH) return MATCH;++ int ch = next();+ if (ch=='>') return MATCH;++ // if it starts with <! and isn't a comment,+ // simply read until ">"+ while (true) {+ ch = next();+ if (ch=='>') {+ return MATCH;+ }+ else if (ch<0) {+ return MISMATCH;+ }+ }+ }++ // tries to read comments the way browsers do, not+ // strictly by the standards.+ //+ // GRRRR. it turns out that in the wild, a <script> can have a HTML comment+ // that contains a script that contains a quoted comment.+ // <script><!-- document.write("<!--embedded comment-->") --></script>+ //+ private int readComment(boolean inScript) throws IOException {+ // at this point "<!" has been read+ int ch = next();+ if (ch!='-') {+ // not a comment+ push(ch);+ return MISMATCH;+ }++ ch = next();+ if (ch!='-') {+ // not a comment+ push(ch);+ push('-');+ return MISMATCH;+ }++ while (true) {+ ch = next();+ if (ch<0) return MISMATCH;+ if (ch=='-') {+ ch = next();+ if (ch<0) return MISMATCH;+ if (ch!='-') {+ push(ch);+ continue;+ }++ ch = next();+ if (ch<0) return MISMATCH;+ if (ch!='>') {+ push(ch);+ push('-');+ continue;+ }++ return MATCH;+ } else if ((ch=='\'' || ch=='"') && inScript) {+ push(ch);+ int ret=readScriptString();+ // if this wasn't a string, there's not much we can do+ // at this point without having a stack of stream states in+ // order to "undo" just the latest.+ } else if (ch=='<') {+ eatSSI();+ }+ }+ }++++ private int readTag() throws IOException {+ // at this point '<' has already been read+ int ch = next();+ if (!isAlpha(ch)) {+ push(ch);+ return MISMATCH;+ }++ sb.setLength(0);+ sb.append((char)ch);++ while(true) {+ ch = next();+ if (isIdChar(ch)) {+ sb.append((char)ch);+ } else if (ch=='/') {+ // Hmmm, a tag can close with "/>" as well as "/ >"+ // read end tag '/>' or '/ >', etc+ return nextSkipWS()=='>' ? MATCH : MISMATCH;+ } else {+ break;+ }+ }++ // After the tag id, there needs to be either whitespace or+ // '>'+ if ( !(ch=='>' || isSpace(ch)) ) {+ return MISMATCH;+ }++ if (ch!='>') {+ // process attributes+ while (true) {+ ch=next();+ if (isSpace(ch)) {+ continue;+ } else if (isFirstIdChar(ch)) {+ push(ch);+ int ret = readAttr2();+ if (ret==MISMATCH) return ret;+ } else if (ch=='/') {+ // read end tag '/>' or '/ >', etc+ return nextSkipWS()=='>' ? MATCH : MISMATCH;+ } else if (ch=='>') {+ break;+ } else {+ return MISMATCH;+ }+ }+ }++ // We only get to this point after we have read the+ // entire tag. Now let's see if it's a special tag.+ String name=sb.toString();+ if (name.equals("script") || name.equals("style")) {+ // The content of script and style elements is+ // CDATA in HTML 4 but PCDATA in XHTML.++ /* From HTML4:+ Although the STYLE and SCRIPT elements use CDATA for their data model,+ for these elements, CDATA must be handled differently by user agents.+ Markup and entities must be treated as raw text and passed to the application+ as is. The first occurrence of the character sequence "</" (end-tag open+ delimiter) is treated as terminating the end of the element's content. In+ valid documents, this would be the end tag for the element.+ */++ // discard everything until endtag is hit (except+ // if it occurs in a comment.++ // reset the stream mark to here, since we know that we sucessfully matched+ // a tag, and if we can't find the end tag, this is where we will want+ // to roll back to.+ saveState();+ pushed.setLength(0);+ return findEndTag();+ }+ return MATCH;+ }+++ // find an end tag, but beware of comments...+ // <script><!-- </script> -->foo</script>+ // beware markup in script strings: </script>...document.write("</script>")foo</script>+ // TODO: do I need to worry about CDATA sections "<![CDATA[" ?+ int findEndTag() throws IOException {+ while (true) {+ int ch = next();+ if (ch=='<') {+ ch = next();+ // skip looking for end-tag in comments+ if (ch=='!') {+ int ret = readBang(true);+ if (ret==MATCH) continue;+ // yikes... what now? It wasn't a comment, but I can't get+ // back to the state I was at. Just continue from where I+ // am I guess...+ continue;+ }+ // did we match "</"+ if (ch!='/') {+ push(ch);+ continue;+ }+ int ret = readName();+ if (ret==MISMATCH) return MISMATCH;+ ch=nextSkipWS();+ if (ch!='>') return MISMATCH;+ return MATCH;+ } else if (ch=='\'' || ch=='"') {+ // read javascript string to avoid a false match.+ push(ch);+ int ret = readScriptString();+ // what to do about a non-match (non-terminated string?)+ // play it safe and index the rest of the data I guess...+ if (ret==MISMATCH) return MISMATCH;+ } else if (ch<0) {+ return MISMATCH;+ }+ }+ }+++ // read a string escaped by backslashes+ private int readScriptString() throws IOException {+ int quoteChar = next();+ if (quoteChar!='\'' && quoteChar!='"') return MISMATCH;+ while(true) {+ int ch = next();+ if (ch==quoteChar) return MATCH;+ else if (ch=='\\') {+ ch=next();+ } else if (ch<0) {+ return MISMATCH;+ } else if (ch=='<') {+ eatSSI();+ }+ }+ }+++ private int readName() throws IOException {+ int ch = read();+ if (!isFirstIdChar(ch)) return MISMATCH;+ ch = read();+ while(isIdChar(ch)) ch=read();+ if (ch!=-1) push(ch);+ return MATCH;+ }++ /***+ [10] AttValue ::= '"' ([^<&"] | Reference)* '"'+ | "'" ([^<&'] | Reference)* "'"++ need to also handle unquoted attributes, and attributes w/o values:+ <td id=msviGlobalToolbar height="22" nowrap align=left>++ ***/+ private int readAttr() throws IOException {+ int ch = read();+ if (!isFirstIdChar(ch)) return MISMATCH;+ ch = read();+ while(isIdChar(ch)) ch=read();+ if (isSpace(ch)) ch = nextSkipWS();++ // attributes may not have a value at all!+ // if (ch != '=') return MISMATCH;+ if (ch != '=') {+ push(ch);+ return MATCH;+ }++ int quoteChar = nextSkipWS();++ if (quoteChar=='"' || quoteChar=='\'') {+ // TODO: should I set a max size to try and find the other+ // quote? Otherwise, I may read to much to restore+ // the stream.+ while (true) {+ ch = next();+ if (ch<0) return MISMATCH;+ else if (ch==quoteChar) {+ return MATCH;+ //} else if (ch=='<') {+ // return MISMATCH;+ }+ }+ } else {+ // unquoted attribute+ while (true) {+ ch = next();+ if (ch<0) return MISMATCH;+ else if (isSpace(ch)) {+ push(ch);+ return MATCH;+ } else if (ch=='>') {+ push(ch);+ return MATCH;+ }+ }+ }++ }++ // This reads attributes and attempts to handle any+ // embedded server side includes that would otherwise+ // mess up the quote handling.+ // <a href="a/<!--#echo "path"-->">+ private int readAttr2() throws IOException {+ int ch = read();+ if (!isFirstIdChar(ch)) return MISMATCH;+ ch = read();+ while(isIdChar(ch)) ch=read();+ if (isSpace(ch)) ch = nextSkipWS();++ // attributes may not have a value at all!+ // if (ch != '=') return MISMATCH;+ if (ch != '=') {+ push(ch);+ return MATCH;+ }++ int quoteChar = nextSkipWS();++ if (quoteChar=='"' || quoteChar=='\'') {+ // TODO: should I set a max size to try and find the other+ // quote? Otherwise, I may read to much to restore+ // the stream.+ while (true) {+ ch = next();+ if (ch<0) return MISMATCH;+ else if (ch=='<') {+ eatSSI();+ }+ else if (ch==quoteChar) {+ return MATCH;+ //} else if (ch=='<') {+ // return MISMATCH;+ }+ }+ } else {+ // unquoted attribute+ while (true) {+ ch = next();+ if (ch<0) return MISMATCH;+ else if (isSpace(ch)) {+ push(ch);+ return MATCH;+ } else if (ch=='>') {+ push(ch);+ return MATCH;+ } else if (ch=='<') {+ eatSSI();+ }+ }+ }++ }++ // skip past server side include+ private int eatSSI() throws IOException {+ // at this point, only a "<" was read.+ // on a mismatch, push back the last char so that if it was+ // a quote that closes the attribute, it will be re-read and matched.+ int ch = next();+ if (ch!='!') {+ push(ch);+ return MISMATCH;+ }+ ch=next();+ if (ch!='-') {+ push(ch);+ return MISMATCH;+ }+ ch=next();+ if (ch!='-') {+ push(ch);+ return MISMATCH;+ }+ ch=next();+ if (ch!='#') {+ push(ch);+ return MISMATCH;+ }++ push('#'); push('-'); push('-');+ return readComment(false);+ }++ private int readProcessingInstruction() throws IOException {+ // "<?" has already been read++ while (true) {+ int ch = next();+ if (ch=='?' && peek()=='>') {+ next();+ return MATCH;+ } else if (ch==-1) {+ return MISMATCH;+ }+ }+ }+++ public int read() throws IOException {+ // TODO: Do we ever want to preserve CDATA sections?+ // where do we have to worry about them?+ // <![ CDATA [ unescaped markup ]]>++ while(true) {+ int ch = next();++ switch (ch) {+ case '&':+ saveState();+ ch = readEntity();+ if (ch>=0) return ch;+ if (ch==MISMATCH) {+ restoreState();+ return '&';+ }+ break;++ case '<':+ saveState();+ ch = next();+ int ret = MISMATCH;+ if (ch=='!') {+ ret = readBang(false);+ } else if (ch=='/') {+ ret = readName();+ if (ret==MATCH) {+ ch=nextSkipWS();+ ret= ch=='>' ? MATCH : MISMATCH;+ }+ } else if (isAlpha(ch)) {+ push(ch);+ ret = readTag();+ } else if (ch=='?') {+ ret = readProcessingInstruction();+ }++ // matched something to be discarded, so break+ // from this case and continue in the loop+ if (ret==MATCH) break;++ // didn't match any HTML constructs, so roll back+ // the stream state and just return '<'+ restoreState();+ return '<';++ default: return ch;+ }++ }+++ }++ public int read(char cbuf[], int off, int len) throws IOException {+ int i=0;+ for (i=0; i<len; i++) {+ int ch = read();+ if (ch==-1) break;+ cbuf[off++] = (char)ch;+ }+ if (i==0) {+ if (len==0) return 0;+ return -1;+ }+ return i;+ }++ public void close() throws IOException {+ in.close();+ }+++ private static final HashMap<String,Character> entityTable;+ static {+ entityTable = new HashMap<String,Character>();+ // entityName and entityVal generated from the python script+ // included in comments at the end of this file.+ final String[] entityName={ "zwnj","aring","gt","yen","ograve","Chi","delta","rang","sup","trade","Ntilde","xi","upsih","nbsp","Atilde","radic","otimes","aelig","oelig","equiv","ni","infin","Psi","auml","cup","Epsilon","otilde","lt","Icirc","Eacute","Lambda","sbquo","Prime","prime","psi","Kappa","rsaquo","Tau","uacute","ocirc","lrm","zwj","cedil","Alpha","not","amp","AElig","oslash","acute","lceil","alefsym","laquo","shy","loz","ge","Igrave","nu","Ograve","lsaquo","sube","euro","rarr","sdot","rdquo","Yacute","lfloor","lArr","Auml","Dagger","brvbar","Otilde","szlig","clubs","diams","agrave","Ocirc","Iota","Theta","Pi","zeta","Scaron","frac14","egrave","sub","iexcl","frac12","ordf","sum","prop","Uuml","ntilde","atilde","asymp","uml","prod","nsub","reg","rArr","Oslash","emsp","THORN","yuml","aacute","Mu","hArr","le","thinsp","dArr","ecirc","bdquo","Sigma","Aring","tilde","nabla","mdash","uarr","times","Ugrave","Eta","Agrave","chi","real","circ","eth","rceil","iuml","gamma","lambda","harr","Egrave","frac34","dagger","divide","Ouml","image","ndash","hellip","igrave","Yuml","ang","alpha","frasl","ETH","lowast","Nu","plusmn","bull","sup1","sup2","sup3","Aacute","cent","oline","Beta","perp","Delta","there4","pi","iota","empty","euml","notin","iacute","para","epsilon","weierp","OElig","uuml","larr","icirc","Upsilon","omicron","upsilon","copy","Iuml","Oacute","Xi","kappa","ccedil","Ucirc","cap","mu","scaron","lsquo","isin","Zeta","minus","deg","and","tau","pound","curren","int","ucirc","rfloor","ensp","crarr","ugrave","exist","cong","theta","oplus","permil","Acirc","piv","Euml","Phi","Iacute","quot","Uacute","Omicron","ne","iquest","eta","rsquo","yacute","Rho","darr","Ecirc","Omega","acirc","sim","phi","sigmaf","macr","thetasym","Ccedil","ordm","uArr","forall","beta","fnof","rho","micro","eacute","omega","middot","Gamma","rlm","lang","spades","supe","thorn","ouml","or","raquo","part","sect","ldquo","hearts","sigma","oacute"};+ final char[] entityVal={ 8204,229,62,165,242,935,948,9002,8835,8482,209,958,978,160,195,8730,8855,230,339,8801,8715,8734,936,228,8746,917,245,60,206,201,923,8218,8243,8242,968,922,8250,932,250,244,8206,8205,184,913,172,38,198,248,180,8968,8501,171,173,9674,8805,204,957,210,8249,8838,8364,8594,8901,8221,221,8970,8656,196,8225,166,213,223,9827,9830,224,212,921,920,928,950,352,188,232,8834,161,189,170,8721,8733,220,241,227,8776,168,8719,8836,174,8658,216,8195,222,255,225,924,8660,8804,8201,8659,234,8222,931,197,732,8711,8212,8593,215,217,919,192,967,8476,710,240,8969,239,947,955,8596,200,190,8224,247,214,8465,8211,8230,236,376,8736,945,8260,208,8727,925,177,8226,185,178,179,193,162,8254,914,8869,916,8756,960,953,8709,235,8713,237,182,949,8472,338,252,8592,238,933,959,965,169,207,211,926,954,231,219,8745,956,353,8216,8712,918,8722,176,8743,964,163,164,8747,251,8971,8194,8629,249,8707,8773,952,8853,8240,194,982,203,934,205,34,218,927,8800,191,951,8217,253,929,8595,202,937,226,8764,966,962,175,977,199,186,8657,8704,946,402,961,181,233,969,183,915,8207,9001,9824,8839,254,246,8744,187,8706,167,8220,9829,963,243};+ for (int i=0; i<entityName.length; i++) {+ entityTable.put(entityName[i], new Character(entityVal[i]));+ }+ // special-case nbsp to a simple space instead of 0xa0+ entityTable.put("nbsp",new Character(' '));+ }++}++/********************* htmlentity.py **********************+# a simple python script to generate an HTML entity table+# from text taken from http://www.w3.org/TR/REC-html40/sgml/entities.html++text="""+24 Character entity references in HTML 4++Contents++ 1. Introduction to character entity references+ 2. Character entity references for ISO 8859-1 characters+ 1. The list of characters+ 3. Character entity references for symbols, mathematical symbols, and Greek letters+ 1. The list of characters+ 4. Character entity references for markup-significant and internationalization characters+ 1. The list of characters++24.1 Introduction to character entity references+A character entity reference is an SGML construct that references a character of the document character set.++This version of HTML supports several sets of character entity references:++ * ISO 8859-1 (Latin-1) characters In accordance with section 14 of [RFC1866], the set of Latin-1 entities has been extended by this specification to cover the whole right part of ISO-8859-1 (all code positions with the high-order bit set), including the already commonly used , © and ®. The names of the entities are taken from the appendices of SGML (defined in [ISO8879]).+ * symbols, mathematical symbols, and Greek letters. These characters may be represented by glyphs in the Adobe font "Symbol".+ * markup-significant and internationalization characters (e.g., for bidirectional text).++The following sections present the complete lists of character entity references. Although, by convention, [ISO10646] the comments following each entry are usually written with uppercase letters, we have converted them to lowercase in this specification for reasons of readability.+24.2 Character entity references for ISO 8859-1 characters++The character entity references in this section produce characters whose numeric equivalents should already be supported by conforming HTML 2.0 user agents. Thus, the character entity reference ÷ is a more convenient form than ÷ for obtaining the division sign (�).++To support these named entities, user agents need only recognize the entity names and convert them to characters that lie within the repertoire of [ISO88591].++Character 65533 (FFFD hexadecimal) is the last valid character in UCS-2. 65534 (FFFE hexadecimal) is unassigned and reserved as the byte-swapped version of ZERO WIDTH NON-BREAKING SPACE for byte-order detection purposes. 65535 (FFFF hexadecimal) is unassigned.+24.2.1 The list of characters++<!-- Portions � International Organization for Standardization 1986+ Permission to copy in any form is granted for use with+ conforming SGML systems and applications as defined in+ ISO 8879, provided this notice is included in all copies.+-->+<!-- Character entity set. Typical invocation:+ <!ENTITY % HTMLlat1 PUBLIC+ "-//W3C//ENTITIES Latin 1//EN//HTML">+ %HTMLlat1;+-->++<!ENTITY nbsp CDATA " " -- no-break space = non-breaking space,+ U+00A0 ISOnum -->+<!ENTITY iexcl CDATA "¡" -- inverted exclamation mark, U+00A1 ISOnum -->+<!ENTITY cent CDATA "¢" -- cent sign, U+00A2 ISOnum -->+<!ENTITY pound CDATA "£" -- pound sign, U+00A3 ISOnum -->+<!ENTITY curren CDATA "¤" -- currency sign, U+00A4 ISOnum -->+<!ENTITY yen CDATA "¥" -- yen sign = yuan sign, U+00A5 ISOnum -->+<!ENTITY brvbar CDATA "¦" -- broken bar = broken vertical bar,+ U+00A6 ISOnum -->+<!ENTITY sect CDATA "§" -- section sign, U+00A7 ISOnum -->+<!ENTITY uml CDATA "¨" -- diaeresis = spacing diaeresis,+ U+00A8 ISOdia -->+<!ENTITY copy CDATA "©" -- copyright sign, U+00A9 ISOnum -->+<!ENTITY ordf CDATA "ª" -- feminine ordinal indicator, U+00AA ISOnum -->+<!ENTITY laquo CDATA "«" -- left-pointing double angle quotation mark+ = left pointing guillemet, U+00AB ISOnum -->+<!ENTITY not CDATA "¬" -- not sign, U+00AC ISOnum -->+<!ENTITY shy CDATA "­" -- soft hyphen = discretionary hyphen,+ U+00AD ISOnum -->+<!ENTITY reg CDATA "®" -- registered sign = registered trade mark sign,+ U+00AE ISOnum -->+<!ENTITY macr CDATA "¯" -- macron = spacing macron = overline+ = APL overbar, U+00AF ISOdia -->+<!ENTITY deg CDATA "°" -- degree sign, U+00B0 ISOnum -->+<!ENTITY plusmn CDATA "±" -- plus-minus sign = plus-or-minus sign,+ U+00B1 ISOnum -->+<!ENTITY sup2 CDATA "²" -- superscript two = superscript digit two+ = squared, U+00B2 ISOnum -->+<!ENTITY sup3 CDATA "³" -- superscript three = superscript digit three+ = cubed, U+00B3 ISOnum -->+<!ENTITY acute CDATA "´" -- acute accent = spacing acute,+ U+00B4 ISOdia -->+<!ENTITY micro CDATA "µ" -- micro sign, U+00B5 ISOnum -->+<!ENTITY para CDATA "¶" -- pilcrow sign = paragraph sign,+ U+00B6 ISOnum -->+<!ENTITY middot CDATA "·" -- middle dot = Georgian comma+ = Greek middle dot, U+00B7 ISOnum -->+<!ENTITY cedil CDATA "¸" -- cedilla = spacing cedilla, U+00B8 ISOdia -->+<!ENTITY sup1 CDATA "¹" -- superscript one = superscript digit one,+ U+00B9 ISOnum -->+<!ENTITY ordm CDATA "º" -- masculine ordinal indicator,+ U+00BA ISOnum -->+<!ENTITY raquo CDATA "»" -- right-pointing double angle quotation mark+ = right pointing guillemet, U+00BB ISOnum -->+<!ENTITY frac14 CDATA "¼" -- vulgar fraction one quarter+ = fraction one quarter, U+00BC ISOnum -->+<!ENTITY frac12 CDATA "½" -- vulgar fraction one half+ = fraction one half, U+00BD ISOnum -->+<!ENTITY frac34 CDATA "¾" -- vulgar fraction three quarters+ = fraction three quarters, U+00BE ISOnum -->+<!ENTITY iquest CDATA "¿" -- inverted question mark+ = turned question mark, U+00BF ISOnum -->+<!ENTITY Agrave CDATA "À" -- latin capital letter A with grave+ = latin capital letter A grave,+ U+00C0 ISOlat1 -->+<!ENTITY Aacute CDATA "Á" -- latin capital letter A with acute,+ U+00C1 ISOlat1 -->+<!ENTITY Acirc CDATA "Â" -- latin capital letter A with circumflex,+ U+00C2 ISOlat1 -->+<!ENTITY Atilde CDATA "Ã" -- latin capital letter A with tilde,+ U+00C3 ISOlat1 -->+<!ENTITY Auml CDATA "Ä" -- latin capital letter A with diaeresis,+ U+00C4 ISOlat1 -->+<!ENTITY Aring CDATA "Å" -- latin capital letter A with ring above+ = latin capital letter A ring,+ U+00C5 ISOlat1 -->+<!ENTITY AElig CDATA "Æ" -- latin capital letter AE+ = latin capital ligature AE,+ U+00C6 ISOlat1 -->+<!ENTITY Ccedil CDATA "Ç" -- latin capital letter C with cedilla,+ U+00C7 ISOlat1 -->+<!ENTITY Egrave CDATA "È" -- latin capital letter E with grave,+ U+00C8 ISOlat1 -->+<!ENTITY Eacute CDATA "É" -- latin capital letter E with acute,+ U+00C9 ISOlat1 -->+<!ENTITY Ecirc CDATA "Ê" -- latin capital letter E with circumflex,+ U+00CA ISOlat1 -->+<!ENTITY Euml CDATA "Ë" -- latin capital letter E with diaeresis,+ U+00CB ISOlat1 -->+<!ENTITY Igrave CDATA "Ì" -- latin capital letter I with grave,+ U+00CC ISOlat1 -->+<!ENTITY Iacute CDATA "Í" -- latin capital letter I with acute,+ U+00CD ISOlat1 -->+<!ENTITY Icirc CDATA "Î" -- latin capital letter I with circumflex,+ U+00CE ISOlat1 -->+<!ENTITY Iuml CDATA "Ï" -- latin capital letter I with diaeresis,+ U+00CF ISOlat1 -->+<!ENTITY ETH CDATA "Ð" -- latin capital letter ETH, U+00D0 ISOlat1 -->+<!ENTITY Ntilde CDATA "Ñ" -- latin capital letter N with tilde,+ U+00D1 ISOlat1 -->+<!ENTITY Ograve CDATA "Ò" -- latin capital letter O with grave,+ U+00D2 ISOlat1 -->+<!ENTITY Oacute CDATA "Ó" -- latin capital letter O with acute,+ U+00D3 ISOlat1 -->+<!ENTITY Ocirc CDATA "Ô" -- latin capital letter O with circumflex,+ U+00D4 ISOlat1 -->+<!ENTITY Otilde CDATA "Õ" -- latin capital letter O with tilde,+ U+00D5 ISOlat1 -->+<!ENTITY Ouml CDATA "Ö" -- latin capital letter O with diaeresis,+ U+00D6 ISOlat1 -->+<!ENTITY times CDATA "×" -- multiplication sign, U+00D7 ISOnum -->+<!ENTITY Oslash CDATA "Ø" -- latin capital letter O with stroke+ = latin capital letter O slash,+ U+00D8 ISOlat1 -->+<!ENTITY Ugrave CDATA "Ù" -- latin capital letter U with grave,+ U+00D9 ISOlat1 -->+<!ENTITY Uacute CDATA "Ú" -- latin capital letter U with acute,+ U+00DA ISOlat1 -->+<!ENTITY Ucirc CDATA "Û" -- latin capital letter U with circumflex,+ U+00DB ISOlat1 -->+<!ENTITY Uuml CDATA "Ü" -- latin capital letter U with diaeresis,+ U+00DC ISOlat1 -->+<!ENTITY Yacute CDATA "Ý" -- latin capital letter Y with acute,+ U+00DD ISOlat1 -->+<!ENTITY THORN CDATA "Þ" -- latin capital letter THORN,+ U+00DE ISOlat1 -->+<!ENTITY szlig CDATA "ß" -- latin small letter sharp s = ess-zed,+ U+00DF ISOlat1 -->+<!ENTITY agrave CDATA "à" -- latin small letter a with grave+ = latin small letter a grave,+ U+00E0 ISOlat1 -->+<!ENTITY aacute CDATA "á" -- latin small letter a with acute,+ U+00E1 ISOlat1 -->+<!ENTITY acirc CDATA "â" -- latin small letter a with circumflex,+ U+00E2 ISOlat1 -->+<!ENTITY atilde CDATA "ã" -- latin small letter a with tilde,+ U+00E3 ISOlat1 -->+<!ENTITY auml CDATA "ä" -- latin small letter a with diaeresis,+ U+00E4 ISOlat1 -->+<!ENTITY aring CDATA "å" -- latin small letter a with ring above+ = latin small letter a ring,+ U+00E5 ISOlat1 -->+<!ENTITY aelig CDATA "æ" -- latin small letter ae+ = latin small ligature ae, U+00E6 ISOlat1 -->+<!ENTITY ccedil CDATA "ç" -- latin small letter c with cedilla,+ U+00E7 ISOlat1 -->+<!ENTITY egrave CDATA "è" -- latin small letter e with grave,+ U+00E8 ISOlat1 -->+<!ENTITY eacute CDATA "é" -- latin small letter e with acute,+ U+00E9 ISOlat1 -->+<!ENTITY ecirc CDATA "ê" -- latin small letter e with circumflex,+ U+00EA ISOlat1 -->+<!ENTITY euml CDATA "ë" -- latin small letter e with diaeresis,+ U+00EB ISOlat1 -->+<!ENTITY igrave CDATA "ì" -- latin small letter i with grave,+ U+00EC ISOlat1 -->+<!ENTITY iacute CDATA "í" -- latin small letter i with acute,+ U+00ED ISOlat1 -->+<!ENTITY icirc CDATA "î" -- latin small letter i with circumflex,+ U+00EE ISOlat1 -->+<!ENTITY iuml CDATA "ï" -- latin small letter i with diaeresis,+ U+00EF ISOlat1 -->+<!ENTITY eth CDATA "ð" -- latin small letter eth, U+00F0 ISOlat1 -->+<!ENTITY ntilde CDATA "ñ" -- latin small letter n with tilde,+ U+00F1 ISOlat1 -->+<!ENTITY ograve CDATA "ò" -- latin small letter o with grave,+ U+00F2 ISOlat1 -->+<!ENTITY oacute CDATA "ó" -- latin small letter o with acute,+ U+00F3 ISOlat1 -->+<!ENTITY ocirc CDATA "ô" -- latin small letter o with circumflex,+ U+00F4 ISOlat1 -->+<!ENTITY otilde CDATA "õ" -- latin small letter o with tilde,+ U+00F5 ISOlat1 -->+<!ENTITY ouml CDATA "ö" -- latin small letter o with diaeresis,+ U+00F6 ISOlat1 -->+<!ENTITY divide CDATA "÷" -- division sign, U+00F7 ISOnum -->+<!ENTITY oslash CDATA "ø" -- latin small letter o with stroke,+ = latin small letter o slash,+ U+00F8 ISOlat1 -->+<!ENTITY ugrave CDATA "ù" -- latin small letter u with grave,+ U+00F9 ISOlat1 -->+<!ENTITY uacute CDATA "ú" -- latin small letter u with acute,+ U+00FA ISOlat1 -->+<!ENTITY ucirc CDATA "û" -- latin small letter u with circumflex,+ U+00FB ISOlat1 -->+<!ENTITY uuml CDATA "ü" -- latin small letter u with diaeresis,+ U+00FC ISOlat1 -->+<!ENTITY yacute CDATA "ý" -- latin small letter y with acute,+ U+00FD ISOlat1 -->+<!ENTITY thorn CDATA "þ" -- latin small letter thorn,+ U+00FE ISOlat1 -->+<!ENTITY yuml CDATA "ÿ" -- latin small letter y with diaeresis,+ U+00FF ISOlat1 -->++24.3 Character entity references for symbols, mathematical symbols, and Greek letters++The character entity references in this section produce characters that may be represented by glyphs in the widely available Adobe Symbol font, including Greek characters, various bracketing symbols, and a selection of mathematical operators such as gradient, product, and summation symbols.++To support these entities, user agents may support full [ISO10646] or use other means. Display of glyphs for these characters may be obtained by being able to display the relevant [ISO10646] characters or by other means, such as internally mapping the listed entities, numeric character references, and characters to the appropriate position in some font that contains the requisite glyphs.++When to use Greek entities. This entity set contains all the letters used in modern Greek. However, it does not include Greek punctuation, precomposed accented characters nor the non-spacing accents (tonos, dialytika) required to compose them. There are no archaic letters, Coptic-unique letters, or precomposed letters for Polytonic Greek. The entities defined here are not intended for the representation of modern Greek text and would not be an efficient representation; rather, they are intended for occasional Greek letters used in technical and mathematical works.+24.3.1 The list of characters++<!-- Mathematical, Greek and Symbolic characters for HTML -->++<!-- Character entity set. Typical invocation:+ <!ENTITY % HTMLsymbol PUBLIC+ "-//W3C//ENTITIES Symbols//EN//HTML">+ %HTMLsymbol; -->++<!-- Portions � International Organization for Standardization 1986:+ Permission to copy in any form is granted for use with+ conforming SGML systems and applications as defined in+ ISO 8879, provided this notice is included in all copies.+-->++<!-- Relevant ISO entity set is given unless names are newly introduced.+ New names (i.e., not in ISO 8879 list) do not clash with any+ existing ISO 8879 entity names. ISO 10646 character numbers+ are given for each character, in hex. CDATA values are decimal+ conversions of the ISO 10646 values and refer to the document+ character set. Names are ISO 10646 names.++-->++<!-- Latin Extended-B -->+<!ENTITY fnof CDATA "ƒ" -- latin small f with hook = function+ = florin, U+0192 ISOtech -->++<!-- Greek -->+<!ENTITY Alpha CDATA "Α" -- greek capital letter alpha, U+0391 -->+<!ENTITY Beta CDATA "Β" -- greek capital letter beta, U+0392 -->+<!ENTITY Gamma CDATA "Γ" -- greek capital letter gamma,+ U+0393 ISOgrk3 -->+<!ENTITY Delta CDATA "Δ" -- greek capital letter delta,+ U+0394 ISOgrk3 -->+<!ENTITY Epsilon CDATA "Ε" -- greek capital letter epsilon, U+0395 -->+<!ENTITY Zeta CDATA "Ζ" -- greek capital letter zeta, U+0396 -->+<!ENTITY Eta CDATA "Η" -- greek capital letter eta, U+0397 -->+<!ENTITY Theta CDATA "Θ" -- greek capital letter theta,+ U+0398 ISOgrk3 -->+<!ENTITY Iota CDATA "Ι" -- greek capital letter iota, U+0399 -->+<!ENTITY Kappa CDATA "Κ" -- greek capital letter kappa, U+039A -->+<!ENTITY Lambda CDATA "Λ" -- greek capital letter lambda,+ U+039B ISOgrk3 -->+<!ENTITY Mu CDATA "Μ" -- greek capital letter mu, U+039C -->+<!ENTITY Nu CDATA "Ν" -- greek capital letter nu, U+039D -->+<!ENTITY Xi CDATA "Ξ" -- greek capital letter xi, U+039E ISOgrk3 -->+<!ENTITY Omicron CDATA "Ο" -- greek capital letter omicron, U+039F -->+<!ENTITY Pi CDATA "Π" -- greek capital letter pi, U+03A0 ISOgrk3 -->+<!ENTITY Rho CDATA "Ρ" -- greek capital letter rho, U+03A1 -->+<!-- there is no Sigmaf, and no U+03A2 character either -->+<!ENTITY Sigma CDATA "Σ" -- greek capital letter sigma,+ U+03A3 ISOgrk3 -->+<!ENTITY Tau CDATA "Τ" -- greek capital letter tau, U+03A4 -->+<!ENTITY Upsilon CDATA "Υ" -- greek capital letter upsilon,+ U+03A5 ISOgrk3 -->+<!ENTITY Phi CDATA "Φ" -- greek capital letter phi,+ U+03A6 ISOgrk3 -->+<!ENTITY Chi CDATA "Χ" -- greek capital letter chi, U+03A7 -->+<!ENTITY Psi CDATA "Ψ" -- greek capital letter psi,+ U+03A8 ISOgrk3 -->+<!ENTITY Omega CDATA "Ω" -- greek capital letter omega,+ U+03A9 ISOgrk3 -->++<!ENTITY alpha CDATA "α" -- greek small letter alpha,+ U+03B1 ISOgrk3 -->+<!ENTITY beta CDATA "β" -- greek small letter beta, U+03B2 ISOgrk3 -->+<!ENTITY gamma CDATA "γ" -- greek small letter gamma,+ U+03B3 ISOgrk3 -->+<!ENTITY delta CDATA "δ" -- greek small letter delta,+ U+03B4 ISOgrk3 -->+<!ENTITY epsilon CDATA "ε" -- greek small letter epsilon,+ U+03B5 ISOgrk3 -->+<!ENTITY zeta CDATA "ζ" -- greek small letter zeta, U+03B6 ISOgrk3 -->+<!ENTITY eta CDATA "η" -- greek small letter eta, U+03B7 ISOgrk3 -->+<!ENTITY theta CDATA "θ" -- greek small letter theta,+ U+03B8 ISOgrk3 -->+<!ENTITY iota CDATA "ι" -- greek small letter iota, U+03B9 ISOgrk3 -->+<!ENTITY kappa CDATA "κ" -- greek small letter kappa,+ U+03BA ISOgrk3 -->+<!ENTITY lambda CDATA "λ" -- greek small letter lambda,+ U+03BB ISOgrk3 -->+<!ENTITY mu CDATA "μ" -- greek small letter mu, U+03BC ISOgrk3 -->+<!ENTITY nu CDATA "ν" -- greek small letter nu, U+03BD ISOgrk3 -->+<!ENTITY xi CDATA "ξ" -- greek small letter xi, U+03BE ISOgrk3 -->+<!ENTITY omicron CDATA "ο" -- greek small letter omicron, U+03BF NEW -->+<!ENTITY pi CDATA "π" -- greek small letter pi, U+03C0 ISOgrk3 -->+<!ENTITY rho CDATA "ρ" -- greek small letter rho, U+03C1 ISOgrk3 -->+<!ENTITY sigmaf CDATA "ς" -- greek small letter final sigma,+ U+03C2 ISOgrk3 -->+<!ENTITY sigma CDATA "σ" -- greek small letter sigma,+ U+03C3 ISOgrk3 -->+<!ENTITY tau CDATA "τ" -- greek small letter tau, U+03C4 ISOgrk3 -->+<!ENTITY upsilon CDATA "υ" -- greek small letter upsilon,+ U+03C5 ISOgrk3 -->+<!ENTITY phi CDATA "φ" -- greek small letter phi, U+03C6 ISOgrk3 -->+<!ENTITY chi CDATA "χ" -- greek small letter chi, U+03C7 ISOgrk3 -->+<!ENTITY psi CDATA "ψ" -- greek small letter psi, U+03C8 ISOgrk3 -->+<!ENTITY omega CDATA "ω" -- greek small letter omega,+ U+03C9 ISOgrk3 -->+<!ENTITY thetasym CDATA "ϑ" -- greek small letter theta symbol,+ U+03D1 NEW -->+<!ENTITY upsih CDATA "ϒ" -- greek upsilon with hook symbol,+ U+03D2 NEW -->+<!ENTITY piv CDATA "ϖ" -- greek pi symbol, U+03D6 ISOgrk3 -->++<!-- General Punctuation -->+<!ENTITY bull CDATA "•" -- bullet = black small circle,+ U+2022 ISOpub -->+<!-- bullet is NOT the same as bullet operator, U+2219 -->+<!ENTITY hellip CDATA "…" -- horizontal ellipsis = three dot leader,+ U+2026 ISOpub -->+<!ENTITY prime CDATA "′" -- prime = minutes = feet, U+2032 ISOtech -->+<!ENTITY Prime CDATA "″" -- double prime = seconds = inches,+ U+2033 ISOtech -->+<!ENTITY oline CDATA "‾" -- overline = spacing overscore,+ U+203E NEW -->+<!ENTITY frasl CDATA "⁄" -- fraction slash, U+2044 NEW -->++<!-- Letterlike Symbols -->+<!ENTITY weierp CDATA "℘" -- script capital P = power set+ = Weierstrass p, U+2118 ISOamso -->+<!ENTITY image CDATA "ℑ" -- blackletter capital I = imaginary part,+ U+2111 ISOamso -->+<!ENTITY real CDATA "ℜ" -- blackletter capital R = real part symbol,+ U+211C ISOamso -->+<!ENTITY trade CDATA "™" -- trade mark sign, U+2122 ISOnum -->+<!ENTITY alefsym CDATA "ℵ" -- alef symbol = first transfinite cardinal,+ U+2135 NEW -->+<!-- alef symbol is NOT the same as hebrew letter alef,+ U+05D0 although the same glyph could be used to depict both characters -->++<!-- Arrows -->+<!ENTITY larr CDATA "←" -- leftwards arrow, U+2190 ISOnum -->+<!ENTITY uarr CDATA "↑" -- upwards arrow, U+2191 ISOnum-->+<!ENTITY rarr CDATA "→" -- rightwards arrow, U+2192 ISOnum -->+<!ENTITY darr CDATA "↓" -- downwards arrow, U+2193 ISOnum -->+<!ENTITY harr CDATA "↔" -- left right arrow, U+2194 ISOamsa -->+<!ENTITY crarr CDATA "↵" -- downwards arrow with corner leftwards+ = carriage return, U+21B5 NEW -->+<!ENTITY lArr CDATA "⇐" -- leftwards double arrow, U+21D0 ISOtech -->+<!-- ISO 10646 does not say that lArr is the same as the 'is implied by' arrow+ but also does not have any other character for that function. So ? lArr can+ be used for 'is implied by' as ISOtech suggests -->+<!ENTITY uArr CDATA "⇑" -- upwards double arrow, U+21D1 ISOamsa -->+<!ENTITY rArr CDATA "⇒" -- rightwards double arrow,+ U+21D2 ISOtech -->+<!-- ISO 10646 does not say this is the 'implies' character but does not have+ another character with this function so ?+ rArr can be used for 'implies' as ISOtech suggests -->+<!ENTITY dArr CDATA "⇓" -- downwards double arrow, U+21D3 ISOamsa -->+<!ENTITY hArr CDATA "⇔" -- left right double arrow,+ U+21D4 ISOamsa -->++<!-- Mathematical Operators -->+<!ENTITY forall CDATA "∀" -- for all, U+2200 ISOtech -->+<!ENTITY part CDATA "∂" -- partial differential, U+2202 ISOtech -->+<!ENTITY exist CDATA "∃" -- there exists, U+2203 ISOtech -->+<!ENTITY empty CDATA "∅" -- empty set = null set = diameter,+ U+2205 ISOamso -->+<!ENTITY nabla CDATA "∇" -- nabla = backward difference,+ U+2207 ISOtech -->+<!ENTITY isin CDATA "∈" -- element of, U+2208 ISOtech -->+<!ENTITY notin CDATA "∉" -- not an element of, U+2209 ISOtech -->+<!ENTITY ni CDATA "∋" -- contains as member, U+220B ISOtech -->+<!-- should there be a more memorable name than 'ni'? -->+<!ENTITY prod CDATA "∏" -- n-ary product = product sign,+ U+220F ISOamsb -->+<!-- prod is NOT the same character as U+03A0 'greek capital letter pi' though+ the same glyph might be used for both -->+<!ENTITY sum CDATA "∑" -- n-ary sumation, U+2211 ISOamsb -->+<!-- sum is NOT the same character as U+03A3 'greek capital letter sigma'+ though the same glyph might be used for both -->+<!ENTITY minus CDATA "−" -- minus sign, U+2212 ISOtech -->+<!ENTITY lowast CDATA "∗" -- asterisk operator, U+2217 ISOtech -->+<!ENTITY radic CDATA "√" -- square root = radical sign,+ U+221A ISOtech -->+<!ENTITY prop CDATA "∝" -- proportional to, U+221D ISOtech -->+<!ENTITY infin CDATA "∞" -- infinity, U+221E ISOtech -->+<!ENTITY ang CDATA "∠" -- angle, U+2220 ISOamso -->+<!ENTITY and CDATA "∧" -- logical and = wedge, U+2227 ISOtech -->+<!ENTITY or CDATA "∨" -- logical or = vee, U+2228 ISOtech -->+<!ENTITY cap CDATA "∩" -- intersection = cap, U+2229 ISOtech -->+<!ENTITY cup CDATA "∪" -- union = cup, U+222A ISOtech -->+<!ENTITY int CDATA "∫" -- integral, U+222B ISOtech -->+<!ENTITY there4 CDATA "∴" -- therefore, U+2234 ISOtech -->+<!ENTITY sim CDATA "∼" -- tilde operator = varies with = similar to,+ U+223C ISOtech -->+<!-- tilde operator is NOT the same character as the tilde, U+007E,+ although the same glyph might be used to represent both -->+<!ENTITY cong CDATA "≅" -- approximately equal to, U+2245 ISOtech -->+<!ENTITY asymp CDATA "≈" -- almost equal to = asymptotic to,+ U+2248 ISOamsr -->+<!ENTITY ne CDATA "≠" -- not equal to, U+2260 ISOtech -->+<!ENTITY equiv CDATA "≡" -- identical to, U+2261 ISOtech -->+<!ENTITY le CDATA "≤" -- less-than or equal to, U+2264 ISOtech -->+<!ENTITY ge CDATA "≥" -- greater-than or equal to,+ U+2265 ISOtech -->+<!ENTITY sub CDATA "⊂" -- subset of, U+2282 ISOtech -->+<!ENTITY sup CDATA "⊃" -- superset of, U+2283 ISOtech -->+<!-- note that nsup, 'not a superset of, U+2283' is not covered by the Symbol+ font encoding and is not included. Should it be, for symmetry?+ It is in ISOamsn -->+<!ENTITY nsub CDATA "⊄" -- not a subset of, U+2284 ISOamsn -->+<!ENTITY sube CDATA "⊆" -- subset of or equal to, U+2286 ISOtech -->+<!ENTITY supe CDATA "⊇" -- superset of or equal to,+ U+2287 ISOtech -->+<!ENTITY oplus CDATA "⊕" -- circled plus = direct sum,+ U+2295 ISOamsb -->+<!ENTITY otimes CDATA "⊗" -- circled times = vector product,+ U+2297 ISOamsb -->+<!ENTITY perp CDATA "⊥" -- up tack = orthogonal to = perpendicular,+ U+22A5 ISOtech -->+<!ENTITY sdot CDATA "⋅" -- dot operator, U+22C5 ISOamsb -->+<!-- dot operator is NOT the same character as U+00B7 middle dot -->++<!-- Miscellaneous Technical -->+<!ENTITY lceil CDATA "⌈" -- left ceiling = apl upstile,+ U+2308 ISOamsc -->+<!ENTITY rceil CDATA "⌉" -- right ceiling, U+2309 ISOamsc -->+<!ENTITY lfloor CDATA "⌊" -- left floor = apl downstile,+ U+230A ISOamsc -->+<!ENTITY rfloor CDATA "⌋" -- right floor, U+230B ISOamsc -->+<!ENTITY lang CDATA "〈" -- left-pointing angle bracket = bra,+ U+2329 ISOtech -->+<!-- lang is NOT the same character as U+003C 'less than'+ or U+2039 'single left-pointing angle quotation mark' -->+<!ENTITY rang CDATA "〉" -- right-pointing angle bracket = ket,+ U+232A ISOtech -->+<!-- rang is NOT the same character as U+003E 'greater than'+ or U+203A 'single right-pointing angle quotation mark' -->++<!-- Geometric Shapes -->+<!ENTITY loz CDATA "◊" -- lozenge, U+25CA ISOpub -->++<!-- Miscellaneous Symbols -->+<!ENTITY spades CDATA "♠" -- black spade suit, U+2660 ISOpub -->+<!-- black here seems to mean filled as opposed to hollow -->+<!ENTITY clubs CDATA "♣" -- black club suit = shamrock,+ U+2663 ISOpub -->+<!ENTITY hearts CDATA "♥" -- black heart suit = valentine,+ U+2665 ISOpub -->+<!ENTITY diams CDATA "♦" -- black diamond suit, U+2666 ISOpub -->++24.4 Character entity references for markup-significant and internationalization characters++The character entity references in this section are for escaping markup-significant characters (these are the same as those in HTML 2.0 and 3.2), for denoting spaces and dashes. Other characters in this section apply to internationalization issues such as the disambiguation of bidirectional text (see the section on bidirectional text for details).++Entities have also been added for the remaining characters occurring in CP-1252 which do not occur in the HTMLlat1 or HTMLsymbol entity sets. These all occur in the 128 to 159 range within the CP-1252 charset. These entities permit the characters to be denoted in a platform-independent manner.++To support these entities, user agents may support full [ISO10646] or use other means. Display of glyphs for these characters may be obtained by being able to display the relevant [ISO10646] characters or by other means, such as internally mapping the listed entities, numeric character references, and characters to the appropriate position in some font that contains the requisite glyphs.+24.4.1 The list of characters++<!-- Special characters for HTML -->++<!-- Character entity set. Typical invocation:+ <!ENTITY % HTMLspecial PUBLIC+ "-//W3C//ENTITIES Special//EN//HTML">+ %HTMLspecial; -->++<!-- Portions � International Organization for Standardization 1986:+ Permission to copy in any form is granted for use with+ conforming SGML systems and applications as defined in+ ISO 8879, provided this notice is included in all copies.+-->++<!-- Relevant ISO entity set is given unless names are newly introduced.+ New names (i.e., not in ISO 8879 list) do not clash with any+ existing ISO 8879 entity names. ISO 10646 character numbers+ are given for each character, in hex. CDATA values are decimal+ conversions of the ISO 10646 values and refer to the document+ character set. Names are ISO 10646 names.++-->++<!-- C0 Controls and Basic Latin -->+<!ENTITY quot CDATA """ -- quotation mark = APL quote,+ U+0022 ISOnum -->+<!ENTITY amp CDATA "&" -- ampersand, U+0026 ISOnum -->+<!ENTITY lt CDATA "<" -- less-than sign, U+003C ISOnum -->+<!ENTITY gt CDATA ">" -- greater-than sign, U+003E ISOnum -->++<!-- Latin Extended-A -->+<!ENTITY OElig CDATA "Œ" -- latin capital ligature OE,+ U+0152 ISOlat2 -->+<!ENTITY oelig CDATA "œ" -- latin small ligature oe, U+0153 ISOlat2 -->+<!-- ligature is a misnomer, this is a separate character in some languages -->+<!ENTITY Scaron CDATA "Š" -- latin capital letter S with caron,+ U+0160 ISOlat2 -->+<!ENTITY scaron CDATA "š" -- latin small letter s with caron,+ U+0161 ISOlat2 -->+<!ENTITY Yuml CDATA "Ÿ" -- latin capital letter Y with diaeresis,+ U+0178 ISOlat2 -->++<!-- Spacing Modifier Letters -->+<!ENTITY circ CDATA "ˆ" -- modifier letter circumflex accent,+ U+02C6 ISOpub -->+<!ENTITY tilde CDATA "˜" -- small tilde, U+02DC ISOdia -->++<!-- General Punctuation -->+<!ENTITY ensp CDATA " " -- en space, U+2002 ISOpub -->+<!ENTITY emsp CDATA " " -- em space, U+2003 ISOpub -->+<!ENTITY thinsp CDATA " " -- thin space, U+2009 ISOpub -->+<!ENTITY zwnj CDATA "‌" -- zero width non-joiner,+ U+200C NEW RFC 2070 -->+<!ENTITY zwj CDATA "‍" -- zero width joiner, U+200D NEW RFC 2070 -->+<!ENTITY lrm CDATA "‎" -- left-to-right mark, U+200E NEW RFC 2070 -->+<!ENTITY rlm CDATA "‏" -- right-to-left mark, U+200F NEW RFC 2070 -->+<!ENTITY ndash CDATA "–" -- en dash, U+2013 ISOpub -->+<!ENTITY mdash CDATA "—" -- em dash, U+2014 ISOpub -->+<!ENTITY lsquo CDATA "‘" -- left single quotation mark,+ U+2018 ISOnum -->+<!ENTITY rsquo CDATA "’" -- right single quotation mark,+ U+2019 ISOnum -->+<!ENTITY sbquo CDATA "‚" -- single low-9 quotation mark, U+201A NEW -->+<!ENTITY ldquo CDATA "“" -- left double quotation mark,+ U+201C ISOnum -->+<!ENTITY rdquo CDATA "”" -- right double quotation mark,+ U+201D ISOnum -->+<!ENTITY bdquo CDATA "„" -- double low-9 quotation mark, U+201E NEW -->+<!ENTITY dagger CDATA "†" -- dagger, U+2020 ISOpub -->+<!ENTITY Dagger CDATA "‡" -- double dagger, U+2021 ISOpub -->+<!ENTITY permil CDATA "‰" -- per mille sign, U+2030 ISOtech -->+<!ENTITY lsaquo CDATA "‹" -- single left-pointing angle quotation mark,+ U+2039 ISO proposed -->+<!-- lsaquo is proposed but not yet ISO standardized -->+<!ENTITY rsaquo CDATA "›" -- single right-pointing angle quotation mark,+ U+203A ISO proposed -->+<!-- rsaquo is proposed but not yet ISO standardized -->+<!ENTITY euro CDATA "€" -- euro sign, U+20AC NEW -->+"""++codes={}+for line in text.split('\n'):+ parts = line.split()+ if len(parts)<3 or parts[0]!='<!ENTITY' or parts[2]!='CDATA': continue+ codes[parts[1]] = parts[3].strip('&#";')++print 'entityName={', ','.join([ '"'+key+'"' for key in codes]), '};'+print 'entityVal={', ','.join([ str(codes[key]) for key in codes]), '};'+++********************** end htmlentity.py ********************/diff --git a/src/java/org/apache/solr/analysis/HTMLStripStandardTokenizerFactory.java b/src/java/org/apache/solr/analysis/HTMLStripStandardTokenizerFactory.javanew file mode 100644index 00000000000..72ef68c09f9--- /dev/null+++ b/src/java/org/apache/solr/analysis/HTMLStripStandardTokenizerFactory.java@@ -0,0 +1,32 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.standard.StandardTokenizer;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id$+ */+public class HTMLStripStandardTokenizerFactory extends BaseTokenizerFactory {+ public TokenStream create(Reader input) {+ return new StandardTokenizer(new HTMLStripReader(input));+ }+}diff --git a/src/java/org/apache/solr/analysis/HTMLStripWhitespaceTokenizerFactory.java b/src/java/org/apache/solr/analysis/HTMLStripWhitespaceTokenizerFactory.javanew file mode 100644index 00000000000..57fea2bdf66--- /dev/null+++ b/src/java/org/apache/solr/analysis/HTMLStripWhitespaceTokenizerFactory.java@@ -0,0 +1,32 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.WhitespaceTokenizer;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id$+ */+public class HTMLStripWhitespaceTokenizerFactory extends BaseTokenizerFactory {+ public TokenStream create(Reader input) {+ return new WhitespaceTokenizer(new HTMLStripReader(input));+ }+}diff --git a/src/java/org/apache/solr/analysis/LengthFilter.java b/src/java/org/apache/solr/analysis/LengthFilter.javanew file mode 100644index 00000000000..6d88a9d9156--- /dev/null+++ b/src/java/org/apache/solr/analysis/LengthFilter.java@@ -0,0 +1,47 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenFilter;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.Token;++import java.io.IOException;++/**+ * @author yonik+ * @version $Id: LengthFilter.java,v 1.2 2005/04/24 02:53:35 yonik Exp $+ */+public final class LengthFilter extends TokenFilter {+ final int min,max;++ public LengthFilter(TokenStream in, int min, int max) {+ super(in);+ this.min=min;+ this.max=max;+ //System.out.println("min="+min+" max="+max);+ }++ public final Token next() throws IOException {+ for (Token token=input.next(); token!=null; token=input.next()) {+ final int len = token.endOffset() - token.startOffset();+ if (len<min || len>max) continue;+ return token;+ }+ return null;+ }+}diff --git a/src/java/org/apache/solr/analysis/LengthFilterFactory.java b/src/java/org/apache/solr/analysis/LengthFilterFactory.javanew file mode 100644index 00000000000..40c1c9c9052--- /dev/null+++ b/src/java/org/apache/solr/analysis/LengthFilterFactory.java@@ -0,0 +1,38 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.LengthFilter;++import java.util.Map;++/**+ * @author yonik+ * @version $Id$+ */+public class LengthFilterFactory extends BaseTokenFilterFactory {+ int min,max;+ public void init(Map<String, String> args) {+ super.init(args);+ min=Integer.parseInt(args.get("min"));+ max=Integer.parseInt(args.get("max"));+ }+ public TokenStream create(TokenStream input) {+ return new LengthFilter(input,min,max);+ }+}diff --git a/src/java/org/apache/solr/analysis/LetterTokenizerFactory.java b/src/java/org/apache/solr/analysis/LetterTokenizerFactory.javanew file mode 100644index 00000000000..56d1742ba39--- /dev/null+++ b/src/java/org/apache/solr/analysis/LetterTokenizerFactory.java@@ -0,0 +1,32 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.LetterTokenizer;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id$+ */+public class LetterTokenizerFactory extends BaseTokenizerFactory {+ public TokenStream create(Reader input) {+ return new LetterTokenizer(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/LowerCaseFilterFactory.java b/src/java/org/apache/solr/analysis/LowerCaseFilterFactory.javanew file mode 100644index 00000000000..d8b9e93e2b5--- /dev/null+++ b/src/java/org/apache/solr/analysis/LowerCaseFilterFactory.java@@ -0,0 +1,30 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.LowerCaseFilter;++/**+ * @author yonik+ * @version $Id$+ */+public class LowerCaseFilterFactory extends BaseTokenFilterFactory {+ public TokenStream create(TokenStream input) {+ return new LowerCaseFilter(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/LowerCaseTokenizerFactory.java b/src/java/org/apache/solr/analysis/LowerCaseTokenizerFactory.javanew file mode 100644index 00000000000..ffbf3749165--- /dev/null+++ b/src/java/org/apache/solr/analysis/LowerCaseTokenizerFactory.java@@ -0,0 +1,32 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.LowerCaseTokenizer;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id$+ */+public class LowerCaseTokenizerFactory extends BaseTokenizerFactory {+ public TokenStream create(Reader input) {+ return new LowerCaseTokenizer(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/PorterStemFilterFactory.java b/src/java/org/apache/solr/analysis/PorterStemFilterFactory.javanew file mode 100644index 00000000000..0ecb4af46c7--- /dev/null+++ b/src/java/org/apache/solr/analysis/PorterStemFilterFactory.java@@ -0,0 +1,30 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.PorterStemFilter;++/**+ * @author yonik+ * @version $Id$+ */+public class PorterStemFilterFactory extends BaseTokenFilterFactory {+ public TokenStream create(TokenStream input) {+ return new PorterStemFilter(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/SnowballPorterFilterFactory.java b/src/java/org/apache/solr/analysis/SnowballPorterFilterFactory.javanew file mode 100644index 00000000000..c5ab0d5c32e--- /dev/null+++ b/src/java/org/apache/solr/analysis/SnowballPorterFilterFactory.java@@ -0,0 +1,34 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.snowball.SnowballFilter;++/**+ * @author yonik+ * @version $Id$+ */+public class SnowballPorterFilterFactory extends BaseTokenFilterFactory {+ public TokenStream create(TokenStream input) {+ // Browsing the code, SnowballFilter uses reflection to adapt to Lucene...+ // don't use this if you are concerned about speed. Use EnglishPorterFilterFactory.++ // TODO: make language configurable+ return new SnowballFilter(input,"English");+ }+}diff --git a/src/java/org/apache/solr/analysis/StandardFilterFactory.java b/src/java/org/apache/solr/analysis/StandardFilterFactory.javanew file mode 100644index 00000000000..7104996d76c--- /dev/null+++ b/src/java/org/apache/solr/analysis/StandardFilterFactory.java@@ -0,0 +1,30 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.standard.StandardFilter;++/**+ * @author yonik+ * @version $Id$+ */+public class StandardFilterFactory extends BaseTokenFilterFactory {+ public TokenStream create(TokenStream input) {+ return new StandardFilter(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/StandardTokenizerFactory.java b/src/java/org/apache/solr/analysis/StandardTokenizerFactory.javanew file mode 100644index 00000000000..624f4d36f09--- /dev/null+++ b/src/java/org/apache/solr/analysis/StandardTokenizerFactory.java@@ -0,0 +1,33 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.standard.StandardTokenizer;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id$+ */++public class StandardTokenizerFactory extends BaseTokenizerFactory {+ public TokenStream create(Reader input) {+ return new StandardTokenizer(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/StopFilterFactory.java b/src/java/org/apache/solr/analysis/StopFilterFactory.javanew file mode 100644index 00000000000..624ecae7c28--- /dev/null+++ b/src/java/org/apache/solr/analysis/StopFilterFactory.java@@ -0,0 +1,55 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.solr.core.Config;+import org.apache.lucene.analysis.StopFilter;+import org.apache.lucene.analysis.StopAnalyzer;+import org.apache.lucene.analysis.TokenStream;++import java.util.Map;+import java.util.List;+import java.util.Set;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id$+ */+public class StopFilterFactory extends BaseTokenFilterFactory {+ public void init(Map<String, String> args) {+ super.init(args);+ String stopWordFile = args.get("words");+ ignoreCase = getBoolean("ignoreCase",false);++ if (stopWordFile != null) {+ try {+ List<String> wlist = Config.getLines(stopWordFile);+ stopWords = StopFilter.makeStopSet((String[])wlist.toArray(new String[0]), ignoreCase);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ }++ private Set stopWords = StopFilter.makeStopSet(StopAnalyzer.ENGLISH_STOP_WORDS);+ private boolean ignoreCase;++ public TokenStream create(TokenStream input) {+ return new StopFilter(input,stopWords,ignoreCase);+ }+}diff --git a/src/java/org/apache/solr/analysis/SynonymFilterFactory.java b/src/java/org/apache/solr/analysis/SynonymFilterFactory.javanew file mode 100644index 00000000000..9aad95715d0--- /dev/null+++ b/src/java/org/apache/solr/analysis/SynonymFilterFactory.java@@ -0,0 +1,125 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.SynonymFilter;+import org.apache.lucene.analysis.SynonymMap;++import java.util.Map;+import java.util.ArrayList;+import java.util.List;+import java.io.IOException;++import org.apache.solr.util.StrUtils;+import org.apache.solr.analysis.BaseTokenFilterFactory;+import org.apache.solr.core.Config;+import org.apache.solr.core.SolrCore;+/**+ * @author yonik+ * @version $Id$+ */+public class SynonymFilterFactory extends BaseTokenFilterFactory {+ public void init(Map<String, String> args) {+ super.init(args);+ String synonyms = args.get("synonyms");++ ignoreCase = getBoolean("ignoreCase",false);+ expand = getBoolean("expand",true);++ if (synonyms != null) {+ List<String> wlist=null;+ try {+ wlist = Config.getLines(synonyms);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ synMap = new SynonymMap();+ parseRules(wlist, synMap, "=>", ",", ignoreCase,expand);+ if (wlist.size()<=20) {+ SolrCore.log.fine("SynonymMap "+synonyms +":"+synMap);+ }+ }++ }++ private SynonymMap synMap;+ private boolean ignoreCase;+ private boolean expand;++ private static void parseRules(List<String> rules, SynonymMap map, String mappingSep, String synSep, boolean ignoreCase, boolean expansion) {+ int count=0;+ for (String rule : rules) {+ // To use regexes, we need an expression that specifies an odd number of chars.+ // This can't really be done with string.split(), and since we need to+ // do unescaping at some point anyway, we wouldn't be saving any effort+ // by using regexes.++ List<String> mapping = StrUtils.splitSmart(rule, mappingSep, false);++ List<List<String>> source;+ List<List<String>> target;++ if (mapping.size() > 2) {+ throw new RuntimeException("Invalid Synonym Rule:" + rule);+ } else if (mapping.size()==2) {+ source = getSynList(mapping.get(0), synSep);+ target = getSynList(mapping.get(1), synSep);+ } else {+ source = getSynList(mapping.get(0), synSep);+ if (expansion) {+ // expand to all arguments+ target = source;+ } else {+ // reduce to first argument+ target = new ArrayList<List<String>>(1);+ target.add(source.get(0));+ }+ }++ boolean includeOrig=false;+ for (List<String> fromToks : source) {+ count++;+ for (List<String> toToks : target) {+ map.add(ignoreCase ? StrUtils.toLower(fromToks) : fromToks,+ SynonymMap.makeTokens(toToks),+ includeOrig,+ true);+ }+ }+ }+ }++ // a , b c , d e f => [[a],[b,c],[d,e,f]]+ private static List<List<String>> getSynList(String str, String separator) {+ List<String> strList = StrUtils.splitSmart(str, separator, false);+ // now split on whitespace to get a list of token strings+ List<List<String>> synList = new ArrayList<List<String>>();+ for (String toks : strList) {+ List<String> tokList = StrUtils.splitWS(toks, true);+ synList.add(tokList);+ }+ return synList;+ }+++ public TokenStream create(TokenStream input) {+ return new SynonymFilter(input,synMap,ignoreCase);+ }+++}diff --git a/src/java/org/apache/solr/analysis/TokenFilterFactory.java b/src/java/org/apache/solr/analysis/TokenFilterFactory.javanew file mode 100644index 00000000000..6b9d6baf089--- /dev/null+++ b/src/java/org/apache/solr/analysis/TokenFilterFactory.java@@ -0,0 +1,34 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;++import java.util.Map;++/**+ * Factory to create a token filter that transforms one TokenStream to another.+ *+ * @author yonik+ * @version $Id: TokenFilterFactory.java,v 1.3 2005/09/20 04:58:28 yonik Exp $+ */++public interface TokenFilterFactory {+ public void init(Map<String,String> args);+ public Map<String,String> getArgs();+ public TokenStream create(TokenStream input);+}diff --git a/src/java/org/apache/solr/analysis/TokenizerChain.java b/src/java/org/apache/solr/analysis/TokenizerChain.javanew file mode 100644index 00000000000..84b43a3a657--- /dev/null+++ b/src/java/org/apache/solr/analysis/TokenizerChain.java@@ -0,0 +1,65 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.TokenStream;+import org.apache.solr.analysis.TokenizerFactory;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id: TokenizerChain.java,v 1.3 2005/08/26 05:21:08 yonik Exp $+ */++//+// An analyzer that uses a tokenizer and a list of token filters to+// create a TokenStream.+//+public class TokenizerChain extends Analyzer {+ final private TokenizerFactory tokenizer;+ final private TokenFilterFactory[] filters;++ public TokenizerChain(TokenizerFactory tokenizer, TokenFilterFactory[] filters) {+ this.tokenizer = tokenizer;+ this.filters = filters;+ }++ public TokenizerFactory getTokenizerFactory() { return tokenizer; }+ public TokenFilterFactory[] getTokenFilterFactories() { return filters; }++ public TokenStream tokenStream(String fieldName, Reader reader) {+ TokenStream ts = tokenizer.create(reader);+ for (int i=0; i<filters.length; i++) {+ ts = filters[i].create(ts);+ }+ return ts;+ }++ public String toString() {+ StringBuilder sb = new StringBuilder("TokenizerChain(");+ sb.append(tokenizer);+ for (TokenFilterFactory filter: filters) {+ sb.append(", ");+ sb.append(filter);+ }+ sb.append(')');+ return sb.toString();+ }++}diff --git a/src/java/org/apache/solr/analysis/TokenizerFactory.java b/src/java/org/apache/solr/analysis/TokenizerFactory.javanew file mode 100644index 00000000000..45069b1e627--- /dev/null+++ b/src/java/org/apache/solr/analysis/TokenizerFactory.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import java.io.*;+import java.util.Map;++import org.apache.lucene.analysis.*;+++/**+ * A <code>TokenizerFactory</code> creates a <code>Tokenizer</code> on demand+ * that breaks up a stream of characters into tokens.+ *+ * @author yonik+ * @version $Id: TokenizerFactory.java,v 1.10 2005/12/13 05:16:03 yonik Exp $+ */+public interface TokenizerFactory {+ public void init(Map<String,String> args);+ public Map<String,String> getArgs();+ public TokenStream create(Reader input);+}+diff --git a/src/java/org/apache/solr/analysis/WhitespaceTokenizerFactory.java b/src/java/org/apache/solr/analysis/WhitespaceTokenizerFactory.javanew file mode 100644index 00000000000..e1a32e36d33--- /dev/null+++ b/src/java/org/apache/solr/analysis/WhitespaceTokenizerFactory.java@@ -0,0 +1,32 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.WhitespaceTokenizer;++import java.io.Reader;++/**+ * @author yonik+ * @version $Id$+ */+public class WhitespaceTokenizerFactory extends BaseTokenizerFactory {+ public TokenStream create(Reader input) {+ return new WhitespaceTokenizer(input);+ }+}diff --git a/src/java/org/apache/solr/analysis/WordDelimiterFilter.java b/src/java/org/apache/solr/analysis/WordDelimiterFilter.javanew file mode 100644index 00000000000..ea47c08595c--- /dev/null+++ b/src/java/org/apache/solr/analysis/WordDelimiterFilter.java@@ -0,0 +1,444 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenFilter;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.Token;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++/**+ * Splits words into subwords and performs optional transformations on subword groups.+ * Words are split into subwords with the following rules:+ * - split on intra-word delimiters (by default, all non alpha-numeric characters).+ * - "Wi-Fi" -> "Wi", "Fi"+ * - split on case transitions+ * - "PowerShot" -> "Power", "Shot"+ * - split on letter-number transitions+ * - "SD500" -> "SD", "500"+ * - leading and trailing intra-word delimiters on each subword are ignored+ * - "//hello---there, 'dude'" -> "hello", "there", "dude"+ * - trailing "'s" are removed for each subword+ * - "O'Neil's" -> "O", "Neil"+ * - Note: this step isn't performed in a separate filter because of possible subword combinations.+ *+ * The <b>combinations</b> parameter affects how subwords are combined:+ * - combinations="0" causes no subword combinations.+ * - "PowerShot" -> 0:"Power", 1:"Shot" (0 and 1 are the token positions)+ * - combinations="1" means that in addition to the subwords, maximum runs of non-numeric subwords are catenated and produced at the same position of the last subword in the run.+ * - "PowerShot" -> 0:"Power", 1:"Shot" 1:"PowerShot"+ * - "A's+B's&C's" -> 0:"A", 1:"B", 2:"C", 2:"ABC"+ * - "Super-Duper-XL500-42-AutoCoder!" -> 0:"Super", 1:"Duper", 2:"XL", 2:"SuperDuperXL", 3:"500" 4:"42", 5:"Auto", 6:"Coder", 6:"AutoCoder"+ *+ * One use for WordDelimiterFilter is to help match words with different subword delimiters.+ * For example, if the source text contained "wi-fi" one may want "wifi" "WiFi" "wi-fi" "wi+fi"+ * queries to all match.+ * One way of doing so is to specify combinations="1" in the analyzer+ * used for indexing, and combinations="0" (the default) in the analyzer+ * used for querying. Given that the current StandardTokenizer+ * immediately removes many intra-word delimiters, it is recommended that+ * this filter be used after a tokenizer that does not do this+ * (such as WhitespaceTokenizer).+ *+ * @author yonik+ * @version $Id: WordDelimiterFilter.java,v 1.6 2005/09/20 03:54:05 yonik Exp $+ */+final class WordDelimiterFilter extends TokenFilter {+ private final byte[] charTypeTable;++ public static final int LOWER=0x01;+ public static final int UPPER=0x02;+ public static final int DIGIT=0x04;+ public static final int SUBWORD_DELIM=0x08;++ // combinations: for testing, not for setting bits+ public static final int ALPHA=0x03;+ public static final int ALPHANUM=0x07;++ // TODO: should there be a WORD_DELIM category for+ // chars that only separate words (no catenation of subwords+ // will be done if separated by these chars?)+ // "," would be an obvious candidate...++ static byte[] defaultWordDelimTable;+ static {+ byte[] tab = new byte[256];+ for (int i=0; i<256; i++) {+ byte code = 0;+ if (Character.isLowerCase(i)) code |= LOWER;+ else if (Character.isUpperCase(i)) code |= UPPER;+ else if (Character.isDigit(i)) code |= DIGIT;+ if (code==0) code=SUBWORD_DELIM;+ tab[i]=code;+ }+ defaultWordDelimTable = tab;+ }++ final int generateWordParts;+ final int generateNumberParts;+ final int catenateWords;+ final int catenateNumbers;+ final int catenateAll;++ public WordDelimiterFilter(TokenStream in, byte[] charTypeTable, int generateWordParts, int generateNumberParts, int catenateWords, int catenateNumbers, int catenateAll) {+ super(in);+ this.generateWordParts = generateWordParts;+ this.generateNumberParts = generateNumberParts;+ this.catenateWords = catenateWords;+ this.catenateNumbers = catenateNumbers;+ this.catenateAll = catenateAll;+ this.charTypeTable = charTypeTable;+ }++ public WordDelimiterFilter(TokenStream in, int generateWordParts, int generateNumberParts, int catenateWords, int catenateNumbers, int catenateAll) {+ this(in, defaultWordDelimTable, generateWordParts, generateNumberParts, catenateWords, catenateNumbers, catenateAll);+ }++ int charType(int ch) {+ if (ch<charTypeTable.length) {+ return charTypeTable[ch];+ } else if (Character.isLowerCase(ch)) {+ return LOWER;+ } else if (Character.isLetter(ch)) {+ return UPPER;+ } else {+ return SUBWORD_DELIM;+ }+ }++ private int charType(String s, int pos) {+ return charType(s.charAt(pos));+ }++ // use the type of the first char as the type+ // of the token.+ private int tokType(Token t) {+ return charType(t.termText().charAt(0));+ }++ // There isn't really an efficient queue class, so we will+ // just use an array for now.+ private ArrayList<Token> queue = new ArrayList<Token>(4);+ private int queuePos=0;++ // temporary working queue+ private ArrayList<Token> tlist = new ArrayList<Token>(4);+++ private Token newTok(Token orig, int start, int end) {+ return new Token(orig.termText().substring(start,end),+ orig.startOffset() + start,+ orig.startOffset() + end,+ orig.type());+ }+++ public final Token next() throws IOException {++ // check the queue first+ if (queuePos<queue.size()) {+ return queue.get(queuePos++);+ }++ // reset the queue if it had been previously used+ if (queuePos!=0) {+ queuePos=0;+ queue.clear();+ }+++ // optimize for the common case: assume there will be+ // no subwords (just a simple word)+ //+ // Would it actually be faster to check for the common form+ // of isLetter() isLower()*, and then backtrack if it doesn't match?++ while(true) {+ Token t = input.next();+ if (t == null) return null;++ String s = t.termText();+ int off=t.startOffset();+ int start=0;+ int end=s.length();+ if (end==0) continue;++ // Avoid calling charType more than once for each char (basically+ // avoid any backtracking).+ // makes code slightly more difficult, but faster.+ int ch=s.charAt(start);+ int type=charType(ch);++ int numWords=0;++ while (start<end) {+ // first eat delimiters at the start of this subword+ while ((type & SUBWORD_DELIM)!=0 && ++start<end) {+ ch=s.charAt(start);+ type=charType(ch);+ }++ int pos=start;++ // save the type of the first char of the subword+ // as a way to tell what type of subword token this is (number, word, etc)+ int firstType=type;+ int lastType=type; // type of the previously read char+++ while (pos<end) {++ if (type!=lastType) {+ // check and remove "'s" from the end of a token.+ // the pattern to check for is+ // ALPHA "'" ("s"|"S") (SUBWORD_DELIM | END)+ if ((lastType & ALPHA)!=0) {+ if (ch=='\'' && pos+1<end+ && (s.charAt(pos+1)=='s' || s.charAt(pos+1)=='S'))+ {+ int subWordEnd=pos;+ if (pos+2>=end) {+ // end of string detected after "'s"+ pos+=2;+ } else {+ // make sure that a delimiter follows "'s"+ int ch2 = s.charAt(pos+2);+ int type2 = charType(ch2);+ if ((type2 & SUBWORD_DELIM)!=0) {+ // if delimiter, move position pointer+ // to it (skipping over "'s"+ ch=ch2;+ type=type2;+ pos+=2;+ }+ }++ queue.add(newTok(t,start,subWordEnd));+ if ((firstType & ALPHA)!=0) numWords++;+ break;+ }+ }++ // For case changes, only split on a transition from+ // lower to upper case, not vice-versa.+ // That will correctly handle the+ // case of a word starting with a capital (won't split).+ // It will also handle pluralization of+ // an uppercase word such as FOOs (won't split).++ if ((lastType & UPPER)!=0 && (type & LOWER)!=0) {+ // UPPER->LOWER: Don't split+ } else {+ // NOTE: this code currently assumes that only one flag+ // is set for each character now, so we don't have+ // to explicitly check for all the classes of transitions+ // listed below.++ // LOWER->UPPER+ // ALPHA->NUMERIC+ // NUMERIC->ALPHA+ // *->DELIMITER+ queue.add(newTok(t,start,pos));+ if ((firstType & ALPHA)!=0) numWords++;+ break;+ }+ }++ if (++pos >= end) {+ if (start==0) {+ // the subword is the whole original token, so+ // return it unchanged.+ return t;+ }++ Token newtok = newTok(t,start,pos);++ // optimization... if this is the only token,+ // return it immediately.+ if (queue.size()==0) {+ return newtok;+ }++ queue.add(newtok);+ if ((firstType & ALPHA)!=0) numWords++;+ break;+ }++ lastType = type;+ ch = s.charAt(pos);+ type = charType(ch);+ }++ // start of the next subword is the current position+ start=pos;+ }++ // System.out.println("##########TOKEN=" + s + " ######### WORD DELIMITER QUEUE=" + str(queue));++ final int numtok = queue.size();++ // We reached the end of the current token.+ // If the queue is empty, we should continue by reading+ // the next token+ if (numtok==0) {+ continue;+ }++ // if number of tokens is 1, always return the single tok+ if (numtok==1) {+ break;+ }++ final int numNumbers = numtok - numWords;++ // check conditions under which the current token+ // queue may be used as-is (no catenations needed)+ if (catenateAll==0 // no "everything" to catenate+ && (catenateWords==0 || numWords<=1) // no words to catenate+ && (catenateNumbers==0 || numNumbers<=1) // no numbers to catenate+ && (generateWordParts!=0 || numWords==0) // word generation is on+ && (generateNumberParts!=0 || numNumbers==0)) // number generation is on+ {+ break;+ }+++ // swap queue and the temporary working list, then clear the+ // queue in preparation for adding all combinations back to it.+ ArrayList<Token> tmp=tlist;+ tlist=queue;+ queue=tmp;+ queue.clear();++ if (numWords==0) {+ // all numbers+ addCombos(tlist,0,numtok,generateNumberParts!=0,catenateNumbers!=0 || catenateAll!=0, 1);+ break;+ } else if (numNumbers==0) {+ // all words+ addCombos(tlist,0,numtok,generateWordParts!=0,catenateWords!=0 || catenateAll!=0, 1);+ break;+ } else if (generateNumberParts==0 && generateWordParts==0 && catenateNumbers==0 && catenateWords==0) {+ // catenate all *only*+ // OPT:could be optimized to add to current queue...+ addCombos(tlist,0,numtok,false,catenateAll!=0, 1);+ break;+ }++ //+ // Find all adjacent tokens of the same type.+ //+ Token tok = tlist.get(0);+ boolean isWord = (tokType(tok) & ALPHA) != 0;+ boolean wasWord=isWord;++ for(int i=0; i<numtok;) {+ int j;+ for (j=i+1; j<numtok; j++) {+ wasWord=isWord;+ tok = tlist.get(j);+ isWord = (tokType(tok) & ALPHA) != 0;+ if (isWord != wasWord) break;+ }+ if (wasWord) {+ addCombos(tlist,i,j,generateWordParts!=0,catenateWords!=0,1);+ } else {+ addCombos(tlist,i,j,generateNumberParts!=0,catenateNumbers!=0,1);+ }+ i=j;+ }++ // take care catenating all subwords+ if (catenateAll!=0) {+ addCombos(tlist,0,numtok,false,true,0);+ }++ break;+ }++ // System.out.println("##########AFTER COMBINATIONS:"+ str(queue));++ queuePos=1;+ return queue.get(0);+ }+++ // index "a","b","c" as pos0="a", pos1="b", pos2="c", pos2="abc"+ private void addCombos(List<Token> lst, int start, int end, boolean generateSubwords, boolean catenateSubwords, int posOffset) {+ if (end-start==1) {+ // always generate a word alone, even if generateSubwords=0 because+ // the catenation of all the subwords *is* the subword.+ queue.add(lst.get(start));+ return;+ }++ StringBuilder sb = null;+ if (catenateSubwords) sb=new StringBuilder();+ Token firstTok=null;+ Token tok=null;+ for (int i=start; i<end; i++) {+ tok = lst.get(i);+ if (catenateSubwords) {+ if (i==start) firstTok=tok;+ sb.append(tok.termText());+ }+ if (generateSubwords) {+ queue.add(tok);+ }+ }++ if (catenateSubwords) {+ Token concatTok = new Token(sb.toString(),+ firstTok.startOffset(),+ tok.endOffset(),+ firstTok.type());+ // if we indexed some other tokens, then overlap concatTok with the last.+ // Otherwise, use the value passed in as the position offset.+ concatTok.setPositionIncrement(generateSubwords==true ? 0 : posOffset);+ queue.add(concatTok);+ }+ }++ private String str(List<Token> lst) {+ StringBuilder sb = new StringBuilder();+ sb.append('{');+ for (Token t : lst) {+ sb.append('(');+ sb.append('"');+ sb.append(t.termText());+ sb.append("\",increment=");+ sb.append(Integer.toString(t.getPositionIncrement()));+ sb.append(')');++ sb.append(',');+ }+ sb.append('}');+ return sb.toString();+ }++++ // questions:+ // negative numbers? -42 indexed as just 42?+ // dollar sign? $42+ // percent sign? 33%+ // downsides: if source text is "powershot" then a query of "PowerShot" won't match!++}diff --git a/src/java/org/apache/solr/analysis/WordDelimiterFilterFactory.java b/src/java/org/apache/solr/analysis/WordDelimiterFilterFactory.javanew file mode 100644index 00000000000..8b477f6d5c5--- /dev/null+++ b/src/java/org/apache/solr/analysis/WordDelimiterFilterFactory.java@@ -0,0 +1,48 @@+/**+ * 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.+ */++package org.apache.solr.analysis;++import org.apache.lucene.analysis.TokenStream;++import java.util.Map;++/**+ * @author yonik+ * @version $Id$+ */+public class WordDelimiterFilterFactory extends BaseTokenFilterFactory {+ int generateWordParts=0;+ int generateNumberParts=0;+ int catenateWords=0;+ int catenateNumbers=0;+ int catenateAll=0;++ public void init(Map<String, String> args) {+ super.init(args);+ generateWordParts = getInt("generateWordParts",1);+ generateNumberParts = getInt("generateNumberParts",1);+ catenateWords = getInt("catenateWords",0);+ catenateNumbers = getInt("catenateNumbers",0);+ catenateAll = getInt("catenateAll",0);+ }++ public TokenStream create(TokenStream input) {+ return new WordDelimiterFilter(input,+ generateWordParts, generateNumberParts,+ catenateWords, catenateNumbers, catenateAll);+ }+}diff --git a/src/java/org/apache/solr/core/AbstractSolrEventListener.java b/src/java/org/apache/solr/core/AbstractSolrEventListener.javanew file mode 100644index 00000000000..c3f5f4a22f7--- /dev/null+++ b/src/java/org/apache/solr/core/AbstractSolrEventListener.java@@ -0,0 +1,43 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.NamedList;++/**+ * @author yonik+ */+class AbstractSolrEventListener implements SolrEventListener {+ protected NamedList args;++ public void init(NamedList args) {+ this.args = args;+ }++ public void postCommit() {+ throw new UnsupportedOperationException();+ }++ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {+ throw new UnsupportedOperationException();+ }++ public String toString() {+ return getClass().getName() + args;+ }+}diff --git a/src/java/org/apache/solr/core/Config.java b/src/java/org/apache/solr/core/Config.javanew file mode 100644index 00000000000..d99b36fa15e--- /dev/null+++ b/src/java/org/apache/solr/core/Config.java@@ -0,0 +1,260 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.w3c.dom.Document;+import org.w3c.dom.Node;+import org.xml.sax.SAXException;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;++import javax.xml.parsers.*;+import javax.xml.xpath.XPath;+import javax.xml.xpath.XPathFactory;+import javax.xml.xpath.XPathConstants;+import javax.xml.xpath.XPathExpressionException;+import javax.xml.namespace.QName;+import java.io.*;+import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * @author yonik+ * @version $Id: Config.java,v 1.10 2005/12/20 16:05:46 yonik Exp $+ */+public class Config {+ public static final Logger log = Logger.getLogger(SolrCore.class.getName());++ static final XPathFactory xpathFactory = XPathFactory.newInstance();++ private Document doc;+ private String prefix;+ private String name;++ public Config(String name, InputStream is, String prefix) throws ParserConfigurationException, IOException, SAXException {+ this.name = name;+ this.prefix = prefix;+ if (prefix!=null && !prefix.endsWith("/")) prefix += '/';++ javax.xml.parsers.DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();+ doc = builder.parse(is);+ }++ public Document getDocument() {+ return doc;+ }++ public XPath getXPath() {+ return xpathFactory.newXPath();+ }++ private String normalize(String path) {+ return (prefix==null || path.startsWith("/")) ? path : prefix+path;+ }+++ public Object evaluate(String path, QName type) {+ XPath xpath = xpathFactory.newXPath();+ try {+ String xstr=normalize(path);++ // TODO: instead of prepending /prefix/, we could do the search rooted at /prefix...+ Object o = xpath.evaluate(xstr, doc, type);+ return o;++ } catch (XPathExpressionException e) {+ throw new SolrException(500,"Error in xpath:" + path +" for " + name,e,false);+ }+ }++ public Node getNode(String path, boolean errIfMissing) {+ XPath xpath = xpathFactory.newXPath();+ Node nd = null;+ String xstr = normalize(path);++ try {+ nd = (Node)xpath.evaluate(xstr, doc, XPathConstants.NODE);++ if (nd==null) {+ if (errIfMissing) {+ throw new RuntimeException(name + " missing "+path);+ } else {+ log.fine(name + " missing optional " + path);+ return null;+ }+ }++ log.finest(name + ":" + path + "=" + nd);+ return nd;++ } catch (XPathExpressionException e) {+ SolrException.log(log,"Error in xpath",e);+ throw new SolrException(500,"Error in xpath:" + xstr + " for " + name,e,false);+ } catch (SolrException e) {+ throw(e);+ } catch (Throwable e) {+ SolrException.log(log,"Error in xpath",e);+ throw new SolrException(500,"Error in xpath:" + xstr+ " for " + name,e,false);+ }+ }++ public String getVal(String path, boolean errIfMissing) {+ Node nd = getNode(path,errIfMissing);+ if (nd==null) return null;++ // should do the right thing for both attributes and elements.+ // Oops, when running in Resin, I get an unsupported operation+ // exception... need to use Sun default (apache)+ String txt = nd.getTextContent();+ log.fine(name + ' '+path+'='+txt);+ return txt;++ /******+ short typ = nd.getNodeType();+ if (typ==Node.ATTRIBUTE_NODE || typ==Node.TEXT_NODE) {+ return nd.getNodeValue();+ }+ return nd.getTextContent();+ ******/+ }+++ public String get(String path) {+ return getVal(path,true);+ }++ public String get(String path, String def) {+ String val = getVal(path, false);+ return val!=null ? val : def;+ }++ public int getInt(String path) {+ return Integer.parseInt(getVal(path, false));+ }++ public int getInt(String path, int def) {+ String val = getVal(path, false);+ return val!=null ? Integer.parseInt(val) : def;+ }++ public boolean getBool(String path) {+ return Boolean.parseBoolean(getVal(path, false));+ }++ public boolean getBool(String path, boolean def) {+ String val = getVal(path, false);+ return val!=null ? Boolean.parseBoolean(val) : def;+ }++ public float getFloat(String path) {+ return Float.parseFloat(getVal(path, false));+ }++ public float getFloat(String path, float def) {+ String val = getVal(path, false);+ return val!=null ? Float.parseFloat(val) : def;+ }+++ //+ // classloader related functions+ //++ private static final String project = "solr";+ private static final String base = "org.apache" + "." + project;+ private static final String[] packages = {"","analysis.","schema.","search.","update.","core.","request.","util."};++ public static Class findClass(String cname, String... subpackages) {+ ClassLoader loader = Thread.currentThread().getContextClassLoader();+ if (subpackages.length==0) subpackages = packages;++ // first try cname == full name+ try {+ return Class.forName(cname, true, loader);+ } catch (ClassNotFoundException e) {+ String newName=cname;+ if (newName.startsWith("solar.")) {+ // handle legacy package names+ newName = cname.substring("solar.".length());+ } else if (cname.startsWith(project+".")) {+ newName = cname.substring(project.length()+1);+ }++ for (String subpackage : subpackages) {+ try {+ String name = base + '.' + subpackage + newName;+ log.finest("Trying class name " + name);+ return Class.forName(name, true, loader);+ } catch (ClassNotFoundException e1) {+ // ignore... assume first exception is best.+ }+ }++ throw new SolrException(500, "Error loading class '" + cname + "'", e, false);+ }+ }++ public static Object newInstance(String cname, String... subpackages) {+ Class clazz = findClass(cname,subpackages);+ try {+ return clazz.newInstance();+ } catch (Exception e) {+ throw new SolrException(500,"Error instantiating class " + clazz, e, false);+ }+ }+++ public static InputStream openResource(String resource) {+ ClassLoader loader = Thread.currentThread().getContextClassLoader();+ InputStream is = loader.getResourceAsStream(resource);+ if (is==null) {+ throw new SolrException(500,"Can't open " + resource);+ }+ return is;+ }++ /**+ * Returns a list of non-blank non-comment lines with whitespace trimmed from front and back.+ * @param resource+ * @return+ * @throws IOException+ */+ public static List<String> getLines(String resource) throws IOException {+ BufferedReader input = null;+ try {+ // todo - allow configurable charset?+ input = new BufferedReader(new InputStreamReader(openResource(resource), "UTF-8"));+ } catch (UnsupportedEncodingException e) {+ throw new RuntimeException(e);+ }+ ArrayList<String> lines = new ArrayList<String>();+ for (String word=null; (word=input.readLine())!=null;) {+ // skip comments+ if (word.startsWith("#")) continue;+ word=word.trim();+ // skip blank lines+ if (word.length()==0) continue;+ lines.add(word);+ }+ return lines;+ }+++++}diff --git a/src/java/org/apache/solr/core/QuerySenderListener.java b/src/java/org/apache/solr/core/QuerySenderListener.javanew file mode 100644index 00000000000..3301e03f9bd--- /dev/null+++ b/src/java/org/apache/solr/core/QuerySenderListener.java@@ -0,0 +1,51 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.request.LocalSolrQueryRequest;+import org.apache.solr.request.SolrQueryResponse;+import org.apache.solr.util.NamedList;++import java.util.List;++/**+ * @author yonik+ * @version $Id$+ */+class QuerySenderListener extends AbstractSolrEventListener {++ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {+ SolrCore core = SolrCore.getSolrCore();+ log.info("QuerySenderListener sending requests to " + newSearcher);+ for (NamedList nlst : (List<NamedList>)args.get("queries")) {+ try {+ LocalSolrQueryRequest req = new LocalSolrQueryRequest(core, nlst);++ SolrQueryResponse rsp = new SolrQueryResponse();+ core.execute(req,rsp);+ } catch (Exception e) {+ // do nothing... we want to continue with the other requests.+ // the failure should have already been logged.+ }+ log.info("QuerySenderListener done.");+ }+ }++++}diff --git a/src/java/org/apache/solr/core/RequestHandlers.java b/src/java/org/apache/solr/core/RequestHandlers.javanew file mode 100644index 00000000000..85630e79fe5--- /dev/null+++ b/src/java/org/apache/solr/core/RequestHandlers.java@@ -0,0 +1,91 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.solr.util.DOMUtil;+import org.apache.solr.request.SolrRequestHandler;+import org.apache.solr.request.StandardRequestHandler;+import org.w3c.dom.NodeList;+import org.w3c.dom.Node;++import javax.xml.xpath.XPathConstants;+import java.util.logging.Logger;+import java.util.HashMap;++/**+ * @author yonik+ */+final class RequestHandlers {+ public static Logger log = Logger.getLogger(org.apache.solr.core.RequestHandlers.class.getName());++ public static final String DEFAULT_HANDLER_NAME="standard";++ final HashMap<String, SolrRequestHandler> map = new HashMap<String,SolrRequestHandler>();++ public RequestHandlers(Config config) {+ NodeList nodes = (NodeList)config.evaluate("requestHandler", XPathConstants.NODESET);++ if (nodes!=null) {+ for (int i=0; i<nodes.getLength(); i++) {+ Node node = nodes.item(i);++ // We can tolerate an error in some request handlers, still load the+ // others, and have a working system.+ try {+ String name = DOMUtil.getAttr(node,"name","requestHandler config");+ String className = DOMUtil.getAttr(node,"class","requestHandler config");+ log.info("adding requestHandler " + name + "=" + className);++ SolrRequestHandler handler = (SolrRequestHandler) Config.newInstance(className);+ handler.init(DOMUtil.childNodesToNamedList(node));++ put(name, handler);++ } catch (Exception e) {+ SolrException.logOnce(log,null,e);+ }+ }+ }++ //+ // Get the default handler and add it in the map under null and empty+ // to act as the default.+ //+ SolrRequestHandler handler = get(DEFAULT_HANDLER_NAME);+ if (handler == null) {+ handler = new StandardRequestHandler();+ put(DEFAULT_HANDLER_NAME, handler);+ }+ put(null, handler);+ put("", handler);++ }++ public SolrRequestHandler get(String handlerName) {+ return map.get(handlerName);+ }++ public void put(String handlerName, SolrRequestHandler handler) {+ map.put(handlerName, handler);+ if (handlerName != null && handlerName != "") {+ if (handler instanceof SolrInfoMBean) {+ SolrInfoRegistry.getRegistry().put(handlerName, (SolrInfoMBean)handler);+ }+ }+ }++}diff --git a/src/java/org/apache/solr/core/RunExecutableListener.java b/src/java/org/apache/solr/core/RunExecutableListener.javanew file mode 100644index 00000000000..51533dde274--- /dev/null+++ b/src/java/org/apache/solr/core/RunExecutableListener.java@@ -0,0 +1,103 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.solr.util.NamedList;+import org.apache.solr.search.SolrIndexSearcher;++import java.io.File;+import java.io.IOException;+import java.util.List;+import java.util.ArrayList;+import java.util.logging.Level;++/**+ * @author yonik+ */+class RunExecutableListener extends AbstractSolrEventListener {+ protected String[] cmd;+ protected File dir;+ protected String[] envp;+ protected boolean wait=true;++ public void init(NamedList args) {+ super.init(args);++ List cmdlist = new ArrayList();+ cmdlist.add(args.get("exe"));+ List lst = (List)args.get("args");+ if (lst != null) cmdlist.addAll(lst);+ cmd = (String[])cmdlist.toArray(new String[cmdlist.size()]);++ lst = (List)args.get("env");+ if (lst != null) {+ envp = (String[])lst.toArray(new String[lst.size()]);+ }++ String str = (String)args.get("dir");+ if (str==null || str.equals("") || str.equals(".") || str.equals("./")) {+ dir = null;+ } else {+ dir = new File(str);+ }++ if ("false".equals(args.get("wait"))) wait=false;+ }++ protected int exec(String callback) {+ int ret = 0;++ try {+ boolean doLog = log.isLoggable(Level.FINE);+ if (doLog) {+ log.fine("About to exec " + cmd[0]);+ }+ Process proc = Runtime.getRuntime().exec(cmd, envp ,dir);++ if (wait) {+ try {+ ret = proc.waitFor();+ } catch (InterruptedException e) {+ SolrException.log(log,e);+ }+ }++ if (wait && doLog) {+ log.fine("Executable " + cmd[0] + " returned " + ret);+ }++ } catch (IOException e) {+ // don't throw exception, just log it...+ SolrException.log(log,e);+ }++ return ret;+ }+++ public void postCommit() {+ // anything generic need to be passed to the external program?+ // the directory of the index? the command that caused it to be+ // invoked? the version of the index?+ exec("postCommit");+ }++ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {+ exec("newSearcher");+ }++}diff --git a/src/java/org/apache/solr/core/SolrConfig.java b/src/java/org/apache/solr/core/SolrConfig.javanew file mode 100644index 00000000000..3be8d097ad4--- /dev/null+++ b/src/java/org/apache/solr/core/SolrConfig.java@@ -0,0 +1,51 @@+/**+ * 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.+ */++package org.apache.solr.core;++import java.io.InputStream;+++/**+ * @author yonik+ * @version $Id: SolrConfig.java,v 1.3 2005/12/02 04:31:06 yonik Exp $+ */+public class SolrConfig {+ public static Config config;+ static {+ Exception e=null;+ String file="solrconfig.xml";+ InputStream is;+ try {+ is = Config.openResource(file);+ } catch (Exception ee) {+ e=ee;+ file = "solarconfig.xml"; // backward compat+ is = Config.openResource(file);+ }+ if (is!=null) {+ try {+ config=new Config(file, is, "/config/");+ is.close();+ } catch (Exception ee) {+ throw new RuntimeException(ee);+ }+ Config.log.info("Loaded Config solarconfig.xml");+ } else {+ throw new RuntimeException(e);+ }+ }+}diff --git a/src/java/org/apache/solr/core/SolrCore.java b/src/java/org/apache/solr/core/SolrCore.javanew file mode 100644index 00000000000..a7cfe8a60ad--- /dev/null+++ b/src/java/org/apache/solr/core/SolrCore.java@@ -0,0 +1,970 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FSDirectory;+import org.apache.solr.request.SolrRequestHandler;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.request.SolrQueryResponse;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.update.*;+import org.apache.solr.util.DOMUtil;+import org.apache.solr.util.RefCounted;+import org.apache.solr.util.StrUtils;+import org.apache.solr.util.XML;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;+import org.xmlpull.v1.XmlPullParser;+import org.xmlpull.v1.XmlPullParserException;+import org.xmlpull.v1.XmlPullParserFactory;++import javax.xml.xpath.XPathConstants;+import java.io.File;+import java.io.IOException;+import java.io.Reader;+import java.io.Writer;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.Callable;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.logging.Logger;+++/**+ * @author yonik+ * @version $Id: SolrCore.java,v 1.47 2006/01/10 05:04:44 yonik Exp $+ */++public final class SolrCore {+ public static final String cvsId="$Id: SolrCore.java,v 1.47 2006/01/10 05:04:44 yonik Exp $";+ public static final String cvsSource="$Source: /cvs/main/searching/solr/solarcore/src/solr/SolrCore.java,v $";+ public static final String cvsTag="$Name: $";+ public static final String version="1.0";++ public static Logger log = Logger.getLogger(SolrCore.class.getName());++ private final IndexSchema schema;+ private final String index_path;+ private final UpdateHandler updateHandler;++ public static SolrIndexConfig mainIndexConfig = new SolrIndexConfig("mainIndex");++ static {+ BooleanQuery.setMaxClauseCount(SolrConfig.config.getInt("query/maxBooleanClauses",BooleanQuery.getMaxClauseCount()));+ }+++ public static List<SolrEventListener> parseListener(String path) {+ List<SolrEventListener> lst = new ArrayList<SolrEventListener>();+ log.info("Searching for listeners: " +path);+ NodeList nodes = (NodeList)SolrConfig.config.evaluate(path, XPathConstants.NODESET);+ if (nodes!=null) {+ for (int i=0; i<nodes.getLength(); i++) {+ Node node = nodes.item(i);+ String className = DOMUtil.getAttr(node,"class");+ SolrEventListener listener = (SolrEventListener)Config.newInstance(className);+ listener.init(DOMUtil.childNodesToNamedList(node));+ lst.add(listener);+ log.info("added SolrEventListener: " + listener);+ }+ }+ return lst;+ }++ List<SolrEventListener> firstSearcherListeners;+ List<SolrEventListener> newSearcherListeners;+ private void parseListeners() {+ firstSearcherListeners = parseListener("//listener[@event=\"firstSearcher\"]");+ newSearcherListeners = parseListener("//listener[@event=\"newSearcher\"]");+ }+++ public IndexSchema getSchema() { return schema; }+ public String getDir() { return index_path; }+++ private final RequestHandlers reqHandlers = new RequestHandlers(SolrConfig.config);++ public SolrRequestHandler getRequestHandler(String handlerName) {+ return reqHandlers.get(handlerName);+ }+++ // TODO - what about a master that not might have a searcher normally open?+ @Deprecated+ public int maxDoc() {+ RefCounted<SolrIndexSearcher> holder=null;+ int num=0;+ try {+ holder = getSearcher();+ SolrIndexSearcher searcher = holder.get();+ num = searcher.maxDoc();+ } catch (IOException e) {+ log(e);+ } finally {+ if (holder != null) holder.decref();+ }+ return num;+ }+++ // gets a non-caching searcher+ public SolrIndexSearcher newSearcher(String name) throws IOException {+ return new SolrIndexSearcher(schema, name,getDir(),false);+ }+++ void initIndex() {+ try {+ File dirFile = new File(getDir());+ boolean indexExists = dirFile.canRead();+++ boolean removeLocks = SolrConfig.config.getBool("mainIndex/unlockOnStartup", false);+ if (removeLocks) {+ // to remove locks, the directory must already exist... so we create it+ // if it didn't exist already...+ Directory dir = FSDirectory.getDirectory(dirFile, !indexExists);+ if (IndexReader.isLocked(dir)) {+ log.warning("WARNING: Solr index directory '" + getDir() + "' is locked. Unlocking...");+ IndexReader.unlock(dir);+ }+ }++ // Create the index if it doesn't exist. Note that indexExists was tested *before*+ // lock removal, since that will result in the creation of the directory.+ if(!indexExists) {+ log.warning("Solr index directory '" + dirFile + "' doesn't exist."+ + " Creating new index...");++ SolrIndexWriter writer = new SolrIndexWriter("SolrCore.initIndex",getDir(), true, schema, mainIndexConfig);+ writer.close();++ }++ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+++ private UpdateHandler createUpdateHandler(String className) {+ try {+ Class handlerClass = Config.findClass(className);+ java.lang.reflect.Constructor cons = handlerClass.getConstructor(new Class[]{SolrCore.class});+ return (UpdateHandler)cons.newInstance(new Object[]{this});+ } catch (SolrException e) {+ throw e;+ } catch (Exception e) {+ throw new SolrException(500,"Error Instantiating Update Handler "+className, e);+ }+ }+++ // Singleton for now...+ private static SolrCore core;++ public static SolrCore getSolrCore() {+ synchronized (SolrCore.class) {+ if (core==null) core = new SolrCore(null,null);+ return core;+ }+ }+++ public SolrCore(String index_path, IndexSchema schema) {+ synchronized (SolrCore.class) {+ // this is for backward compatibility (and also the reason+ // the sync block is needed)+ core = this; // set singleton+ try {+ if (index_path==null) {+ index_path=SolrConfig.config.get("indexDir","index");+ }++ log.info("Opening new SolrCore at " + index_path);++ if (schema==null) {+ schema = new IndexSchema("schema.xml");+ }++ this.schema = schema;+ this.index_path = index_path;++ parseListeners();++ initIndex();++ try {+ // Open the searcher *before* the handler so we don't end up opening+ // one in the middle.+ getSearcher(false,false,null);++ updateHandler = createUpdateHandler(+ SolrConfig.config.get("updateHandler/@class", DirectUpdateHandler.class.getName())+ );++ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ } finally {++ }+++ }+ }+++ public void close() {+ log.info("CLOSING SolrCore!");+ try {+ closeSearcher();+ } catch (Exception e) {+ SolrException.log(log,e);+ }+ try {+ searcherExecutor.shutdown();+ } catch (Exception e) {+ SolrException.log(log,e);+ }+ try {+ updateHandler.close();+ } catch (Exception e) {+ SolrException.log(log,e);+ }+ }+++ void finalizer() { close(); }+++ ////////////////////////////////////////////////////////////////////////////////+ // Searcher Control+ ////////////////////////////////////////////////////////////////////////////////++ // The current searcher used to service queries.+ // Don't access this directly!!!! use getSearcher() to+ // get it (and it will increment the ref count at the same time)+ private RefCounted<SolrIndexSearcher> _searcher;++ final ExecutorService searcherExecutor = Executors.newSingleThreadExecutor();+ private int onDeckSearchers; // number of searchers preparing+ private Object searcherLock = new Object(); // the sync object for the searcher+++ public RefCounted<SolrIndexSearcher> getSearcher() {+ try {+ return getSearcher(false,true,null);+ } catch (IOException e) {+ SolrException.log(log,null,e);+ return null;+ }+ }++ /**+ * Get a {@link SolrIndexSearcher} or start the process of creating a new one.+ * <p>+ * The registered searcher is the default searcher used to service queries.+ * A searcher will normally be registered after all of the warming+ * and event handlers (newSearcher or firstSearcher events) have run.+ * In the case where there is no registered searcher, the newly created searcher will+ * be registered before running the event handlers (a slow searcher is better than no searcher).+ *+ * <p>+ * If <tt>forceNew==true</tt> then+ * A new searcher will be opened and registered irregardless if there is already+ * a registered searcher or other searchers in the process of being created.+ * <p>+ * If <tt>forceNew==false</tt> then:<ul>+ * <li>If a searcher is already registered, that searcher will be returned</li>+ * <li>If no searcher is currently registered, but at least one is in the process of being created, then+ * this call will block until the first searcher is registered</li>+ * <li>If no searcher is currently registered, and no searchers in the process of being registered, a new+ * searcher will be created.</li>+ * </ul>+ * <p>+ * If <tt>returnSearcher==true</tt> then a {@link RefCounted}<{@link SolrIndexSearcher}> will be returned with+ * the reference count incremented. It <b>must</b> be decremented when no longer needed.+ * <p>+ * If <tt>waitSearcher!=null</tt> and a new {@link SolrIndexSearcher} was created,+ * then it is filled in with a Future that will return after the searcher is registered. The Future may be set to+ * <tt>null</tt> in which case the SolrIndexSearcher created has already been registered at the time+ * this method returned.+ * <p>+ * @param forceNew if true, force the open of a new index searcher regardless if there is already one open.+ * @param returnSearcher if true, returns a {@link <SolrIndexSearcher>} holder with the refcount already incremented.+ * @param waitSearcher if non-null, will be filled in with a {@link Future} that will return after the new searcher is registered.+ * @return+ * @throws IOException+ */+ public RefCounted<SolrIndexSearcher> getSearcher(boolean forceNew, boolean returnSearcher, final Future[] waitSearcher) throws IOException {+ // it may take some time to open an index.... we may need to make+ // sure that two threads aren't trying to open one at the same time+ // if it isn't necessary.++ synchronized (searcherLock) {+ // see if we can return the current searcher+ if (_searcher!=null && !forceNew) {+ if (returnSearcher) {+ _searcher.incref();+ return _searcher;+ } else {+ return null;+ }+ }++ // check to see if we can wait for someone elses searcher to be set+ if (onDeckSearchers>0 && !forceNew && _searcher==null) {+ try {+ searcherLock.wait();+ } catch (InterruptedException e) {+ log.info(SolrException.toStr(e));+ }+ }++ // check again: see if we can return right now+ if (_searcher!=null && !forceNew) {+ if (returnSearcher) {+ _searcher.incref();+ return _searcher;+ } else {+ return null;+ }+ }++ // At this point, we know we need to open a new searcher...+ // first: increment count to signal other threads that we are+ // opening a new searcher.+ onDeckSearchers++;+ }++ // open the index synchronously+ // if this fails, we need to decrement onDeckSearchers again.+ SolrIndexSearcher tmp;+ try {+ if (onDeckSearchers < 1) {+ // should never happen... just a sanity check+ log.severe("ERROR!!! onDeckSearchers is " + onDeckSearchers);+ // reset to 1 (don't bother synchronizing)+ onDeckSearchers=1;+ } else if (onDeckSearchers > 1) {+ log.info("PERFORMANCE WARNING: Overlapping onDeckSearchers=" + onDeckSearchers);+ }+ tmp = new SolrIndexSearcher(schema, "main", index_path, true);+ } catch (Throwable th) {+ synchronized(searcherLock) {+ onDeckSearchers--;+ // notify another waiter to continue... it may succeed+ // and wake any others.+ searcherLock.notify();+ }+ // need to close the searcher here??? we shouldn't have to.+ throw new RuntimeException(th);+ }++ final SolrIndexSearcher newSearcher=tmp;++ RefCounted<SolrIndexSearcher> currSearcherHolder=null;+ final RefCounted<SolrIndexSearcher> newSearchHolder=newHolder(newSearcher);+ if (returnSearcher) newSearchHolder.incref();++ // a signal to decrement onDeckSearchers if something goes wrong.+ final boolean[] decrementOnDeckCount=new boolean[1];+ decrementOnDeckCount[0]=true;++ try {++ synchronized (searcherLock) {+ if (_searcher == null) {+ // if there isn't a current searcher then register this one+ // before warming is complete instead of waiting.+ registerSearcher(newSearchHolder);+ decrementOnDeckCount[0]=false;+ } else {+ // get a reference to the current searcher for purposes of autowarming.+ currSearcherHolder=_searcher;+ currSearcherHolder.incref();+ }+ }+++ final SolrIndexSearcher currSearcher = currSearcherHolder==null ? null : currSearcherHolder.get();++ //+ // Note! if we registered the new searcher (but didn't increment it's+ // reference count because returnSearcher==false, it's possible for+ // someone else to register another searcher, and thus cause newSearcher+ // to close while we are warming.+ //+ // Should we protect against that by incrementing the reference count?+ // Maybe we should just let it fail? After all, if returnSearcher==false+ // and newSearcher has been de-registered, what's the point of continuing?+ //++ Future future=null;++ // warm the new searcher based on the current searcher.+ // should this go before the other event handlers or after?+ if (currSearcher != null) {+ future = searcherExecutor.submit(+ new Callable() {+ public Object call() throws Exception {+ try {+ newSearcher.warm(currSearcher);+ } catch (Throwable e) {+ SolrException.logOnce(log,null,e);+ }+ return null;+ }+ }+ );+ }++ if (currSearcher==null && firstSearcherListeners.size() > 0) {+ future = searcherExecutor.submit(+ new Callable() {+ public Object call() throws Exception {+ try {+ for (SolrEventListener listener : firstSearcherListeners) {+ listener.newSearcher(newSearcher,null);+ }+ } catch (Throwable e) {+ SolrException.logOnce(log,null,e);+ }+ return null;+ }+ }+ );+ }++ if (currSearcher!=null && newSearcherListeners.size() > 0) {+ future = searcherExecutor.submit(+ new Callable() {+ public Object call() throws Exception {+ try {+ for (SolrEventListener listener : newSearcherListeners) {+ listener.newSearcher(newSearcher,null);+ }+ } catch (Throwable e) {+ SolrException.logOnce(log,null,e);+ }+ return null;+ }+ }+ );+ }++ // WARNING: this code assumes a single threaded executor (that all tasks+ // queued will finish first).+ final RefCounted<SolrIndexSearcher> currSearcherHolderF = currSearcherHolder;+ Future finalFuture=null;+ if (currSearcherHolder != null) {+ finalFuture = searcherExecutor.submit(+ new Callable() {+ public Object call() throws Exception {+ try {+ // signal that we no longer need to decrement+ // the count *before* registering the searcher since+ // registertSearcher will decrement even if it errors.+ decrementOnDeckCount[0]=false;+ registerSearcher(newSearchHolder);+ } catch (Throwable e) {+ SolrException.logOnce(log,null,e);+ } finally {+ // we are all done with the old searcher we used+ // for warming...+ currSearcherHolderF.decref();+ }+ return null;+ }+ }+ );+ }++ if (waitSearcher != null) {+ waitSearcher[0] = finalFuture;+ }++ // Return the searcher as the warming tasks run in parallel+ // callers may wait on the waitSearcher future returned.+ return returnSearcher ? newSearchHolder : null;++ }+ catch (Exception e) {+ SolrException.logOnce(log,null,e);+ if (currSearcherHolder != null) currSearcherHolder.decref();++ synchronized (searcherLock) {+ if (decrementOnDeckCount[0]) {+ onDeckSearchers--;+ }+ if (onDeckSearchers < 0) {+ // sanity check... should never happen+ log.severe("ERROR!!! onDeckSearchers after decrement=" + onDeckSearchers);+ onDeckSearchers=0; // try and recover+ }+ // if we failed, we need to wake up at least one waiter to continue the process+ searcherLock.notify();+ }++ // since the indexreader was already opened, assume we can continue on+ // even though we got an exception.+ return returnSearcher ? newSearchHolder : null;+ }++ }+++ private RefCounted<SolrIndexSearcher> newHolder(SolrIndexSearcher newSearcher) {+ RefCounted<SolrIndexSearcher> holder = new RefCounted<SolrIndexSearcher>(newSearcher)+ {+ public void close() {+ try {+ resource.close();+ } catch (IOException e) {+ log.severe("Error closing searcher:" + SolrException.toStr(e));+ }+ }+ };+ holder.incref(); // set ref count to 1 to account for this._searcher+ return holder;+ }+++ // Take control of newSearcherHolder (which should have a reference count of at+ // least 1 already. If the caller wishes to use the newSearcherHolder directly+ // after registering it, then they should increment the reference count *before*+ // calling this method.+ //+ // onDeckSearchers will also be decremented (it should have been incremented+ // as a result of opening a new searcher).+ private void registerSearcher(RefCounted<SolrIndexSearcher> newSearcherHolder) throws IOException {+ synchronized (searcherLock) {+ try {+ if (_searcher != null) {+ _searcher.decref(); // dec refcount for this._searcher+ _searcher=null;+ }++ _searcher = newSearcherHolder;+ SolrIndexSearcher newSearcher = newSearcherHolder.get();++ SolrInfoRegistry.getRegistry().put("currentSearcher", newSearcher);+ newSearcher.register(); // register subitems (caches)+ log.info("Registered new searcher " + newSearcher);++ } catch (Throwable e) {+ log(e);+ } finally {+ // wake up anyone waiting for a searcher+ // even in the face of errors.+ onDeckSearchers--;+ searcherLock.notifyAll();+ }+ }+ }++++ public void closeSearcher() {+ log.info("Closing main searcher on request.");+ synchronized (searcherLock) {+ if (_searcher != null) {+ _searcher.decref(); // dec refcount for this._searcher+ _searcher=null;+ SolrInfoRegistry.getRegistry().remove("currentSearcher");+ }+ }+ }++++ public void execute(SolrQueryRequest req, SolrQueryResponse rsp) {+ SolrRequestHandler handler = getRequestHandler(req.getQueryType());+ if (handler==null) {+ log.warning("Unknown Request Handler '" + req.getQueryType() +"' :" + req);+ throw new SolrException(400,"Unknown Request Handler '" + req.getQueryType() + "'", true);+ }+ handler.handleRequest(req,rsp);+ log.info(req.getParamString()+ " 0 "++ (int)(rsp.getEndTime() - req.getStartTime()));+ }++++++ XmlPullParserFactory factory;+ {+ try {+ factory = XmlPullParserFactory.newInstance();+ } catch (XmlPullParserException e) {+ throw new RuntimeException(e);+ }+ factory.setNamespaceAware(false);+ }+++ private int findNextTag(XmlPullParser xpp, String tag) throws XmlPullParserException, IOException {+ int eventType;+ while((eventType=xpp.next()) != XmlPullParser.END_DOCUMENT) {+ if(eventType == XmlPullParser.START_TAG) {+ if (tag.equals(xpp.getName())) break;+ }+ }+ return eventType;+ }+++ public void update(Reader reader, Writer writer) {++ // TODO: add param to specify maximum time to commit?++ // todo - might be nice to separate command parsing w/ a factory+ // then new commands could be added w/o risk to old ones+++ XmlPullParser xpp = null;+ try {+ xpp = factory.newPullParser();+ } catch (XmlPullParserException e) {+ throw new RuntimeException(e);+ }++ long startTime=System.currentTimeMillis();++ try {+ xpp.setInput(reader);+ xpp.nextTag();++ String currTag = xpp.getName();+ if ("add".equals(currTag)) {+ log.finest("SolrCore.update(add)");+ AddUpdateCommand cmd = new AddUpdateCommand();+ cmd.allowDups=false; // the default++ int status=0;+ boolean pendingAttr=false, committedAttr=false;+ int attrcount = xpp.getAttributeCount();+ for (int i=0; i<attrcount; i++) {+ String attrName = xpp.getAttributeName(i);+ String attrVal = xpp.getAttributeValue(i);+ if ("allowDups".equals(attrName)) {+ cmd.allowDups = StrUtils.parseBoolean(attrVal);+ } else if ("overwritePending".equals(attrName)) {+ cmd.overwritePending = StrUtils.parseBoolean(attrVal);+ pendingAttr=true;+ } else if ("overwriteCommitted".equals(attrName)) {+ cmd.overwriteCommitted = StrUtils.parseBoolean(attrVal);+ committedAttr=true;+ } else {+ log.warning("Unknown attribute id in add:" + attrName);+ }+ }++ //set defaults for committed and pending based on allowDups value+ if (!pendingAttr) cmd.overwritePending=!cmd.allowDups;+ if (!committedAttr) cmd.overwriteCommitted=!cmd.allowDups;++ DocumentBuilder builder = new DocumentBuilder(schema);+ int eventType=0;+ while(true) {+ // this may be our second time through the loop in the case+ // that there are multiple docs in the add... so make sure that+ // objects can handle that.++ cmd.id = null; // reset the id for this add++ if (eventType !=0) {+ eventType=xpp.getEventType();+ if (eventType==XmlPullParser.END_DOCUMENT) break;+ }+ // eventType = xpp.next();+ eventType = xpp.nextTag();+ if (eventType == XmlPullParser.END_TAG || eventType == XmlPullParser.END_DOCUMENT) break; // should match </add>++ try {+ readDoc(builder,xpp);+ builder.endDoc();+ cmd.doc = builder.getDoc();+ log.finest("adding doc...");+ updateHandler.addDoc(cmd);+ log.info("add "+status+" "+(System.currentTimeMillis()-startTime));+ writer.write("<result status=\"" + status + "\"></result>");+ } catch (SolrException e) {+ log(e);+ log.info("add "+e.code+" "+(System.currentTimeMillis()-startTime));+ writeResult(writer,e);+ // we may not have finised reading the XML for this cmd,+ // so eat any unused input up till "</add>"+ eventType = xpp.getEventType();+ while (true) {+ if ( eventType == XmlPullParser.END_DOCUMENT+ || (eventType == XmlPullParser.END_TAG && "add".equals(xpp.getName())))+ {+ break;+ }+ eventType = xpp.next();+ }+ }+ }++ /***+ while (findNextTag(xpp,"doc") != XmlPullParser.END_DOCUMENT) {+ readDoc(builder,xpp);+ Document doc = builder.endDoc();+ indexWriter.addDocument(doc);+ docsAdded++;+ }+ ***/++ } // end add++ else if ("commit".equals(currTag) || "optimize".equals(currTag)) {+ log.finest("parsing "+currTag);+ try {+ CommitUpdateCommand cmd = new CommitUpdateCommand("optimize".equals(currTag));++ boolean sawWaitSearcher=false, sawWaitFlush=false;+ int attrcount = xpp.getAttributeCount();+ for (int i=0; i<attrcount; i++) {+ String attrName = xpp.getAttributeName(i);+ String attrVal = xpp.getAttributeValue(i);+ if ("waitFlush".equals(attrName)) {+ cmd.waitFlush = StrUtils.parseBoolean(attrVal);+ sawWaitFlush=true;+ } else if ("waitSearcher".equals(attrName)) {+ cmd.waitSearcher = StrUtils.parseBoolean(attrVal);+ sawWaitSearcher=true;+ } else {+ log.warning("unexpected attribute commit/@" + attrName);+ }+ }++ // If waitFlush is specified and waitSearcher wasn't, then+ // clear waitSearcher.+ if (sawWaitFlush && !sawWaitSearcher) {+ cmd.waitSearcher=false;+ }++ updateHandler.commit(cmd);+ if ("optimize".equals(currTag)) {+ log.info("optimize 0 "+(System.currentTimeMillis()-startTime));+ }+ else {+ log.info("commit 0 "+(System.currentTimeMillis()-startTime));+ }+ while (true) {+ int eventType = xpp.nextTag();+ if (eventType == XmlPullParser.END_TAG) break; // match </commit>+ }+ writer.write("<result status=\"0\"></result>");+ } catch (SolrException e) {+ log(e);+ if ("optimize".equals(currTag)) {+ log.info("optimize "+e.code+" "++ (System.currentTimeMillis()-startTime));+ }+ else {+ log.info("commit "+e.code+" "++ (System.currentTimeMillis()-startTime));+ }+ writeResult(writer,e);+ } catch (Exception e) {+ SolrException.log(log, "Exception during commit/optimize",e);+ writeResult(writer,e);+ }+ } // end commit++ else if ("delete".equals(currTag)) {+ log.finest("parsing delete");+ try {+ DeleteUpdateCommand cmd = new DeleteUpdateCommand();+ cmd.fromPending=true;+ cmd.fromCommitted=true;+ int attrcount = xpp.getAttributeCount();+ for (int i=0; i<attrcount; i++) {+ String attrName = xpp.getAttributeName(i);+ String attrVal = xpp.getAttributeValue(i);+ if ("fromPending".equals(attrName)) {+ cmd.fromPending = StrUtils.parseBoolean(attrVal);+ } else if ("fromCommitted".equals(attrName)) {+ cmd.fromCommitted = StrUtils.parseBoolean(attrVal);+ } else {+ log.warning("unexpected attribute delete/@" + attrName);+ }+ }++ int eventType = xpp.nextTag();+ currTag = xpp.getName();+ String val = xpp.nextText();++ if ("id".equals(currTag)) {+ cmd.id = val;+ updateHandler.delete(cmd);+ log.info("delete(id " + val + ") 0 " ++ (System.currentTimeMillis()-startTime));+ } else if ("query".equals(currTag)) {+ cmd.query = val;+ updateHandler.deleteByQuery(cmd);+ log.info("deleteByQuery(query " + val + ") 0 " ++ (System.currentTimeMillis()-startTime));+ } else {+ log.warning("unexpected XML tag /delete/"+currTag);+ throw new SolrException(400,"unexpected XML tag /delete/"+currTag);+ }++ writer.write("<result status=\"0\"></result>");++ while (xpp.nextTag() != XmlPullParser.END_TAG);++ } catch (SolrException e) {+ log(e);+ log.info("delete "+e.code+" "+(System.currentTimeMillis()-startTime));+ writeResult(writer,e);+ } catch (Exception e) {+ log(e);+ writeResult(writer,e);+ }+ } // end delete+++ } catch (XmlPullParserException e) {+ log(e);+ writeResult(writer,e);+ } catch (IOException e) {+ log(e);+ writeResult(writer,e);+ } catch (SolrException e) {+ log(e);+ log.info("update "+e.code+" "+(System.currentTimeMillis()-startTime));+ writeResult(writer,e);+ } catch (Throwable e) {+ log(e);+ writeResult(writer,e);+ }++ }++ private void readDoc(DocumentBuilder builder, XmlPullParser xpp) throws IOException, XmlPullParserException {+ // xpp should be at <doc> at this point++ builder.startDoc();++ int attrcount = xpp.getAttributeCount();+ float docBoost = 1.0f;++ for (int i=0; i<attrcount; i++) {+ String attrName = xpp.getAttributeName(i);+ String attrVal = xpp.getAttributeValue(i);+ if ("boost".equals(attrName)) {+ docBoost = Float.parseFloat(attrVal);+ } else {+ log.warning("Unknown attribute doc/@" + attrName);+ }+ }+ if (docBoost != 1.0f) builder.setBoost(docBoost);++ // while (findNextTag(xpp,"field") != XmlPullParser.END_DOCUMENT) {++ while(true) {+ int eventType = xpp.nextTag();+ if (eventType == XmlPullParser.END_TAG) break; // </doc>++ String tname=xpp.getName();+ // System.out.println("FIELD READER AT TAG " + tname);++ if (!"field".equals(tname)) {+ log.warning("unexpected XML tag doc/"+tname);+ throw new SolrException(400,"unexpected XML tag doc/"+tname);+ }++ //+ // get field name and parse field attributes+ //+ attrcount = xpp.getAttributeCount();+ String name=null;+ float boost=1.0f;+ boolean isNull=false;++ for (int i=0; i<attrcount; i++) {+ String attrName = xpp.getAttributeName(i);+ String attrVal = xpp.getAttributeValue(i);+ if ("name".equals(attrName)) {+ name=attrVal;+ } else if ("boost".equals(attrName)) {+ boost=Float.parseFloat(attrVal);+ } else if ("null".equals(attrName)) {+ isNull=StrUtils.parseBoolean(attrVal);+ } else {+ log.warning("Unknown attribute doc/field/@" + attrName);+ }+ }++ // now get the field value+ String val = xpp.nextText(); // todo... text event for <field></field>???+ // need this line for isNull???+ // Don't add fields marked as null (for now at least)+ if (!isNull) {+ if (docBoost != 1.0f) {+ builder.addField(name,val,docBoost);+ } else {+ builder.addField(name,val);+ }+ }++ // do I have to do a nextTag here to read the end_tag?++ } // end field loop++ }+++ final public static void log(Throwable e) {+ SolrException.logOnce(log,null,e);+ }+++ final static void writeResult(Writer out, SolrException e) {+ try {+ XML.writeXML(out,"result",e.getMessage(),"status",e.code());+ } catch (Exception ee) {+ log.severe("Error writing to putput stream: "+ee);+ }+ }++ final static void writeResult(Writer out, Throwable e) {+ try {+ XML.writeXML(out,"result",SolrException.toStr(e),"status","1");+ } catch (Exception ee) {+ log.severe("Error writing to putput stream: "+ee);+ }+ }+++}++++diff --git a/src/java/org/apache/solr/core/SolrEventListener.java b/src/java/org/apache/solr/core/SolrEventListener.javanew file mode 100644index 00000000000..a41721f9211--- /dev/null+++ b/src/java/org/apache/solr/core/SolrEventListener.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.solr.util.NamedList;+import org.apache.solr.search.SolrIndexSearcher;++import java.util.logging.Logger;++/**+ * @author yonik+ * @version $Id: SolrEventListener.java,v 1.4 2005/05/25 04:26:47 yonik Exp $+ */+public interface SolrEventListener {+ static final Logger log = Logger.getLogger(SolrCore.class.getName());++ public void init(NamedList args);++ public void postCommit();++ public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher);++}\ No newline at end of filediff --git a/src/java/org/apache/solr/core/SolrException.java b/src/java/org/apache/solr/core/SolrException.javanew file mode 100644index 00000000000..a4938615aed--- /dev/null+++ b/src/java/org/apache/solr/core/SolrException.java@@ -0,0 +1,108 @@+/**+ * 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.+ */++package org.apache.solr.core;++import java.util.logging.Logger;+import java.io.CharArrayWriter;+import java.io.PrintWriter;++/**+ * @author yonik+ * @version $Id: SolrException.java,v 1.6 2005/06/14 20:42:26 yonik Exp $+ */+++public class SolrException extends RuntimeException {+ public boolean logged=false;++ public SolrException(int code, String msg) {+ super(msg);+ this.code=code;+ }+ public SolrException(int code, String msg, boolean alreadyLogged) {+ super(msg);+ this.code=code;+ this.logged=alreadyLogged;+ }++ public SolrException(int code, String msg, Throwable th, boolean alreadyLogged) {+ super(msg,th);+ this.code=code;+ logged=alreadyLogged;+ }++ public SolrException(int code, String msg, Throwable th) {+ this(code,msg,th,true);+ }++ public SolrException(int code, Throwable th) {+ super(th);+ this.code=code;+ logged=true;+ }++ int code=0;+ public int code() { return code; }+++++ public void log(Logger log) { log(log,this); }+ public static void log(Logger log, Throwable e) {+ log.severe(toStr(e));+ if (e instanceof SolrException) {+ ((SolrException)e).logged = true;+ }+ }++ public static void log(Logger log, String msg, Throwable e) {+ log.severe(msg + ':' + toStr(e));+ if (e instanceof SolrException) {+ ((SolrException)e).logged = true;+ }+ }++ public static void logOnce(Logger log, String msg, Throwable e) {+ if (e instanceof SolrException) {+ if(((SolrException)e).logged) return;+ }+ if (msg!=null) log(log,msg,e);+ else log(log,e);+ }+++ // public String toString() { return toStr(this); } // oops, inf loop+ public String toString() { return super.toString(); }++ public static String toStr(Throwable e) {+ CharArrayWriter cw = new CharArrayWriter();+ PrintWriter pw = new PrintWriter(cw);+ e.printStackTrace(pw);+ pw.flush();+ return cw.toString();++/** This doesn't work for some reason!!!!!+ StringWriter sw = new StringWriter();+ PrintWriter pw = new PrintWriter(sw);+ e.printStackTrace(pw);+ pw.flush();+ System.out.println("The STRING:" + sw.toString());+ return sw.toString();+**/+ }++}diff --git a/src/java/org/apache/solr/core/SolrInfo.java b/src/java/org/apache/solr/core/SolrInfo.javanew file mode 100644index 00000000000..ec640e86b87--- /dev/null+++ b/src/java/org/apache/solr/core/SolrInfo.java@@ -0,0 +1,104 @@+/**+ * 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.+ */++package org.apache.solr.core;++import java.net.URL;+import org.apache.solr.util.*;++/**+ * @author ronp+ * @version $Id: SolrInfo.java,v 1.3 2005/05/02 19:04:59 ronp Exp $+ */++// MBean pattern for holding various ui friendly strings and URLs+// for use by objects which are 'plugable' to make administering+// production use easier+ // name - simple common usage name, e.g. BasicQueryHandler+ // version - simple common usage version, e.g. 2.0+ // description - simple one or two line description+ // cvsId - yes, really the CVS Id (type 'man co')+ // cvsName - yes, really the CVS Name (type 'man co')+ // cvsSource - yes, really the CVS Source (type 'man co')+ // docs - URL list: TWIKI, Faq, Design doc, something! :)++abstract class SolrInfo implements SolrInfoMBean {+ public static String _cvsId="$Id: SolrInfo.java,v 1.3 2005/05/02 19:04:59 ronp Exp $";+ public static String _cvsSource="$Source: /cvs/main/searching/solr/solarcore/src/solr/SolrInfo.java,v $";+ public static String _cvsName="$Name: $";+++ public String getName() { return this.name; }+ public String getVersion() { return this.version; }+ public String getDescription() { return this.description; }+ public Category getCategory() { return SolrInfoMBean.Category.QUERYHANDLER; }+ public String getCvsId() { return this.cvsId; }+ public String getCvsName() { return this.cvsName; }+ public String getCvsSource() { return this.cvsSource; }+ public URL[] getDocs() { return this.docs; }+ public NamedList getStatistics() { return null; }+++ public void setName(String name ) { this.name = name; }+ public void setVersion(String vers) { this.version = vers; }+ public void setDescription(String desc) { this.description = desc; }+ public void setCvsId(String cvsId) { this.cvsId = cvsId; }+ public void setCvsName(String cvsName) { this.cvsName = cvsName; }+ public void setCvsSource(String cvsSource) { this.cvsSource = cvsSource; }+ public void setDocs(URL[] docs) { this.docs = docs; }++ public void addDoc(URL doc)+ {+ if (doc == null) {+ // should throw runtime exception+ return;+ }+ if (docs != null) {+ URL[] newDocs = new URL[docs.length+1];+ int i;+ for (i = 0; i < docs.length; i++) {+ newDocs[i] = docs[i];+ }+ newDocs[i] = doc;+ docs = newDocs;+ } else {+ docs = new URL[1];+ docs[0] = doc;+ }+ }++ public void addDoc(String doc)+ {+ if (doc == null) {+ // should throw runtime exception+ return;+ }+ try {+ URL docURL = new URL(doc);+ addDoc(docURL);+ } catch (Exception e) {+ // ignore for now+ }+ }++ private String name;+ private String version;+ private String description;+ public String cvsId;+ public String cvsSource;+ public String cvsName;+ private URL[] docs;+}diff --git a/src/java/org/apache/solr/core/SolrInfoMBean.java b/src/java/org/apache/solr/core/SolrInfoMBean.javanew file mode 100644index 00000000000..ed8dba097d8--- /dev/null+++ b/src/java/org/apache/solr/core/SolrInfoMBean.java@@ -0,0 +1,52 @@+/**+ * 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.+ */++package org.apache.solr.core;++import java.net.URL;+import org.apache.solr.util.*;++/**+ * @author ronp+ * @version $Id: SolrInfoMBean.java,v 1.3 2005/05/04 19:15:23 ronp Exp $+ */++// MBean interface for getting various ui friendly strings and URLs+// for use by objects which are 'plugable' to make administering+// production use easier+ // name - simple common usage name, e.g. BasicQueryHandler+ // version - simple common usage version, e.g. 2.0+ // description - simple one or two line description+ // cvsId - yes, really the CVS Id (type 'man co')+ // cvsName - yes, really the CVS Name (type 'man co')+ // cvsSource - yes, really the CVS Source (type 'man co')+ // docs - URL list: TWIKI, Faq, Design doc, something! :)++public interface SolrInfoMBean {++ public enum Category { CORE, QUERYHANDLER, UPDATEHANDLER, CACHE, OTHER };++ public String getName();+ public String getVersion();+ public String getDescription();+ public Category getCategory();+ public String getCvsId();+ public String getCvsName();+ public String getCvsSource();+ public URL[] getDocs();+ public NamedList getStatistics();++}diff --git a/src/java/org/apache/solr/core/SolrInfoRegistry.java b/src/java/org/apache/solr/core/SolrInfoRegistry.javanew file mode 100644index 00000000000..bd61bc77c09--- /dev/null+++ b/src/java/org/apache/solr/core/SolrInfoRegistry.java@@ -0,0 +1,42 @@+/**+ * 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.+ */++package org.apache.solr.core;++import org.apache.solr.core.SolrInfoMBean;++import java.util.*;++/**+ * @author ronp+ * @version $Id: SolrInfoRegistry.java,v 1.5 2005/05/14 03:34:39 yonik Exp $+ */++// A Registry to hold a collection of SolrInfo objects++public class SolrInfoRegistry {+ public static final String cvsId="$Id: SolrInfoRegistry.java,v 1.5 2005/05/14 03:34:39 yonik Exp $";+ public static final String cvsSource="$Source: /cvs/main/searching/solr/solarcore/src/solr/SolrInfoRegistry.java,v $";+ public static final String cvsName="$Name: $";++ private static final Map<String,SolrInfoMBean> inst = Collections.synchronizedMap(new LinkedHashMap<String,SolrInfoMBean>());++ public static Map<String, SolrInfoMBean> getRegistry()+ {+ return inst;+ }++}diff --git a/src/java/org/apache/solr/request/LocalSolrQueryRequest.java b/src/java/org/apache/solr/request/LocalSolrQueryRequest.javanew file mode 100644index 00000000000..4de38a5d8b1--- /dev/null+++ b/src/java/org/apache/solr/request/LocalSolrQueryRequest.java@@ -0,0 +1,198 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.RefCounted;+import org.apache.solr.util.StrUtils;+import org.apache.solr.util.NamedList;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.core.SolrCore;++import java.util.Map;+import java.util.HashMap;++/**+ * @author yonik+ * @version $Id: LocalSolrQueryRequest.java,v 1.6 2005/06/02 22:03:38 yonik Exp $+ */+public class LocalSolrQueryRequest extends SolrQueryRequestBase {+ private final NamedList args;+ private final String query;+ private final String qtype;+ private final int start;+ private final int limit;++ public final static Map emptyArgs = new HashMap(0,1);++ public LocalSolrQueryRequest(SolrCore core, String query, String qtype, int start, int limit, Map args) {+ super(core);+ this.query=query;+ this.qtype=qtype;+ this.start=start;+ this.limit=limit;++ this.args = new NamedList();+ if (query!=null) this.args.add(SolrQueryRequestBase.QUERY_NAME, query);+ if (qtype!=null) this.args.add(SolrQueryRequestBase.QUERYTYPE_NAME, qtype);+ this.args.add(SolrQueryRequestBase.START_NAME, Integer.toString(start));+ this.args.add(SolrQueryRequestBase.ROWS_NAME, Integer.toString(limit));++ if (args!=null) this.args.addAll(args);+ }+++ public LocalSolrQueryRequest(SolrCore core, NamedList args) {+ super(core);+ this.args=args;+ this.query=getStrParam(QUERY_NAME,null);+ this.qtype=getStrParam(QUERYTYPE_NAME,null);;+ this.start=getIntParam(START_NAME,0);+ this.limit=getIntParam(ROWS_NAME,10);+ }+++ public String getParam(String name) {+ return (String)args.get(name);+ }++ public String getQueryString() {+ return query;+ }++ // signifies the syntax and the handler that should be used+ // to execute this query.+ public String getQueryType() {+ return qtype;+ }+++ // starting position in matches to return to client+ public int getStart() {+ return start;+ }++ // number of matching documents to return+ public int getLimit() {+ return limit;+ }++ final long startTime=System.currentTimeMillis();+ // Get the start time of this request in milliseconds+ public long getStartTime() {+ return startTime;+ }++ // The index searcher associated with this request+ RefCounted<SolrIndexSearcher> searcherHolder;+ public SolrIndexSearcher getSearcher() {+ // should this reach out and get a searcher from the core singleton, or+ // should the core populate one in a factory method to create requests?+ // or there could be a setSearcher() method that Solr calls++ if (searcherHolder==null) {+ searcherHolder = core.getSearcher();+ }++ return searcherHolder.get();+ }++ // The solr core (coordinator, etc) associated with this request+ public SolrCore getCore() {+ return core;+ }++ // The index schema associated with this request+ public IndexSchema getSchema() {+ return core.getSchema();+ }++ public String getParamString() {+ StringBuilder sb = new StringBuilder(128);+ try {++ boolean first=true;+ if (query!=null) {+ if (!first) {+ sb.append('&');+ }+ first=false;+ sb.append("q=");+ StrUtils.partialURLEncodeVal(sb,query);+ }++ // null, "", and "standard" are all the default query handler.+ if (qtype!=null && !(qtype.equals("") || qtype.equals("standard"))) {+ if (!first) {+ sb.append('&');+ }+ first=false;+ sb.append("qt=");+ sb.append(qtype);+ }++ if (start!=0) {+ if (!first) {+ sb.append('&');+ }+ first=false;+ sb.append("start=");+ sb.append(start);+ }++ if (!first) {+ sb.append('&');+ }+ first=false;+ sb.append("rows=");+ sb.append(limit);++ if (args != null && args.size() > 0) {+ for (int i=0; i<args.size(); i++) {+ if (!first) {+ sb.append('&');+ }+ first=false;++ sb.append(args.getName(i));+ sb.append('=');+ StrUtils.partialURLEncodeVal(sb,args.getVal(i).toString());+ }+ }++ } catch (Exception e) {+ // should never happen... we only needed this because+ // partialURLEncodeVal can throw an IOException, but it+ // never will when adding to a StringBuilder.+ throw new RuntimeException(e);+ }++ return sb.toString();+ }+++ public void close() {+ if (searcherHolder!=null) {+ searcherHolder.decref();+ }+ }++++}++diff --git a/src/java/org/apache/solr/request/QueryResponseWriter.java b/src/java/org/apache/solr/request/QueryResponseWriter.javanew file mode 100644index 00000000000..09022b8b7ff--- /dev/null+++ b/src/java/org/apache/solr/request/QueryResponseWriter.java@@ -0,0 +1,29 @@+/**+ * 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.+ */++package org.apache.solr.request;++import java.io.Writer;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id: QueryResponseWriter.java,v 1.2 2005/04/24 02:53:35 yonik Exp $+ */+public interface QueryResponseWriter {+ public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException;+}+diff --git a/src/java/org/apache/solr/request/SolrQueryRequest.java b/src/java/org/apache/solr/request/SolrQueryRequest.javanew file mode 100644index 00000000000..eb3531fe511--- /dev/null+++ b/src/java/org/apache/solr/request/SolrQueryRequest.java@@ -0,0 +1,65 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.core.SolrCore;++/**+ * @author yonik+ * @version $Id: SolrQueryRequest.java,v 1.3 2005/05/10 19:40:12 yonik Exp $+ */+public interface SolrQueryRequest {+ public String getParam(String name);++ public String getQueryString();++ // signifies the syntax and the handler that should be used+ // to execute this query.+ public String getQueryType();++ // starting position in matches to return to client+ public int getStart();++ // number of matching documents to return+ public int getLimit();++ // Get the start time of this request in milliseconds+ public long getStartTime();++ // The index searcher associated with this request+ public SolrIndexSearcher getSearcher();++ // The solr core (coordinator, etc) associated with this request+ public SolrCore getCore();++ // The index schema associated with this request+ public IndexSchema getSchema();++ /**+ * Returns a string representing all the important parameters.+ * Suitable for logging.+ */+ public String getParamString();++ /******+ // Get the current elapsed time in milliseconds+ public long getElapsedTime();+ ******/+}+diff --git a/src/java/org/apache/solr/request/SolrQueryRequestBase.java b/src/java/org/apache/solr/request/SolrQueryRequestBase.javanew file mode 100644index 00000000000..b5a940d345a--- /dev/null+++ b/src/java/org/apache/solr/request/SolrQueryRequestBase.java@@ -0,0 +1,130 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.RefCounted;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;++/**+* @author yonik+* @version $Id: SolrQueryRequestBase.java,v 1.6 2005/06/12 02:36:09 yonik Exp $+*/+public abstract class SolrQueryRequestBase implements SolrQueryRequest {+ // some standard query argument names+ public static final String QUERY_NAME="q";+ public static final String START_NAME="start";+ public static final String ROWS_NAME="rows";+ public static final String XSL_NAME="xsl";+ public static final String QUERYTYPE_NAME="qt";+++ protected final SolrCore core;++ public SolrQueryRequestBase(SolrCore core) {+ this.core=core;+ }++ public int getIntParam(String name) {+ String s = getParam(name);+ if (s==null) {+ throw new SolrException(500,"Missing required parameter '"+name+"' from " + this);+ }+ return Integer.parseInt(s);+ }++ public int getIntParam(String name, int defval) {+ String s = getParam(name);+ return s==null ? defval : Integer.parseInt(s);+ }++ public String getStrParam(String name) {+ String s = getParam(name);+ if (s==null) {+ throw new SolrException(500,"Missing required parameter '"+name+"' from " + this);+ }+ return s;+ }++ public String getStrParam(String name, String defval) {+ String s = getParam(name);+ return s==null ? defval : s;+ }++ public String getQueryString() {+ return getParam(QUERY_NAME);+ }++ public String getQueryType() {+ return getParam(QUERYTYPE_NAME);+ }++ // starting position in matches to return to client+ public int getStart() {+ return getIntParam(START_NAME, 0);+ }++ // number of matching documents to return+ public int getLimit() {+ return getIntParam(ROWS_NAME, 10);+ }+++ protected final long startTime=System.currentTimeMillis();+ // Get the start time of this request in milliseconds+ public long getStartTime() {+ return startTime;+ }++ // The index searcher associated with this request+ protected RefCounted<SolrIndexSearcher> searcherHolder;+ public SolrIndexSearcher getSearcher() {+ // should this reach out and get a searcher from the core singleton, or+ // should the core populate one in a factory method to create requests?+ // or there could be a setSearcher() method that Solr calls++ if (searcherHolder==null) {+ searcherHolder = core.getSearcher();+ }++ return searcherHolder.get();+ }++ // The solr core (coordinator, etc) associated with this request+ public SolrCore getCore() {+ return core;+ }++ // The index schema associated with this request+ public IndexSchema getSchema() {+ return core.getSchema();+ }+++ public void close() {+ if (searcherHolder!=null) {+ searcherHolder.decref();+ }+ }++ public String toString() {+ return this.getClass().getSimpleName() + '{' + getParamString() + '}';+ }++}diff --git a/src/java/org/apache/solr/request/SolrQueryResponse.java b/src/java/org/apache/solr/request/SolrQueryResponse.javanew file mode 100644index 00000000000..3b86f6aa7ec--- /dev/null+++ b/src/java/org/apache/solr/request/SolrQueryResponse.java@@ -0,0 +1,125 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.solr.util.NamedList;++import java.util.*;++/**+ * <code>SolrQueryResponse</code> is used by a query handler to return+ * the response to a query.+ * @author yonik+ * @version $Id: SolrQueryResponse.java,v 1.5 2005/08/10 04:27:04 yonik Exp $+ * @since solr 0.9+ */++public class SolrQueryResponse {++ protected NamedList values = new NamedList();+ // current holder for user defined values++ protected Set<String> defaultReturnFields;++ // error if this is set...+ protected Exception err;++ /***+ // another way of returning an error+ int errCode;+ String errMsg;+ ***/++ public NamedList getValues() { return values; }++ /**+ * Sets a list of all the named values to return.+ */+ public void setAllValues(NamedList nameValuePairs) {+ values=nameValuePairs;+ }++ /**+ * Sets the document field names of fields to return by default.+ */+ public void setReturnFields(Set<String> fields) {+ defaultReturnFields=fields;+ }+ // TODO: should this be represented as a String[] such+ // that order can be maintained if needed?++ /**+ * The document field names to return by default.+ */+ public Set<String> getReturnFields() {+ return defaultReturnFields;+ }+++ /**+ * Appends a named value to the list of named values to be returned.+ * @param name the name of the value - may be null if unnamed+ * @param val the value to add - also may be null since null is a legal value+ */+ public void add(String name, Object val) {+ values.add(name,val);+ }++ /**+ * Causes an error to be returned instead of the results.+ */+ public void setException(Exception e) {+ err=e;+ }++ /**+ * Returns an Exception if there was a fatal error in processing the request.+ * Returns null if the request succeeded.+ */+ public Exception getException() {+ return err;+ }++ // Get and Set the endtime in milliseconds... used+ // to calculate query time.+ protected long endtime;++ /** Time in milliseconds when the response officially finished.+ */+ public long getEndTime() {+ if (endtime==0) {+ setEndTime();+ }+ return endtime;+ }++ /**+ * Stop the timer for how long this query took.+ */+ public long setEndTime() {+ return setEndTime(System.currentTimeMillis());+ }++ public long setEndTime(long endtime) {+ if (endtime!=0) {+ this.endtime=endtime;+ }+ return this.endtime;+ }+++}diff --git a/src/java/org/apache/solr/request/SolrRequestHandler.java b/src/java/org/apache/solr/request/SolrRequestHandler.javanew file mode 100644index 00000000000..fcbd831d493--- /dev/null+++ b/src/java/org/apache/solr/request/SolrRequestHandler.java@@ -0,0 +1,63 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.solr.util.NamedList;+import org.apache.solr.core.SolrInfoMBean;++/**+ * Implementations of <code>SolrRequestHandler</code> are called to handle query requests.+ *+ * Different <code>SolrRequestHandler</code>s are registered with the <code>SolrCore</code>.+ * One way to register a SolrRequestHandler with the core is thorugh the <code>solarconfig.xml</code> file.+ * <p>+ * Example <code>solarconfig.xml</code> entry to register a <code>SolrRequestHandler</code> implementation to+ * handle all queries with a query type of "test":+ * <p>+ * <code>+ * <requestHandler name="test" class="solr.tst.TestRequestHandler" />+ * </code>+ * <p>+ * A single instance of any registered SolrRequestHandler is created+ * via the default constructor and is reused for all relevant queries.+ *+ * @author yonik+ * @version $Id: SolrRequestHandler.java,v 1.7 2005/12/02 04:31:06 yonik Exp $+ */+public interface SolrRequestHandler extends SolrInfoMBean {++ /** <code>init</code> will be called just once, immediately after creation.+ * <p>The args are user-level initialization parameters that+ * may be specified when declaring a request handler in+ * solarconfig.xml+ */+ public void init(NamedList args);+++ /**+ * Handles a query request. This method must be thread safe.+ * <p>+ * Information about the request may be obtained from <code>req</code> and+ * response information may be set using <code>rsp</code>.+ * <p>+ * There are no mandatory actions that handleRequest must perform.+ * An empty handleRequest implementation would fulfill+ * all interface obligations.+ */+ public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp);+}+diff --git a/src/java/org/apache/solr/request/StandardRequestHandler.java b/src/java/org/apache/solr/request/StandardRequestHandler.javanew file mode 100644index 00000000000..22442236ebc--- /dev/null+++ b/src/java/org/apache/solr/request/StandardRequestHandler.java@@ -0,0 +1,225 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.lucene.search.*;+import org.apache.lucene.document.Document;++import java.util.List;+import java.util.Set;+import java.util.HashSet;+import java.util.logging.Level;+import java.util.regex.Pattern;+import java.io.IOException;+import java.net.URL;++import org.apache.solr.util.StrUtils;+import org.apache.solr.util.NamedList;+import org.apache.solr.search.*;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrInfoMBean;+import org.apache.solr.core.SolrException;++/**+ * @author yonik+ * @version $Id: StandardRequestHandler.java,v 1.17 2005/12/02 04:31:06 yonik Exp $+ */+public class StandardRequestHandler implements SolrRequestHandler, SolrInfoMBean {++ // statistics+ // TODO: should we bother synchronizing these, or is an off-by-one error+ // acceptable every million requests or so?+ long numRequests;+ long numErrors;+++ public void init(NamedList args) {+ SolrCore.log.log(Level.INFO, "Unused request handler arguments:" + args);+ }+++ private final Pattern splitList=Pattern.compile(",| ");++ public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {+ numRequests++;+++ // TODO: test if lucene will accept an escaped ';', otherwise+ // we need to un-escape them before we pass to QueryParser+ try {+ String sreq = req.getQueryString();+ String debug = req.getParam("debugQuery");++ // find fieldnames to return (fieldlist)+ String fl = req.getParam("fl");+ int flags=0;+ if (fl != null) {+ // TODO - this could become more efficient if widely used.+ // TODO - should field order be maintained?+ String[] flst = splitList.split(fl,0);+ if (flst.length > 0 && !(flst.length==1 && flst[0].length()==0)) {+ Set<String> set = new HashSet<String>();+ for (String fname : flst) {+ if ("score".equals(fname)) flags |= SolrIndexSearcher.GET_SCORES;+ set.add(fname);+ }+ rsp.setReturnFields(set);+ }+ }++ if (sreq==null) throw new SolrException(400,"Missing queryString");+ List<String> commands = StrUtils.splitSmart(sreq,';');++ String qs = commands.size() >= 1 ? commands.get(0) : "";+ Query query = QueryParsing.parseQuery(qs, req.getSchema());++ // If the first non-query, non-filter command is a simple sort on an indexed field, then+ // we can use the Lucene sort ability.+ Sort sort = null;+ if (commands.size() >= 2) {+ QueryParsing.SortSpec sortSpec = QueryParsing.parseSort(commands.get(1), req.getSchema());+ if (sortSpec != null) {+ sort = sortSpec.getSort();+ // ignore the count for now... it's currently only controlled by start & limit on req+ // count = sortSpec.getCount();+ }+ }++ DocList results = req.getSearcher().getDocList(query, null, sort, req.getStart(), req.getLimit(), flags);+ rsp.add(null,results);++ if (debug!=null) {+ NamedList dbg = new NamedList();+ try {+ dbg.add("querystring",qs);+ dbg.add("parsedquery",QueryParsing.toString(query,req.getSchema()));+ dbg.add("explain", getExplainList(query, results, req.getSearcher(), req.getSchema()));+ String otherQueryS = req.getParam("explainOther");+ if (otherQueryS != null && otherQueryS.length() > 0) {+ DocList otherResults = doQuery(otherQueryS,req.getSearcher(), req.getSchema(),0,10);+ dbg.add("otherQuery",otherQueryS);+ dbg.add("explainOther", getExplainList(query, otherResults, req.getSearcher(), req.getSchema()));+ }+ } catch (Exception e) {+ SolrException.logOnce(SolrCore.log,"Exception during debug:",e);+ dbg.add("exception_during_debug", SolrException.toStr(e));+ }+ rsp.add("debug",dbg);+ }++ } catch (SolrException e) {+ rsp.setException(e);+ numErrors++;+ return;+ } catch (Exception e) {+ SolrException.log(SolrCore.log,e);+ rsp.setException(e);+ numErrors++;+ return;+ }+ }++ private NamedList getExplainList(Query query, DocList results, SolrIndexSearcher searcher, IndexSchema schema) throws IOException {+ NamedList explainList = new NamedList();+ DocIterator iterator = results.iterator();+ for (int i=0; i<results.size(); i++) {+ int id = iterator.nextDoc();++ Explanation explain = searcher.explain(query, id);+ //explainList.add(Integer.toString(id), explain.toString().split("\n"));++ Document doc = searcher.doc(id);+ String strid = schema.printableUniqueKey(doc);+ String docname = "";+ if (strid != null) docname="id="+strid+",";+ docname = docname + "internal_docid="+id;++ explainList.add(docname, "\n" +explain.toString());+ }+ return explainList;+ }+++ private DocList doQuery(String sreq, SolrIndexSearcher searcher, IndexSchema schema, int start, int limit) throws IOException {+ List<String> commands = StrUtils.splitSmart(sreq,';');++ String qs = commands.size() >= 1 ? commands.get(0) : "";+ Query query = QueryParsing.parseQuery(qs, schema);++ // If the first non-query, non-filter command is a simple sort on an indexed field, then+ // we can use the Lucene sort ability.+ Sort sort = null;+ if (commands.size() >= 2) {+ QueryParsing.SortSpec sortSpec = QueryParsing.parseSort(commands.get(1), schema);+ if (sortSpec != null) {+ sort = sortSpec.getSort();+ if (sortSpec.getCount() >= 0) {+ limit = sortSpec.getCount();+ }+ }+ }++ DocList results = searcher.getDocList(query,(DocSet)null, sort, start, limit);+ return results;+ }++++ //////////////////////// SolrInfoMBeans methods //////////////////////+++ public String getName() {+ return StandardRequestHandler.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "The standard Solr request handler";+ }++ public Category getCategory() {+ return Category.QUERYHANDLER;+ }++ public String getCvsId() {+ return "$Id: StandardRequestHandler.java,v 1.17 2005/12/02 04:31:06 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/StandardRequestHandler.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }++ public NamedList getStatistics() {+ NamedList lst = new NamedList();+ lst.add("requests", numRequests);+ lst.add("errors", numErrors);+ return lst;+ }+}+diff --git a/src/java/org/apache/solr/request/XMLResponseWriter.java b/src/java/org/apache/solr/request/XMLResponseWriter.javanew file mode 100644index 00000000000..a41a25f0fab--- /dev/null+++ b/src/java/org/apache/solr/request/XMLResponseWriter.java@@ -0,0 +1,33 @@+/**+ * 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.+ */++package org.apache.solr.request;++import java.io.Writer;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id: XMLResponseWriter.java,v 1.6 2005/04/24 02:53:35 yonik Exp $+ */++public class XMLResponseWriter implements QueryResponseWriter {+ public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {+ XMLWriter.writeResponse(writer,req,rsp);+ }+}++diff --git a/src/java/org/apache/solr/request/XMLWriter.java b/src/java/org/apache/solr/request/XMLWriter.javanew file mode 100644index 00000000000..b5ad05a2022--- /dev/null+++ b/src/java/org/apache/solr/request/XMLWriter.java@@ -0,0 +1,620 @@+/**+ * 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.+ */++package org.apache.solr.request;++import org.apache.solr.util.NamedList;+import org.apache.solr.util.XML;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.search.DocList;+import org.apache.solr.search.DocIterator;+import org.apache.solr.search.DocSet;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;++import java.io.Writer;+import java.io.IOException;+import java.util.*;++import org.apache.lucene.document.Field;+import org.apache.lucene.document.Document;+/**+ * @author yonik+ * @version $Id: XMLWriter.java,v 1.16 2005/12/02 04:31:06 yonik Exp $+ */+final public class XMLWriter {+ //+ // static thread safe part+ //+ private static final char[] XML_START1="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".toCharArray();++ private static final char[] XML_STYLESHEET="<?xml-stylesheet type=\"text/xsl\" href=\"/admin/".toCharArray();+ private static final char[] XML_STYLESHEET_END=".xsl\"?>\n".toCharArray();++ private static final char[] XML_START2_SCHEMA=(+ "<response xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"+ +" xsi:noNamespaceSchemaLocation=\"http://pi.cnet.com/cnet-search/response.xsd\">\n"+ ).toCharArray();+ private static final char[] XML_START2_NOSCHEMA=(+ "<response>\n"+ ).toCharArray();+++ public static void writeResponse(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {++ // get total time up until now+ int qtime=(int)(rsp.getEndTime() - req.getStartTime());++ String ver = req.getParam("version");++ writer.write(XML_START1);++ String stylesheet = req.getParam("stylesheet");+ if (stylesheet != null && stylesheet.length() > 0) {+ writer.write(XML_STYLESHEET);+ writer.write(stylesheet);+ writer.write(XML_STYLESHEET_END);+ }++ String noSchema = req.getParam("noSchema");+ // todo - change when schema becomes available?+ if (false && noSchema == null)+ writer.write(XML_START2_SCHEMA);+ else+ writer.write(XML_START2_NOSCHEMA);++ writer.write("<responseHeader><status>");+ writer.write('0'); // it's 0 (success) if we got this far...+ writer.write("</status><QTime>");+ writer.write(Integer.toString((int)qtime));+ writer.write("</QTime></responseHeader>\n");++ //+ // create an instance for each request to handle+ // non-thread safe stuff (indentation levels, etc)+ // and to encapsulate writer, schema, and searcher so+ // they don't have to be passed around in every function.+ //+ XMLWriter xw = new XMLWriter(writer, req.getSchema(), req.getSearcher(), ver);+ xw.defaultFieldList = rsp.getReturnFields();++ String indent = req.getParam("indent");+ if (indent != null) {+ if ("".equals(indent) || "off".equals(indent)) {+ xw.setIndent(false);+ } else {+ xw.setIndent(true);+ }+ }++ NamedList lst = rsp.getValues();+ int sz = lst.size();+ for (int i=0; i<sz; i++) {+ xw.writeVal(lst.getName(i),lst.getVal(i));+ }++ writer.write("\n</response>\n");+ }+++ ////////////////////////////////////////////////////////////+ // request instance specific (non-static, not shared between threads)+ ////////////////////////////////////////////////////////////++ private final Writer writer;+ private final IndexSchema schema; // needed to write fields of docs+ private final SolrIndexSearcher searcher; // needed to retrieve docs++ private int level;+ private boolean defaultIndent=false;+ private boolean doIndent=false;++ // fieldList... the set of fields to return for each document+ private Set<String> defaultFieldList;+++ // if a list smaller than this threshold is encountered, elements+ // will be written on the same line.+ // maybe constructed types should always indent first?+ private final int indentThreshold=0;++ private final int version;+++ // temporary working objects...+ // be careful not to use these recursively...+ private final ArrayList tlst = new ArrayList();+ private final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));+ private final StringBuilder sb = new StringBuilder();++ XMLWriter(Writer writer, IndexSchema schema, SolrIndexSearcher searcher, String version) {+ this.writer = writer;+ this.schema = schema;+ this.searcher = searcher;+ float ver = version==null? 2.1f : Float.parseFloat(version);+ this.version = (int)(ver*1000);+ }++ //+ // Functions to manipulate the current logical nesting level.+ // Any indentation will be partially based on level.+ //+ public void setLevel(int level) { this.level = level; }+ public int level() { return level; }+ public int incLevel() { return ++level; }+ public int decLevel() { return --level; }+ public void setIndent(boolean doIndent) {+ this.doIndent = doIndent;+ defaultIndent = doIndent;+ }++ public void writeAttr(String name, String val) throws IOException {+ if (val != null) {+ writer.write(' ');+ writer.write(name);+ writer.write("=\"");+ writer.write(val);+ writer.write('"');+ }+ }++ public void startTag(String tag, String name, boolean closeTag) throws IOException {+ if (doIndent) indent();++ writer.write('<');+ writer.write(tag);+ if (name!=null) {+ writer.write(" name=\"");+ writer.write(name);+ if (closeTag) {+ writer.write("\"/>");+ } else {+ writer.write("\">");+ }+ } else {+ if (closeTag) {+ writer.write("/>");+ } else {+ writer.write('>');+ }+ }+ }++ private static final String[] indentArr = new String[] {+ "\n",+ "\n ",+ "\n ",+ "\n\t",+ "\n\t ",+ "\n\t ", // could skip this one (the only 3 char seq)+ "\n\t\t" };++ public void indent() throws IOException {+ indent(level);+ }++ public void indent(int lev) throws IOException {+ int arrsz = indentArr.length-1;+ // another option would be lev % arrsz (wrap around)+ String istr = indentArr[ lev > arrsz ? arrsz : lev ];+ writer.write(istr);+ }++ private static final Comparator fieldnameComparator = new Comparator() {+ public int compare(Object o, Object o1) {+ Field f1 = (Field)o; Field f2 = (Field)o1;+ int cmp = f1.name().compareTo(f2.name());+ return cmp;+ // note - the sort is stable, so this should not have affected the ordering+ // of fields with the same name w.r.t eachother.+ }+ };++ public final void writeDoc(String name, Document doc, Set<String> returnFields, float score, boolean includeScore) throws IOException {+ startTag("doc", name, false);+ incLevel();++ if (includeScore) {+ writeFloat("score", score);+ }+++ // Lucene Documents have multivalued types as multiple fields+ // with the same name.+ // The XML needs to represent these as+ // an array. The fastest way to detect multiple fields+ // with the same name is to sort them first.++ Enumeration ee = doc.fields();++ // using global tlst here, so we shouldn't call any other+ // function that uses it until we are done.+ tlst.clear();+ while (ee.hasMoreElements()) {+ Field ff = (Field) ee.nextElement();+ // skip this field if it is not a field to be returned.+ if (returnFields!=null && !returnFields.contains(ff.name())) {+ continue;+ }+ tlst.add(ff);+ }+ Collections.sort(tlst, fieldnameComparator);++ int sz = tlst.size();+ int fidx1 = 0, fidx2 = 0;+ while (fidx1 < sz) {+ Field f1 = (Field)tlst.get(fidx1);+ String fname = f1.name();++ // find the end of fields with this name+ fidx2 = fidx1+1;+ while (fidx2 < sz && fname.equals(((Field)tlst.get(fidx2)).name()) ) {+ fidx2++;+ }++ /***+ // more efficient to use getFieldType instead of+ // getField since that way dynamic fields won't have+ // to create a SchemaField on the fly.+ FieldType ft = schema.getFieldType(fname);+ ***/++ SchemaField sf = schema.getField(fname);++ if (fidx1+1 == fidx2) {+ // single field value+ if (version>=2100 && sf.multiValued()) {+ startTag("arr",fname,false);+ doIndent=false;+ sf.write(this, null, f1);+ writer.write("</arr>");+ doIndent=defaultIndent;+ } else {+ sf.write(this, f1.name(), f1);+ }+ } else {+ // multiple fields with same name detected++ startTag("arr",fname,false);+ incLevel();+ doIndent=false;+ int cnt=0;+ for (int i=fidx1; i<fidx2; i++) {+ if (defaultIndent && ++cnt==4) { // only indent every 4th item+ indent();+ cnt=0;+ }+ sf.write(this, null, (Field)tlst.get(i));+ }+ decLevel();+ // if (doIndent) indent();+ writer.write("</arr>");+ // doIndent=true;+ doIndent=defaultIndent;+ }+ fidx1 = fidx2;+ }++ decLevel();+ if (doIndent) indent();+ writer.write("</doc>");+ }++ public final void writeDocList(String name, DocList ids, Set<String> fields) throws IOException {+ boolean includeScore=false;+ if (fields!=null) {+ includeScore = fields.contains("score");+ if (fields.size()==0 || (fields.size()==1 && includeScore) || fields.contains("*")) {+ fields=null; // null means return all stored fields+ }+ }++ int sz=ids.size();++ if (doIndent) indent();+ writer.write("<result");+ writeAttr("name",name);+ writeAttr("numFound",Integer.toString(ids.matches()));+ writeAttr("start",Integer.toString(ids.offset()));+ if (includeScore) {+ writeAttr("maxScore",Float.toString(ids.maxScore()));+ }+ if (sz==0) {+ writer.write("/>");+ return;+ } else {+ writer.write('>');+ }++ incLevel();+ DocIterator iterator = ids.iterator();+ for (int i=0; i<sz; i++) {+ int id = iterator.nextDoc();+ Document doc = searcher.doc(id);+ writeDoc(null, doc, fields, (includeScore ? iterator.score() : 0.0f), includeScore);+ }+ decLevel();++ if (doIndent) indent();+ writer.write("</result>");+ }+++ public void writeVal(String name, Object val) throws IOException {++ // if there get to be enough types, perhaps hashing on the type+ // to get a handler might be faster (but types must be exact to do that...)++ // go in order of most common to least common+ if (val==null) {+ writeNull(name);+ } else if (val instanceof String) {+ writeStr(name, (String)val);+ } else if (val instanceof Integer) {+ // it would be slower to pass the int ((Integer)val).intValue()+ writeInt(name, val.toString());+ } else if (val instanceof Boolean) {+ // could be optimized... only two vals+ writeBool(name, val.toString());+ } else if (val instanceof Long) {+ writeLong(name, val.toString());+ } else if (val instanceof Date) {+ writeDate(name,(Date)val);+ } else if (val instanceof Float) {+ // we pass the float instead of using toString() because+ // it may need special formatting. same for double.+ writeFloat(name, ((Float)val).floatValue());+ } else if (val instanceof Double) {+ writeDouble(name, ((Double)val).doubleValue());+ } else if (val instanceof Document) {+ writeDoc(name, (Document)val, null, 0.0f, false);+ } else if (val instanceof DocList) {+ // requires access to IndexReader+ writeDocList(name, (DocList)val, defaultFieldList);+ } else if (val instanceof DocSet) {+ // how do we know what fields to read?+ // todo: have a DocList/DocSet wrapper that+ // restricts the fields to write...?+ } else if (val instanceof Map) {+ writeMap(name, (Map)val);+ } else if (val instanceof NamedList) {+ writeNamedList(name, (NamedList)val);+ } else if (val instanceof Collection) {+ writeArray(name,(Collection)val);+ } else if (val instanceof Object[]) {+ writeArray(name,(Object[])val);+ } else {+ // default...+ writeStr(name, val.getClass().getName() + ':' + val.toString());+ }+ }++ //+ // Generic compound types+ //++ public void writeNamedList(String name, NamedList val) throws IOException {+ int sz = val.size();+ startTag("lst", name, sz<=0);++ if (sz<indentThreshold) {+ doIndent=false;+ }++ incLevel();+ for (int i=0; i<sz; i++) {+ writeVal(val.getName(i),val.getVal(i));+ }+ decLevel();++ if (sz > 0) {+ if (doIndent) indent();+ writer.write("</lst>");+ }+ }++++ //A map is currently represented as a named list+ public void writeMap(String name, Map val) throws IOException {+ Map map = val;+ int sz = map.size();+ startTag("lst", name, sz<=0);+ incLevel();+ for (Map.Entry entry : (Set<Map.Entry>)map.entrySet()) {+ // possible class-cast exception here...+ String k = (String)entry.getKey();+ Object v = entry.getValue();+ // if (sz<indentThreshold) indent();+ writeVal(k,v);+ }+ decLevel();+ if (sz > 0) {+ if (doIndent) indent();+ writer.write("</lst>");+ }+ }++ public void writeArray(String name, Object[] val) throws IOException {+ writeArray(name, Arrays.asList(val));+ }++ public void writeArray(String name, Collection val) throws IOException {+ int sz = val.size();+ startTag("arr", name, sz<=0);+ incLevel();+ for (Object o : val) {+ // if (sz<indentThreshold) indent();+ writeVal(null, o);+ }+ decLevel();+ if (sz > 0) {+ if (doIndent) indent();+ writer.write("</arr>");+ }+ }++ //+ // Primitive types+ //++ public void writeNull(String name) throws IOException {+ writePrim("null",name,"",false);+ }++ public void writeStr(String name, String val) throws IOException {+ writePrim("str",name,val,true);+ }++ public void writeInt(String name, String val) throws IOException {+ writePrim("int",name,val,false);+ }++ public void writeInt(String name, int val) throws IOException {+ writeInt(name,Integer.toString(val));+ }++ public void writeLong(String name, String val) throws IOException {+ writePrim("long",name,val,false);+ }++ public void writeLong(String name, long val) throws IOException {+ writeLong(name,Long.toString(val));+ }++ public void writeBool(String name, String val) throws IOException {+ writePrim("bool",name,val,false);+ }++ public void writeBool(String name, boolean val) throws IOException {+ writeBool(name,Boolean.toString(val));+ }++ public void writeFloat(String name, String val) throws IOException {+ writePrim("float",name,val,false);+ }++ public void writeFloat(String name, float val) throws IOException {+ writeFloat(name,Float.toString(val));+ }++ public void writeDouble(String name, String val) throws IOException {+ writePrim("double",name,val,false);+ }++ public void writeDouble(String name, double val) throws IOException {+ writeDouble(name,Double.toString(val));+ }++ public void writeDate(String name, Date val) throws IOException {+ // using a stringBuilder for numbers can be nice since+ // a temporary string isn't used (it's added directly to the+ // builder's buffer.++ cal.setTime(val);++ sb.setLength(0);+ int i = cal.get(Calendar.YEAR);+ sb.append(i);+ sb.append('-');+ i = cal.get(Calendar.MONTH) + 1; // 0 based, so add 1+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append('-');+ i=cal.get(Calendar.DAY_OF_MONTH);+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append('T');+ i=cal.get(Calendar.HOUR_OF_DAY); // 24 hour time format+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append(':');+ i=cal.get(Calendar.MINUTE);+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append(':');+ i=cal.get(Calendar.SECOND);+ if (i<10) sb.append('0');+ sb.append(i);+ i=cal.get(Calendar.MILLISECOND);+ if (i != 0) {+ sb.append('.');+ if (i<100) sb.append('0');+ if (i<10) sb.append('0');+ sb.append(i);++ // handle canonical format specifying fractional+ // seconds shall not end in '0'. Given the slowness of+ // integer div/mod, simply checking the last character+ // is probably the fastest way to check.+ int lastIdx = sb.length()-1;+ if (sb.charAt(lastIdx)=='0') {+ lastIdx--;+ if (sb.charAt(lastIdx)=='0') {+ lastIdx--;+ }+ sb.setLength(lastIdx+1);+ }++ }+ sb.append('Z');+ writeDate(name, sb.toString());+ }++ public void writeDate(String name, String val) throws IOException {+ writePrim("date",name,val,false);+ }+++ //+ // OPT - specific writeInt, writeFloat, methods might be faster since+ // there would be less write calls (write("<int name=\"" + name + ... + </int>)+ //+ public void writePrim(String tag, String name, String val, boolean escape) throws IOException {+ // OPT - we could use a temp char[] (or a StringBuilder) and if the+ // size was small enough to fit (if escape==false we can calc exact size)+ // then we could put things directly in the temp buf.+ // need to see what percent of CPU this takes up first though...+ // Could test a reusable StringBuilder...++ // is this needed here???+ // Only if a fieldtype calls writeStr or something+ // with a null val instead of calling writeNull+ /***+ if (val==null) {+ if (name==null) writer.write("<null/>");+ else writer.write("<null name=\"" + name + "/>");+ }+ ***/++ int contentLen=val.length();++ startTag(tag, name, contentLen==0);+ if (contentLen==0) return;++ if (escape) {+ XML.escapeCharData(val,writer);+ } else {+ writer.write(val,0,contentLen);+ }++ writer.write("</");+ writer.write(tag);+ writer.write('>');+ }+++}diff --git a/src/java/org/apache/solr/schema/BCDIntField.java b/src/java/org/apache/solr/schema/BCDIntField.javanew file mode 100644index 00000000000..f3a41029626--- /dev/null+++ b/src/java/org/apache/solr/schema/BCDIntField.java@@ -0,0 +1,60 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.document.Field;+import org.apache.solr.util.BCDUtils;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class BCDIntField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ throw new UnsupportedOperationException("ValueSource not implemented");+ }++ public String toInternal(String val) {+ return BCDUtils.base10toBase10kSortableInt(val);+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public String indexedToReadable(String indexedForm) {+ return BCDUtils.base10kSortableIntToBase10(indexedForm);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeInt(name,toExternal(f));+ }+}++diff --git a/src/java/org/apache/solr/schema/BCDLongField.java b/src/java/org/apache/solr/schema/BCDLongField.javanew file mode 100644index 00000000000..2716f9657a0--- /dev/null+++ b/src/java/org/apache/solr/schema/BCDLongField.java@@ -0,0 +1,31 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.solr.request.XMLWriter;+import org.apache.lucene.document.Field;++import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class BCDLongField extends BCDIntField {+ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeLong(name,toExternal(f));+ }+}diff --git a/src/java/org/apache/solr/schema/BCDStrField.java b/src/java/org/apache/solr/schema/BCDStrField.javanew file mode 100644index 00000000000..bf41f1832b6--- /dev/null+++ b/src/java/org/apache/solr/schema/BCDStrField.java@@ -0,0 +1,31 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.solr.request.XMLWriter;+import org.apache.lucene.document.Field;++import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class BCDStrField extends BCDIntField {+ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeStr(name,toExternal(f));+ }+}diff --git a/src/java/org/apache/solr/schema/BoolField.java b/src/java/org/apache/solr/schema/BoolField.javanew file mode 100644index 00000000000..c4665ebbd46--- /dev/null+++ b/src/java/org/apache/solr/schema/BoolField.java@@ -0,0 +1,97 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.OrdFieldSource;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.Tokenizer;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.Reader;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class BoolField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new OrdFieldSource(field.name);+ }++ // avoid instantiating every time...+ protected final static Token TRUE_TOKEN = new Token("T",0,1);+ protected final static Token FALSE_TOKEN = new Token("F",0,1);++ ////////////////////////////////////////////////////////////////////////+ // TODO: look into creating my own queryParser that can more efficiently+ // handle single valued non-text fields (int,bool,etc) if needed.+++ protected final static Analyzer boolAnalyzer = new Analyzer() {+ public TokenStream tokenStream(String fieldName, Reader reader) {+ return new Tokenizer(reader) {+ boolean done=false;+ public Token next() throws IOException {+ if (done) return null;+ done=true;+ int ch = input.read();+ if (ch==-1) return null;+ return (ch=='t' || ch=='T' || ch=='1') ? TRUE_TOKEN : FALSE_TOKEN;+ }+ };+ }+ };++ public Analyzer getAnalyzer() {+ return boolAnalyzer;+ }++ public Analyzer getQueryAnalyzer() {+ return boolAnalyzer;+ }++ public String toInternal(String val) {+ char ch = (val!=null && val.length()>0) ? val.charAt(0) : 0;+ return (ch=='1' || ch=='t' || ch=='T') ? "T" : "F";+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public String indexedToReadable(String indexedForm) {+ char ch = indexedForm.charAt(0);+ return ch=='T' ? "true" : "false";+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeBool(name, f.stringValue().charAt(0) =='T');+ }+}diff --git a/src/java/org/apache/solr/schema/DateField.java b/src/java/org/apache/solr/schema/DateField.javanew file mode 100644index 00000000000..f7e38551185--- /dev/null+++ b/src/java/org/apache/solr/schema/DateField.java@@ -0,0 +1,94 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.solr.core.SolrException;+import org.apache.solr.request.XMLWriter;+import org.apache.lucene.document.Field;+import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.OrdFieldSource;++import java.util.Map;+import java.io.IOException;++/***+Date Format for the XML, incoming and outgoing:++A date field shall be of the form 1995-12-31T23:59:59Z+The trailing "Z" designates UTC time and is mandatory.+Optional fractional seconds are allowed: 1995-12-31T23:59:59.999Z+All other parts are mandatory.++This format was derived to be standards compliant (ISO 8601) and is a more+restricted form of the canonical representation of dateTime from XML schema part 2.+http://www.w3.org/TR/xmlschema-2/#dateTime++"In 1970 the Coordinated Universal Time system was devised by an international+advisory group of technical experts within the International Telecommunication+Union (ITU). The ITU felt it was best to designate a single abbreviation for+use in all languages in order to minimize confusion. Since unanimous agreement+could not be achieved on using either the English word order, CUT, or the+French word order, TUC, the acronym UTC was chosen as a compromise."+***/++// The XML (external) date format will sort correctly, except if+// fractions of seconds are present (because '.' is lower than 'Z').+// The easiest fix is to simply remove the 'Z' for the internal+// format.++// TODO: make a FlexibleDateField that can accept dates in multiple+// formats, better for human entered dates.++// TODO: make a DayField that only stores the day?++/**+ * @author yonik+ * @version $Id$+ */+public class DateField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public String toInternal(String val) {+ int len=val.length();+ if (val.charAt(len-1)=='Z') {+ return val.substring(0,len-1);+ }+ throw new SolrException(1,"Invalid Date String:'" +val+'\'');+ }++ public String indexedToReadable(String indexedForm) {+ return indexedForm + 'Z';+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new OrdFieldSource(field.name);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeDate(name, toExternal(f));+ }+}diff --git a/src/java/org/apache/solr/schema/DoubleField.java b/src/java/org/apache/solr/schema/DoubleField.javanew file mode 100644index 00000000000..b54cc289eec--- /dev/null+++ b/src/java/org/apache/solr/schema/DoubleField.java@@ -0,0 +1,50 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.FloatFieldSource;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class DoubleField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ restrictProps(SORT_MISSING_FIRST | SORT_MISSING_LAST);+ }++ /////////////////////////////////////////////////////////////+ // TODO: ACK.. there is currently no SortField.DOUBLE!+ public SortField getSortField(SchemaField field,boolean reverse) {+ return new SortField(field.name,SortField.FLOAT, reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ // fieldCache doesn't support double+ return new FloatFieldSource(field.name);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeDouble(name, f.stringValue());+ }+}diff --git a/src/java/org/apache/solr/schema/FieldProperties.java b/src/java/org/apache/solr/schema/FieldProperties.javanew file mode 100644index 00000000000..57dff753888--- /dev/null+++ b/src/java/org/apache/solr/schema/FieldProperties.java@@ -0,0 +1,144 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import java.util.Map;+import java.util.HashMap;++/**+ * @author yonik+ * @version $Id$+ */+abstract class FieldProperties {++ // use a bitfield instead of many different boolean variables since+ // many of the variables are independent or semi-independent.++ // bit values for boolean field properties.+ final static int INDEXED = 0x00000001;+ final static int TOKENIZED = 0x00000002;+ final static int STORED = 0x00000004;+ final static int BINARY = 0x00000008;+ final static int COMPRESSED = 0x00000010;+ final static int OMIT_NORMS = 0x00000020;+ final static int STORE_TERMVECTORS = 0x00000040;+ final static int STORE_TERMPOSITIONS = 0x00000080;+ final static int STORE_TERMOFFSETS = 0x00000100;++ final static int MULTIVALUED = 0x00000200;+ final static int SORT_MISSING_FIRST = 0x00000400;+ final static int SORT_MISSING_LAST = 0x00000800;++ static final String[] propertyNames = {+ "indexed", "tokenized", "stored",+ "binary", "compressed", "omitNorms",+ "termVectors", "termPositions", "termOffsets",+ "multiValued",+ "sortMissingFirst","sortMissingLast"+ };++ static final Map<String,Integer> propertyMap = new HashMap<String,Integer>();+ static {+ for (String prop : propertyNames) {+ propertyMap.put(prop, propertyNameToInt(prop));+ }+ }+++ /** Returns the symbolic name for the property. */+ static String getPropertyName(int property) {+ return propertyNames[ Integer.numberOfTrailingZeros(property) ];+ }++ static int propertyNameToInt(String name) {+ for (int i=0; i<propertyNames.length; i++) {+ if (propertyNames[i].equals(name)) {+ return 1 << i;+ }+ }+ return 0;+ }+++ static String propertiesToString(int properties) {+ StringBuilder sb = new StringBuilder();+ boolean first=true;+ while (properties != 0) {+ if (!first) sb.append(',');+ first=false;+ int bitpos = Integer.numberOfTrailingZeros(properties);+ sb.append(getPropertyName(1 << bitpos));+ properties &= ~(1<<bitpos); // clear that bit position+ }+ return sb.toString();+ }++ static boolean on(int bitfield, int props) {+ return (bitfield & props) != 0;+ }++ static boolean off(int bitfield, int props) {+ return (bitfield & props) == 0;+ }++ /***+ static int normalize(int properties) {+ int p = properties;+ if (on(p,TOKENIZED) && off(p,INDEXED)) {+ throw new RuntimeException("field must be indexed to be tokenized.");+ }++ if (on(p,STORE_TERMPOSITIONS)) p|=STORE_TERMVECTORS;+ if (on(p,STORE_TERMOFFSETS)) p|=STORE_TERMVECTORS;+ if (on(p,STORE_TERMOFFSETS) && off(p,INDEXED)) {+ throw new RuntimeException("field must be indexed to store term vectors.");+ }++ if (on(p,OMIT_NORMS) && off(p,INDEXED)) {+ throw new RuntimeException("field must be indexed for norms to be omitted.");+ }++ if (on(p,SORT_MISSING_FIRST) && on(p,SORT_MISSING_LAST)) {+ throw new RuntimeException("conflicting options sortMissingFirst,sortMissingLast.");+ }++ if ((on(p,SORT_MISSING_FIRST) || on(p,SORT_MISSING_LAST)) && off(p,INDEXED)) {+ throw new RuntimeException("field must be indexed to be sorted.");+ }++ if ((on(p,BINARY) || on(p,COMPRESSED)) && off(p,STORED)) {+ throw new RuntimeException("field must be stored for compressed or binary options.");+ }++ return p;+ }+ ***/+++ static int parseProperties(Map<String,String> properties, boolean which) {+ int props = 0;+ for (String prop : properties.keySet()) {+ if (propertyMap.get(prop)==null) continue;+ String val = properties.get(prop);+ if (Boolean.parseBoolean(val) == which) {+ props |= propertyNameToInt(prop);+ }+ }+ return props;+ }++}diff --git a/src/java/org/apache/solr/schema/FieldType.java b/src/java/org/apache/solr/schema/FieldType.javanew file mode 100644index 00000000000..3fcc1434b47--- /dev/null+++ b/src/java/org/apache/solr/schema/FieldType.java@@ -0,0 +1,271 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.document.Field;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.analysis.Tokenizer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.OrdFieldSource;+import org.apache.solr.search.Sorting;+import org.apache.solr.request.XMLWriter;++import java.util.logging.Logger;+import java.util.Map;+import java.util.HashMap;+import java.io.Reader;+import java.io.IOException;++/**+ * Base class for all field types used by an index schema.+ *+ * @author yonik+ * @version $Id: FieldType.java,v 1.14 2006/01/06 04:23:15 yonik Exp $+ */+public abstract class FieldType extends FieldProperties {+ public static final Logger log = Logger.getLogger(FieldType.class.getName());++ protected String typeName; // the name of the type, not the name of the field+ protected Map<String,String> args; // additional arguments+ protected int trueProperties; // properties explicitly set to true+ protected int falseProperties; // properties explicitly set to false+ int properties;++ // these are common enough, they were moved to the base class to handle.+ // not all subclasses will be able to support these options.+ protected int positionIncrementGap;++ protected boolean isTokenized() {+ return (properties & TOKENIZED) != 0;+ }++ /** subclasses should initialize themselves with the args provided+ * and remove valid arguments. leftover arguments will cause an exception.+ * Common boolean properties have already been handled.+ *+ */+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ // Handle additional arguments...+ void setArgs(IndexSchema schema, Map<String,String> args) {+ // default to STORED and INDEXED, and MULTIVALUED depending on schema version+ properties = (STORED | INDEXED);+ if (schema.getVersion()< 1.1f) properties |= MULTIVALUED;++ this.args=args;+ Map<String,String> initArgs = new HashMap<String,String>(args);++ String str;++ str = initArgs.get("positionIncrementGap");+ if (str!=null) positionIncrementGap = Integer.parseInt(str);+ initArgs.remove("positionIncrementGap");++ trueProperties = FieldProperties.parseProperties(initArgs,true);+ falseProperties = FieldProperties.parseProperties(initArgs,false);++ properties &= ~falseProperties;+ properties |= trueProperties;++ for (String prop : FieldProperties.propertyNames) initArgs.remove(prop);++ init(schema, initArgs);++ if (initArgs.size() > 0) {+ throw new RuntimeException("schema fieldtype " + typeName+ + "("+ this.getClass().getName() + ")"+ + " invalid arguments:" + initArgs);+ }+ }++ protected void restrictProps(int props) {+ if ((properties & props) != 0) {+ throw new RuntimeException("schema fieldtype " + typeName+ + "("+ this.getClass().getName() + ")"+ + " invalid properties:" + propertiesToString(properties & props));+ }+ }+++ public String getTypeName() {+ return typeName;+ }++ void setTypeName(String typeName) {+ this.typeName = typeName;+ }++ public String toString() {+ return typeName + "{class=" + this.getClass().getName()+// + propertiesToString(properties)+ + (analyzer != null ? ",analyzer=" + analyzer.getClass().getName() : "")+ + ",args=" + args+ +"}";+ }+++ // used for adding a document when a field needs to be created from a type and a string+ // by default, the indexed value is the same as the stored value (taken from toInternal())+ // Having a different representation for external, internal, and indexed would present quite+ // a few problems given the current Lucene architecture. An analyzer for adding docs would+ // need to translate internal->indexed while an analyzer for querying would need to+ // translate external->indexed.+ //+ // The only other alternative to having internal==indexed would be to have+ // internal==external.+ // In this case, toInternal should convert to the indexed representation,+ // toExternal() should do nothing, and createField() should *not* call toInternal,+ // but use the external value and set tokenized=true to get Lucene to convert+ // to the internal(indexed) form.+ public Field createField(SchemaField field, String externalVal, float boost) {+ String val = toInternal(externalVal);+ if (val==null) return null;+ Field f = new Field(field.getName(), val, field.stored(), field.indexed(), isTokenized());+ f.setOmitNorms(field.omitNorms());+ f.setBoost(boost);+ return f;+ }+++ // Convert an external value (from XML update command or from query string)+ // into the internal format.+ // - used in delete when a Term needs to be created.+ // - used by the default getTokenizer() and createField()+ public String toInternal(String val) {+ return val;+ }++ // Convert the stored-field format to an external (string, human readable) value+ // currently used in writing XML of the search result (but perhaps+ // a more efficient toXML(Field f, Writer w) should be used+ // in the future.+ public String toExternal(Field f) {+ return f.stringValue();+ }+++ public String indexedToReadable(String indexedForm) {+ return indexedForm;+ }+++ /*********+ // default analyzer for non-text fields.+ // Only reads 80 bytes, but that should be plenty for a single value.+ public Analyzer getAnalyzer() {+ if (analyzer != null) return analyzer;++ // the default analyzer...+ return new Analyzer() {+ public TokenStream tokenStream(String fieldName, Reader reader) {+ return new Tokenizer(reader) {+ final char[] cbuf = new char[80];+ public Token next() throws IOException {+ int n = input.read(cbuf,0,80);+ if (n<=0) return null;+ String s = toInternal(new String(cbuf,0,n));+ return new Token(s,0,n);+ };+ };+ }+ };+ }+ **********/+++ //+ // Default analyzer for types that only produce 1 verbatim token...+ // A maximum size of chars to be read must be specified+ //+ protected final class DefaultAnalyzer extends Analyzer {+ final int maxChars;++ DefaultAnalyzer(int maxChars) {+ this.maxChars=maxChars;+ }++ public TokenStream tokenStream(String fieldName, Reader reader) {+ return new Tokenizer(reader) {+ char[] cbuf = new char[maxChars];+ public Token next() throws IOException {+ int n = input.read(cbuf,0,maxChars);+ if (n<=0) return null;+ String s = toInternal(new String(cbuf,0,n)); // virtual func on parent+ return new Token(s,0,n);+ };+ };+ }++ public int getPositionIncrementGap(String fieldName) {+ return positionIncrementGap;+ }+ }+++ //analyzer set by schema for text types.+ //subclasses can set analyzer themselves or override getAnalyzer()+ protected Analyzer analyzer=new DefaultAnalyzer(256);+ protected Analyzer queryAnalyzer=analyzer;++ // get analyzer should be fast to call... since the addition of dynamic fields,+ // this can be called all the time instead of just once at startup.+ // The analyzer will only be used in the following scenarios:+ // - during a document add for any field that has "tokenized" set (typically+ // only Text fields)+ // - during query parsing++ public Analyzer getAnalyzer() {+ return analyzer;+ }++ public Analyzer getQueryAnalyzer() {+ return queryAnalyzer;+ }++ // This is called by the schema parser if a custom analyzer is defined+ public void setAnalyzer(Analyzer analyzer) {+ this.analyzer = analyzer;+ log.finest("FieldType: " + typeName + ".setAnalyzer(" + analyzer.getClass().getName() + ")" );+ }++ // This is called by the schema parser if a custom analyzer is defined+ public void setQueryAnalyzer(Analyzer analyzer) {+ this.queryAnalyzer = analyzer;+ log.finest("FieldType: " + typeName + ".setQueryAnalyzer(" + analyzer.getClass().getName() + ")" );+ }+++ public abstract void write(XMLWriter xmlWriter, String name, Field f) throws IOException;+++ public abstract SortField getSortField(SchemaField field, boolean top);++ protected SortField getStringSort(SchemaField field, boolean reverse) {+ return Sorting.getStringSortField(field.name, reverse, field.sortMissingLast(),field.sortMissingFirst());+ }++ /** called to get the default value source (normally, from the+ * Lucene FieldCache.)+ */+ public ValueSource getValueSource(SchemaField field) {+ return new OrdFieldSource(field.name);+ }+}diff --git a/src/java/org/apache/solr/schema/FloatField.java b/src/java/org/apache/solr/schema/FloatField.javanew file mode 100644index 00000000000..f8137d7bc37--- /dev/null+++ b/src/java/org/apache/solr/schema/FloatField.java@@ -0,0 +1,48 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.FloatFieldSource;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class FloatField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ restrictProps(SORT_MISSING_FIRST | SORT_MISSING_LAST);+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return new SortField(field.name,SortField.FLOAT, reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new FloatFieldSource(field.name);+ }+++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeFloat(name, f.stringValue());+ }+}diff --git a/src/java/org/apache/solr/schema/IndexSchema.java b/src/java/org/apache/solr/schema/IndexSchema.javanew file mode 100644index 00000000000..cb1e7f018ba--- /dev/null+++ b/src/java/org/apache/solr/schema/IndexSchema.java@@ -0,0 +1,542 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.document.Field;+import org.apache.lucene.search.DefaultSimilarity;+import org.apache.lucene.search.Similarity;+import org.apache.solr.core.SolrException;+import org.apache.solr.core.Config;+import org.apache.solr.analysis.TokenFilterFactory;+import org.apache.solr.analysis.TokenizerChain;+import org.apache.solr.analysis.TokenizerFactory;+import org.apache.solr.util.DOMUtil;+import org.w3c.dom.Document;+import org.w3c.dom.NamedNodeMap;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;++import javax.xml.xpath.XPath;+import javax.xml.xpath.XPathConstants;+import javax.xml.xpath.XPathExpressionException;+import javax.xml.xpath.XPathFactory;+import java.io.InputStream;+import java.io.Reader;+import java.util.*;+import java.util.logging.Logger;++/**+ * <code>IndexSchema</code> contains information about the valid fields in an index+ * and the types of those fields.+ *+ * @author yonik+ * @version $Id: IndexSchema.java,v 1.21 2005/12/20 16:05:46 yonik Exp $+ */++public final class IndexSchema {+ final static Logger log = Logger.getLogger(IndexSchema.class.getName());++ private final String schemaFile;+ private String name;+ private float version;++ public IndexSchema(String schemaFile) {+ this.schemaFile=schemaFile;+ readConfig();+ }++ public InputStream getInputStream() {+ return Config.openResource(schemaFile);+ }+++ float getVersion() {+ return version;+ }++ public String getName() { return name; }++ private final HashMap<String, SchemaField> fields = new HashMap<String,SchemaField>();+ private final HashMap<String, FieldType> fieldTypes = new HashMap<String,FieldType>();++ public Map<String,SchemaField> getFields() { return fields; }+ public Map<String,FieldType> getFieldTypes() { return fieldTypes; }+++ private Similarity similarity;+ public Similarity getSimilarity() { return similarity; }++ private Analyzer analyzer;+ public Analyzer getAnalyzer() { return analyzer; }++ private Analyzer queryAnalyzer;+ public Analyzer getQueryAnalyzer() { return queryAnalyzer; }++ private String defaultSearchFieldName=null;+ public String getDefaultSearchFieldName() {+ return defaultSearchFieldName;+ }++ private SchemaField uniqueKeyField;+ public SchemaField getUniqueKeyField() { return uniqueKeyField; }++ private String uniqueKeyFieldName;+ private FieldType uniqueKeyFieldType;++ public Field getUniqueKeyField(org.apache.lucene.document.Document doc) {+ return doc.getField(uniqueKeyFieldName); // this should return null if name is null+ }++ public String printableUniqueKey(org.apache.lucene.document.Document doc) {+ Field f = doc.getField(uniqueKeyFieldName);+ return f==null ? null : uniqueKeyFieldType.toExternal(f);+ }++ private SchemaField getIndexedField(String fname) {+ SchemaField f = getFields().get(fname);+ if (f==null) {+ throw new RuntimeException("unknown field '" + fname + "'");+ }+ if (!f.indexed()) {+ throw new RuntimeException("'"+fname+"' is not an indexed field:" + f);+ }+ return f;+ }++++ private class SolrAnalyzer extends Analyzer {+ protected final HashMap<String,Analyzer> analyzers;++ SolrAnalyzer() {+ analyzers = analyzerCache();+ }++ protected HashMap<String,Analyzer> analyzerCache() {+ HashMap<String,Analyzer> cache = new HashMap<String,Analyzer>();+ for (SchemaField f : getFields().values()) {+ Analyzer analyzer = f.getType().getAnalyzer();+ cache.put(f.getName(), analyzer);+ }+ return cache;+ }++ protected Analyzer getAnalyzer(String fieldName)+ {+ Analyzer analyzer = analyzers.get(fieldName);+ return analyzer!=null ? analyzer : getDynamicFieldType(fieldName).getAnalyzer();+ }++ public TokenStream tokenStream(String fieldName, Reader reader)+ {+ return getAnalyzer(fieldName).tokenStream(fieldName,reader);+ }++ public int getPositionIncrementGap(String fieldName) {+ return getAnalyzer(fieldName).getPositionIncrementGap(fieldName);+ }+ }+++ private class SolrQueryAnalyzer extends SolrAnalyzer {+ protected HashMap<String,Analyzer> analyzerCache() {+ HashMap<String,Analyzer> cache = new HashMap<String,Analyzer>();+ for (SchemaField f : getFields().values()) {+ Analyzer analyzer = f.getType().getQueryAnalyzer();+ cache.put(f.getName(), analyzer);+ }+ return cache;+ }++ protected Analyzer getAnalyzer(String fieldName)+ {+ Analyzer analyzer = analyzers.get(fieldName);+ return analyzer!=null ? analyzer : getDynamicFieldType(fieldName).getQueryAnalyzer();+ }+ }+++ private void readConfig() {+ log.info("Reading Solr Schema");++ try {+ /***+ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();+ Document document = builder.parse(getInputStream());+ ***/++ Config config = new Config("schema", getInputStream(), "/schema/");+ Document document = config.getDocument();+ XPath xpath = config.getXPath();++ Node nd = (Node) xpath.evaluate("/schema/@name", document, XPathConstants.NODE);+ if (nd==null) {+ log.warning("schema has no name!");+ } else {+ name = nd.getNodeValue();+ log.info("Schema name=" + name);+ }++ version = config.getFloat("/schema/@version", 1.0f);++ String expression = "/schema/types/fieldtype";+ NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);+++ for (int i=0; i<nodes.getLength(); i++) {+ Node node = nodes.item(i);+ NamedNodeMap attrs = node.getAttributes();++ String name = DOMUtil.getAttr(attrs,"name","fieldtype error");+ log.finest("reading fieldtype "+name);+ String clsName = DOMUtil.getAttr(attrs,"class", "fieldtype error");+ FieldType ft = (FieldType)Config.newInstance(clsName);+ ft.setTypeName(name);++ expression = "./analyzer[@type='query']";+ Node anode = (Node)xpath.evaluate(expression, node, XPathConstants.NODE);+ Analyzer queryAnalyzer = readAnalyzer(anode);++ // An analyzer without a type specified, or with type="index"+ expression = "./analyzer[not(@type)] | ./analyzer[@type='index']";+ anode = (Node)xpath.evaluate(expression, node, XPathConstants.NODE);+ Analyzer analyzer = readAnalyzer(anode);++ if (queryAnalyzer==null) queryAnalyzer=analyzer;+ if (analyzer==null) analyzer=queryAnalyzer;+ if (analyzer!=null) {+ ft.setAnalyzer(analyzer);+ ft.setQueryAnalyzer(queryAnalyzer);+ }+++ ft.setArgs(this, DOMUtil.toMapExcept(attrs,"name","class"));+ fieldTypes.put(ft.typeName,ft);+ log.finest("fieldtype defined: " + ft);+ }+++ ArrayList<DynamicField> dFields = new ArrayList<DynamicField>();+ expression = "/schema/fields/field | /schema/fields/dynamicField";+ nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);++ for (int i=0; i<nodes.getLength(); i++) {+ Node node = nodes.item(i);++ NamedNodeMap attrs = node.getAttributes();++ String name = DOMUtil.getAttr(attrs,"name","field definition");+ log.finest("reading field def "+name);+ String type = DOMUtil.getAttr(attrs,"type","field " + name);+ String val;++ FieldType ft = fieldTypes.get(type);+ if (ft==null) {+ throw new SolrException(400,"Unknown fieldtype '" + type + "'",false);+ }++ Map<String,String> args = DOMUtil.toMapExcept(attrs, "name", "type");++ SchemaField f = SchemaField.create(name,ft,args);++ if (node.getNodeName().equals("field")) {+ fields.put(f.getName(),f);+ log.fine("field defined: " + f);+ } else if (node.getNodeName().equals("dynamicField")) {+ dFields.add(new DynamicField(f));+ log.fine("dynamic field defined: " + f);+ } else {+ // we should never get here+ throw new RuntimeException("Unknown field type");+ }+ }++ // OK, now sort the dynamic fields largest to smallest size so we don't get+ // any false matches. We want to act like a compiler tool and try and match+ // the largest string possible.+ Collections.sort(dFields, new Comparator<DynamicField>() {+ public int compare(DynamicField a, DynamicField b) {+ // swap natural ordering to get biggest first.+ // The sort is stable, so elements of the same size should+ // be+ if (a.regex.length() < b.regex.length()) return 1;+ else if (a.regex.length() > b.regex.length()) return -1;+ return 0;+ }+ }+ );++ log.finest("Dynamic Field Ordering:" + dFields);++ // stuff it in a normal array for faster access+ dynamicFields = (DynamicField[])dFields.toArray(new DynamicField[dFields.size()]);+++ Node node = (Node) xpath.evaluate("/schema/similarity/@class", document, XPathConstants.NODE);+ if (node==null) {+ similarity = new DefaultSimilarity();+ log.fine("using default similarity");+ } else {+ similarity = (Similarity)Config.newInstance(node.getNodeValue().trim());+ log.fine("using similarity " + similarity.getClass().getName());+ }++ node = (Node) xpath.evaluate("/schema/defaultSearchField/text()", document, XPathConstants.NODE);+ if (node==null) {+ log.warning("no default search field specified in schema.");+ } else {+ String defName=node.getNodeValue().trim();+ defaultSearchFieldName = getIndexedField(defName)!=null ? defName : null;+ log.info("default search field is "+defName);+ }++ node = (Node) xpath.evaluate("/schema/uniqueKey/text()", document, XPathConstants.NODE);+ if (node==null) {+ log.warning("no uniqueKey specified in schema.");+ } else {+ uniqueKeyField=getIndexedField(node.getNodeValue().trim());+ uniqueKeyFieldName=uniqueKeyField.getName();+ uniqueKeyFieldType=uniqueKeyField.getType();+ log.info("unique key field: "+uniqueKeyFieldName);+ }++ /////////////// parse out copyField commands ///////////////+ // Map<String,ArrayList<SchemaField>> cfields = new HashMap<String,ArrayList<SchemaField>>();+ // expression = "/schema/copyField";+ expression = "//copyField";+ nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);++ for (int i=0; i<nodes.getLength(); i++) {+ node = nodes.item(i);+ NamedNodeMap attrs = node.getAttributes();++ String source = DOMUtil.getAttr(attrs,"source","copyField definition");+ String dest = DOMUtil.getAttr(attrs,"dest","copyField definition");+ log.fine("copyField source='"+source+"' dest='"+dest+"'");+ SchemaField f = getField(source);+ SchemaField d = getField(dest);+ SchemaField[] destArr = copyFields.get(source);+ if (destArr==null) {+ destArr=new SchemaField[]{d};+ } else {+ destArr = (SchemaField[])append(destArr,d);+ }+ copyFields.put(source,destArr);+ }+++ } catch (SolrException e) {+ throw e;+ } catch(Exception e) {+ // unexpected exception...+ throw new SolrException(1,"Schema Parsing Failed",e,false);+ }++ analyzer = new SolrAnalyzer();+ queryAnalyzer = new SolrQueryAnalyzer();+ }++ private static Object[] append(Object[] orig, Object item) {+ Object[] newArr = (Object[])java.lang.reflect.Array.newInstance(orig.getClass().getComponentType(), orig.length+1);+ System.arraycopy(orig, 0, newArr, 0, orig.length);+ newArr[orig.length] = item;+ return newArr;+ }++ //+ // <analyzer><tokenizer class="...."/><tokenizer class="...." arg="....">+ //+ //+ private Analyzer readAnalyzer(Node node) throws XPathExpressionException {+ // parent node used to be passed in as "fieldtype"+ // if (!fieldtype.hasChildNodes()) return null;+ // Node node = DOMUtil.getChild(fieldtype,"analyzer");++ if (node == null) return null;+ NamedNodeMap attrs = node.getAttributes();+ String analyzerName = DOMUtil.getAttr(attrs,"class");+ if (analyzerName != null) {+ return (Analyzer)Config.newInstance(analyzerName);+ }++ XPath xpath = XPathFactory.newInstance().newXPath();+ Node tokNode = (Node)xpath.evaluate("./tokenizer", node, XPathConstants.NODE);+ NodeList nList = (NodeList)xpath.evaluate("./filter", node, XPathConstants.NODESET);++ if (tokNode==null){+ throw new SolrException(1,"analyzer without class or tokenizer & filter list");+ }+ TokenizerFactory tfac = readTokenizerFactory(tokNode);++ /******+ // oops, getChildNodes() includes text (newlines, etc) in addition+ // to the actual child elements+ NodeList nList = node.getChildNodes();+ TokenizerFactory tfac = readTokenizerFactory(nList.item(0));+ if (tfac==null) {+ throw new SolrException(1,"TokenizerFactory must be specified first in analyzer");+ }+ ******/++ ArrayList<TokenFilterFactory> filters = new ArrayList<TokenFilterFactory>();+ for (int i=0; i<nList.getLength(); i++) {+ TokenFilterFactory filt = readTokenFilterFactory(nList.item(i));+ if (filt != null) filters.add(filt);+ }++ return new TokenizerChain(tfac, filters.toArray(new TokenFilterFactory[filters.size()]));+ };++ // <tokenizer class="solr.StandardFilterFactory"/>+ private TokenizerFactory readTokenizerFactory(Node node) {+ // if (node.getNodeName() != "tokenizer") return null;+ NamedNodeMap attrs = node.getAttributes();+ String className = DOMUtil.getAttr(attrs,"class","tokenizer");+ TokenizerFactory tfac = (TokenizerFactory)Config.newInstance(className);+ tfac.init(DOMUtil.toMapExcept(attrs,"class"));+ return tfac;+ }++ // <tokenizer class="solr.StandardFilterFactory"/>+ private TokenFilterFactory readTokenFilterFactory(Node node) {+ // if (node.getNodeName() != "filter") return null;+ NamedNodeMap attrs = node.getAttributes();+ String className = DOMUtil.getAttr(attrs,"class","token filter");+ TokenFilterFactory tfac = (TokenFilterFactory)Config.newInstance(className);+ tfac.init(DOMUtil.toMapExcept(attrs,"class"));+ return tfac;+ }+++ //+ // Instead of storing a type, this could be implemented as a hierarchy+ // with a virtual matches().+ // Given how often a search will be done, however, speed is the overriding+ // concern and I'm not sure which is faster.+ //+ final static class DynamicField {+ final static int STARTS_WITH=1;+ final static int ENDS_WITH=2;++ final String regex;+ final int type;+ final SchemaField prototype;++ final String str;++ DynamicField(SchemaField prototype) {+ this.regex=prototype.name;+ if (regex.startsWith("*")) {+ type=ENDS_WITH;+ str=regex.substring(1);+ }+ else if (regex.endsWith("*")) {+ type=STARTS_WITH;+ str=regex.substring(0,regex.length()-1);+ }+ else {+ throw new RuntimeException("dynamic field name must start or end with *");+ }+ this.prototype=prototype;+ }++ boolean matches(String name) {+ if (type==STARTS_WITH && name.startsWith(str)) return true;+ else if (type==ENDS_WITH && name.endsWith(str)) return true;+ else return false;+ }++ SchemaField makeSchemaField(String name) {+ // could have a cache instead of returning a new one each time, but it might+ // not be worth it.+ // Actually, a higher level cache could be worth it to avoid too many+ // .startsWith() and .endsWith() comparisons. it depends on how many+ // dynamic fields there are.+ return new SchemaField(prototype, name);+ }++ public String toString() {+ return prototype.toString();+ }+ }++++ private DynamicField[] dynamicFields;+++ // get a field, and if not statically defined, check dynamic fields.+ public SchemaField getField(String fieldName) {+ SchemaField f = fields.get(fieldName);+ if (f != null) return f;++ for (DynamicField df : dynamicFields) {+ if (df.matches(fieldName)) return df.makeSchemaField(fieldName);+ }++ // Hmmm, default field could also be implemented with a dynamic field of "*".+ // It would have to be special-cased and only used if nothing else matched.+ /*** REMOVED -YCS+ if (defaultFieldType != null) return new SchemaField(fieldName,defaultFieldType);+ ***/+ throw new SolrException(1,"undefined field "+fieldName);+ }++ // This method exists because it can be more efficient for dynamic fields+ // if a full SchemaField isn't needed.+ public FieldType getFieldType(String fieldName) {+ SchemaField f = fields.get(fieldName);+ if (f != null) return f.getType();++ return getDynamicFieldType(fieldName);+ }++ /**+ * return null instead of throwing an exception if+ * the field is undefined.+ */+ public FieldType getFieldTypeNoEx(String fieldName) {+ SchemaField f = fields.get(fieldName);+ if (f != null) return f.getType();+ return dynFieldType(fieldName);+ }+++ public FieldType getDynamicFieldType(String fieldName) {+ for (DynamicField df : dynamicFields) {+ if (df.matches(fieldName)) return df.prototype.getType();+ }+ throw new SolrException(400,"undefined field "+fieldName);+ }++ private FieldType dynFieldType(String fieldName) {+ for (DynamicField df : dynamicFields) {+ if (df.matches(fieldName)) return df.prototype.getType();+ }+ return null;+ };+++ private final Map<String, SchemaField[]> copyFields = new HashMap<String,SchemaField[]>();+ public SchemaField[] getCopyFields(String sourceField) {+ return copyFields.get(sourceField);+ }++}+diff --git a/src/java/org/apache/solr/schema/IntField.java b/src/java/org/apache/solr/schema/IntField.javanew file mode 100644index 00000000000..3a04f9c54b7--- /dev/null+++ b/src/java/org/apache/solr/schema/IntField.java@@ -0,0 +1,47 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.IntFieldSource;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class IntField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ restrictProps(SORT_MISSING_FIRST | SORT_MISSING_LAST);+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return new SortField(field.name,SortField.INT, reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new IntFieldSource(field.name);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeInt(name, f.stringValue());+ }+}diff --git a/src/java/org/apache/solr/schema/LongField.java b/src/java/org/apache/solr/schema/LongField.javanew file mode 100644index 00000000000..897431e026b--- /dev/null+++ b/src/java/org/apache/solr/schema/LongField.java@@ -0,0 +1,52 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.IntFieldSource;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class LongField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ restrictProps(SORT_MISSING_FIRST | SORT_MISSING_LAST);+ }++ /////////////////////////////////////////////////////////////+ // TODO: ACK.. there is no SortField.LONG!+ public SortField getSortField(SchemaField field,boolean reverse) {+ // todo - log warning+ return new SortField(field.name,SortField.INT, reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ // todo - log warning+ return new IntFieldSource(field.name);+ }+++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeLong(name, f.stringValue());+ }+}diff --git a/src/java/org/apache/solr/schema/SchemaField.java b/src/java/org/apache/solr/schema/SchemaField.javanew file mode 100644index 00000000000..cee51ec9b7c--- /dev/null+++ b/src/java/org/apache/solr/schema/SchemaField.java@@ -0,0 +1,159 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.document.Field;+import org.apache.lucene.search.SortField;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id: SchemaField.java,v 1.8 2005/11/28 06:03:19 yonik Exp $+ */++++public final class SchemaField extends FieldProperties {+ final String name;+ final FieldType type;+ final int properties;+++ /** Create a new SchemaField with the given name and type,+ * using all the default properties from the type.+ */+ public SchemaField(String name, FieldType type) {+ this(name, type, type.properties);+ }++ /** Create a new SchemaField from an existing one by using all+ * of the properties of the prototype except the field name.+ */+ public SchemaField(SchemaField prototype, String name) {+ this(name, prototype.type, prototype.properties);+ }++ /** Create a new SchemaField with the given name and type,+ * and with the specified properties. Properties are *not*+ * inherited from the type in this case, so users of this+ * constructor should derive the properties from type.getProperties()+ * using all the default properties from the type.+ */+ public SchemaField(String name, FieldType type, int properties) {+ this.name = name;+ this.type = type;+ this.properties = properties;+ }++ public String getName() { return name; }+ public FieldType getType() { return type; }+ int getProperties() { return properties; }++ public boolean indexed() { return (properties & INDEXED)!=0; }+ public boolean stored() { return (properties & STORED)!=0; }+ public boolean storeTermVector() { return (properties & STORE_TERMVECTORS)!=0; }+ public boolean storeTermPositions() { return (properties & STORE_TERMPOSITIONS)!=0; }+ public boolean storeTermOffsets() { return (properties & STORE_TERMOFFSETS)!=0; }+ public boolean omitNorms() { return (properties & OMIT_NORMS)!=0; }+ public boolean multiValued() { return (properties & MULTIVALUED)!=0; }+ public boolean sortMissingFirst() { return (properties & SORT_MISSING_FIRST)!=0; }+ public boolean sortMissingLast() { return (properties & SORT_MISSING_LAST)!=0; }++ // things that should be determined by field type, not set as options+ boolean isTokenized() { return (properties & TOKENIZED)!=0; }+ boolean isBinary() { return (properties & BINARY)!=0; }+ boolean isCompressed() { return (properties & COMPRESSED)!=0; }++ public Field createField(String val, float boost) {+ return type.createField(this,val,boost);+ }++ public String toString() {+ return name + "{type="+type.getTypeName()+ + ",properties=" + propertiesToString(properties)+ + "}";+ }++ public void write(XMLWriter writer, String name, Field val) throws IOException {+ // name is passed in because it may be null if name should not be used.+ type.write(writer,name,val);+ }++ public SortField getSortField(boolean top) {+ return type.getSortField(this, top);+ }+++ static SchemaField create(String name, FieldType ft, Map props) {+ int trueProps = parseProperties(props,true);+ int falseProps = parseProperties(props,false);++ int p = ft.properties;++ //+ // If any properties were explicitly turned off, then turn off other properties+ // that depend on that.+ //+ if (on(falseProps,STORED)) {+ int pp = STORED | BINARY | COMPRESSED;+ if (on(pp,trueProps)) {+ throw new RuntimeException("SchemaField: " + name + " conflicting stored field options:" + props);+ }+ p &= ~pp;+ }++ if (on(falseProps,INDEXED)) {+ int pp = (INDEXED | OMIT_NORMS+ | STORE_TERMVECTORS | STORE_TERMPOSITIONS | STORE_TERMOFFSETS+ | SORT_MISSING_FIRST | SORT_MISSING_LAST);+ if (on(pp,trueProps)) {+ throw new RuntimeException("SchemaField: " + name + " conflicting indexed field options:" + props);+ }+ p &= ~pp;++ }++ if (on(falseProps,STORE_TERMVECTORS)) {+ int pp = (STORE_TERMVECTORS | STORE_TERMPOSITIONS | STORE_TERMOFFSETS);+ if (on(pp,trueProps)) {+ throw new RuntimeException("SchemaField: " + name + " conflicting termvector field options:" + props);+ }+ p &= ~pp;+ }++ // override sort flags+ if (on(trueProps,SORT_MISSING_FIRST)) {+ p &= ~SORT_MISSING_LAST;+ }++ if (on(trueProps,SORT_MISSING_LAST)) {+ p &= ~SORT_MISSING_FIRST;+ }++ p &= ~falseProps;+ p |= trueProps;++ return new SchemaField(name, ft, p);+ }+}++++diff --git a/src/java/org/apache/solr/schema/SortableDoubleField.java b/src/java/org/apache/solr/schema/SortableDoubleField.javanew file mode 100644index 00000000000..566d0ee4067--- /dev/null+++ b/src/java/org/apache/solr/schema/SortableDoubleField.java@@ -0,0 +1,132 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.FieldCacheSource;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;+import org.apache.solr.util.NumberUtils;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class SortableDoubleField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new SortableDoubleFieldSource(field.name);+ }++ public String toInternal(String val) {+ return NumberUtils.double2sortableStr(val);+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public String indexedToReadable(String indexedForm) {+ return NumberUtils.SortableStr2doubleStr(indexedForm);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ String sval = f.stringValue();+ xmlWriter.writeDouble(name, NumberUtils.SortableStr2double(sval));+ }+}+++++class SortableDoubleFieldSource extends FieldCacheSource {+ protected double defVal;++ public SortableDoubleFieldSource(String field) {+ this(field, 0.0);+ }++ public SortableDoubleFieldSource(String field, double defVal) {+ super(field);+ this.defVal = defVal;+ }++ public String description() {+ return "sdouble(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final FieldCache.StringIndex index = cache.getStringIndex(reader, field);+ final int[] order = index.order;+ final String[] lookup = index.lookup;+ final double def = defVal;++ return new DocValues() {+ public float floatVal(int doc) {+ return (float)doubleVal(doc);+ }++ public int intVal(int doc) {+ return (int)doubleVal(doc);+ }++ public long longVal(int doc) {+ return (long)doubleVal(doc);+ }++ public double doubleVal(int doc) {+ int ord=order[doc];+ return ord==0 ? def : NumberUtils.SortableStr2double(lookup[ord]);+ }++ public String strVal(int doc) {+ return Double.toString(doubleVal(doc));+ }++ public String toString(int doc) {+ return description() + '=' + doubleVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ return o instanceof SortableDoubleFieldSource+ && super.equals(o)+ && defVal == ((SortableDoubleFieldSource)o).defVal;+ }++ private static int hcode = SortableDoubleFieldSource.class.hashCode();+ public int hashCode() {+ long bits = Double.doubleToLongBits(defVal);+ int ibits = (int)(bits ^ (bits>>>32)); // mix upper bits into lower.+ return hcode + super.hashCode() + ibits;+ };+}++diff --git a/src/java/org/apache/solr/schema/SortableFloatField.java b/src/java/org/apache/solr/schema/SortableFloatField.javanew file mode 100644index 00000000000..6ce103c217c--- /dev/null+++ b/src/java/org/apache/solr/schema/SortableFloatField.java@@ -0,0 +1,129 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.FieldCacheSource;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;+import org.apache.solr.util.NumberUtils;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class SortableFloatField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new SortableFloatFieldSource(field.name);+ }++ public String toInternal(String val) {+ return NumberUtils.float2sortableStr(val);+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public String indexedToReadable(String indexedForm) {+ return NumberUtils.SortableStr2floatStr(indexedForm);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ String sval = f.stringValue();+ xmlWriter.writeFloat(name, NumberUtils.SortableStr2float(sval));+ }+}+++++class SortableFloatFieldSource extends FieldCacheSource {+ protected float defVal;++ public SortableFloatFieldSource(String field) {+ this(field, 0.0f);+ }++ public SortableFloatFieldSource(String field, float defVal) {+ super(field);+ this.defVal = defVal;+ }++ public String description() {+ return "sfloat(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final FieldCache.StringIndex index = cache.getStringIndex(reader, field);+ final int[] order = index.order;+ final String[] lookup = index.lookup;+ final float def = defVal;++ return new DocValues() {+ public float floatVal(int doc) {+ int ord=order[doc];+ return ord==0 ? def : NumberUtils.SortableStr2float(lookup[ord]);+ }++ public int intVal(int doc) {+ return (int)floatVal(doc);+ }++ public long longVal(int doc) {+ return (long)floatVal(doc);+ }++ public double doubleVal(int doc) {+ return (double)floatVal(doc);+ }++ public String strVal(int doc) {+ return Float.toString(floatVal(doc));+ }++ public String toString(int doc) {+ return description() + '=' + floatVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ return o instanceof SortableFloatFieldSource+ && super.equals(o)+ && defVal == ((SortableFloatFieldSource)o).defVal;+ }++ private static int hcode = SortableFloatFieldSource.class.hashCode();+ public int hashCode() {+ return hcode + super.hashCode() + Float.floatToIntBits(defVal);+ };+}+diff --git a/src/java/org/apache/solr/schema/SortableIntField.java b/src/java/org/apache/solr/schema/SortableIntField.javanew file mode 100644index 00000000000..dd8ff86507f--- /dev/null+++ b/src/java/org/apache/solr/schema/SortableIntField.java@@ -0,0 +1,132 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.FieldCacheSource;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;+import org.apache.solr.util.NumberUtils;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class SortableIntField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new SortableIntFieldSource(field.name);+ }++ public String toInternal(String val) {+ // special case single digits? years?, etc+ // stringCache? general stringCache on a+ // global field level?+ return NumberUtils.int2sortableStr(val);+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public String indexedToReadable(String indexedForm) {+ return NumberUtils.SortableStr2int(indexedForm);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ String sval = f.stringValue();+ // since writeInt an int instead of a String since that may be more efficient+ // in the future (saves the construction of one String)+ xmlWriter.writeInt(name, NumberUtils.SortableStr2int(sval,0,sval.length()));+ }+}++++class SortableIntFieldSource extends FieldCacheSource {+ protected int defVal;++ public SortableIntFieldSource(String field) {+ this(field, 0);+ }++ public SortableIntFieldSource(String field, int defVal) {+ super(field);+ this.defVal = defVal;+ }++ public String description() {+ return "sint(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final FieldCache.StringIndex index = cache.getStringIndex(reader, field);+ final int[] order = index.order;+ final String[] lookup = index.lookup;+ final int def = defVal;++ return new DocValues() {+ public float floatVal(int doc) {+ return (float)intVal(doc);+ }++ public int intVal(int doc) {+ int ord=order[doc];+ return ord==0 ? def : NumberUtils.SortableStr2int(lookup[ord],0,3);+ }++ public long longVal(int doc) {+ return (long)intVal(doc);+ }++ public double doubleVal(int doc) {+ return (double)intVal(doc);+ }++ public String strVal(int doc) {+ return Integer.toString(intVal(doc));+ }++ public String toString(int doc) {+ return description() + '=' + intVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ return o instanceof SortableIntFieldSource+ && super.equals(o)+ && defVal == ((SortableIntFieldSource)o).defVal;+ }++ private static int hcode = SortableIntFieldSource.class.hashCode();+ public int hashCode() {+ return hcode + super.hashCode() + defVal;+ };+}diff --git a/src/java/org/apache/solr/schema/SortableLongField.java b/src/java/org/apache/solr/schema/SortableLongField.javanew file mode 100644index 00000000000..9bd8db1df6f--- /dev/null+++ b/src/java/org/apache/solr/schema/SortableLongField.java@@ -0,0 +1,129 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.function.FieldCacheSource;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;+import org.apache.solr.util.NumberUtils;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+public class SortableLongField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public ValueSource getValueSource(SchemaField field) {+ return new SortableLongFieldSource(field.name);+ }++ public String toInternal(String val) {+ return NumberUtils.long2sortableStr(val);+ }++ public String indexedToReadable(String indexedForm) {+ return NumberUtils.SortableStr2long(indexedForm);+ }++ public String toExternal(Field f) {+ return indexedToReadable(f.stringValue());+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ String sval = f.stringValue();+ xmlWriter.writeLong(name, NumberUtils.SortableStr2long(sval,0,sval.length()));+ }+}++++++class SortableLongFieldSource extends FieldCacheSource {+ protected long defVal;++ public SortableLongFieldSource(String field) {+ this(field, 0);+ }++ public SortableLongFieldSource(String field, long defVal) {+ super(field);+ this.defVal = defVal;+ }++ public String description() {+ return "slong(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final FieldCache.StringIndex index = cache.getStringIndex(reader, field);+ final int[] order = index.order;+ final String[] lookup = index.lookup;+ final long def = defVal;++ return new DocValues() {+ public float floatVal(int doc) {+ return (float)longVal(doc);+ }++ public int intVal(int doc) {+ return (int)longVal(doc);+ }++ public long longVal(int doc) {+ int ord=order[doc];+ return ord==0 ? def : NumberUtils.SortableStr2long(lookup[ord],0,5);+ }++ public double doubleVal(int doc) {+ return (double)longVal(doc);+ }++ public String strVal(int doc) {+ return Long.toString(longVal(doc));+ }++ public String toString(int doc) {+ return description() + '=' + longVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ return o instanceof SortableLongFieldSource+ && super.equals(o)+ && defVal == ((SortableLongFieldSource)o).defVal;+ }++ private static int hcode = SortableLongFieldSource.class.hashCode();+ public int hashCode() {+ return hcode + super.hashCode() + (int)defVal;+ };+}diff --git a/src/java/org/apache/solr/schema/StrField.java b/src/java/org/apache/solr/schema/StrField.javanew file mode 100644index 00000000000..9a6ec36b8de--- /dev/null+++ b/src/java/org/apache/solr/schema/StrField.java@@ -0,0 +1,41 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;+/**+ * @author yonik+ * @version $Id$+ */+//TODO: allow specification of max string size?+public class StrField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ }++ public SortField getSortField(SchemaField field,boolean reverse) {+ return getStringSort(field,reverse);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeStr(name, f.stringValue());+ }+}diff --git a/src/java/org/apache/solr/schema/TextField.java b/src/java/org/apache/solr/schema/TextField.javanew file mode 100644index 00000000000..54975f75050--- /dev/null+++ b/src/java/org/apache/solr/schema/TextField.java@@ -0,0 +1,43 @@+/**+ * 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.+ */++package org.apache.solr.schema;++import org.apache.lucene.search.SortField;+import org.apache.lucene.document.Field;+import org.apache.solr.request.XMLWriter;++import java.util.Map;+import java.io.IOException;++/** <code>TextField</code> is the basic type for configurable text analysis.+ * Analyzers for field types using this implementation should be defined in the schema.+ * @author yonik+ * @version $Id$+ */+public class TextField extends FieldType {+ protected void init(IndexSchema schema, Map<String,String> args) {+ properties |= TOKENIZED;+ }++ public SortField getSortField(SchemaField field, boolean reverse) {+ return new SortField(field.name,SortField.STRING, reverse);+ }++ public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {+ xmlWriter.writeStr(name, f.stringValue());+ }+}diff --git a/src/java/org/apache/solr/search/BitDocSet.java b/src/java/org/apache/solr/search/BitDocSet.javanew file mode 100644index 00000000000..b3ad13f44ea--- /dev/null+++ b/src/java/org/apache/solr/search/BitDocSet.java@@ -0,0 +1,112 @@+/**+ * 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.+ */++package org.apache.solr.search;++import java.util.BitSet;++/**+ * <code>BitDocSet</code> represents an unordered set of Lucene Document Ids+ * using a BitSet. A set bit represents inclusion in the set for that document.+ *+ * @author yonik+ * @version $Id: BitDocSet.java,v 1.4 2005/10/27 04:14:49 yonik Exp $+ * @since solr 0.9+ */+public class BitDocSet extends DocSetBase {+ final BitSet bits;+ int size; // number of docs in the set (cached for perf)++ public BitDocSet() {+ bits = new BitSet();+ }++ public BitDocSet(BitSet bits) {+ this.bits = bits;+ size=-1;+ }++ public BitDocSet(BitSet bits, int size) {+ this.bits = bits;+ this.size = size;+ }++ public DocIterator iterator() {+ return new DocIterator() {+ int pos=bits.nextSetBit(0);+ public boolean hasNext() {+ return pos>=0;+ }++ public Integer next() {+ return nextDoc();+ }++ public void remove() {+ bits.clear(pos);+ }++ public int nextDoc() {+ int old=pos;+ pos=bits.nextSetBit(old+1);+ return old;+ }++ public float score() {+ return 0.0f;+ }+ };+ }++ /**+ *+ * @return the <b>internal</b> BitSet that should <b>not</b> be modified.+ */+ public BitSet getBits() {+ return bits;+ }++ public void add(int doc) {+ bits.set(doc);+ size=-1; // invalidate size+ }++ public void addUnique(int doc) {+ size++;+ bits.set(doc);+ }++ public int size() {+ if (size!=-1) return size;+ return size=bits.cardinality();+ }++ /**+ * The number of set bits - size - is cached. If the bitset is changed externally,+ * this method should be used to invalidate the previously cached size.+ */+ public void invalidateSize() {+ size=-1;+ }++ public boolean exists(int doc) {+ return bits.get(doc);+ }++ public long memSize() {+ return (bits.size() >> 3) + 16;+ }+}diff --git a/src/java/org/apache/solr/search/CacheConfig.java b/src/java/org/apache/solr/search/CacheConfig.javanew file mode 100644index 00000000000..b0e52c1c2b5--- /dev/null+++ b/src/java/org/apache/solr/search/CacheConfig.java@@ -0,0 +1,110 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.w3c.dom.Node;+import org.w3c.dom.NodeList;++import java.util.Map;++import org.apache.solr.util.DOMUtil;+import org.apache.solr.core.SolrException;+import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.Config;++import javax.xml.xpath.XPathConstants;++/**+ * Contains the knowledge of how cache config is+ * stored in the solarconfig.xml file, and implements a+ * factory to create caches.+ *+ * @author yonik+ * @version $Id: CacheConfig.java,v 1.2 2005/09/07 20:37:57 yonik Exp $+ */+class CacheConfig {+ private String nodeName;+ private Map args;++ private String cacheImpl;+ private Class clazz;++ private Object[] persistence = new Object[1];++ private String regenImpl;+ private CacheRegenerator regenerator;++ public CacheRegenerator getRegenerator() {+ return regenerator;+ }++ public void setRegenerator(CacheRegenerator regenerator) {+ this.regenerator = regenerator;+ }++ public static CacheConfig[] getMultipleConfigs(String configPath) {+ NodeList nodes = (NodeList)SolrConfig.config.evaluate(configPath, XPathConstants.NODESET);+ if (nodes==null || nodes.getLength()==0) return null;+ CacheConfig[] configs = new CacheConfig[nodes.getLength()];+ for (int i=0; i<nodes.getLength(); i++) {+ configs[i] = getConfig(nodes.item(i));+ }+ return configs;+ }+++ public static CacheConfig getConfig(String xpath) {+ Node node = (Node)SolrConfig.config.getNode(xpath, false);+ return getConfig(node);+ }+++ public static CacheConfig getConfig(Node node) {+ if (node==null) return null;+ CacheConfig config = new CacheConfig();+ config.nodeName = node.getNodeName();+ config.args = DOMUtil.toMap(node.getAttributes());+ String nameAttr = (String)config.args.get("name"); // OPTIONAL+ if (nameAttr==null) {+ config.args.put("name",config.nodeName);+ }++ config.cacheImpl = (String)config.args.get("class");+ config.regenImpl = (String)config.args.get("regenerator");+ config.clazz = Config.findClass(config.cacheImpl);+ if (config.regenImpl != null) {+ config.regenerator = (CacheRegenerator) Config.newInstance(config.regenImpl);+ }+++ return config;+ }++ public SolrCache newInstance() {+ try {+ SolrCache cache = (SolrCache)clazz.newInstance();+ persistence[0] = cache.init(args, persistence[0], regenerator);+ return cache;+ } catch (Exception e) {+ SolrException.log(SolrCache.log,"Error instantiating cache",e);+ // we can carry on without a cache... but should we?+ // in some cases (like an OOM) we probably should try to continue.+ return null;+ }+ }++}diff --git a/src/java/org/apache/solr/search/CacheRegenerator.java b/src/java/org/apache/solr/search/CacheRegenerator.javanew file mode 100644index 00000000000..e78e40ca58c--- /dev/null+++ b/src/java/org/apache/solr/search/CacheRegenerator.java@@ -0,0 +1,43 @@+/**+ * 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.+ */++package org.apache.solr.search;++import java.io.IOException;++/**+ * Implementations of <code>CacheRegenerator</code> are used in autowarming to populate a new cache+ * based on an old cache. <code>regenerateItem</code> is called for each item that should be inserted into the new cache.+ * <p>+ * Implementations should have a noarg constructor and be thread safe (a single instance will be+ * used for all cache autowarmings).+ *+ * @author yonik+ * @version $Id: CacheRegenerator.java,v 1.2 2005/09/07 20:37:57 yonik Exp $+ */+public interface CacheRegenerator {+ /**+ * Regenerate an old cache item and insert it into <code>newCache</code>+ *+ * @param newSearcher the new searcher who's caches are being autowarmed+ * @param newCache where regenerated cache items should be stored. the target of the autowarming+ * @param oldCache the old cache being used as a source for autowarming+ * @param oldKey the key of the old cache item to regenerate in the new cache+ * @param oldVal the old value of the cache item+ * @return true to continue with autowarming, false to stop+ */+ public boolean regenerateItem(SolrIndexSearcher newSearcher, SolrCache newCache, SolrCache oldCache, Object oldKey, Object oldVal) throws IOException;+}diff --git a/src/java/org/apache/solr/search/DocIterator.java b/src/java/org/apache/solr/search/DocIterator.javanew file mode 100644index 00000000000..f1882a80cf8--- /dev/null+++ b/src/java/org/apache/solr/search/DocIterator.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.search;++import java.util.Iterator;++/**+ * @author yonik+ * @version $Id$+ */+public interface DocIterator extends Iterator<Integer> {+ public boolean hasNext();++ /**+ * returns the next document id if hasNext()==true+ */+ public int nextDoc();++ /**+ * returns the score for the document just returned by nextDoc()+ */+ public float score();+}diff --git a/src/java/org/apache/solr/search/DocList.java b/src/java/org/apache/solr/search/DocList.javanew file mode 100644index 00000000000..6471ed9bd2c--- /dev/null+++ b/src/java/org/apache/solr/search/DocList.java@@ -0,0 +1,128 @@+/**+ * 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.+ */++package org.apache.solr.search;+++/**+ * <code>DocList</code> represents the result of a query: an ordered list of document ids with optional score.+ * This list contains a subset of the complete list of documents actually matched: <code>size()</code>+ * document ids starting at <code>offset()</code>.+ *+ * @author yonik+ * @version $Id: DocList.java,v 1.6 2005/11/11 21:57:56 yonik Exp $+ * @since solr 0.9+ */+public interface DocList extends DocSet {++ /**+ * Returns the zero based offset of this list within the total ordered list of matches to the query.+ */+ public int offset();++ /**+ * Returns the number of ids in this list.+ */+ public int size();++ /**+ * Returns the total number of matches for the search+ * (as opposed to just the number collected according+ * to <code>offset()</code> and <code>size()</code>).+ * Hence it's always true that matches() >= size()+ * @return number of matches for the search(query&filter)+ */+ public int matches();+++ /***+ public int getDoc(int pos);+ ***/++ // hmmm, what if a different slice could be generated from an existing DocSet+ // (and was before)...++ // how to distinguish cached values from logical values?+ // docSet could represent docs 10-20, but actually contain 0-100+ // should the big slice be cached independently, and a new class called+ // DocListSubset be created to refer to a range within the DocList?++ /**+ * Get a subset of an existing DocList.+ * Returns null if not possible.+ */+ public DocList subset(int offset, int len);++ /** True if scores were retained */+ public boolean hasScores();++ /** The maximum score for the search... only valid if+ * scores were retained (if hasScores()==true)+ */+ public float maxScore();+}+++/**** Maybe do this at a higher level (more efficient)++class SmartDocSet implements DocSet {+ static int INITIAL_SIZE=10;+ static int TRANSITION_SIZE=10;++ protected BitSet bits;+ int size;++ protected int[] arr; // keep small set as an array, or as a hash?+ protected int arrsize;++ public SmartDocSet() {+ if (INITIAL_SIZE>0) {+ arr=new int[INITIAL_SIZE];+ } else {+ bits=new BitSet();+ }+ }+++ public void addUnique(int doc) {+ size++;+ if (bits != null) {+ bits.set(doc);+ }+ else {+ if (arrsize<10) {+ arr[arrsize++]=doc;+ } else {+ // TODO: transition to bit set+ }+ }+ };++ public int size() {+ return size;+ }+ public boolean exists(int docid) {+ return false;+ }+ public DocSet intersection(DocSet other) {+ return null;++ }+ public DocSet union(DocSet other) {+ return null;+ }+}+***/diff --git a/src/java/org/apache/solr/search/DocListAndSet.java b/src/java/org/apache/solr/search/DocListAndSet.javanew file mode 100644index 00000000000..c00dd654a54--- /dev/null+++ b/src/java/org/apache/solr/search/DocListAndSet.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.search;+++/**+ * A struct who's only purpose is to hold both a DocList and a DocSet so that both+ * may be returned from a single method.+ * <p>+ * The DocList and DocSet returned should <b>not</b> be modified as they may+ * have been retrieved or inserted into a cache and should be considered shared.+ * <p>+ * Oh, if only java had "out" parameters or multiple return args...+ * <p>+ *+ * @author yonik+ * @version $Id: DocListAndSet.java,v 1.3 2005/04/08 05:38:05 yonik Exp $+ * @since solr 0.9+ */+public final class DocListAndSet {+ public DocList docList;+ public DocSet docSet;+}diff --git a/src/java/org/apache/solr/search/DocSet.java b/src/java/org/apache/solr/search/DocSet.javanew file mode 100644index 00000000000..f9e93df3fe3--- /dev/null+++ b/src/java/org/apache/solr/search/DocSet.java@@ -0,0 +1,182 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.solr.core.SolrException;++import java.util.BitSet;++/**+ * <code>DocSet</code> represents an unordered set of Lucene Document Ids.+ * <p>+ * WARNING: Any DocSet returned from SolrIndexSearcher should <b>not</b> be modified as it may have been retrieved from+ * a cache and could be shared.+ * @author yonik+ * @version $Id: DocSet.java,v 1.6 2005/05/13 21:20:15 yonik Exp $+ * @since solr 0.9+ */+public interface DocSet /* extends Collection<Integer> */ {+ public void add(int doc);+ public void addUnique(int doc);++ /**+ * @return The number of document ids in the set.+ */+ public int size();++ /**+ *+ * @param docid+ * @return+ * true if the docid is in the set+ */+ public boolean exists(int docid);++ /**+ *+ * @return an interator that may be used to iterate over all of the documents in the set.+ */+ public DocIterator iterator();++ /**+ * Returns a BitSet view of the DocSet. Any changes to this BitSet <b>may</b>+ * be reflected in the DocSet, hence if the DocSet is shared or was returned from+ * a SolrIndexSearcher method, it's not safe to modify the BitSet.+ *+ * @return+ * A BitSet with the bit number of every docid set in the set.+ */+ @Deprecated+ public BitSet getBits();++ /**+ * Returns the approximate amount of memory taken by this DocSet.+ * This is only an approximation and doesn't take into account java object overhead.+ *+ * @return+ * the approximate memory consumption in bytes+ */+ public long memSize();++ /**+ * Returns the intersection of this set with another set. Neither set is modified - a new DocSet is+ * created and returned.+ * @param other+ * @return a DocSet representing the intersection+ */+ public DocSet intersection(DocSet other);++ /**+ * Returns the number of documents of the intersection of this set with another set.+ * May be more efficient than actually creating the intersection and then getting it's size.+ */+ public int intersectionSize(DocSet other);++ /**+ * Returns the union of this set with another set. Neither set is modified - a new DocSet is+ * created and returned.+ * @param other+ * @return a DocSet representing the union+ */+ public DocSet union(DocSet other);++ /**+ * Returns the number of documents of the union of this set with another set.+ * May be more efficient than actually creating the union and then getting it's size.+ */+ public int unionSize(DocSet other);++}+++abstract class DocSetBase implements DocSet {++ // Not implemented efficiently... for testing purposes only+ public boolean equals(Object obj) {+ if (!(obj instanceof DocSet)) return false;+ DocSet other = (DocSet)obj;+ if (this.size() != other.size()) return false;++ if (this instanceof DocList && other instanceof DocList) {+ // compare ordering+ DocIterator i1=this.iterator();+ DocIterator i2=this.iterator();+ while(i1.hasNext() && i2.hasNext()) {+ if (i1.nextDoc() != i2.nextDoc()) return false;+ }+ return true;+ // don't compare matches+ }++ // if (this.size() != other.size()) return false;+ return this.getBits().equals(other.getBits());+ }++ public void add(int doc) {+ throw new SolrException(500,"Unsupported Operation");+ }++ public void addUnique(int doc) {+ throw new SolrException(500,"Unsupported Operation");+ }++ // Only the inefficient base implementation. DocSets based on+ // BitSets will return the actual BitSet without making a copy.+ public BitSet getBits() {+ BitSet bits = new BitSet();+ for (DocIterator iter = iterator(); iter.hasNext();) {+ bits.set(iter.nextDoc());+ }+ return bits;+ };++ public DocSet intersection(DocSet other) {+ // intersection is overloaded in HashDocSet to be more+ // efficient, so if "other" is a HashDocSet, dispatch off+ // of it instead.+ if (other instanceof HashDocSet) {+ return other.intersection(this);+ }++ // Default... handle with bitsets.+ BitSet newbits = (BitSet)(this.getBits().clone());+ newbits.and(other.getBits());+ return new BitDocSet(newbits);+ }++ public DocSet union(DocSet other) {+ BitSet newbits = (BitSet)(this.getBits().clone());+ newbits.or(other.getBits());+ return new BitDocSet(newbits);+ }++ // TODO: more efficient implementations+ public int intersectionSize(DocSet other) {+ return intersection(other).size();+ }++ // TODO: more efficient implementations+ public int unionSize(DocSet other) {+ return union(other).size();+ }+++}++++diff --git a/src/java/org/apache/solr/search/DocSlice.java b/src/java/org/apache/solr/search/DocSlice.javanew file mode 100644index 00000000000..764f6cc3a5a--- /dev/null+++ b/src/java/org/apache/solr/search/DocSlice.java@@ -0,0 +1,119 @@+/**+ * 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.+ */++package org.apache.solr.search;++/**+ * <code>DocSlice</code> implements DocList as an array of docids and optional scores.+ *+ * @author yonik+ * @version $Id: DocSlice.java,v 1.9 2005/11/11 21:57:56 yonik Exp $+ * @since solr 0.9+ */+public class DocSlice extends DocSetBase implements DocList {+ final int offset; // starting position of the docs (zero based)+ final int len; // number of positions used in arrays+ final int[] docs; // a slice of documents (docs 0-100 of the query)++ final float[] scores; // optional score list+ final int matches;+ final float maxScore;++ /**+ *+ * @param offset starting offset for this range of docs+ * @param len length of results+ * @param docs array of docids starting at position 0+ * @param scores+ * @param matches total number of matches for the query+ */+ public DocSlice(int offset, int len, int[] docs, float[] scores, int matches, float maxScore) {+ this.offset=offset;+ this.len=len;+ this.docs=docs;+ this.scores=scores;+ this.matches=matches;+ this.maxScore=maxScore;+ }++ public DocList subset(int offset, int len) {+ if (this.offset == offset && this.len==len) return this;++ // if we didn't store enough (and there was more to store)+ // then we can't take a subset.+ int requestedEnd = offset + len;+ if (requestedEnd > docs.length && this.matches > docs.length) return null;+ int realEndDoc = Math.min(requestedEnd, docs.length);+ int realLen = Math.max(realEndDoc-offset,0);+ if (this.offset == offset && this.len == realLen) return this;+ return new DocSlice(offset, realLen, docs, scores, matches, maxScore);+ }++ public boolean hasScores() {+ return scores!=null;+ }++ public float maxScore() {+ return maxScore;+ }+++ public int offset() { return offset; }+ public int size() { return len; }+ public int matches() { return matches; }+++ public long memSize() {+ return (docs.length<<2)+ + (scores==null ? 0 : (scores.length<<2))+ + 24;+ }+++ public boolean exists(int doc) {+ for (int i: docs) {+ if (i==doc) return true;+ }+ return false;+ }++ // Hmmm, maybe I could have reused the scorer interface here...+ // except that it carries Similarity baggage...+ public DocIterator iterator() {+ return new DocIterator() {+ int pos=offset;+ final int end=offset+len;+ public boolean hasNext() {+ return pos < end;+ }++ public Integer next() {+ return nextDoc();+ }++ public void remove() {+ }++ public int nextDoc() {+ return docs[pos++];+ }++ public float score() {+ return scores[pos-1];+ }+ };+ }+}diff --git a/src/java/org/apache/solr/search/HashDocSet.java b/src/java/org/apache/solr/search/HashDocSet.javanew file mode 100644index 00000000000..de92c183c13--- /dev/null+++ b/src/java/org/apache/solr/search/HashDocSet.java@@ -0,0 +1,280 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.solr.core.SolrConfig;+++/**+ * <code>HashDocSet</code> represents an unordered set of Lucene Document Ids+ * using a primitive int hash table. It can be a better choice if there are few docs+ * in the set because it takes up less memory and is faster to iterate and take+ * set intersections.+ *+ * @author yonik+ * @version $Id: HashDocSet.java,v 1.7 2005/11/22 17:16:19 yonik Exp $+ * @since solr 0.9+ */+public final class HashDocSet extends DocSetBase {+ // keep track of the inverse of the Loadfactor since+ // multiplication is so much faster than division.+ final static float inverseLoadfactor = 1.0f / SolrConfig.config.getFloat("//HashDocSet/@loadFactor",0.75f);+ public final static int MAX_SIZE = SolrConfig.config.getInt("//HashDocSet/@maxSize",-1);+++ // lucene docs are numbered from 0, so a neg number must be used for missing.+ // an alternative to having to init the array to EMPTY at the start is+ //+ private final static int EMPTY=-1;+ private final int tablesize;+ private final int[] table;+ private final int size;++ private final int mask;++ public HashDocSet(int[] docs, int offset, int len) {+ int tsize = Math.max(nextHighestPowerOfTwo(len), 1);+ if (tsize < len * inverseLoadfactor) {+ tsize <<= 1;+ }+ tablesize = tsize;+ mask=tablesize-1;++ table = new int[tablesize];+ for (int i=0; i<tablesize; i++) table[i]=EMPTY;++ for (int i=offset; i<len; i++) {+ put(docs[i]);+ }++ size = len;+ }++ static int nextHighestPowerOfTwo(int v) {+ v--;+ v |= v >> 1;+ v |= v >> 2;+ v |= v >> 4;+ v |= v >> 8;+ v |= v >> 16;+ v++;+ return v;+ }+++ void put(int doc) {+ table[getSlot(doc)]=doc;+ }++ private int getSlot(int val) {+ int s,v;+ s=val & mask;+ v=table[s];+ // check for EMPTY first since that value is more likely+ if (v==EMPTY || v==val) return s;+ s=rehash(val);+ return s;+ }+++ // As the size of this int hashtable is expected to be small+ // (thousands at most), I did not try to keep the rehash function+ // reversible (important to avoid collisions in large hash tables).+ private int rehash(int val) {+ int h,s,v;+ final int comp=~val;++ // don't left shift too far... the only bits+ // that count in the answer are the ones on the right.+ // We want to put more of the bits on the left+ // into the answer.+ // Keep small tables in mind. We may be only using+ // the first 5 or 6 bits.++ // on the first rehash, use complement instead of val to shift+ // so we don't end up with 0 again if val==0.+ h = val ^ (comp>>8);+ s = h & mask;+ v = table[s];+ if (v==EMPTY || v==val) return s;++ h ^= (v << 17) | (comp >>> 16); // this is reversible+ s = h & mask;+ v = table[s];+ if (v==EMPTY || v==val) return s;++ h ^= (h << 8) | (comp >>> 25); // this is reversible+ s = h & mask;+ v = table[s];+ if (v==EMPTY || v==val) return s;++ /**********************+ // Knuth, Thomas Wang, http://www.concentric.net/~Ttwang/tech/inthash.htm+ // This magic number has no common factors with 2^32, and magic/(2^32) approximates+ // the golden ratio.+ private static final int magic = (int)2654435761L;++ h = magic*val;+ s = h & mask;+ v=table[s];+ if (v==EMPTY || v==val) return s;++ // the mult with magic should have thoroughly mixed the bits.+ // add entropy to the right half from the left half.+ h ^= h>>>16;+ s = h & mask;+ v=table[s];+ if (v==EMPTY || v==val) return s;+ *************************/++ // linear scan now... ug.+ final int start=s;+ while (++s<tablesize) {+ v=table[s];+ if (v==EMPTY || v==val) return s;+ }+ s=start;+ while (--s>=0) {+ v=table[s];+ if (v==EMPTY || v==val) return s;+ }+ return s;+ }+++ /**+ *+ * @return The number of document ids in the set.+ */+ public int size() {+ return size;+ }++ public boolean exists(int docid) {+ int v = table[docid & mask];+ if (v==EMPTY) return false;+ else if (v==docid) return true;+ else {+ v = table[rehash(docid)];+ if (v==docid) return true;+ else return false;+ }+ }++ public DocIterator iterator() {+ return new DocIterator() {+ int pos=0;+ int doc;+ { goNext(); }++ public boolean hasNext() {+ return pos < tablesize;+ }++ public Integer next() {+ return nextDoc();+ }++ public void remove() {+ }++ void goNext() {+ while (pos<tablesize && table[pos]==EMPTY) pos++;+ }++ // modify to return -1 at end of iteration?+ public int nextDoc() {+ int doc = table[pos];+ pos++;+ goNext();+ return doc;+ }++ public float score() {+ return 0.0f;+ }+ };+ }+++ public long memSize() {+ return (tablesize<<2) + 20;+ }+++ public DocSet intersection(DocSet other) {+ if (other instanceof HashDocSet) {+ // set "a" to the smallest doc set for the most efficient+ // intersection.+ final HashDocSet a = size()<=other.size() ? this : (HashDocSet)other;+ final HashDocSet b = size()<=other.size() ? (HashDocSet)other : this;++ int[] result = new int[a.size()];+ int resultCount=0;+ for (int i=0; i<a.table.length; i++) {+ int id=a.table[i];+ if (id >= 0 && b.exists(id)) {+ result[resultCount++]=id;+ }+ }+ return new HashDocSet(result,0,resultCount);++ } else {++ int[] result = new int[size()];+ int resultCount=0;+ for (int i=0; i<table.length; i++) {+ int id=table[i];+ if (id >= 0 && other.exists(id)) {+ result[resultCount++]=id;+ }+ }+ return new HashDocSet(result,0,resultCount);+ }++ }++ public int intersectionSize(DocSet other) {+ if (other instanceof HashDocSet) {+ // set "a" to the smallest doc set for the most efficient+ // intersection.+ final HashDocSet a = size()<=other.size() ? this : (HashDocSet)other;+ final HashDocSet b = size()<=other.size() ? (HashDocSet)other : this;++ int resultCount=0;+ for (int i=0; i<a.table.length; i++) {+ int id=a.table[i];+ if (id >= 0 && b.exists(id)) {+ resultCount++;+ }+ }+ return resultCount;+ } else {+ int resultCount=0;+ for (int i=0; i<table.length; i++) {+ int id=table[i];+ if (id >= 0 && other.exists(id)) {+ resultCount++;+ }+ }+ return resultCount;+ }++ }+++}diff --git a/src/java/org/apache/solr/search/LRUCache.java b/src/java/org/apache/solr/search/LRUCache.javanew file mode 100644index 00000000000..d47933b274d--- /dev/null+++ b/src/java/org/apache/solr/search/LRUCache.java@@ -0,0 +1,274 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;+import org.apache.solr.util.NamedList;++import java.util.*;+import java.util.concurrent.atomic.AtomicLong;+import java.io.IOException;+import java.net.URL;+++/**+ * @author yonik+ * @version $Id: LRUCache.java,v 1.12 2005/11/30 06:12:55 yonik Exp $+ */+public class LRUCache implements SolrCache {++ /* An instance of this class will be shared across multiple instances+ * of an LRUCache at the same time. Make sure everything is thread safe.+ */+ private static class CumulativeStats {+ AtomicLong lookups = new AtomicLong();+ AtomicLong hits = new AtomicLong();+ AtomicLong inserts = new AtomicLong();+ AtomicLong evictions = new AtomicLong();+ }++ private CumulativeStats stats;++ // per instance stats. The synchronization used for the map will also be+ // used for updating these statistics (and hence they are not AtomicLongs+ private long lookups;+ private long hits;+ private long inserts;+ private long evictions;++ private Map map;+ private String name;+ private int autowarmCount;+ private State state;+ private CacheRegenerator regenerator;++ public Object init(Map args, Object persistence, CacheRegenerator regenerator) {+ state=State.CREATED;+ this.regenerator = regenerator;+ name = (String)args.get("name");+ String str = (String)args.get("size");+ final int limit = str==null ? 1024 : Integer.parseInt(str);+ str = (String)args.get("initialSize");+ final int initialSize = Math.min(str==null ? 1024 : Integer.parseInt(str), limit);+ str = (String)args.get("autowarmCount");+ autowarmCount = str==null ? 0 : Integer.parseInt(str);++ map = new LinkedHashMap(initialSize, 0.75f, true) {+ protected boolean removeEldestEntry(Map.Entry eldest) {+ if (size() > limit) {+ // increment evictions regardless of state.+ // this doesn't need to be synchronized because it will+ // only be called in the context of a higher level synchronized block.+ evictions++;+ stats.evictions.incrementAndGet();+ return true;+ }+ return false;+ }+ };++ if (persistence==null) {+ // must be the first time a cache of this type is being created+ persistence = new CumulativeStats();+ }++ stats = (CumulativeStats)persistence;++ return persistence;+ }++ public String name() {+ return name;+ }++ public int size() {+ synchronized(map) {+ return map.size();+ }+ }++ public synchronized Object put(Object key, Object value) {+ if (state == State.LIVE) {+ stats.inserts.incrementAndGet();+ }++ synchronized (map) {+ // increment local inserts regardless of state???+ // it does make it more consistent with the current size...+ inserts++;+ return map.put(key,value);+ }+ }++ public Object get(Object key) {+ synchronized (map) {+ Object val = map.get(key);+ if (state == State.LIVE) {+ // only increment lookups and hits if we are live.+ lookups++;+ stats.lookups.incrementAndGet();+ if (val!=null) {+ hits++;+ stats.hits.incrementAndGet();+ }+ }+ return val;+ }+ }++ public void clear() {+ synchronized(map) {+ map.clear();+ }+ }++ public void setState(State state) {+ this.state = state;+ }++ public State getState() {+ return state;+ }++ public void warm(SolrIndexSearcher searcher, SolrCache old) throws IOException {+ if (regenerator==null) return;++ LRUCache other = (LRUCache)old;++ // warm entries+ if (autowarmCount != 0) {+ Object[] keys,vals = null;++ // Don't do the autowarming in the synchronized block, just pull out the keys and values.+ synchronized (other.map) {+ int sz = other.map.size();+ if (autowarmCount!=-1) sz = Math.min(sz,autowarmCount);+ keys = new Object[sz];+ vals = new Object[sz];++ Iterator iter = other.map.entrySet().iterator();++ // iteration goes from oldest (least recently used) to most recently used,+ // so we need to skip over the oldest entries.+ int skip = other.map.size() - sz;+ for (int i=0; i<skip; i++) iter.next();+++ for (int i=0; i<sz; i++) {+ Map.Entry entry = (Map.Entry)iter.next();+ keys[i]=entry.getKey();+ vals[i]=entry.getValue();+ }+ }++ // autowarm from the oldest to the newest entries so that the ordering will be+ // correct in the new cache.+ for (int i=0; i<keys.length; i++) {+ try {+ boolean continueRegen = regenerator.regenerateItem(searcher, this, old, keys[i], vals[i]);+ if (!continueRegen) break;+ }+ catch (Throwable e) {+ SolrException.log(log,"Error during auto-warming of key:" + keys[i], e);+ }+ }+ }+ }+++ public void close() {+ }+++ //////////////////////// SolrInfoMBeans methods //////////////////////+++ public String getName() {+ return LRUCache.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "LRU Cache";+ }++ public Category getCategory() {+ return Category.CACHE;+ }++ public String getCvsId() {+ return "$Id: LRUCache.java,v 1.12 2005/11/30 06:12:55 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/search/LRUCache.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }+++ // returns a ratio, not a percent.+ private static String calcHitRatio(long lookups, long hits) {+ if (lookups==0) return "0.00";+ if (lookups==hits) return "1.00";+ int hundredths = (int)(hits*100/lookups); // rounded down+ if (hundredths < 10) return "0.0" + hundredths;+ return "0." + hundredths;++ /*** code to produce a percent, if we want it...+ int ones = (int)(hits*100 / lookups);+ int tenths = (int)(hits*1000 / lookups) - ones*10;+ return Integer.toString(ones) + '.' + tenths;+ ***/+ }++ public NamedList getStatistics() {+ NamedList lst = new NamedList();+ synchronized (map) {+ lst.add("lookups", lookups);+ lst.add("hits", hits);+ lst.add("hitratio", calcHitRatio(lookups,hits));+ lst.add("inserts", inserts);+ lst.add("evictions", evictions);+ lst.add("size", map.size());+ }++ long clookups = stats.lookups.get();+ long chits = stats.hits.get();+ lst.add("cumulative_lookups", clookups);+ lst.add("cumulative_hits", chits);+ lst.add("cumulative_hitratio", calcHitRatio(clookups,chits));+ lst.add("cumulative_inserts", stats.inserts.get());+ lst.add("cumulative_evictions", stats.evictions.get());++ return lst;+ }++ public String toString() {+ return name + getStatistics().toString();+ }+}diff --git a/src/java/org/apache/solr/search/LuceneQueryOptimizer.java b/src/java/org/apache/solr/search/LuceneQueryOptimizer.javanew file mode 100644index 00000000000..e8889403d84--- /dev/null+++ b/src/java/org/apache/solr/search/LuceneQueryOptimizer.java@@ -0,0 +1,116 @@+/**+ * 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.+ */++package org.apache.solr.search;++/* Copyright (c) 2003 The Nutch Organization. All rights reserved. */+/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */+++import org.apache.lucene.search.*;++import java.util.LinkedHashMap;+import java.util.Map;+import java.io.IOException;++/** Utility which converts certain query clauses into {@link QueryFilter}s and+ * caches these. Only required {@link TermQuery}s whose boost is zero and+ * whose term occurs in at least a certain fraction of documents are converted+ * to cached filters. This accellerates query constraints like language,+ * document format, etc., which do not affect ranking but might otherwise slow+ * search considerably. */+// Taken from Nutch and modified - YCS+class LuceneQueryOptimizer {+ private LinkedHashMap cache; // an LRU cache of QueryFilter++ private float threshold;++ /** Construct an optimizer that caches and uses filters for required {@link+ * TermQuery}s whose boost is zero.+ * @param cacheSize the number of QueryFilters to cache+ * @param threshold the fraction of documents which must contain term+ */+ public LuceneQueryOptimizer(final int cacheSize, float threshold) {+ this.cache = new LinkedHashMap(cacheSize, 0.75f, true) {+ protected boolean removeEldestEntry(Map.Entry eldest) {+ return size() > cacheSize; // limit size of cache+ }+ };+ this.threshold = threshold;+ }++ public TopDocs optimize(BooleanQuery original,+ Searcher searcher,+ int numHits,+ Query[] queryOut,+ Filter[] filterOut+ )+ throws IOException {++ BooleanQuery query = new BooleanQuery();+ BooleanQuery filterQuery = null;++ BooleanClause[] clauses = original.getClauses();+ for (int i = 0; i < clauses.length; i++) {+ BooleanClause c = clauses[i];++/***+System.out.println("required="+c.required);+System.out.println("boost="+c.query.getBoost());+System.out.println("isTermQuery="+(c.query instanceof TermQuery));+if (c.query instanceof TermQuery) {+ System.out.println("term="+((TermQuery)c.query).getTerm());+ System.out.println("docFreq="+searcher.docFreq(((TermQuery)c.query).getTerm()));+}+***/+ if (c.required // required+ && c.query.getBoost() == 0.0f // boost is zero+ && c.query instanceof TermQuery // TermQuery+ && (searcher.docFreq(((TermQuery)c.query).getTerm())+ / (float)searcher.maxDoc()) >= threshold) { // check threshold+ if (filterQuery == null)+ filterQuery = new BooleanQuery();+ filterQuery.add(c.query, true, false); // filter it+//System.out.println("WooHoo... qualified to be hoisted to a filter!");+ } else {+ query.add(c); // query it+ }+ }++ Filter filter = null;+ if (filterQuery != null) {+ synchronized (cache) { // check cache+ filter = (Filter)cache.get(filterQuery);+ }+ if (filter == null) { // miss+ filter = new QueryFilter(filterQuery); // construct new entry+ synchronized (cache) {+ cache.put(filterQuery, filter); // cache it+ }+ }+ }++ // YCS: added code to pass out optimized query and filter+ // so they can be used with Hits+ if (queryOut != null && filterOut != null) {+ queryOut[0] = query; filterOut[0] = filter;+ return null;+ } else {+ return searcher.search(query, filter, numHits);+ }++ }+}diff --git a/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java b/src/java/org/apache/solr/search/MissingStringLastComparatorSource.javanew file mode 100644index 00000000000..34ae67251da--- /dev/null+++ b/src/java/org/apache/solr/search/MissingStringLastComparatorSource.java@@ -0,0 +1,115 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.search.*;+import org.apache.lucene.index.IndexReader;++import java.io.IOException;+++/**+ * A {@link SortComparatorSource} for strings that orders null values after non-null values.+ * Based on FieldSortedHitQueue.comparatorString+ * <p>+ *+ * @author Chris Hostetter+ * @author yonik+ * @version $Id: MissingStringLastComparatorSource.java,v 1.1 2005/06/02 04:43:06 yonik Exp $+ *+ */++// move to apache package and make public if it is accepted as a patch+class MissingStringLastComparatorSource implements SortComparatorSource {++ public static final String bigString="\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffffNULL_VAL";++ private final String missingValueProxy;++ public MissingStringLastComparatorSource() {+ this(bigString);+ }++ /**+ * Returns the value used to sort the given document. The+ * object returned must implement the java.io.Serializable+ * interface. This is used by multisearchers to determine how to collate results from their searchers.+ * @see FieldDoc+ * @param i Document+ * @return Serializable object+ */++ /** Creates a {@link SortComparatorSource} that uses <tt>missingValueProxy</tt> as the value to return from ScoreDocComparator.sortValue()+ * which is only used my multisearchers to determine how to collate results from their searchers.+ *+ * @param missingValueProxy The value returned when sortValue() is called for a document missing the sort field.+ * This value is *not* normally used for sorting, but used to create+ */+ public MissingStringLastComparatorSource(String missingValueProxy) {+ this.missingValueProxy=missingValueProxy;+ }++ public ScoreDocComparator newComparator(final IndexReader reader,+ final String fieldname)+ throws IOException {++ final String field = fieldname.intern();+ final FieldCache.StringIndex index =+ FieldCache.DEFAULT.getStringIndex (reader, field);++ // :HACK:+ // final String lastString =+ // (index.lookup[index.lookup.length-1]+"X").intern();+ //+ // Note: basing lastStringValue on the StringIndex won't work+ // with a multisearcher.+++ return new ScoreDocComparator () {++ public final int compare (final ScoreDoc i, final ScoreDoc j) {+ final int fi = index.order[i.doc];+ final int fj = index.order[j.doc];++ // 0 is the magic position of null++ /**** alternate logic+ if (fi < fj && fi != 0) return -1;+ if (fj < fi && fj != 0) return 1;+ if (fi==fj) return 0;+ return fi==0 ? 1 : -1;+ ****/++ if (fi==fj) return 0;+ if (fi==0) return 1;+ if (fj==0) return -1;+ return fi < fj ? -1 : 1;++ }++ public Comparable sortValue (final ScoreDoc i) {+ int f = index.order[i.doc];+ return (0 == f) ? missingValueProxy : index.lookup[f];+ }++ public int sortType() {+ return SortField.CUSTOM;+ }+ };++ }+}diff --git a/src/java/org/apache/solr/search/QueryParsing.java b/src/java/org/apache/solr/search/QueryParsing.javanew file mode 100644index 00000000000..24f0c41022b--- /dev/null+++ b/src/java/org/apache/solr/search/QueryParsing.java@@ -0,0 +1,479 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.search.*;+import org.apache.lucene.search.function.*;+import org.apache.lucene.queryParser.ParseException;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.Term;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;+import org.apache.solr.schema.FieldType;++import java.util.ArrayList;+import java.util.regex.Pattern;+import java.util.logging.Level;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id: QueryParsing.java,v 1.10 2005/12/20 21:34:44 yonik Exp $+ */+public class QueryParsing {++ public static Query parseQuery(String qs, IndexSchema schema) {+ try {+ Query query = new SolrQueryParser(schema).parse(qs);++ if (SolrCore.log.isLoggable(Level.FINEST)) {+ SolrCore.log.finest("After QueryParser:" + query);+ }++ return query;++ } catch (ParseException e) {+ SolrCore.log(e);+ throw new SolrException(400,"Error parsing Lucene query",e);+ }+ }++++ /***+ * SortSpec encapsulates a Lucene Sort and a count of the number of documents+ * to return.+ */+ public static class SortSpec {+ private final Sort sort;+ private final int num;++ SortSpec(Sort sort, int num) {+ this.sort=sort;+ this.num=num;+ }++ /**+ * Gets the Lucene Sort object, or null for the default sort+ * by score descending.+ */+ public Sort getSort() { return sort; }++ /**+ * Gets the number of documens to return after sorting.+ * -1 means there is no cutoff (only do the sort)+ * @return+ */+ public int getCount() { return num; }+ }+++ private static Pattern sortSeparator = Pattern.compile("[\\s,]+");++ /**+ * Returns null if the sortSpec string doesn't look like a sort specification,+ * or if the sort specification couldn't be converted into a Lucene Sort+ * (because of a field not being indexed or undefined, etc).+ *+ * The form of the sort specification string currently parsed is:+ * SortSpec ::= SingleSort [, SingleSort]* <number>?+ * SingleSort ::= <fieldname> SortDirection+ * SortDirection ::= top | desc | bottom | asc+ *+ * Examples:+ * top 10 #take the top 10 by score+ * desc 10 #take the top 10 by score+ * score desc 10 #take the top 10 by score+ * weight bottom 10 #sort by weight ascending and take the first 10+ * weight desc #sort by weight descending+ * height desc,weight desc #sort by height descending, and use weight descending to break any ties+ * height desc,weight asc top 20 #sort by height descending, using weight ascending as a tiebreaker+ *+ */+ public static SortSpec parseSort(String sortSpec, IndexSchema schema) {+ if (sortSpec==null || sortSpec.length()==0) return null;++ // I wonder how fast the regex is??? as least we cache the pattern.+ String[] parts = sortSeparator.split(sortSpec.trim(),0);+ if (parts.length == 0) return null;++ ArrayList<SortField> lst = new ArrayList<SortField>();+ int num=-1;++ int pos=0;+ String fn;+ boolean top=true;+ boolean normalSortOnScore=false;++ while (pos < parts.length) {+ String str=parts[pos];+ if ("top".equals(str) || "bottom".equals(str) || "asc".equals(str) || "desc".equals(str)) {+ // if the field name seems to be missing, default to "score".+ // note that this will mess up a field name that has the same name+ // as a sort direction specifier.+ fn="score";+ } else {+ fn=str;+ pos++;+ }++ // get the direction of the sort+ str=parts[pos];+ if ("top".equals(str) || "desc".equals(str)) {+ top=true;+ } else if ("bottom".equals(str) || "asc".equals(str)) {+ top=false;+ } else {+ return null; // must not be a sort command+ }++ // get the field to sort on+ // hmmm - should there be a fake/pseudo-field named "score" in the schema?+ if ("score".equals(fn)) {+ if (top) {+ normalSortOnScore=true;+ lst.add(SortField.FIELD_SCORE);+ } else {+ lst.add(new SortField(null, SortField.SCORE, true));+ }+ } else {+ // getField could throw an exception if the name isn't found+ try {+ SchemaField f = schema.getField(fn);+ if (f == null || !f.indexed()) return null;+ lst.add(f.getType().getSortField(f,top));+ } catch (Exception e) {+ return null;+ }+ }+ pos++;++ // If there is a leftover part, assume it is a count+ if (pos+1 == parts.length) {+ try {+ num = Integer.parseInt(parts[pos]);+ } catch (Exception e) {+ return null;+ }+ pos++;+ }+ }++ Sort sort;+ if (normalSortOnScore && lst.size() == 1) {+ // Normalize the default sort on score descending to sort=null+ sort=null;+ } else {+ sort = new Sort((SortField[]) lst.toArray(new SortField[lst.size()]));+ }+ return new SortSpec(sort,num);+ }+++ ///////////////////////////+ ///////////////////////////+ ///////////////////////////++ static FieldType writeFieldName(String name, IndexSchema schema, Appendable out, int flags) throws IOException {+ FieldType ft = null;+ ft = schema.getFieldTypeNoEx(name);+ out.append(name);+ if (ft==null) {+ out.append("(UNKNOWN FIELD "+name+')');+ }+ out.append(':');+ return ft;+ }++ static void writeFieldVal(String val, FieldType ft, Appendable out, int flags) throws IOException {+ if (ft!=null) {+ out.append(ft.toExternal(new Field("",val,true,true,false)));+ } else {+ out.append(val);+ }+ }++ public static void toString(Query query, IndexSchema schema, Appendable out, int flags) throws IOException {+ boolean writeBoost=true;++ if (query instanceof TermQuery) {+ TermQuery q = (TermQuery)query;+ Term t = q.getTerm();+ FieldType ft = writeFieldName(t.field(), schema, out, flags);+ writeFieldVal(t.text(), ft, out, flags);+ } else if (query instanceof RangeQuery) {+ RangeQuery q = (RangeQuery)query;+ String fname = q.getField();+ FieldType ft = writeFieldName(fname, schema, out, flags);+ out.append( q.isInclusive() ? '[' : '{' );+ Term lt = q.getLowerTerm();+ Term ut = q.getUpperTerm();+ if (lt==null) {+ out.append('*');+ } else {+ writeFieldVal(lt.text(), ft, out, flags);+ }++ out.append(" TO ");++ if (ut==null) {+ out.append('*');+ } else {+ writeFieldVal(ut.text(), ft, out, flags);+ }++ out.append( q.isInclusive() ? ']' : '}' );++ } else if (query instanceof ConstantScoreRangeQuery) {+ ConstantScoreRangeQuery q = (ConstantScoreRangeQuery)query;+ String fname = q.getField();+ FieldType ft = writeFieldName(fname, schema, out, flags);+ out.append( q.includesLower() ? '[' : '{' );+ String lt = q.getLowerVal();+ String ut = q.getUpperVal();+ if (lt==null) {+ out.append('*');+ } else {+ writeFieldVal(lt, ft, out, flags);+ }++ out.append(" TO ");++ if (ut==null) {+ out.append('*');+ } else {+ writeFieldVal(ut, ft, out, flags);+ }++ out.append( q.includesUpper() ? ']' : '}' );+ } else if (query instanceof BooleanQuery) {+ BooleanQuery q = (BooleanQuery)query;+ boolean needParens=false;++ if (q.getBoost() != 1.0 || q.getMinimumNumberShouldMatch() != 0) {+ needParens=true;+ }+ if (needParens) {+ out.append('(');+ }+ BooleanClause[] clauses = q.getClauses();+ boolean first=true;+ for (BooleanClause c : clauses) {+ if (!first) {+ out.append(' ');+ } else {+ first=false;+ }++ if (c.prohibited) {+ out.append('-');+ } else if (c.required) {+ out.append('+');+ }+ Query subQuery = c.query;+ boolean wrapQuery=false;++ // TODO: may need to put parens around other types+ // of queries too, depending on future syntax.+ if (subQuery instanceof BooleanQuery) {+ wrapQuery=true;+ }++ if (wrapQuery) {+ out.append('(');+ }++ toString(subQuery, schema, out, flags);++ if (wrapQuery) {+ out.append(')');+ }+ }++ if (needParens) {+ out.append(')');+ }+ if (q.getMinimumNumberShouldMatch()>0) {+ out.append('~');+ out.append(Integer.toString(q.getMinimumNumberShouldMatch()));+ }++ } else if (query instanceof PrefixQuery) {+ PrefixQuery q = (PrefixQuery)query;+ Term prefix = q.getPrefix();+ FieldType ft = writeFieldName(prefix.field(), schema, out, flags);+ out.append(prefix.text());+ out.append('*');+ } else if (query instanceof ConstantScorePrefixQuery) {+ ConstantScorePrefixQuery q = (ConstantScorePrefixQuery)query;+ Term prefix = q.getPrefix();+ FieldType ft = writeFieldName(prefix.field(), schema, out, flags);+ out.append(prefix.text());+ out.append('*');+ } else if (query instanceof WildcardQuery) {+ out.append(query.toString());+ writeBoost=false;+ } else if (query instanceof FuzzyQuery) {+ out.append(query.toString());+ writeBoost=false;+ } else if (query instanceof ConstantScoreQuery) {+ out.append(query.toString());+ writeBoost=false;+ } else {+ out.append(query.getClass().getSimpleName()+ + '(' + query.toString() + ')' );+ writeBoost=false;+ }++ if (writeBoost && query.getBoost() != 1.0f) {+ out.append("^");+ out.append(Float.toString(query.getBoost()));+ }++ }++ public static String toString(Query query, IndexSchema schema) {+ try {+ StringBuilder sb = new StringBuilder();+ toString(query, schema, sb, 0);+ return sb.toString();+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+++++ // simple class to help with parsing a string+ private static class StrParser {+ String val;+ int pos;+ int end;++ StrParser(String val) {this.val = val; end=val.length(); }++ void eatws() {+ while (pos<end && Character.isWhitespace(val.charAt(pos))) pos++;+ }++ boolean opt(String s) {+ eatws();+ int slen=s.length();+ if (val.regionMatches(pos, s, 0, slen)) {+ pos+=slen;+ return true;+ }+ return false;+ }++ void expect(String s) throws ParseException {+ eatws();+ int slen=s.length();+ if (val.regionMatches(pos, s, 0, slen)) {+ pos+=slen;+ } else {+ throw new ParseException("Expected '"+s+"' at position " + pos + " in '"+val+"'");+ }+ }++ float getFloat() throws ParseException {+ eatws();+ char[] arr = new char[end-pos];+ int i;+ for (i=0; i<arr.length; i++) {+ char ch = val.charAt(pos);+ if ( (ch>='0' && ch<='9')+ || ch=='+' || ch=='-'+ || ch=='.' || ch=='e' || ch=='E'+ ) {+ pos++;+ arr[i]=ch;+ } else {+ break;+ }+ }++ return Float.parseFloat(new String(arr,0,i));+ }++ String getId() throws ParseException {+ eatws();+ int id_start=pos;+ while (pos<end && Character.isJavaIdentifierPart(val.charAt(pos))) pos++;+ return val.substring(id_start, pos);+ }++ char peek() {+ eatws();+ return pos<end ? val.charAt(pos) : 0;+ }++ public String toString() {+ return "'" + val + "'" + ", pos=" + pos;+ }++ }+++ private static ValueSource parseValSource(StrParser sp, IndexSchema schema) throws ParseException {+ String id = sp.getId();+ if (sp.opt("(")) {+ // a function: could contain a fieldname or another function.+ ValueSource vs=null;+ if (id.equals("ord")) {+ String field = sp.getId();+ vs = new OrdFieldSource(field);+ } else if (id.equals("rord")) {+ String field = sp.getId();+ vs = new ReverseOrdFieldSource(field);+ } else if (id.equals("linear")) {+ ValueSource source = parseValSource(sp, schema);+ sp.expect(",");+ float slope = sp.getFloat();+ sp.expect(",");+ float intercept = sp.getFloat();+ vs = new LinearFloatFunction(source,slope,intercept);+ } else if (id.equals("recip")) {+ ValueSource source = parseValSource(sp,schema);+ sp.expect(",");+ float m = sp.getFloat();+ sp.expect(",");+ float a = sp.getFloat();+ sp.expect(",");+ float b = sp.getFloat();+ vs = new ReciprocalFloatFunction(source,m,a,b);+ } else {+ throw new ParseException("Unknown function " + id + " in FunctionQuery(" + sp + ")");+ }+ sp.expect(")");+ return vs;+ }++ SchemaField f = schema.getField(id);+ return f.getType().getValueSource(f);+ }++ /** Parse a function, returning a FunctionQuery+ */+ public static FunctionQuery parseFunction(String func, IndexSchema schema) throws ParseException {+ return new FunctionQuery(parseValSource(new StrParser(func), schema));+ }++}diff --git a/src/java/org/apache/solr/search/QueryResultKey.java b/src/java/org/apache/solr/search/QueryResultKey.javanew file mode 100644index 00000000000..bedc4bda352--- /dev/null+++ b/src/java/org/apache/solr/search/QueryResultKey.java@@ -0,0 +1,107 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.search.Query;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;++import java.util.List;++/** A hash key encapsulating a query, a list of filters, and a sort+ * @author yonik+ * @version $Id$+ */+public final class QueryResultKey {+ final Query query;+ final Sort sort; // change to normal Sort after Lucene 1.4.3+ final SortField[] sfields;+ final List<Query> filters;+ final int nc_flags; // non-comparable flags... ignored by hashCode and equals++ private final int hc; // cached hashCode++ private static SortField[] defaultSort = new SortField[0];+++ public QueryResultKey(Query query, List<Query> filters, Sort sort, int nc_flags) {+ this.query = query;+ this.sort = sort;+ this.filters = filters;+ this.nc_flags = nc_flags;++ int h = query.hashCode();++ if (filters != null) h ^= filters.hashCode();++ sfields = (this.sort !=null) ? this.sort.getSort() : defaultSort;+ for (SortField sf : sfields) {+ // mix the bits so that sortFields are position dependent+ // so that a,b won't hash to the same value as b,a+ h ^= (h << 8) | (h >>> 25); // reversible hash++ if (sf.getField() != null) h += sf.getField().hashCode();+ h += sf.getType();+ if (sf.getReverse()) h=~h;+ if (sf.getLocale()!=null) h+=sf.getLocale().hashCode();+ if (sf.getFactory()!=null) h+=sf.getFactory().hashCode();+ }++ hc = h;+ }++ public int hashCode() {+ return hc;+ }++ public boolean equals(Object o) {+ if (o==this) return true;+ if (!(o instanceof QueryResultKey)) return false;+ QueryResultKey other = (QueryResultKey)o;++ // fast check of the whole hash code... most hash tables will only use+ // some of the bits, so if this is a hash collision, it's still likely+ // that the full cached hash code will be different.+ if (this.hc != other.hc) return false;++ // check for the thing most likely to be different (and the fastest things)+ // first.+ if (this.sfields.length != other.sfields.length) return false;+ if (!this.query.equals(other.query)) return false;+ if (!isEqual(this.filters, other.filters)) return false;++ for (int i=0; i<sfields.length; i++) {+ SortField sf1 = this.sfields[i];+ SortField sf2 = other.sfields[i];+ if (sf1.getType() != sf2.getType()) return false;+ if (sf1.getReverse() != sf2.getReverse()) return false;+ if (!isEqual(sf1.getField(),sf2.getField())) return false;+ if (!isEqual(sf1.getLocale(), sf2.getLocale())) return false;+ if (!isEqual(sf1.getFactory(), sf2.getFactory())) return false;+ // NOTE: the factory must be identical!!! use singletons!+ }++ return true;+ }+++ private static boolean isEqual(Object o1, Object o2) {+ if (o1==o2) return true; // takes care of identity and null cases+ if (o1==null || o2==null) return false;+ return o1.equals(o2);+ }+}diff --git a/src/java/org/apache/solr/search/SolrCache.java b/src/java/org/apache/solr/search/SolrCache.javanew file mode 100644index 00000000000..d4573481242--- /dev/null+++ b/src/java/org/apache/solr/search/SolrCache.java@@ -0,0 +1,102 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.solr.core.SolrInfoMBean;++import java.util.Map;+import java.util.logging.Logger;+import java.io.IOException;+++/**+ *+ * @author yonik+ * @version $Id: SolrCache.java,v 1.6 2005/06/21 05:26:43 yonik Exp $+ */+public interface SolrCache extends SolrInfoMBean {+ public final static Logger log = Logger.getLogger(SolrCache.class.getName());+++ /**+ * The initialization routine. Instance specific arguments are passed in+ * the <code>args</code> map.+ * <p>+ * The persistence object will exist across different lifetimes of similar caches.+ * For example, all filter caches will share the same persistence object, sometimes+ * at the same time (it must be threadsafe). If null is passed, then the cache+ * implementation should create and return a new persistence object. If not null,+ * the passed in object should be returned again.+ * <p>+ * Since it will exist across the lifetime of many caches, care should be taken to+ * not reference any particular cache instance and prevent it from being+ * garbage collected (no using inner classes unless they are static).+ * <p>+ * Since the persistence object is designed to be used as a way for statistics+ * to accumulate across all instances of the same type of cache, however the+ * object may be of any type desired by the cache implementation.+ * <p>+ * The {@link CacheRegenerator} is what the cache uses during auto-warming to+ * renenerate an item in the new cache from an entry in the old cache.+ *+ */+ public Object init(Map args, Object persistence, CacheRegenerator regenerator);+ // I don't think we need a factory for faster creation given that these+ // will be associated with slow-to-create SolrIndexSearchers.+ // change to NamedList when other plugins do?++ // symbolic name for this cache+ public String name();+++ // Should SolrCache just extend the java.util.Map interface?+ // Following the conventions of the java.util.Map interface in any case.++ public int size();++ public Object put(Object key, Object value);++ public Object get(Object key);++ public void clear();+++ /**+ * Set different cache states.+ * The state a cache is in can have an effect on how statistics are kept.+ * The cache user (SolrIndexSearcher) will take care of switching+ * cache states.+ */+ public enum State { CREATED, STATICWARMING, AUTOWARMING, LIVE }+ public void setState(State state);+ public State getState();+++ /**+ * Warm this cache associated with <code>searcher</code> using the <code>old</code>+ * cache object. <code>this</code> and <code>old</code> will have the same concrete type.+ */+ void warm(SolrIndexSearcher searcher, SolrCache old) throws IOException;+ // Q: an alternative to passing the searcher here would be to pass it in+ // init and have the cache implementation save it.+++ /** Frees any non-memory resources */+ public void close();++}+diff --git a/src/java/org/apache/solr/search/SolrIndexSearcher.java b/src/java/org/apache/solr/search/SolrIndexSearcher.javanew file mode 100644index 00000000000..e63694bb7f0--- /dev/null+++ b/src/java/org/apache/solr/search/SolrIndexSearcher.java@@ -0,0 +1,1163 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.document.Document;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.search.*;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.PriorityQueue;+import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrInfoMBean;+import org.apache.solr.core.SolrInfoRegistry;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.util.NamedList;++import java.io.IOException;+import java.net.URL;+import java.util.*;+import java.util.logging.Level;+import java.util.logging.Logger;+++/**+ * SolrIndexSearcher adds schema awareness and caching functionality+ * over the lucene IndexSearcher.++ * @author yonik+ * @version $Id: SolrIndexSearcher.java,v 1.49 2005/12/20 16:05:46 yonik Exp $+ * @since solr 0.9+ */++// Since the internal reader in IndexSearcher is+// package protected, I can't get to it by inheritance.+// For now, I am using delgation and creating the+// IndexReader to pass to the searcher myself.+// NOTE: as of Lucene 1.9, this has changed!++public class SolrIndexSearcher extends Searcher implements SolrInfoMBean {+ private static Logger log = Logger.getLogger(SolrIndexSearcher.class.getName());++ private final IndexSchema schema;++ private final String name;+ private final IndexSearcher searcher;+ private final IndexReader reader;+ private final boolean closeReader;++ private final boolean cachingEnabled;+ private final SolrCache filterCache;+ private final SolrCache queryResultCache;+ private final SolrCache documentCache;++ // map of generic caches - not synchronized since it's read-only after the constructor.+ private final HashMap<String, SolrCache> cacheMap;+ private static final HashMap<String, SolrCache> noGenericCaches=new HashMap<String,SolrCache>(0);++ // list of all caches associated with this searcher.+ private final SolrCache[] cacheList;+ private static final SolrCache[] noCaches = new SolrCache[0];++ /** Creates a searcher searching the index in the named directory. */+ /** Creates a searcher searching the index in the named directory. */+ public SolrIndexSearcher(IndexSchema schema, String name, String path, boolean enableCache) throws IOException {+ this(schema,name,IndexReader.open(path), true, enableCache);+ }++ /** Creates a searcher searching the index in the provided directory. */+ public SolrIndexSearcher(IndexSchema schema, String name, Directory directory, boolean enableCache) throws IOException {+ this(schema,name,IndexReader.open(directory), true, enableCache);+ }++ /** Creates a searcher searching the provided index. */+ public SolrIndexSearcher(IndexSchema schema, String name, IndexReader r, boolean enableCache) {+ this(schema,name,r, false, enableCache);+ }++ private SolrIndexSearcher(IndexSchema schema, String name, IndexReader r, boolean closeReader, boolean enableCache) {+ this.schema = schema;+ this.name = "Searcher@" + Integer.toHexString(hashCode()) + (name!=null ? " "+name : "");++ log.info("Opening " + this.name);++ reader = r;+ searcher = new IndexSearcher(r);+ this.closeReader = closeReader;+ searcher.setSimilarity(schema.getSimilarity());++ cachingEnabled=enableCache;+ if (cachingEnabled) {+ ArrayList<SolrCache> clist = new ArrayList<SolrCache>();+ filterCache= filterCacheConfig==null ? null : filterCacheConfig.newInstance();+ if (filterCache!=null) clist.add(filterCache);+ queryResultCache = queryResultCacheConfig==null ? null : queryResultCacheConfig.newInstance();+ if (queryResultCache!=null) clist.add(queryResultCache);+ documentCache = documentCacheConfig==null ? null : documentCacheConfig.newInstance();+ if (documentCache!=null) clist.add(documentCache);++ if (userCacheConfigs == null) {+ cacheMap = noGenericCaches;+ } else {+ cacheMap = new HashMap<String,SolrCache>(userCacheConfigs.length);+ for (CacheConfig userCacheConfig : userCacheConfigs) {+ SolrCache cache = null;+ if (userCacheConfig != null) cache = userCacheConfig.newInstance();+ if (cache != null) {+ cacheMap.put(cache.name(), cache);+ clist.add(cache);+ }+ }+ }++ cacheList = clist.toArray(new SolrCache[clist.size()]);+ } else {+ filterCache=null;+ queryResultCache=null;+ documentCache=null;+ cacheMap = noGenericCaches;+ cacheList= noCaches;+ }+ }+++ public String toString() {+ return name;+ }+++ /*** Register sub-objects such as caches+ */+ public void register() {+ for (SolrCache cache : cacheList) {+ cache.setState(SolrCache.State.LIVE);+ SolrInfoRegistry.getRegistry().put(cache.name(), cache);+ }+ }+++ public void close() throws IOException {+ if (cachingEnabled) {+ StringBuilder sb = new StringBuilder();+ sb.append("Closing ").append(name);+ for (SolrCache cache : cacheList) {+ sb.append("\n\t");+ sb.append(cache);+ }+ log.info(sb.toString());+ } else {+ log.fine("Closing " + name);+ }+ try {+ searcher.close();+ }+ finally {+ if(closeReader) reader.close();+ for (SolrCache cache : cacheList) {+ cache.close();+ }+ }+ }++ public IndexReader getReader() { return reader; }+ public IndexSchema getSchema() { return schema; }+++ // params for the "nutch" query optimizer+ private static boolean filtOptEnabled=SolrConfig.config.getBool("query/boolTofilterOptimizer/@enabled",false);+ private static int filtOptCacheSize=SolrConfig.config.getInt("query/boolTofilterOptimizer/@cacheSize",32);+ private static float filtOptThreshold= SolrConfig.config.getFloat("query/boolTofilterOptimizer/@threshold",.05f);+ private LuceneQueryOptimizer optimizer = filtOptEnabled ? new LuceneQueryOptimizer(filtOptCacheSize,filtOptThreshold) : null;+++ private static final CacheConfig filterCacheConfig = CacheConfig.getConfig("query/filterCache");+ private static final CacheConfig queryResultCacheConfig = CacheConfig.getConfig("query/queryResultCache");+ private static final CacheConfig documentCacheConfig = CacheConfig.getConfig("query/documentCache");+ private static final CacheConfig[] userCacheConfigs = CacheConfig.getMultipleConfigs("query/cache");+++ //+ // Set default regenerators on filter and query caches if they don't have any+ //+ static {+ if (filterCacheConfig != null && filterCacheConfig.getRegenerator() == null) {+ filterCacheConfig.setRegenerator(+ new CacheRegenerator() {+ public boolean regenerateItem(SolrIndexSearcher newSearcher, SolrCache newCache, SolrCache oldCache, Object oldKey, Object oldVal) throws IOException {+ newSearcher.cacheDocSet((Query)oldKey, null, false);+ return true;+ }+ }+ );+ }++ if (queryResultCacheConfig != null && queryResultCacheConfig.getRegenerator() == null) {+ queryResultCacheConfig.setRegenerator(+ new CacheRegenerator() {+ public boolean regenerateItem(SolrIndexSearcher newSearcher, SolrCache newCache, SolrCache oldCache, Object oldKey, Object oldVal) throws IOException {+ QueryResultKey key = (QueryResultKey)oldKey;+ int nDocs=1;+ // request 1 doc and let caching round up to the next window size...+ // unless the window size is <=1, in which case we will pick+ // the minimum of the number of documents requested last time and+ // a reasonable number such as 40.+ // TODO: make more configurable later...++ if (queryResultWindowSize<=1) {+ DocList oldList = (DocList)oldVal;+ int oldnDocs = oldList.offset() + oldList.size();+ // 40 has factors of 2,4,5,10,20+ nDocs = Math.min(oldnDocs,40);+ }++ DocListAndSet ret = new DocListAndSet();+ int flags=NO_CHECK_QCACHE | key.nc_flags;++ newSearcher.getDocListC(ret, key.query, key.filters, null, key.sort, 0, nDocs, flags);+ return true;+ }+ }+ );+ }+ }+++ private static boolean useFilterForSortedQuery=SolrConfig.config.getBool("query/useFilterForSortedQuery", false);+ private static int queryResultWindowSize=SolrConfig.config.getInt("query/queryResultWindowSize", 1);+++ public Hits search(Query query, Filter filter, Sort sort) throws IOException {+ // todo - when SOLAR starts accepting filters, need to+ // change this conditional check (filter!=null) and create a new filter+ // that ANDs them together if it already exists.++ if (optimizer==null || filter!=null || !(query instanceof BooleanQuery)+ ) {+ return searcher.search(query,filter,sort);+ } else {+ Query[] newQuery = new Query[1];+ Filter[] newFilter = new Filter[1];+ optimizer.optimize((BooleanQuery)query, searcher, 0, newQuery, newFilter);++ // TODO REMOVE+ if (newFilter[0]!=null) {+ // System.out.println("OPTIMIZED QUERY: FILTER=" + newFilter[0]);+ }++ return searcher.search(newQuery[0], newFilter[0], sort);+ }+ }++ /******+ * Shouldn't be needed since IndexReader has it's own finalize method+ * and there is nothing else to clean up here (for now at least)+ *+ protected void finalize() {+ try {+ close();+ super.finalize();+ } catch (Throwable e) {+ SolrException.log(log,e);+ }+ }+ ******/+++ public Hits search(Query query, Filter filter) throws IOException {+ return searcher.search(query, filter);+ }++ public Hits search(Query query, Sort sort) throws IOException {+ return searcher.search(query, sort);+ }++ /*** Replaced this one with one that does filter optimization+ public Hits search(Query query, Filter filter, Sort sort) throws IOException {+ return searcher.search(query, filter, sort);+ }+ ***/++ public void search(Query query, HitCollector results) throws IOException {+ searcher.search(query, results);+ }++ public void setSimilarity(Similarity similarity) {+ searcher.setSimilarity(similarity);+ }++ public Similarity getSimilarity() {+ return searcher.getSimilarity();+ }++ public int docFreq(Term term) throws IOException {+ return searcher.docFreq(term);+ }++ public Document doc(int i) throws IOException {+ Document d;+ if (documentCache != null) {+ d = (Document)documentCache.get(i);+ if (d!=null) return d;+ }++ d = searcher.doc(i);++ if (documentCache != null) {+ documentCache.put(i,d);+ }++ return d;+ }++ public int maxDoc() throws IOException {+ return searcher.maxDoc();+ }++ public TopDocs search(Weight weight, Filter filter, int i) throws IOException {+ return searcher.search(weight, filter, i);+ }++ public TopDocs search(Query query, Filter filter, int nDocs) throws IOException {+ return searcher.search(query, filter, nDocs);+ }++ public TopFieldDocs search(Query query, Filter filter, int nDocs, Sort sort) throws IOException {+ return searcher.search(query, filter, nDocs, sort);+ }++ public void search(Weight weight, Filter filter, HitCollector hitCollector) throws IOException {+ searcher.search(weight, filter, hitCollector);+ }++ public void search(Query query, Filter filter, HitCollector results) throws IOException {+ searcher.search(query, filter, results);+ }++ public Query rewrite(Query original) throws IOException {+ return searcher.rewrite(original);+ }++ public Explanation explain(Weight weight, int i) throws IOException {+ return searcher.explain(weight, i);+ }++ public Explanation explain(Query query, int doc) throws IOException {+ return searcher.explain(query, doc);+ }++ public TopFieldDocs search(Weight weight, Filter filter, int i, Sort sort) throws IOException {+ return searcher.search(weight, filter, i, sort);+ }++ ////////////////////////////////////////////////////////////////////////////////+ ////////////////////////////////////////////////////////////////////////////////+ ////////////////////////////////////////////////////////////////////////////////++ /**+ * Returns the first document number containing the term <code>t</code>+ * Returns -1 if no document was found.+ * This method is primarily intended for clients that want to fetch+ * documents using a unique identifier."+ * @param t+ * @return the first document number containing the term+ */+ public int getFirstMatch(Term t) throws IOException {+ TermDocs tdocs = null;+ try {+ tdocs = reader.termDocs(t);+ if (!tdocs.next()) return -1;+ return tdocs.doc();+ } finally {+ if (tdocs!=null) tdocs.close();+ }+ }+++ /**+ * Compute and cache the DocSet that matches a query.+ * The normal usage is expected to be cacheDocSet(myQuery, null,false)+ * meaning that Solr will determine if the Query warrants caching, and+ * if so, will compute the DocSet that matches the Query and cache it.+ * If the answer to the query is already cached, nothing further will be done.+ * <p>+ * If the optionalAnswer DocSet is provided, it should *not* be modified+ * after this call.+ *+ * @param query the lucene query that will act as the key+ * @param optionalAnswer the DocSet to be cached - if null, it will be computed.+ * @param mustCache if true, a best effort will be made to cache this entry.+ * if false, heuristics may be used to determine if it should be cached.+ */+ public void cacheDocSet(Query query, DocSet optionalAnswer, boolean mustCache) throws IOException {+ // Even if the cache is null, still compute the DocSet as it may serve to warm the Lucene+ // or OS disk cache.+ if (optionalAnswer != null) {+ if (filterCache!=null) {+ filterCache.put(query,optionalAnswer);+ }+ return;+ }++ // Throw away the result, relying on the fact that getDocSet+ // will currently always cache what it found. If getDocSet() starts+ // using heuristics about what to cache, and mustCache==true, (or if we+ // want this method to start using heuristics too) then+ // this needs to change.+ getDocSet(query);+ }++ /**+ * Returns the set of document ids matching a query.+ * This method is cache-aware and attempts to retrieve the answer from the cache if possible.+ * If the answer was not cached, it may have been inserted into the cache as a result of this call.+ * <p>+ * The DocSet returned should <b>not</b> be modified.+ */+ public DocSet getDocSet(Query query) throws IOException {+ DocSet answer;+ if (filterCache != null) {+ answer = (DocSet)filterCache.get(query);+ if (answer!=null) return answer;+ }++ answer = getDocSetNC(query, null);++ if (filterCache != null) {+ filterCache.put(query, answer);+ }++ return answer;+ }+++ // TODO: do a more efficient version that starts with the+ // smallest DocSet and drives the intersection off that+ // or implement an intersection() function that takes multiple+ // DocSets (prob the better way)+ protected DocSet getDocSet(List<Query> queries) throws IOException {+ DocSet answer=null;+ if (queries==null) return null;+ for (Query q : queries) {+ if (answer==null) {+ answer = getDocSet(q);+ } else {+ answer = answer.intersection(getDocSet(q));+ }+ }+ return answer;+ }++++ protected DocSet getDocSetNC(Query query, DocSet filter) throws IOException {+ SetHitCollector hc = new SetHitCollector(filter, maxDoc());+ searcher.search(query, null, hc);+ return hc.getDocSet();+ }+++ /**+ * Returns the set of document ids matching both the query and the filter.+ * This method is cache-aware and attempts to retrieve the answer from the cache if possible.+ * If the answer was not cached, it may have been inserted into the cache as a result of this call.+ * <p>+ * The DocSet returned should <b>not</b> be modified.+ *+ * @param query+ * @param filter may be null+ */+ public DocSet getDocSet(Query query, DocSet filter) throws IOException {+ if (filter==null) return getDocSet(query);++ DocSet first;+ if (filterCache != null) {+ first = (DocSet)filterCache.get(query);+ if (first==null) {+ first = getDocSetNC(query,null);+ filterCache.put(query,first);+ }+ return first.intersection(filter);+ }+++ // If there isn't a cache, then do a single filtered query.+ return getDocSetNC(query,filter);+++ /******* OLD VERSION that did a filtered query instead of+ * an intersection if the query docset wasn't found in the cache.+ * It made misses != inserts (even if no evictions)+ DocSet first=null;+ if (filterCache != null) {+ first = (DocSet)filterCache.get(query);+ if (first != null) {+ return first.intersection(filter);+ }+ }++ DocSet answer = getDocSetNC(query, filter);+ // nothing is inserted into the cache, because we don't cache materialized filters.+ // Hmmm, we *could* make a hitcollector that made a DocSet out of the query at the+ // same time it was running the filter though...++ // Q: we could call getDocSet(query) and then take the intersection instead of running+ // the query as a filter. Then it could be cached.+ return answer;+ ****************/+ }+++ /**+ * Converts a filter into a DocSet.+ * This method is not cache-aware and no caches are checked.+ */+ public DocSet convertFilter(Filter lfilter) throws IOException {+ return new BitDocSet(lfilter.bits(this.reader));+ }++ /**+ * Returns documents matching both <code>query</code> and <code>filter</code>+ * and sorted by <code>sort</code>.+ * <p>+ * This method is cache aware and may retrieve <code>filter</code> from+ * the cache or make an insertion into the cache as a result of this call.+ * <p>+ * FUTURE: The returned DocList may be retrieved from a cache.+ *+ * The DocList returned should <b>not</b> be modified.+ *+ * @param query+ * @param filter may be null+ * @param lsort criteria by which to sort (if null, query relevance is used)+ * @param offset offset into the list of documents to return+ * @param len maximum number of documents to return+ * @return+ * @throws IOException+ */+ public DocList getDocList(Query query, Query filter, Sort lsort, int offset, int len) throws IOException {+ List<Query> filterList = null;+ if (filter != null) {+ filterList = new ArrayList<Query>(1);+ filterList.add(filter);+ }+ return getDocList(query, filterList, lsort, offset, len, 0);+ }+++ public DocList getDocList(Query query, List<Query> filterList, Sort lsort, int offset, int len, int flags) throws IOException {+ DocListAndSet answer = new DocListAndSet();+ getDocListC(answer,query,filterList,null,lsort,offset,len,flags);+ return answer.docList;+ }+++ static final int NO_CHECK_QCACHE=0x80;++ public static final int GET_SCORES=0x01;+ public static final int NO_CHECK_FILTERCACHE=0x02;++ protected void getDocListC(DocListAndSet out, Query query, List<Query> filterList, DocSet filter, Sort lsort, int offset, int len, int flags) throws IOException {+ QueryResultKey key=null;+ int maxDoc = offset + len;+ int supersetMaxDoc=maxDoc;+ DocList superset;+++ // we can try and look up the complete query in the cache.+ // we can't do that if filter!=null though (we don't want to+ // do hashCode() and equals() for a big DocSet).+ if (queryResultCache != null && filter==null) {+ // all of the current flags can be reused during warming,+ // so set all of them on the cache key.+ key = new QueryResultKey(query, filterList, lsort, flags);+ if ((flags & NO_CHECK_QCACHE)==0) {+ superset = (DocList)queryResultCache.get(key);++ if (superset != null) {+ // check that the cache entry has scores recorded if we need them+ if ((flags & GET_SCORES)==0 || superset.hasScores()) {+ out.docList = superset.subset(offset,len);+ }+ }+ if (out.docList != null) return;+ }++ // If we are going to generate the result, bump up to the+ // next resultWindowSize for better caching.++ // handle 0 special case as well as avoid idiv in the common case.+ if (maxDoc < queryResultWindowSize) {+ supersetMaxDoc=queryResultWindowSize;+ } else {+ supersetMaxDoc = ((maxDoc-1)/queryResultWindowSize + 1)*queryResultWindowSize;+ }+ }+++ // OK, so now we need to generate an answer.+ // One way to do that would be to check if we have an unordered list+ // of results for the base query. If so, we can apply the filters and then+ // sort by the resulting set. This can only be used if:+ // - the sort doesn't contain score+ // - we don't want score returned.++ // check if we should try and use the filter cache+ boolean useFilterCache=false;+ if ((flags & (GET_SCORES|NO_CHECK_FILTERCACHE))==0 && useFilterForSortedQuery && lsort != null && filterCache != null) {+ useFilterCache=true;+ SortField[] sfields = lsort.getSort();+ for (SortField sf : sfields) {+ if (sf.getType() == SortField.SCORE) {+ useFilterCache=false;+ break;+ }+ }+ }++ if (useFilterCache) {+ // now actually use the filter cache.+ // for large filters that match few documents, this may be+ // slower than simply re-executing the query.+ if (out.docSet == null) {+ out.docSet = getDocSet(query,filter);+ DocSet bigFilt = getDocSet(filterList);+ if (bigFilt != null) out.docSet = out.docSet.intersection(bigFilt);+ }+ // todo: there could be a sortDocSet that could take a list of+ // the filters instead of anding them first...+ // perhaps there should be a multi-docset-iterator+ superset = sortDocSet(out.docSet,lsort,supersetMaxDoc);+ out.docList = superset.subset(offset,len);+ } else {+ // do it the normal way...+ DocSet theFilt = filter!=null ? filter : getDocSet(filterList);+ superset = getDocListNC(query,theFilt,lsort,0,supersetMaxDoc,flags);+ // OPT... if getDocListNC can get the set at the same time (later version)+ // then set it as out.docSet.+ out.docList = superset.subset(offset,len);+ }++ // lastly, put the superset in the cache+ if (key != null) {+ queryResultCache.put(key, superset);+ }+ }++++ private DocList getDocListNC(Query query, DocSet filter, Sort lsort, int offset, int len, int flags) throws IOException {+ final int lastDocRequested = offset+len;+ int nDocsReturned;+ int totalHits;+ float maxScore;+ int[] ids;+ float[] scores;+++ // handle zero case...+ if (lastDocRequested<=0) {+ final DocSet filt = filter;+ final float[] topscore = new float[] { Float.NEGATIVE_INFINITY };+ final int[] numHits = new int[1];++ searcher.search(query, new HitCollector() {+ public void collect(int doc, float score) {+ if (filt!=null && !filt.exists(doc)) return;+ numHits[0]++;+ if (score > topscore[0]) topscore[0]=score;+ }+ }+ );++ nDocsReturned=0;+ ids = new int[nDocsReturned];+ scores = new float[nDocsReturned];+ totalHits = numHits[0];+ maxScore = totalHits>0 ? topscore[0] : 0.0f;+ } else if (lsort != null) {+ // can't use TopDocs if there is a sort since it+ // will do automatic score normalization.+ // NOTE: this changed late in Lucene 1.9++ final DocSet filt = filter;+ final PublicFieldSortedHitQueue hq = new PublicFieldSortedHitQueue(reader, lsort.getSort(), offset+len);++ searcher.search(query, new HitCollector() {+ public void collect(int doc, float score) {+ if (filt!=null && !filt.exists(doc)) return;+ hq.insert(new FieldDoc(doc, score));+ }+ }+ );++ totalHits = hq.getTotalHits();+ maxScore = totalHits>0 ? hq.getMaxScore() : 0.0f;++ nDocsReturned = hq.size();+ ids = new int[nDocsReturned];+ scores = (flags&GET_SCORES)!=0 ? new float[nDocsReturned] : null;+ for (int i = nDocsReturned -1; i >= 0; i--) {+ FieldDoc fieldDoc = (FieldDoc)hq.pop();+ // fillFields is the point where score normalization happens+ // hq.fillFields(fieldDoc)+ ids[i] = fieldDoc.doc;+ if (scores != null) scores[i] = fieldDoc.score;+ }+ } else {+ // No Sort specified (sort by score descending)+ // This case could be done with TopDocs, but would currently require+ // getting a BitSet filter from a DocSet which may be inefficient.++ final DocSet filt = filter;+ final ScorePriorityQueue hq = new ScorePriorityQueue(lastDocRequested);+ final int[] numHits = new int[1];+ searcher.search(query, new HitCollector() {+ float minScore=Float.NEGATIVE_INFINITY; // minimum score in the priority queue+ public void collect(int doc, float score) {+ if (filt!=null && !filt.exists(doc)) return;+ if (numHits[0]++ < lastDocRequested || score >= minScore) {+ // if docs are always delivered in order, we could use "score>minScore"+ // but might BooleanScorer14 might still be used and deliver docs out-of-order?+ hq.insert(new ScoreDoc(doc, score));+ minScore = ((ScoreDoc)hq.top()).score;+ }+ }+ }+ );++ totalHits = numHits[0];+ nDocsReturned = hq.size();+ ids = new int[nDocsReturned];+ scores = (flags&GET_SCORES)!=0 ? new float[nDocsReturned] : null;+ ScoreDoc sdoc =null;+ for (int i = nDocsReturned -1; i >= 0; i--) {+ sdoc = (ScoreDoc)hq.pop();+ ids[i] = sdoc.doc;+ if (scores != null) scores[i] = sdoc.score;+ }+ maxScore = sdoc ==null ? 0.0f : sdoc.score;+ }+++ int sliceLen = Math.min(lastDocRequested,nDocsReturned) - offset;+ if (sliceLen < 0) sliceLen=0;+ return new DocSlice(offset,sliceLen,ids,scores,totalHits,maxScore);++++ /**************** older implementation using TopDocs *******************+++ Filter lfilter=null;+ if (filter != null) {+ final BitSet bits = filter.getBits(); // avoid if possible+ lfilter = new Filter() {+ public BitSet bits(IndexReader reader) {+ return bits;+ }+ };+ }++ int lastDocRequested=offset+len;++ // lucene doesn't allow 0 to be passed for nDocs+ if (lastDocRequested==0) lastDocRequested=1;++ // TopFieldDocs sortedDocs; // use TopDocs so both versions can use it+ TopDocs sortedDocs;+ if (lsort!=null) {+ sortedDocs = searcher.search(query, lfilter, lastDocRequested, lsort);+ } else {+ sortedDocs = searcher.search(query, lfilter, lastDocRequested);+ }++ int nDocsReturned = sortedDocs.scoreDocs.length;+ int[] docs = new int[nDocsReturned];+ for (int i=0; i<nDocsReturned; i++) {+ docs[i] = sortedDocs.scoreDocs[i].doc;+ }+ float[] scores=null;+ float maxScore=0.0f;+ if ((flags & GET_SCORES) != 0) {+ scores = new float[nDocsReturned];+ for (int i=0; i<nDocsReturned; i++) {+ scores[i] = sortedDocs.scoreDocs[i].score;+ }+ if (nDocsReturned>0) {+ maxScore=sortedDocs.scoreDocs[0].score;+ }+ }+ int sliceLen = Math.min(offset+len,nDocsReturned) - offset;+ if (sliceLen < 0) sliceLen=0;+ return new DocSlice(offset,sliceLen,docs,scores,sortedDocs.totalHits, maxScore);++ **********************************************************************************/++ }+++++ /**+ * Returns documents matching both <code>query</code> and <code>filter</code>+ * and sorted by <code>sort</code>.+ * FUTURE: The returned DocList may be retrieved from a cache.+ * <p>+ * The DocList returned should <b>not</b> be modified.+ *+ * @param query+ * @param filter may be null+ * @param lsort criteria by which to sort (if null, query relevance is used)+ * @param offset offset into the list of documents to return+ * @param len maximum number of documents to return+ * @return+ * @throws IOException+ */+ public DocList getDocList(Query query, DocSet filter, Sort lsort, int offset, int len) throws IOException {+ DocListAndSet answer = new DocListAndSet();+ getDocListC(answer,query,null,filter,lsort,offset,len,0);+ return answer.docList;+ }++ /**+ * Returns documents matching both <code>query</code> and <code>filter</code>+ * and sorted by <code>sort</code>. Also returns the compete set of documents+ * matching <code>query</code> and <code>filter</code> (regardless of <code>offset</code> and <code>len</code>).+ * <p>+ * This method is cache aware and may retrieve <code>filter</code> from+ * the cache or make an insertion into the cache as a result of this call.+ * <p>+ * FUTURE: The returned DocList may be retrieved from a cache.+ * <p>+ * The DocList and DocSet returned should <b>not</b> be modified.+ *+ * @param query+ * @param filter may be null+ * @param lsort criteria by which to sort (if null, query relevance is used)+ * @param offset offset into the list of documents to return+ * @param len maximum number of documents to return+ * @return+ * @throws IOException+ */+ public DocListAndSet getDocListAndSet(Query query, Query filter, Sort lsort, int offset, int len) throws IOException {+ List<Query> filterList = null;+ if (filter != null) {+ filterList = new ArrayList<Query>(2);+ filterList.add(filter);+ }+ return getDocListAndSet(query, filterList, lsort, offset, len);++ }+++ public DocListAndSet getDocListAndSet(Query query, List<Query> filterList, Sort lsort, int offset, int len) throws IOException {+ DocListAndSet ret = new DocListAndSet();+ getDocListC(ret,query,filterList,null,lsort,offset,len,0);+ if (ret.docSet == null) {+ List<Query> newList = new ArrayList<Query>(filterList.size()+1);+ newList.add(query);+ newList.addAll(filterList);+ ret.docSet = getDocSet(newList);+ }+ return ret;+ }++++ /**+ * Returns documents matching both <code>query</code> and <code>filter</code>+ * and sorted by <code>sort</code>. Also returns the compete set of documents+ * matching <code>query</code> and <code>filter</code> (regardless of <code>offset</code> and <code>len</code>).+ * <p>+ * FUTURE: The returned DocList may be retrieved from a cache.+ * <p>+ * The DocList and DocSet returned should <b>not</b> be modified.+ *+ * @param query+ * @param filter may be null+ * @param lsort criteria by which to sort (if null, query relevance is used)+ * @param offset offset into the list of documents to return+ * @param len maximum number of documents to return+ * @return+ * @throws IOException+ */+ public DocListAndSet getDocListAndSet(Query query, DocSet filter, Sort lsort, int offset, int len) throws IOException {+ DocListAndSet ret = new DocListAndSet();+ getDocListC(ret,query,null,filter,lsort,offset,len,0);+ if (ret.docSet == null) {+ ret.docSet = getDocSet(query,filter);+ }++ // TODO: OPT: Hmmm, but if docList.size() == docList.matches() then+ // we actually already have all the ids (the set)! We could simply+ // return the docList as the docSet also, or hash the ids into+ // a HashDocSet, etc... no need to run the query again!+ //++ assert(ret.docList.matches() == ret.docSet.size());+ return ret;+ }+++ protected DocList sortDocSet(DocSet set, Sort sort, int nDocs) throws IOException {+ final PublicFieldSortedHitQueue hq =+ new PublicFieldSortedHitQueue(reader, sort.getSort(), nDocs);+ DocIterator iter = set.iterator();+ int hits=0;+ while(iter.hasNext()) {+ int doc = iter.nextDoc();+ hits++; // could just use set.size(), but that would be slower for a bitset+ hq.insert(new FieldDoc(doc,1.0f));+ }++ int numCollected = hq.size();+ int[] ids = new int[numCollected];+ for (int i = numCollected-1; i >= 0; i--) {+ FieldDoc fieldDoc = (FieldDoc)hq.pop();+ // hq.fillFields(fieldDoc) // optional, if we need that info+ ids[i] = fieldDoc.doc;+ }++ return new DocSlice(0,numCollected,ids,null,hits,0.0f);+ }++++ /**+ * Returns the number of documents that match both <code>a</code> and <code>b</code>.+ * <p>+ * This method is cache-aware and may check as well as modify the cache.+ *+ * @param a+ * @param b+ * @return the numer of documents in the intersection between <code>a</code> and <code>b</code>.+ * @throws IOException+ */+ public int numDocs(Query a, DocSet b) throws IOException {+ // reverse: do the query on filter and filter using docs...+ // or if filter is a term query, can get the freq and+ // drive things off that.+ // this higher level API leaves open more optimization possibilities.+ // prob only worth it if cacheHitRatio is bad...++ return b.intersectionSize(getDocSet(a));+ }++ /**+ * Returns the number of documents that match both <code>a</code> and <code>b</code>.+ * <p>+ * This method is cache-aware and may check as well as modify the cache.+ *+ * @param a+ * @param b+ * @return the numer of documents in the intersection between <code>a</code> and <code>b</code>.+ * @throws IOException+ */+ public int numDocs(Query a, Query b) throws IOException {+ return getDocSet(b).intersectionSize(getDocSet(a));+ }+++ // Takes a list of docs (the doc ids actually), and returns all of+ // the stored fields.+ public Document[] readDocs(DocList ids) throws IOException {+ Document[] docs = new Document[ids.size()];+ readDocs(docs,ids);+ return docs;+ }++ public void readDocs(Document[] docs, DocList ids) throws IOException {+ DocIterator iter = ids.iterator();+ for (int i=0; i<docs.length; i++) {+ docs[i] = doc(iter.nextDoc());+ }+ }++++ /**+ * Warm this searcher based on an old one (primarily for auto-cache warming).+ */+ public void warm(SolrIndexSearcher old) throws IOException {+ // Make sure this is first! filters can help queryResults execute!+ boolean logme = log.isLoggable(Level.INFO);++ // warm the caches in order...+ for (int i=0; i<cacheList.length; i++) {+ if (logme) log.info("autowarming " + this + " from " + old + "\n\t" + old.cacheList[i]);+ this.cacheList[i].warm(this, old.cacheList[i]);+ if (logme) log.info("autowarming result for " + this + "\n\t" + this.cacheList[i]);+ }+ }+++ /**+ * return the named generic cache+ */+ public SolrCache getCache(String cacheName) {+ return cacheMap.get(cacheName);+ }++ /**+ * lookup an entry in a generic cache+ */+ public Object cacheLookup(String cacheName, Object key) {+ SolrCache cache = cacheMap.get(cacheName);+ return cache==null ? null : cache.get(key);+ }++ /**+ * insert an entry in a generic cache+ */+ public Object cacheInsert(String cacheName, Object key, Object val) {+ SolrCache cache = cacheMap.get(cacheName);+ return cache==null ? null : cache.put(key,val);+ }+++ /////////////////////////////////////////////////////////////////////+ // SolrInfoMBean stuff: Statistics and Module Info+ /////////////////////////////////////////////////////////////////////++ public String getName() {+ return SolrIndexSearcher.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "the searcher that handles all index queries";+ }++ public Category getCategory() {+ return Category.CORE;+ }++ public String getCvsId() {+ return "$Id: SolrIndexSearcher.java,v 1.49 2005/12/20 16:05:46 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/search/SolrIndexSearcher.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }++ public NamedList getStatistics() {+ /***+ NamedList lst = new NamedList();+ lst.add("requests", numRequests);+ lst.add("errors", numErrors);+ return lst;+ ***/+ return new NamedList();+ }+++++}++++++// Todo: counting only hit collector (for speed comparison w/ caching filters)+// todo: fast term query+// todo: do a both hit collector that can get a DocList and DocSet at the same time++final class SetHitCollector extends HitCollector {+ int pos=0;+ final DocSet filter;+ // should we bother with filters at this point?+ // how much faster would it be to take the check for+ // filter!=null out of the loop??? depends on HotSpot... it may+ // optimize it anyway.++ final BitSet bits;++ // in case there aren't that many hits, we may not want a very sparse+ // bit array. Optimistically collect the first few docs in an array+ // in case there are only a few.+ static final int ARRAY_COLLECT_SZ=HashDocSet.MAX_SIZE;+ final int[] scratch = ARRAY_COLLECT_SZ>0 ? new int[ARRAY_COLLECT_SZ] : null;++ public SetHitCollector(DocSet filter, int maxDoc) {+ bits = new BitSet(maxDoc);+ this.filter = filter;+ }++ public void collect(int doc, float score) {+ if (filter!=null && !filter.exists(doc)) return;++ // OPTIMIZATION: should I only set bits *after* I have run out of+ // room in scratch? (then at the end I could add all of the docs+ // in scratch to the bitset.+ bits.set(doc);++ // optimistically collect the first docs in an array+ // in case the total number will be small enough to represent+ // as a HashDocSet() instead...+ // It is assumed that storing in this array will be quicker to convert+ // than scanning through a potentially huge bit vector.+ // FUTURE: when search methods all start returning docs in order, maybe+ // we could have a SortedListDocSet() and use the collected array directly.+ if (pos < ARRAY_COLLECT_SZ) {+ scratch[pos]=doc;+ }++ pos++;+ }++ public DocSet getDocSet() {+ if (pos<=ARRAY_COLLECT_SZ) {+ return new HashDocSet(scratch,0,pos);+ }+ return new BitDocSet(bits,pos);+ }++}++++// Lucene's HitQueue isn't public, so here is our own.+final class ScorePriorityQueue extends PriorityQueue {+ ScorePriorityQueue(int size) {+ initialize(size);+ }++ protected final boolean lessThan(Object o1, Object o2) {+ ScoreDoc sd1 = (ScoreDoc)o1;+ ScoreDoc sd2 = (ScoreDoc)o2;+ // use index order as a tiebreaker to make sorts stable+ return sd1.score < sd2.score || (sd1.score==sd2.score && sd1.doc > sd2.doc);+ }+}++++diff --git a/src/java/org/apache/solr/search/SolrQueryParser.java b/src/java/org/apache/solr/search/SolrQueryParser.javanew file mode 100644index 00000000000..b8e2982eeca--- /dev/null+++ b/src/java/org/apache/solr/search/SolrQueryParser.java@@ -0,0 +1,81 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.queryParser.ParseException;+import org.apache.lucene.search.*;+import org.apache.lucene.index.Term;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.FieldType;++// TODO: implement the analysis of simple fields with+// FieldType.toInternal() instead of going through the+// analyzer. Should lead to faster query parsing.++/**+ * @author yonik+ */+public class SolrQueryParser extends QueryParser {+ protected final IndexSchema schema;++ public SolrQueryParser(IndexSchema schema) {+ super(schema.getDefaultSearchFieldName(), schema.getQueryAnalyzer());+ this.schema = schema;+ setLowercaseExpandedTerms(false);+ }++ protected Query getFieldQuery(String field, String queryText) throws ParseException {+ // intercept magic field name of "_" to use as a hook for our+ // own functions.+ if (field.equals("_val_")) {+ return QueryParsing.parseFunction(queryText, schema);+ }++ // default to a normal field query+ return super.getFieldQuery(field, queryText);+ }++ protected Query getRangeQuery(String field, String part1, String part2, boolean inclusive) throws ParseException {+ FieldType ft = schema.getFieldType(field);+ return new ConstantScoreRangeQuery(+ field,+ "*".equals(part1) ? null : ft.toInternal(part1),+ "*".equals(part2) ? null : ft.toInternal(part2),+ inclusive, inclusive);+ }++ protected Query getPrefixQuery(String field, String termStr) throws ParseException {+ if (getLowercaseExpandedTerms()) {+ termStr = termStr.toLowerCase();+ }++ // TODO: toInternal() won't necessarily work on partial+ // values, so it looks like i need a getPrefix() function+ // on fieldtype? Or at the minimum, a method on fieldType+ // that can tell me if I should lowercase or not...+ // Schema could tell if lowercase filter is in the chain,+ // but a more sure way would be to run something through+ // the first time and check if it got lowercased.++ // TODO: throw exception of field type doesn't support prefixes?+ // (sortable numeric types don't do prefixes, but can do range queries)+ Term t = new Term(field, termStr);+ return new ConstantScorePrefixQuery(t);+ }++}diff --git a/src/java/org/apache/solr/search/SolrSimilarity.java b/src/java/org/apache/solr/search/SolrSimilarity.javanew file mode 100644index 00000000000..2fe4d7ac96a--- /dev/null+++ b/src/java/org/apache/solr/search/SolrSimilarity.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.search.DefaultSimilarity;++import java.util.HashMap;++/**+ * @author yonik+ */+// don't make it public for now... easier to change later.++// This class is currently unused.+class SolrSimilarity extends DefaultSimilarity {+ private final HashMap<String,Float> lengthNormConfig = new HashMap<String,Float>();++ public float lengthNorm(String fieldName, int numTerms) {+ // Float f = lengthNormConfig.+ // if (lengthNormDisabled.)+ return super.lengthNorm(fieldName, numTerms);+ }+}diff --git a/src/java/org/apache/solr/search/Sorting.java b/src/java/org/apache/solr/search/Sorting.javanew file mode 100644index 00000000000..e6571f40898--- /dev/null+++ b/src/java/org/apache/solr/search/Sorting.java@@ -0,0 +1,57 @@+/**+ * 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.+ */++package org.apache.solr.search;++import org.apache.lucene.search.*;++/**+ * Extra lucene sorting utilities & convenience methods+ *+ * @author yonik+ * @version $Id: Sorting.java,v 1.1 2005/06/02 04:43:06 yonik Exp $+ *+ */++public class Sorting {+++ /** Returns a {@link SortField} for a string field.+ * If nullLast and nullFirst are both false, then default lucene string sorting is used where+ * null strings sort first in an ascending sort, and last in a descending sort.+ *+ * @param fieldName the name of the field to sort on+ * @param reverse true for a reverse (desc) sort+ * @param nullLast true if null should come last, regardless of sort order+ * @param nullFirst true if null should come first, regardless of sort order+ * @return SortField+ */+ public static SortField getStringSortField(String fieldName, boolean reverse, boolean nullLast, boolean nullFirst) {+ if (nullLast) {+ if (!reverse) return new SortField(fieldName, nullStringLastComparatorSource);+ else return new SortField(fieldName, SortField.STRING, true);+ } else if (nullFirst) {+ if (reverse) return new SortField(fieldName, nullStringLastComparatorSource);+ else return new SortField(fieldName, SortField.STRING, false);+ } else {+ return new SortField(fieldName, SortField.STRING, reverse);+ }+ }+++ static final SortComparatorSource nullStringLastComparatorSource = new MissingStringLastComparatorSource();+}+diff --git a/src/java/org/apache/solr/search/test/TestDocSet.java b/src/java/org/apache/solr/search/test/TestDocSet.javanew file mode 100644index 00000000000..5901b094650--- /dev/null+++ b/src/java/org/apache/solr/search/test/TestDocSet.java@@ -0,0 +1,180 @@+/**+ * 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.+ */++package org.apache.solr.search.test;++import org.apache.solr.search.BitDocSet;+import org.apache.solr.search.HashDocSet;+import org.apache.solr.search.DocSet;++import java.util.Random;+import java.util.BitSet;++/**+ * @author yonik+ */+public class TestDocSet {++ // use test instead of assert since asserts may be turned off+ public static void test(boolean condition) {+ if (!condition) {+ throw new RuntimeException("test requestHandler: assertion failed!");+ }+ }++ static Random rand = new Random();+++ static BitSet bs;+ static BitDocSet bds;+ static HashDocSet hds;+ static int[] ids; // not unique++ static void generate(int maxSize, int bitsToSet) {+ bs = new BitSet(maxSize);+ ids = new int[bitsToSet];+ int count=0;+ if (maxSize>0) {+ for (int i=0; i<bitsToSet; i++) {+ int id=rand.nextInt(maxSize);+ if (!bs.get(id)) {+ bs.set(id);+ ids[count++]=id;+ }+ }+ }+ bds = new BitDocSet(bs,bitsToSet);+ hds = new HashDocSet(ids,0,count);+ }++++ public static void main(String[] args) {+ String bsSize=args[0];+ boolean randSize=false;++ if (bsSize.endsWith("-")) {+ bsSize=bsSize.substring(0,bsSize.length()-1);+ randSize=true;+ }++ int bitSetSize = Integer.parseInt(bsSize);+ int numSets = Integer.parseInt(args[1]);+ int numBitsSet = Integer.parseInt(args[2]);+ String test = args[3].intern();+ int iter = Integer.parseInt(args[4]);++ int ret=0;++ BitSet[] sets = new BitSet[numSets];+ DocSet[] bset = new DocSet[numSets];+ DocSet[] hset = new DocSet[numSets];+ BitSet scratch=new BitSet();++ for (int i=0; i<numSets; i++) {+ generate(randSize ? rand.nextInt(bitSetSize) : bitSetSize, numBitsSet);+ sets[i] = bs;+ bset[i] = bds;+ hset[i] = hds;+ }++ long start = System.currentTimeMillis();++ if ("test".equals(test)) {+ for (int it=0; it<iter; it++) {+ generate(randSize ? rand.nextInt(bitSetSize) : bitSetSize, numBitsSet);+ BitSet bs1=bs;+ BitDocSet bds1=bds;+ HashDocSet hds1=hds;+ generate(randSize ? rand.nextInt(bitSetSize) : bitSetSize, numBitsSet);++ BitSet res = ((BitSet)bs1.clone());+ res.and(bs);+ int icount = res.cardinality();++ test(bds1.intersection(bds).size() == icount);+ test(bds1.intersectionSize(bds) == icount);+ if (bds1.intersection(hds).size() != icount) {+ DocSet ds = bds1.intersection(hds);+ System.out.println("STOP");+ }++ test(bds1.intersection(hds).size() == icount);+ test(bds1.intersectionSize(hds) == icount);+ test(hds1.intersection(bds).size() == icount);+ test(hds1.intersectionSize(bds) == icount);+ test(hds1.intersection(hds).size() == icount);+ test(hds1.intersectionSize(hds) == icount);++ ret += icount;+ }+ }++ String type=null;+ String oper=null;++ if (test.endsWith("B")) { type="B"; }+ if (test.endsWith("H")) { type="H"; }+ if (test.endsWith("M")) { type="M"; }+ if (test.startsWith("intersect")) oper="intersect";+ if (test.startsWith("intersectSize")) oper="intersectSize";+ if (test.startsWith("intersectAndSize")) oper="intersectSize";+++ if (oper!=null) {+ for (int it=0; it<iter; it++) {+ int idx1 = rand.nextInt(numSets);+ int idx2 = rand.nextInt(numSets);+ DocSet a=null,b=null;++ if (type=="B") {+ a=bset[idx1]; b=bset[idx2];+ } else if (type=="H") {+ a=hset[idx1]; b=bset[idx2];+ } else if (type=="M") {+ if (idx1 < idx2) {+ a=bset[idx1];+ b=hset[idx2];+ } else {+ a=hset[idx1];+ b=bset[idx2];+ }+ }++ if (oper=="intersect") {+ DocSet res = a.intersection(b);+ ret += res.memSize();+ } else if (oper=="intersectSize") {+ ret += a.intersectionSize(b);+ } else if (oper=="intersectAndSize") {+ DocSet res = a.intersection(b);+ ret += res.size();+ }+ }+ }++++ long end = System.currentTimeMillis();+ System.out.println("TIME="+(end-start));++ // System.out.println("ret="+ret + " scratchsize="+scratch.size());+ System.out.println("ret="+ret);+ }++++}diff --git a/src/java/org/apache/solr/tst/OldRequestHandler.java b/src/java/org/apache/solr/tst/OldRequestHandler.javanew file mode 100644index 00000000000..8f20de00919--- /dev/null+++ b/src/java/org/apache/solr/tst/OldRequestHandler.java@@ -0,0 +1,149 @@+/**+ * 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.+ */++package org.apache.solr.tst;++import org.apache.lucene.search.*;+import org.apache.lucene.document.Document;++import java.util.List;+import java.util.logging.Level;+import java.io.IOException;+import java.net.URL;++import org.apache.solr.util.StrUtils;+import org.apache.solr.util.NamedList;+import org.apache.solr.search.DocSlice;+import org.apache.solr.search.QueryParsing;+import org.apache.solr.core.SolrCore;+import org.apache.solr.request.SolrRequestHandler;+import org.apache.solr.request.SolrQueryResponse;+import org.apache.solr.request.SolrQueryRequest;++/**+ * @author yonik+ * @version $Id: OldRequestHandler.java,v 1.7 2005/12/02 04:31:05 yonik Exp $+ */+++public class OldRequestHandler implements SolrRequestHandler {++ long numRequests;+ long numErrors;++ public void init(NamedList args) {+ SolrCore.log.log(Level.INFO, "Unused request handler arguments:" + args);+ }+++ public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {+ numRequests++;++ Query query = null;+ Filter filter = null;++ List<String> commands = StrUtils.splitSmart(req.getQueryString(),';');++ String qs = commands.size() >= 1 ? commands.get(0) : "";+ query = QueryParsing.parseQuery(qs, req.getSchema());++ // If the first non-query, non-filter command is a simple sort on an indexed field, then+ // we can use the Lucene sort ability.+ Sort sort = null;+ if (commands.size() >= 2) {+ QueryParsing.SortSpec sortSpec = QueryParsing.parseSort(commands.get(1), req.getSchema());+ if (sortSpec != null) {+ sort = sortSpec.getSort();+ // ignore the count for now... it's currently only controlled by start & limit on req+ // count = sortSpec.getCount();+ }+ }++ Hits hits=null;++ try {+ hits = req.getSearcher().search(query,filter,sort);++ int numHits = hits.length();+ int startRow = Math.min(numHits, req.getStart());+ int endRow = Math.min(numHits,req.getStart()+req.getLimit());+ int numRows = endRow-startRow;++ int[] ids = new int[numRows];+ Document[] data = new Document[numRows];+ for (int i=startRow; i<endRow; i++) {+ ids[i] = hits.id(i);+ data[i] = hits.doc(i);+ }++ rsp.add(null, new DocSlice(0,numRows,ids,null,numHits,0.0f));++ /***********************+ rsp.setResults(new DocSlice(0,numRows,ids,null,numHits));++ // Setting the actual document objects is optional+ rsp.setResults(data);+ ************************/+ } catch (IOException e) {+ rsp.setException(e);+ numErrors++;+ return;+ }++ }+++ public String getName() {+ return OldRequestHandler.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "The original Hits based request handler";+ }++ public Category getCategory() {+ return Category.QUERYHANDLER;+ }++ public String getCvsId() {+ return "$Id: OldRequestHandler.java,v 1.7 2005/12/02 04:31:05 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/tst/OldRequestHandler.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }++ public NamedList getStatistics() {+ NamedList lst = new NamedList();+ lst.add("requests", numRequests);+ lst.add("errors", numErrors);+ return lst;+ }+++}diff --git a/src/java/org/apache/solr/tst/TestRequestHandler.java b/src/java/org/apache/solr/tst/TestRequestHandler.javanew file mode 100644index 00000000000..6fa87ecf026--- /dev/null+++ b/src/java/org/apache/solr/tst/TestRequestHandler.java@@ -0,0 +1,300 @@+/**+ * 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.+ */++package org.apache.solr.tst;++import org.apache.lucene.search.*;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;++import java.util.*;+import java.util.regex.Pattern;+import java.util.logging.Logger;+import java.util.logging.Level;+import java.net.URL;++import org.apache.solr.util.StrUtils;+import org.apache.solr.util.NamedList;+import org.apache.solr.search.*;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;+import org.apache.solr.request.SolrRequestHandler;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.request.SolrQueryResponse;++/**+ * @author yonik+ * @version $Id: TestRequestHandler.java,v 1.19 2005/12/02 04:31:05 yonik Exp $+ */++public class TestRequestHandler implements SolrRequestHandler {+ private static Logger log = Logger.getLogger(SolrIndexSearcher.class.getName());++ public void init(NamedList args) {+ SolrCore.log.log(Level.INFO, "Unused request handler arguments:" + args);+ }++++ // use test instead of assert since asserts may be turned off+ public void test(boolean condition) {+ try {+ if (!condition) {+ throw new RuntimeException("test requestHandler: assertion failed!");+ }+ } catch (RuntimeException e) {+ SolrException.log(log,e);+ throw(e);+ }+ }+++ private long numRequests;+ private long numErrors;++ private final Pattern splitList=Pattern.compile(",| ");+++ public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {+ numRequests++;++ // TODO: test if lucene will accept an escaped ';', otherwise+ // we need to un-escape them before we pass to QueryParser+ try {+ String sreq = req.getQueryString();+ if (sreq==null) throw new SolrException(400,"Missing queryString");+ List<String> commands = StrUtils.splitSmart(sreq,';');++ String qs = commands.size() >= 1 ? commands.get(0) : "";+ Query query = QueryParsing.parseQuery(qs, req.getSchema());++ // find fieldnames to return (fieldlist)+ String fl = req.getParam("fl");+ int flags=0;+ if (fl != null) {+ // TODO - this could become more efficient if widely used.+ // TODO - should field order be maintained?+ String[] flst = splitList.split(fl,0);+ if (flst.length > 0 && !(flst.length==1 && flst[0].length()==0)) {+ Set<String> set = new HashSet<String>();+ for (String fname : flst) {+ if ("score".equals(fname)) flags |= SolrIndexSearcher.GET_SCORES;+ set.add(fname);+ }+ rsp.setReturnFields(set);+ }+ }+++ // If the first non-query, non-filter command is a simple sort on an indexed field, then+ // we can use the Lucene sort ability.+ Sort sort = null;+ if (commands.size() >= 2) {+ QueryParsing.SortSpec sortSpec = QueryParsing.parseSort(commands.get(1), req.getSchema());+ if (sortSpec != null) {+ sort = sortSpec.getSort();+ // ignore the count for now... it's currently only controlled by start & limit on req+ // count = sortSpec.getCount();+ }+ }++ SolrIndexSearcher searcher = req.getSearcher();++ /***+ Object o = searcher.cacheLookup("dfllNode", query);+ if (o == null) {+ searcher.cacheInsert("dfllNode",query,"Hello Bob");+ } else {+ System.out.println("User Cache Hit On " + o);+ }+ ***/++ int start=req.getStart();+ int limit=req.getLimit();++ Query filterQuery=null;+ DocSet filter=null;+ Filter lfilter=null;++ DocList results = req.getSearcher().getDocList(query, null, sort, req.getStart(), req.getLimit(), flags);+ rsp.add(null, results);+++ if (qs.startsWith("values")) {+ rsp.add("testname1","testval1");++ rsp.add("testarr1",new String[]{"my val 1","my val 2"});++ NamedList nl = new NamedList();+ nl.add("myInt", 333);+ nl.add("myNullVal", null);+ nl.add("myFloat",1.414213562f);+ nl.add("myDouble", 1e100d);+ nl.add("myBool", false);+ nl.add("myLong",999999999999L);++ Document doc = new Document();+ doc.add(new Field("id","55",true,true,false));+ nl.add("myDoc",doc);++ nl.add("myResult",results);+ nl.add("myStr","&wow! test escaping: a&b<c&");+ nl.add(null, "this value had a null name...");+ nl.add("myIntArray", new Integer[] { 100, 5, -10, 42 });+ nl.add("epoch", new Date(0));+ nl.add("currDate", new Date(System.currentTimeMillis()));+ rsp.add("myNamedList", nl);+ } else if (qs.startsWith("fields")) {+ NamedList nl = new NamedList();+ Collection flst;+ flst = searcher.getReader().getFieldNames(IndexReader.FieldOption.INDEXED);+ nl.add("indexed",flst);+ flst = searcher.getReader().getFieldNames(IndexReader.FieldOption.UNINDEXED);+ nl.add("unindexed",flst);+ rsp.add("fields", nl);+ }++ test(results.size() <= limit);+ test(results.size() <= results.matches());+ // System.out.println("limit="+limit+" results.size()="+results.size()+" matches="+results.matches());+ test((start==0 && limit>=results.matches()) ? results.size()==results.matches() : true );++ //+ // test against hits+ //+ Hits hits = searcher.search(query, lfilter, sort);+ test(hits.length() == results.matches());+++ DocList rrr2 = results.subset(start,limit);+ test(rrr2 == results);++ DocIterator iter=results.iterator();+++ /***+ for (int i=0; i<hits.length(); i++) {+ System.out.println("doc="+hits.id(i) + " score="+hits.score(i));+ }+ ***/++ for (int i=0; i<results.size(); i++) {+ test( iter.nextDoc() == hits.id(i+results.offset()) );++ // Document doesn't implement equals()+ // test( searcher.document(i).equals(hits.doc(i)));+ }+++ DocList results2 = req.getSearcher().getDocList(query,query,sort,start,limit);+ test(results2.size()==results.size() && results2.matches()==results.matches());+ DocList results3 = req.getSearcher().getDocList(query,query,null,start,limit);+ test(results3.size()==results.size() && results3.matches()==results.matches());++ //+ // getting both the list and set+ //+ DocListAndSet both = searcher.getDocListAndSet(query,filter,sort,start, limit);+ test( both.docList.equals(results) );+ test( both.docList.matches() == both.docSet.size() );+ test( (start==0 && both.docSet.size() <= limit) ? both.docSet.equals(both.docList) : true);++ // use the result set as a filter itself...+ DocListAndSet both2 = searcher.getDocListAndSet(query,both.docSet,sort,start, limit);+ test( both2.docList.equals(both.docList) );+ test( both2.docSet.equals(both.docSet) );++ BitSet bits = both.docSet.getBits();+ BitSet neg = ((BitSet)bits.clone());+ neg.flip(0, bits.length());++ // use the negative as a filter (should result in 0 matches)+ // todo - fix if filter is not null+ both2 = searcher.getDocListAndSet(query,new BitDocSet(neg),sort, start, limit);+ test( both2.docList.size() == 0 );+ test( both2.docList.matches() == 0 );+ test( both2.docSet.size() == 0 );++ DocSet allResults=searcher.getDocSet(query,filter);+ test ( allResults.equals(both.docSet) );++ if (filter != null) {+ DocSet res=searcher.getDocSet(query);+ test( res.size() >= results.size() );+ test( res.intersection(filter).equals(both.docSet));++ test( res.intersectionSize(filter) == both.docSet.size() );+ if (filterQuery != null) {+ test( searcher.numDocs(filterQuery,res) == both.docSet.size() );+ }+ }+++ } catch (Exception e) {+ rsp.setException(e);+ numErrors++;+ return;+ }+ }+++ //////////////////////// SolrInfoMBeans methods //////////////////////+++ public String getName() {+ return TestRequestHandler.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "A test handler that runs some sanity checks on results";+ }++ public Category getCategory() {+ return Category.QUERYHANDLER;+ }++ public String getCvsId() {+ return "$Id: TestRequestHandler.java,v 1.19 2005/12/02 04:31:05 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/tst/TestRequestHandler.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }++ public NamedList getStatistics() {+ NamedList lst = new NamedList();+ lst.add("requests", numRequests);+ lst.add("errors", numErrors);+ return lst;+ }++++}+diff --git a/src/java/org/apache/solr/update/AddUpdateCommand.java b/src/java/org/apache/solr/update/AddUpdateCommand.javanew file mode 100644index 00000000000..cca5f07182e--- /dev/null+++ b/src/java/org/apache/solr/update/AddUpdateCommand.java@@ -0,0 +1,44 @@+/**+ * 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.+ */++package org.apache.solr.update;++import org.apache.lucene.document.Document;+/**+ * @author yonik+ * @version $Id$+ */+public class AddUpdateCommand extends UpdateCommand {+ public String id;+ public Document doc;+ public boolean allowDups;+ public boolean overwritePending;+ public boolean overwriteCommitted;++ public AddUpdateCommand() {+ super("add");+ }++ public String toString() {+ StringBuilder sb = new StringBuilder(commandName);+ sb.append(':');+ if (id!=null) sb.append("id=").append(id);+ sb.append(",allowDups=").append(allowDups);+ sb.append(",overwritePending=").append(overwritePending);+ sb.append(",overwriteCommitted=").append(overwriteCommitted);+ return sb.toString();+ }+ }diff --git a/src/java/org/apache/solr/update/CommitUpdateCommand.java b/src/java/org/apache/solr/update/CommitUpdateCommand.javanew file mode 100644index 00000000000..2dfa7f6e6fe--- /dev/null+++ b/src/java/org/apache/solr/update/CommitUpdateCommand.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.update;+/**+ * @author yonik+ * @version $Id$+ */+public class CommitUpdateCommand extends UpdateCommand {+ public boolean optimize;+ public boolean waitFlush;+ public boolean waitSearcher=true;++ public CommitUpdateCommand(boolean optimize) {+ super("commit");+ this.optimize=optimize;+ }+ public String toString() {+ return "commit(optimize="+optimize+ +",waitFlush="+waitFlush+ +",waitSearcher="+waitSearcher+ +')';+ }+}diff --git a/src/java/org/apache/solr/update/DeleteUpdateCommand.java b/src/java/org/apache/solr/update/DeleteUpdateCommand.javanew file mode 100644index 00000000000..7eeb875b6e5--- /dev/null+++ b/src/java/org/apache/solr/update/DeleteUpdateCommand.java@@ -0,0 +1,41 @@+/**+ * 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.+ */++package org.apache.solr.update;+/**+ * @author yonik+ * @version $Id$+ */+public class DeleteUpdateCommand extends UpdateCommand {+ public String id;+ public String query;+ public boolean fromPending;+ public boolean fromCommitted;++ public DeleteUpdateCommand() {+ super("delete");+ }++ public String toString() {+ StringBuilder sb = new StringBuilder(commandName);+ sb.append(':');+ if (id!=null) sb.append("id=").append(id);+ else sb.append("query=`").append(query).append('`');+ sb.append(",fromPending=").append(fromPending);+ sb.append(",fromCommitted=").append(fromCommitted);+ return sb.toString();+ }+}diff --git a/src/java/org/apache/solr/update/DirectUpdateHandler.java b/src/java/org/apache/solr/update/DirectUpdateHandler.javanew file mode 100644index 00000000000..234f013a25e--- /dev/null+++ b/src/java/org/apache/solr/update/DirectUpdateHandler.java@@ -0,0 +1,381 @@+/**+ * 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.+ */++/**+ * @author yonik+ */++package org.apache.solr.update;++import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.document.Document;+import org.apache.lucene.search.Query;++import java.util.HashSet;+import java.util.concurrent.Future;+import java.util.concurrent.ExecutionException;+import java.util.logging.Level;+import java.io.IOException;+import java.net.URL;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.search.QueryParsing;+import org.apache.solr.util.NamedList;+import org.apache.solr.update.UpdateHandler;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;++/**+ * <code>DirectUpdateHandler</code> implements an UpdateHandler where documents are added+ * directly to the main lucene index as opposed to adding to a separate smaller index.+ * For this reason, not all combinations to/from pending and committed are supported.+ *+ * @author yonik+ * @version $Id: DirectUpdateHandler.java,v 1.13 2005/06/17 20:44:42 yonik Exp $+ * @since solr 0.9+ */++public class DirectUpdateHandler extends UpdateHandler {++ // the set of ids in the "pending set" (those docs that have been added, but+ // that are not yet visible.+ final HashSet<String> pset;+ IndexWriter writer;+ SolrIndexSearcher searcher;+ int numAdds=0; // number of docs added to the pending set+ int numPending=0; // number of docs currently in this pending set+ int numDeleted=0; // number of docs deleted or+++ public DirectUpdateHandler(SolrCore core) throws IOException {+ super(core);+ pset = new HashSet<String>(256);+ }+++ protected void openWriter() throws IOException {+ if (writer==null) {+ writer = createMainIndexWriter("DirectUpdateHandler");+ }+ }++ protected void closeWriter() throws IOException {+ try {+ if (writer!=null) writer.close();+ } finally {+ // TODO: if an exception causes the writelock to not be+ // released, we could delete it here.+ writer=null;+ }+ }++ protected void openSearcher() throws IOException {+ if (searcher==null) {+ searcher = core.newSearcher("DirectUpdateHandler");+ }+ }++ protected void closeSearcher() throws IOException {+ try {+ if (searcher!=null) searcher.close();+ } finally {+ // TODO: if an exception causes the writelock to not be+ // released, we could delete it here.+ searcher=null;+ }+ }++ protected void doAdd(Document doc) throws IOException {+ closeSearcher(); openWriter();+ writer.addDocument(doc);+ }++ protected boolean existsInIndex(String id) throws IOException {+ if (idField == null) throw new SolrException(2,"Operation requires schema to have a unique key field");++ closeWriter(); openSearcher();+ IndexReader ir = searcher.getReader();+ TermDocs tdocs = null;+ boolean exists=false;+ try {+ tdocs = ir.termDocs(idTerm(id));+ if (tdocs.next()) exists=true;+ } finally {+ try { if (tdocs != null) tdocs.close(); } catch (Exception e) {}+ }+ return exists;+ }+++ protected int deleteInIndex(String id) throws IOException {+ if (idField == null) throw new SolrException(2,"Operation requires schema to have a unique key field");++ closeWriter(); openSearcher();+ IndexReader ir = searcher.getReader();+ TermDocs tdocs = null;+ int num=0;+ try {+ num = ir.delete(idTerm(id));+ if (SolrCore.log.isLoggable(Level.FINEST)) {+ SolrCore.log.finest("deleted " + num + " docs matching id " + id);+ }+ } finally {+ try { if (tdocs != null) tdocs.close(); } catch (Exception e) {}+ }+ return num;+ }++ protected void overwrite(String id, Document doc) throws IOException {+ if (id==null) id=getId(doc);+ deleteInIndex(id);+ doAdd(doc);+ }++ /************** Direct update handler - pseudo code ***********+ def add(doc, id, allowDups, overwritePending, overwriteCommitted):+ if not overwritePending and not overwriteCommitted:+ #special case... no need to check pending set, and we don't keep+ #any state around about this addition+ if allowDups:+ committed[id]=doc #100+ return+ else:+ #if no dups allowed, we must check the *current* index (pending and committed)+ if not committed[id]: committed[id]=doc #000+ return+ #001 (searchd addConditionally)+ if not allowDups and not overwritePending and pending[id]: return+ del committed[id] #delete from pending and committed 111 011+ committed[id]=doc+ pending[id]=True+ ****************************************************************/++ // could return the number of docs deleted, but is that always possible to know???+ public void delete(DeleteUpdateCommand cmd) throws IOException {+ if (!cmd.fromPending && !cmd.fromCommitted)+ throw new SolrException(400,"meaningless command: " + cmd);+ if (!cmd.fromPending || !cmd.fromCommitted)+ throw new SolrException(400,"operation not supported" + cmd);++ synchronized(this) {+ deleteInIndex(cmd.id);+ pset.remove(cmd.id);+ }+ }++ // TODO - return number of docs deleted?+ // Depending on implementation, we may not be able to immediately determine num...+ public void deleteByQuery(DeleteUpdateCommand cmd) throws IOException {+ if (!cmd.fromPending && !cmd.fromCommitted)+ throw new SolrException(400,"meaningless command: " + cmd);+ if (!cmd.fromPending || !cmd.fromCommitted)+ throw new SolrException(400,"operation not supported" + cmd);++ Query q = QueryParsing.parseQuery(cmd.query, schema);++ int totDeleted = 0;+ synchronized(this) {+ closeWriter(); openSearcher();++ // if we want to count the number of docs that were deleted, then+ // we need a new instance of the DeleteHitCollector+ final DeleteHitCollector deleter = new DeleteHitCollector(searcher);+ searcher.search(q, null, deleter);+ totDeleted = deleter.deleted;+ }++ if (SolrCore.log.isLoggable(Level.FINE)) {+ SolrCore.log.fine("docs deleted:" + totDeleted);+ }++ }++ /**************** old hit collector... new one is in base class+ // final DeleteHitCollector deleter = new DeleteHitCollector();+ class DeleteHitCollector extends HitCollector {+ public int deleted=0;+ public void collect(int doc, float score) {+ try {+ searcher.getReader().delete(doc);+ deleted++;+ } catch (IOException e) {+ try { closeSearcher(); } catch (Exception ee) { SolrException.log(SolrCore.log,ee); }+ SolrException.log(SolrCore.log,e);+ throw new SolrException(500,"Error deleting doc# "+doc,e);+ }+ }+ }+ ***************************/++ public void commit(CommitUpdateCommand cmd) throws IOException {+ Future[] waitSearcher = null;+ if (cmd.waitSearcher) {+ waitSearcher = new Future[1];+ }++ synchronized (this) {+ pset.clear();+ closeSearcher(); // flush any deletes+ if (cmd.optimize) {+ openWriter(); // writer needs to be open to optimize+ writer.optimize();+ }+ closeWriter();++ callPostCommitCallbacks();++ core.getSearcher(true,false,waitSearcher);+ }++ if (waitSearcher[0] != null) {+ try {+ waitSearcher[0].get();+ } catch (InterruptedException e) {+ SolrException.log(log,e);+ } catch (ExecutionException e) {+ SolrException.log(log,e);+ }+ }++ return;+ }++++ ///////////////////////////////////////////////////////////////////+ /////////////////// helper method for each add type ///////////////+ ///////////////////////////////////////////////////////////////////++ protected int addNoOverwriteNoDups(AddUpdateCommand cmd) throws IOException {+ if (cmd.id==null) {+ cmd.id=getId(cmd.doc);+ }+ synchronized (this) {+ if (existsInIndex(cmd.id)) return 0;+ doAdd(cmd.doc);+ }+ return 1;+ }++ protected int addConditionally(AddUpdateCommand cmd) throws IOException {+ if (cmd.id==null) {+ cmd.id=getId(cmd.doc);+ }+ synchronized(this) {+ if (pset.contains(cmd.id)) return 0;+ // since case 001 is currently the only case to use pset, only add+ // to it in that instance.+ pset.add(cmd.id);+ overwrite(cmd.id,cmd.doc);+ return 1;+ }+ }+++ // overwrite both pending and committed+ protected synchronized int overwriteBoth(AddUpdateCommand cmd) throws IOException {+ overwrite(cmd.id, cmd.doc);+ return 1;+ }+++ // add without checking+ protected synchronized int allowDups(AddUpdateCommand cmd) throws IOException {+ doAdd(cmd.doc);+ return 1;+ }+++ public int addDoc(AddUpdateCommand cmd) throws IOException {+ if (!cmd.allowDups && !cmd.overwritePending && !cmd.overwriteCommitted) {+ return addNoOverwriteNoDups(cmd);+ } else if (!cmd.allowDups && !cmd.overwritePending && cmd.overwriteCommitted) {+ return addConditionally(cmd);+ } else if (!cmd.allowDups && cmd.overwritePending && !cmd.overwriteCommitted) {+ // return overwriteBoth(cmd);+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } else if (!cmd.allowDups && cmd.overwritePending && cmd.overwriteCommitted) {+ return overwriteBoth(cmd);+ } else if (cmd.allowDups && !cmd.overwritePending && !cmd.overwriteCommitted) {+ return allowDups(cmd);+ } else if (cmd.allowDups && !cmd.overwritePending && cmd.overwriteCommitted) {+ // return overwriteBoth(cmd);+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } else if (cmd.allowDups && cmd.overwritePending && !cmd.overwriteCommitted) {+ // return overwriteBoth(cmd);+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } else if (cmd.allowDups && cmd.overwritePending && cmd.overwriteCommitted) {+ return overwriteBoth(cmd);+ }+ throw new SolrException(400,"unsupported param combo:" + cmd);+ }++ public void close() throws IOException {+ synchronized(this) {+ closeSearcher();+ closeWriter();+ }+ }++++ /////////////////////////////////////////////////////////////////////+ // SolrInfoMBean stuff: Statistics and Module Info+ /////////////////////////////////////////////////////////////////////++ public String getName() {+ return DirectUpdateHandler.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "Update handler that directly changes the on-disk main lucene index";+ }++ public Category getCategory() {+ return Category.CORE;+ }++ public String getCvsId() {+ return "$Id: DirectUpdateHandler.java,v 1.13 2005/06/17 20:44:42 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/DirectUpdateHandler.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }++ public NamedList getStatistics() {+ NamedList lst = new NamedList();+ return lst;+ }+++++}diff --git a/src/java/org/apache/solr/update/DirectUpdateHandler2.java b/src/java/org/apache/solr/update/DirectUpdateHandler2.javanew file mode 100644index 00000000000..398b7299b74--- /dev/null+++ b/src/java/org/apache/solr/update/DirectUpdateHandler2.java@@ -0,0 +1,569 @@+/**+ * 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.+ */++/**+ * @author yonik+ */++package org.apache.solr.update;++import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.document.Document;+import org.apache.lucene.search.Query;++import java.util.HashMap;+import java.util.Map;+import java.util.concurrent.Future;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.atomic.AtomicLong;+import java.util.logging.Level;+import java.io.IOException;+import java.net.URL;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.search.QueryParsing;+import org.apache.solr.util.NamedList;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;++/**+ * <code>DirectUpdateHandler2</code> implements an UpdateHandler where documents are added+ * directly to the main Lucene index as opposed to adding to a separate smaller index.+ * For this reason, not all combinations to/from pending and committed are supported.+ * This version supports efficient removal of duplicates on a commit. It works by maintaining+ * a related count for every document being added or deleted. At commit time, for every id with a count,+ * all but the last "count" docs with that id are deleted.+ * <p>+ *+ * Supported add command parameters:+ <TABLE BORDER>+ <TR>+ <TH>allowDups</TH>+ <TH>overwritePending</TH>+ <TH>overwriteCommitted</TH>+ <TH>efficiency</TH>+ </TR>+ <TR>+ <TD>false</TD>+ <TD>false</TD>+ <TD>true</TD>++ <TD>fast</TD>+ </TR>+ <TR>+ <TD>true or false</TD>+ <TD>true</TD>+ <TD>true</TD>++ <TD>fast</TD>+ </TR>+ <TR>+ <TD>true</TD>+ <TD>false</TD>+ <TD>false</TD>+ <TD>fastest</TD>+ </TR>++</TABLE>++ <p>Supported delete commands:+ <TABLE BORDER>+ <TR>+ <TH>command</TH>+ <TH>fromPending</TH>+ <TH>fromCommitted</TH>+ <TH>efficiency</TH>+ </TR>+ <TR>+ <TD>delete</TD>+ <TD>true</TD>+ <TD>true</TD>+ <TD>fast</TD>+ </TR>+ <TR>+ <TD>deleteByQuery</TD>+ <TD>true</TD>+ <TD>true</TD>+ <TD>very slow*</TD>+ </TR>+</TABLE>++ <p>* deleteByQuery causes a commit to happen (close current index writer, open new index reader)+ before it can be processed. If deleteByQuery functionality is needed, it's best if they can+ be batched and executed together so they may share the same index reader.++ *+ * @author yonik+ * @version $Id: DirectUpdateHandler2.java,v 1.12 2005/06/17 20:44:42 yonik Exp $+ * @since solr 0.9+ */++public class DirectUpdateHandler2 extends UpdateHandler {++ // stats+ AtomicLong addCommands = new AtomicLong();+ AtomicLong addCommandsCumulative = new AtomicLong();+ AtomicLong deleteByIdCommands= new AtomicLong();+ AtomicLong deleteByIdCommandsCumulative= new AtomicLong();+ AtomicLong deleteByQueryCommands= new AtomicLong();+ AtomicLong deleteByQueryCommandsCumulative= new AtomicLong();+ AtomicLong commitCommands= new AtomicLong();+ AtomicLong optimizeCommands= new AtomicLong();+ AtomicLong numDocsDeleted= new AtomicLong();+ AtomicLong numDocsPending= new AtomicLong();+ AtomicLong numErrors = new AtomicLong();+ AtomicLong numErrorsCumulative = new AtomicLong();++++ // The key is the id, the value (Integer) is the number+ // of docs to save (delete all except the last "n" added)+ protected final HashMap<String,Integer> pset;++ // commonly used constants for the count in the pset+ protected final static Integer ZERO = 0;+ protected final static Integer ONE = 1;++ protected IndexWriter writer;+ protected SolrIndexSearcher searcher;++ public DirectUpdateHandler2(SolrCore core) throws IOException {+ super(core);+ pset = new HashMap<String,Integer>(256); // 256 is just an optional head-start+ }++ protected void openWriter() throws IOException {+ if (writer==null) {+ writer = createMainIndexWriter("DirectUpdateHandler2");+ }+ }++ protected void closeWriter() throws IOException {+ try {+ numDocsPending.set(0);+ if (writer!=null) writer.close();+ } finally {+ // if an exception causes the writelock to not be+ // released, we could try and delete it here+ writer=null;+ }+ }++ protected void openSearcher() throws IOException {+ if (searcher==null) {+ searcher = core.newSearcher("DirectUpdateHandler2");+ }+ }++ protected void closeSearcher() throws IOException {+ try {+ if (searcher!=null) searcher.close();+ } finally {+ // if an exception causes a lock to not be+ // released, we could try to delete it.+ searcher=null;+ }+ }++ protected void doAdd(Document doc) throws IOException {+ closeSearcher(); openWriter();+ writer.addDocument(doc);+ }++++ public int addDoc(AddUpdateCommand cmd) throws IOException {+ addCommands.incrementAndGet();+ addCommandsCumulative.incrementAndGet();+ int rc=-1;+ try {+ if (!cmd.allowDups && !cmd.overwritePending && !cmd.overwriteCommitted) {+ throw new SolrException(400,"unsupported param combo:" + cmd);+ // this would need a reader to implement (to be able to check committed+ // before adding.)+ // return addNoOverwriteNoDups(cmd);+ } else if (!cmd.allowDups && !cmd.overwritePending && cmd.overwriteCommitted) {+ rc = addConditionally(cmd);+ return rc;+ } else if (!cmd.allowDups && cmd.overwritePending && !cmd.overwriteCommitted) {+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } else if (!cmd.allowDups && cmd.overwritePending && cmd.overwriteCommitted) {+ rc = overwriteBoth(cmd);+ return rc;+ } else if (cmd.allowDups && !cmd.overwritePending && !cmd.overwriteCommitted) {+ rc = allowDups(cmd);+ return rc;+ } else if (cmd.allowDups && !cmd.overwritePending && cmd.overwriteCommitted) {+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } else if (cmd.allowDups && cmd.overwritePending && !cmd.overwriteCommitted) {+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } else if (cmd.allowDups && cmd.overwritePending && cmd.overwriteCommitted) {+ rc = overwriteBoth(cmd);+ return rc;+ }+ throw new SolrException(400,"unsupported param combo:" + cmd);+ } finally {+ if (rc!=1) {+ numErrors.incrementAndGet();+ numErrorsCumulative.incrementAndGet();+ } else {+ numDocsPending.incrementAndGet();+ }+ }+ }+++ // could return the number of docs deleted, but is that always possible to know???+ public void delete(DeleteUpdateCommand cmd) throws IOException {+ deleteByIdCommands.incrementAndGet();+ deleteByIdCommandsCumulative.incrementAndGet();++ if (!cmd.fromPending && !cmd.fromCommitted) {+ numErrors.incrementAndGet();+ numErrorsCumulative.incrementAndGet();+ throw new SolrException(400,"meaningless command: " + cmd);+ }+ if (!cmd.fromPending || !cmd.fromCommitted) {+ numErrors.incrementAndGet();+ numErrorsCumulative.incrementAndGet();+ throw new SolrException(400,"operation not supported" + cmd);+ }++ synchronized(this) {+ pset.put(cmd.id, ZERO);+ }+ }++ // why not return number of docs deleted?+ // Depending on implementation, we may not be able to immediately determine the num...+ public void deleteByQuery(DeleteUpdateCommand cmd) throws IOException {+ deleteByQueryCommands.incrementAndGet();+ deleteByQueryCommandsCumulative.incrementAndGet();++ if (!cmd.fromPending && !cmd.fromCommitted) {+ numErrors.incrementAndGet();+ numErrorsCumulative.incrementAndGet();+ throw new SolrException(400,"meaningless command: " + cmd);+ }+ if (!cmd.fromPending || !cmd.fromCommitted) {+ numErrors.incrementAndGet();+ numErrorsCumulative.incrementAndGet();+ throw new SolrException(400,"operation not supported" + cmd);+ }++ boolean madeIt=false;+ try {+ Query q = QueryParsing.parseQuery(cmd.query, schema);++ int totDeleted = 0;+ synchronized(this) {+ // we need to do much of the commit logic (mainly doing queued+ // deletes since deleteByQuery can throw off our counts.+ doDeletions();++ closeWriter();+ openSearcher();++ // if we want to count the number of docs that were deleted, then+ // we need a new instance of the DeleteHitCollector+ final DeleteHitCollector deleter = new DeleteHitCollector(searcher);+ searcher.search(q, null, deleter);+ totDeleted = deleter.deleted;+ }++ if (SolrCore.log.isLoggable(Level.FINE)) {+ SolrCore.log.fine("docs deleted by query:" + totDeleted);+ }+ numDocsDeleted.getAndAdd(totDeleted);+ madeIt=true;+ } finally {+ if (!madeIt) {+ numErrors.incrementAndGet();+ numErrorsCumulative.incrementAndGet();+ }+ }+ }+++ ///////////////////////////////////////////////////////////////////+ /////////////////// helper method for each add type ///////////////+ ///////////////////////////////////////////////////////////////////+++ protected int addConditionally(AddUpdateCommand cmd) throws IOException {+ if (cmd.id==null) {+ cmd.id=getId(cmd.doc);+ }+ synchronized(this) {+ Integer saveCount = pset.get(cmd.id);+ if (saveCount!=null && saveCount!=0) {+ // a doc with this id already exists in the pending set+ return 0;+ }+ pset.put(cmd.id, ONE);+ doAdd(cmd.doc);+ return 1;+ }+ }+++ // overwrite both pending and committed+ protected synchronized int overwriteBoth(AddUpdateCommand cmd) throws IOException {+ if (cmd.id==null) {+ cmd.id=getId(cmd.doc);+ }+ synchronized (this) {+ pset.put(cmd.id, ONE);+ doAdd(cmd.doc);+ }+ return 1;+ }+++ // add without checking+ protected synchronized int allowDups(AddUpdateCommand cmd) throws IOException {+ if (cmd.id==null) {+ cmd.id=getOptId(cmd.doc);+ }+ synchronized(this) {+ doAdd(cmd.doc);++ if (cmd.id != null) {+ Integer saveCount = pset.get(cmd.id);++ // if there weren't any docs marked for deletion before, then don't mark+ // any for deletion now.+ if (saveCount == null) return 1;++ // If there were docs marked for deletion, then increment the number of+ // docs to save at the end.++ // the following line is optional, but it saves an allocation in the common case.+ if (saveCount == ZERO) saveCount=ONE;+ else saveCount++;++ pset.put(cmd.id, saveCount);+ }+ }+ return 1;+ }++ // NOT FOR USE OUTSIDE OF A "synchronized(this)" BLOCK+ private int[] docnums;++ //+ // do all needed deletions.+ // call in a synchronized context.+ //+ protected void doDeletions() throws IOException {++ if (pset.size() > 0) { // optimization: only open searcher if there is something to delete...+ log.info("DirectUpdateHandler2 deleting and removing dups for " + pset.size() +" ids");+ int numDeletes=0;++ closeWriter();+ openSearcher();+ IndexReader reader = searcher.getReader();+ TermDocs tdocs = reader.termDocs();+ String fieldname = idField.getName();++ for (Map.Entry<String,Integer> entry : pset.entrySet()) {+ String id = entry.getKey();+ int saveLast = entry.getValue(); // save the last "saveLast" documents++ //expand our array that keeps track of docs if needed.+ if (docnums==null || saveLast > docnums.length) {+ docnums = new int[saveLast];+ }++ // initialize all docnums in the list to -1 (unused)+ for (int i=0; i<saveLast; i++) {+ docnums[i] = -1;+ }++ tdocs.seek(new Term(fieldname,id));++ //+ // record the docs for this term in the "docnums" array and wrap around+ // at size "saveLast". If we reuse a slot in the array, then we delete+ // the doc that was there from the index.+ //+ int pos=0;+ while (tdocs.next()) {+ if (saveLast==0) {+ // special case - delete all the docs as we see them.+ reader.delete(tdocs.doc());+ numDeletes++;+ continue;+ }++ int prev=docnums[pos];+ docnums[pos]=tdocs.doc();+ if (prev != -1) {+ reader.delete(prev);+ numDeletes++;+ }++ if (++pos >= saveLast) pos=0;+ }+ }++ // should we ever shrink it again, or just clear it?+ pset.clear();+ log.info("DirectUpdateHandler2 docs deleted=" + numDeletes);+ numDocsDeleted.addAndGet(numDeletes);+ }++ }++++ public void commit(CommitUpdateCommand cmd) throws IOException {++ if (cmd.optimize) {+ optimizeCommands.incrementAndGet();+ } else {+ commitCommands.incrementAndGet();+ }++ Future[] waitSearcher = null;+ if (cmd.waitSearcher) {+ waitSearcher = new Future[1];+ }++ boolean error=true;+ try {+ synchronized (this) {+ log.info("start "+cmd);+ doDeletions();++ if (cmd.optimize) {+ closeSearcher();+ openWriter();+ writer.optimize();+ }++ closeSearcher();+ closeWriter();++ callPostCommitCallbacks();++ // open a new searcher in the sync block to avoid opening it+ // after a deleteByQuery changed the index, or in between deletes+ // and adds of another commit being done.+ core.getSearcher(true,false,waitSearcher);++ log.info("end_commit_flush");+ } // end synchronized block++ error=false;+ }+ finally {+ addCommands.set(0);+ deleteByIdCommands.set(0);+ deleteByQueryCommands.set(0);+ numErrors.set(error ? 1 : 0);+ }++ // if we are supposed to wait for the searcher to be registered, then we should do it+ // outside of the synchronized block so that other update operations can proceed.+ if (waitSearcher!=null && waitSearcher[0] != null) {+ try {+ waitSearcher[0].get();+ } catch (InterruptedException e) {+ SolrException.log(log,e);+ } catch (ExecutionException e) {+ SolrException.log(log,e);+ }+ }++ return;+ }+++ public void close() throws IOException {+ log.info("closing " + this);+ synchronized(this) {+ doDeletions();+ closeSearcher();+ closeWriter();+ }+ log.info("closed " + this);+ }++ /////////////////////////////////////////////////////////////////////+ // SolrInfoMBean stuff: Statistics and Module Info+ /////////////////////////////////////////////////////////////////////++ public String getName() {+ return DirectUpdateHandler2.class.getName();+ }++ public String getVersion() {+ return SolrCore.version;+ }++ public String getDescription() {+ return "Update handler that efficiently directly updates the on-disk main lucene index";+ }++ public Category getCategory() {+ return Category.UPDATEHANDLER;+ }++ public String getCvsId() {+ return "$Id: DirectUpdateHandler2.java,v 1.12 2005/06/17 20:44:42 yonik Exp $";+ }++ public String getCvsName() {+ return "$Name: $";+ }++ public String getCvsSource() {+ return "$Source: /cvs/main/searching/solr/solarcore/src/solr/DirectUpdateHandler2.java,v $";+ }++ public URL[] getDocs() {+ return null;+ }++ public NamedList getStatistics() {+ NamedList lst = new NamedList();+ lst.add("commits", commitCommands.get());+ lst.add("optimizes", optimizeCommands.get());+ lst.add("docsPending", numDocsPending.get());+ // pset.size() not synchronized, but it should be fine to access.+ lst.add("deletesPending", pset.size());+ lst.add("adds", addCommands.get());+ lst.add("deletesById", deleteByIdCommands.get());+ lst.add("deletesByQuery", deleteByQueryCommands.get());+ lst.add("errors", numErrors.get());+ lst.add("cumulative_adds", addCommandsCumulative.get());+ lst.add("cumulative_deletesById", deleteByIdCommandsCumulative.get());+ lst.add("cumulative_deletesByQuery", deleteByQueryCommandsCumulative.get());+ lst.add("cumulative_errors", numErrorsCumulative.get());+ lst.add("docsDeleted", numDocsDeleted.get());++ return lst;+ }++ public String toString() {+ return "DirectUpdateHandler2" + getStatistics();+ }+}diff --git a/src/java/org/apache/solr/update/DocumentBuilder.java b/src/java/org/apache/solr/update/DocumentBuilder.javanew file mode 100644index 00000000000..df2e4092112--- /dev/null+++ b/src/java/org/apache/solr/update/DocumentBuilder.java@@ -0,0 +1,104 @@+/**+ * 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.+ */++package org.apache.solr.update;++import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;+import org.apache.solr.core.SolrException;++import java.util.HashMap;++/**+ * @author yonik+ * @version $Id: DocumentBuilder.java,v 1.7 2005/12/02 04:31:06 yonik Exp $+ */+++// Not thread safe - by design. Create a new builder for each thread.+public class DocumentBuilder {+ private final IndexSchema schema;+ private Document doc;+ private HashMap<String,String> map = new HashMap<String,String>();++ public DocumentBuilder(IndexSchema schema) {+ this.schema = schema;+ }++ public void startDoc() {+ doc = new Document();+ map.clear();+ }++ protected void addSingleField(SchemaField sfield, String val, float boost) {+ //System.out.println("###################ADDING FIELD "+sfield+"="+val);++ // we don't check for a null val ourselves because a solr.FieldType+ // might actually want to map it to something. If createField()+ // returns null, then we don't store the field.+ Field field = sfield.createField(val, boost);+ if (field != null) {+ if (!sfield.multiValued()) {+ String oldValue = map.put(sfield.getName(), val);+ if (oldValue != null) {+ throw new SolrException(400,"ERROR: multiple values encountered for non multiValued field " + sfield.getName()+ + ": first='" + oldValue + "' second='" + val + "'");+ }+ }+ // field.setBoost(boost);+ doc.add(field);+ }+ }+++ public void addField(SchemaField sfield, String val, float boost) {+ addSingleField(sfield,val,boost);++ // Check if we should copy this field to any other fields.+ SchemaField[] destArr = schema.getCopyFields(sfield.getName());+ if (destArr != null) {+ for (SchemaField destField : destArr) {+ addSingleField(destField,val,boost);+ }+ }+ }++ public void addField(String name, String val) {+ SchemaField ftype = schema.getField(name);+ // fields.get(name);+ addField(ftype,val,1.0f);+ }++ public void addField(String name, String val, float boost) {+ SchemaField ftype = schema.getField(name);+ addField(ftype,val,boost);+ }++ public void setBoost(float boost) {+ doc.setBoost(boost);+ }++ public void endDoc() {+ }++ // specific to this type of document builder+ public Document getDoc() {+ Document ret = doc; doc=null;+ return ret;+ }+}diff --git a/src/java/org/apache/solr/update/SolrIndexConfig.java b/src/java/org/apache/solr/update/SolrIndexConfig.javanew file mode 100644index 00000000000..386d09dbc5f--- /dev/null+++ b/src/java/org/apache/solr/update/SolrIndexConfig.java@@ -0,0 +1,62 @@+/**+ * 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.+ */++package org.apache.solr.update;++import org.apache.solr.core.SolrConfig;++//+// For performance reasons, we don't want to re-read+// config params each time an index writer is created.+// This config object encapsulates IndexWriter config params.+//+/**+ * @author yonik+ * @version $Id$+ */+public class SolrIndexConfig {+ public static final String defaultsName ="indexDefaults";++ //default values+ public static final boolean defUseCompoundFile=SolrConfig.config.getBool(defaultsName +"/useCompoundFile", true);+ public static final int defMaxBufferedDocs=SolrConfig.config.getInt(defaultsName +"/maxBufferedDocs", -1);+ public static final int defMaxMergeDocs=SolrConfig.config.getInt(defaultsName +"/maxMergeDocs", -1);+ public static final int defMergeFactor=SolrConfig.config.getInt(defaultsName +"/mergeFactor", -1);+ public static final int defMaxFieldLength=SolrConfig.config.getInt(defaultsName +"/maxFieldLength", -1);+ public static final int writeLockTimeout=SolrConfig.config.getInt(defaultsName +"/writeLockTimeout", -1);+ public static final int commitLockTimeout=SolrConfig.config.getInt(defaultsName +"/commitLockTimeout", -1);++ /*** These are "final" in lucene 1.9+ static {+ if (writeLockTimeout != -1) IndexWriter.WRITE_LOCK_TIMEOUT=writeLockTimeout;+ if (commitLockTimeout != -1) IndexWriter.COMMIT_LOCK_TIMEOUT=commitLockTimeout;+ }+ ***/++ public final boolean useCompoundFile;+ public final int maxBufferedDocs;+ public final int maxMergeDocs;+ public final int mergeFactor;+ public final int maxFieldLength;++ public SolrIndexConfig(String prefix) {+ useCompoundFile=SolrConfig.config.getBool(prefix+"/useCompoundFile", defUseCompoundFile);+ maxBufferedDocs=SolrConfig.config.getInt(prefix+"/maxBufferedDocs",defMaxBufferedDocs);+ maxMergeDocs=SolrConfig.config.getInt(prefix+"/maxMergeDocs",defMaxMergeDocs);+ mergeFactor=SolrConfig.config.getInt(prefix+"/mergeFactor",defMergeFactor);+ maxFieldLength= SolrConfig.config.getInt(prefix+"/maxFieldLength",defMaxFieldLength);+ }+}\ No newline at end of filediff --git a/src/java/org/apache/solr/update/SolrIndexWriter.java b/src/java/org/apache/solr/update/SolrIndexWriter.javanew file mode 100644index 00000000000..9e77f1e8645--- /dev/null+++ b/src/java/org/apache/solr/update/SolrIndexWriter.java@@ -0,0 +1,105 @@+/**+ * 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.+ */++package org.apache.solr.update;++import org.apache.lucene.index.IndexWriter;+import org.apache.solr.schema.IndexSchema;++import java.util.logging.Logger;+import java.io.IOException;++/**+ * An IndexWriter that is configured via Solr config mechanisms.+ *+* @author yonik+* @version $Id: SolrIndexWriter.java,v 1.9 2006/01/09 03:51:44 yonik Exp $+* @since solr 0.9+*/+++public class SolrIndexWriter extends IndexWriter {+ private static Logger log = Logger.getLogger(SolrIndexWriter.class.getName());++ String name;+ IndexSchema schema;++ private void init(String name, IndexSchema schema, SolrIndexConfig config) {+ log.fine("Opened Writer " + name);+ this.name = name;+ this.schema = schema;+ setSimilarity(schema.getSimilarity());+ // setUseCompoundFile(false);++ if (config != null) {+ setUseCompoundFile(config.useCompoundFile);+ if (config.maxBufferedDocs != -1) minMergeDocs=config.maxBufferedDocs;+ if (config.maxMergeDocs != -1) maxMergeDocs=config.maxMergeDocs;+ if (config.mergeFactor != -1) mergeFactor =config.mergeFactor;+ if (config.maxFieldLength != -1) maxFieldLength =config.maxFieldLength;+ }++ }++ public SolrIndexWriter(String name, String path, boolean create, IndexSchema schema) throws IOException {+ super(path, schema.getAnalyzer(), create);+ init(name, schema, null);+ }++ public SolrIndexWriter(String name, String path, boolean create, IndexSchema schema, SolrIndexConfig config) throws IOException {+ super(path, schema.getAnalyzer(), create);+ init(name, schema,config);+ }++ /*** use DocumentBuilder now...+ private final void addField(Document doc, String name, String val) {+ SchemaField ftype = schema.getField(name);++ // we don't check for a null val ourselves because a solr.FieldType+ // might actually want to map it to something. If createField()+ // returns null, then we don't store the field.++ Field field = ftype.createField(val, boost);+ if (field != null) doc.add(field);+ }+++ public void addRecord(String[] fieldNames, String[] fieldValues) throws IOException {+ Document doc = new Document();+ for (int i=0; i<fieldNames.length; i++) {+ String name = fieldNames[i];+ String val = fieldNames[i];++ // first null is end of list. client can reuse arrays if they want+ // and just write a single null if there is unused space.+ if (name==null) break;++ addField(doc,name,val);+ }+ addDocument(doc);+ }+ ******/++ public void close() throws IOException {+ log.fine("Closing Writer " + name);+ super.close();+ }++ void finalizer() {+ try {super.close();} catch (IOException e) {}+ }++}diff --git a/src/java/org/apache/solr/update/UpdateCommand.java b/src/java/org/apache/solr/update/UpdateCommand.javanew file mode 100644index 00000000000..56b0ef19cd3--- /dev/null+++ b/src/java/org/apache/solr/update/UpdateCommand.java@@ -0,0 +1,37 @@+/**+ * 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.+ */++package org.apache.solr.update;++import org.apache.lucene.document.Document;+++/** An index update command encapsulated in an object (Command pattern)+ *+ * @author yonik+ * @version $Id: UpdateCommand.java,v 1.4 2005/05/25 04:26:47 yonik Exp $+ */+ public class UpdateCommand {+ protected String commandName;++ public UpdateCommand(String commandName) {+ this.commandName = commandName;+ }++ public String toString() {+ return commandName;+ }+ }diff --git a/src/java/org/apache/solr/update/UpdateHandler.java b/src/java/org/apache/solr/update/UpdateHandler.javanew file mode 100644index 00000000000..e410b6ce274--- /dev/null+++ b/src/java/org/apache/solr/update/UpdateHandler.java@@ -0,0 +1,148 @@+/**+ * 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.+ */++package org.apache.solr.update;+++import org.apache.lucene.index.Term;+import org.apache.lucene.document.Document;+import org.apache.lucene.search.HitCollector;+import org.w3c.dom.NodeList;+import org.w3c.dom.Node;++import java.util.logging.Logger;+import java.util.Vector;+import java.io.IOException;++import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.DOMUtil;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;+import org.apache.solr.schema.FieldType;+import org.apache.solr.core.*;++import javax.xml.xpath.XPathConstants;++/**+ * <code>UpdateHandler</code> handles requests to change the index+ * (adds, deletes, commits, optimizes, etc).+ *+ * @author yonik+ * @version $Id: UpdateHandler.java,v 1.15 2005/06/21 20:24:25 yonik Exp $+ * @since solr 0.9+ */++public abstract class UpdateHandler implements SolrInfoMBean {+ protected final static Logger log = Logger.getLogger(UpdateHandler.class.getName());++ protected final SolrCore core;+ protected final IndexSchema schema;++ protected final SchemaField idField;+ protected final FieldType idFieldType;++ protected Vector<SolrEventListener> commitCallbacks = new Vector<SolrEventListener>();++ private void parseEventListeners() {+ NodeList nodes = (NodeList) SolrConfig.config.evaluate("updateHandler/listener[@event=\"postCommit\"]", XPathConstants.NODESET);+ if (nodes!=null) {+ for (int i=0; i<nodes.getLength(); i++) {+ Node node = nodes.item(i);+ try {+ String className = DOMUtil.getAttr(node,"class");+ Class clazz = Class.forName(className);+ SolrEventListener listener = (SolrEventListener)clazz.newInstance();+ listener.init(DOMUtil.childNodesToNamedList(node));+ // listener.init(DOMUtil.toMapExcept(node.getAttributes(),"class","synchronized"));+ commitCallbacks.add(listener);+ log.info("added SolrEventListener for postCommit: " + listener);+ } catch (Exception e) {+ throw new SolrException(1,"error parsing event listevers", e, false);+ }+ }+ }+ }++ protected void callPostCommitCallbacks() {+ for (SolrEventListener listener : commitCallbacks) {+ listener.postCommit();+ }+ }++ public UpdateHandler(SolrCore core) {+ this.core=core;+ schema = core.getSchema();+ idField = schema.getUniqueKeyField();+ idFieldType = idField!=null ? idField.getType() : null;++ parseEventListeners();+ SolrInfoRegistry.getRegistry().put("updateHandler", this);+ }++ protected SolrIndexWriter createMainIndexWriter(String name) throws IOException {+ SolrIndexWriter writer = new SolrIndexWriter(name,core.getDir(), false, schema,SolrCore.mainIndexConfig);+ return writer;+ }++ protected final Term idTerm(String id) {+ // to correctly create the Term, the string needs to be run+ // through the Analyzer for that field.+ return new Term(idField.getName(), idFieldType.toInternal(id));+ }++ protected final String getId(Document doc) {+ if (idField == null) throw new SolrException(400,"Operation requires schema to have a unique key field");+ String id = doc.get(idField.getName());+ if (id == null) throw new SolrException(400,"Document is missing uniqueKey field " + idField.getName());+ return id;+ }++ protected final String getOptId(Document doc) {+ if (idField == null) return null;+ return doc.get(idField.getName());+ }+++ public abstract int addDoc(AddUpdateCommand cmd) throws IOException;+ public abstract void delete(DeleteUpdateCommand cmd) throws IOException;+ public abstract void deleteByQuery(DeleteUpdateCommand cmd) throws IOException;+ public abstract void commit(CommitUpdateCommand cmd) throws IOException;+ public abstract void close() throws IOException;+++ class DeleteHitCollector extends HitCollector {+ public int deleted=0;+ public final SolrIndexSearcher searcher;++ public DeleteHitCollector(SolrIndexSearcher searcher) {+ this.searcher = searcher;+ }++ public void collect(int doc, float score) {+ try {+ searcher.getReader().delete(doc);+ deleted++;+ } catch (IOException e) {+ // don't try to close the searcher on failure for now...+ // try { closeSearcher(); } catch (Exception ee) { SolrException.log(log,ee); }+ throw new SolrException(500,"Error deleting doc# "+doc,e,false);+ }+ }+ }++}++diff --git a/src/java/org/apache/solr/util/BCDUtils.java b/src/java/org/apache/solr/util/BCDUtils.javanew file mode 100644index 00000000000..2021d5a96af--- /dev/null+++ b/src/java/org/apache/solr/util/BCDUtils.java@@ -0,0 +1,532 @@+/**+ * 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.+ */++package org.apache.solr.util;+++/**+ * @author yonik+ * @version $Id$+ */+public class BCDUtils {+ // idiv is expensive...+ // use fixed point math to multiply by 1/10+ // http://www.cs.uiowa.edu/~jones/bcd/divide.html+ private static int div10(int a) { return (a * 0xcccd) >>> 19; }+ private static int mul10(int a) { return (a*10); }+ // private static int mul10(int a) { return ((a<<3)+(a<<1)); }+ // private static int mul10(int a) { return (a+(a<<2))<<1; } // attempt to use LEA instr+ // (imul32 on AMD64 only has a 3 cycle latency in any case)+++ // something that won't clash with other base100int+// chars (something >= 100)+ private static final char NEG_CHAR=(char)126;+ // The zero exponent.+// NOTE: for smaller integer representations, this current implementation+// combines sign and exponent into the first char. sign is negative if+// exponent is less than the zero point (no negative exponents themselves)+ private static final int ZERO_EXPONENT='a'; // 97++ // WARNING: assumption is that this is a legal int...+// no validation is done. [+-]?digit*+//+// Normalization of zeros *is* done...+// 0004, 004, 04, 4 will all end up being equal+// 0,-0 are normalized to '' (zero length)+//+// The value is written to the output buffer+// from the end to the start. The return value+// is the start of the Base100 int in the output buffer.+//+// As the output will be smaller than the input, arr and+// out may refer to the same array if desired.+//+ public static int base10toBase100(char[] arr, int start, int end,+ char[] out, int outend+ )+ {+ int wpos=outend; // write position+ boolean neg=false;++ while (--end >= start) {+ int val = arr[end];+ if (val=='+') { break; }+ else if (val=='-') { neg=!neg; break; }+ else {+ val = val - '0';+ if (end > start) {+ int val2 = arr[end-1];+ if (val2=='+') { out[--wpos]=(char)val; break; }+ if (val2=='-') { out[--wpos]=(char)val; neg=!neg; break; }+ end--;+ val = val + (val2 - '0')*10;+ }+ out[--wpos] = (char)val;+ }+ }++ // remove leading base100 zeros+ while (wpos<outend && out[wpos]==0) wpos++;++ // check for a zero value+ if (wpos==outend) {+ // if zero, don't add negative sign+ } else if (neg) {+ out[--wpos]=NEG_CHAR;+ }++ return wpos; // the start of the base100 int+ }++ // Converts a base100 number to base10 character form+// returns number of chars written.+// At least 1 char is always written.+ public static int base100toBase10(char[] arr, int start, int end,+ char[] out, int offset)+ {+ int wpos=offset; // write position+ boolean firstDigit=true;+ for (int i=start; i<end; i++) {+ int val = arr[i];+ if (val== NEG_CHAR) { out[wpos++]='-'; continue; }+ char tens = (char)(val / 10 + '0');+ if (!firstDigit || tens!='0') { // skip leading 0+ out[wpos++] = (char)(val / 10 + '0'); // tens position+ }+ out[wpos++] = (char)(val % 10 + '0'); // ones position+ firstDigit=false;+ }+ if (firstDigit) out[wpos++]='0';+ return wpos-offset;+ }++ public static String base10toBase100SortableInt(String val) {+ char[] arr = new char[val.length()+1];+ val.getChars(0,val.length(),arr,0);+ int len = base10toBase100SortableInt(arr,0,val.length(),arr,arr.length);+ return new String(arr,arr.length-len,len);+ }++ public static String base100SortableIntToBase10(String val) {+ int slen = val.length();+ char[] arr = new char[slen<<2];+ val.getChars(0,slen,arr,0);+ int len = base100SortableIntToBase10(arr,0,slen,arr,slen);+ return new String(arr,slen,len);+ }++ public static String base10toBase10kSortableInt(String val) {+ char[] arr = new char[val.length()+1];+ val.getChars(0,val.length(),arr,0);+ int len = base10toBase10kSortableInt(arr,0,val.length(),arr,arr.length);+ return new String(arr,arr.length-len,len);+ }++ public static String base10kSortableIntToBase10(String val) {+ int slen = val.length();+ char[] arr = new char[slen*5]; // +1 time for orig, +4 for new+ val.getChars(0,slen,arr,0);+ int len = base10kSortableIntToBase10(arr,0,slen,arr,slen);+ return new String(arr,slen,len);+ }++ /********* FUTURE+ // the zero exponent... exponents above this point are positive+ // and below are negative.+ // It is desirable to make ordinary numbers have a single byte+ // exponent when converted to UTF-8+ // For integers, the exponent will always be >=0, but this format+ // is meant to be valid for floating point numbers as well...+ private static final int ZERO_EXPONENT='a'; // 97++ // if exponent is larger than what can be represented+ // in a single byte (char), then this is the multibyte+ // escape char.+ // UCS-2 surrogates start at 0xD800+ private static final int POSITIVE_EXPONENT_ESCAPE=0x3fff;++ // if exponent is smaller than what can be represented in+ // a single byte, then this is the multibyte escape+ private static final int NEGATIVE_EXPONENT_ESCAPE=1;++ // if number is negative, it starts with this optional value+ // this should not overlap with any exponent values+ private static final int NEGATIVE_SIGN=0;+ **********/++ // WARNING: assumption is that this is a legal int...+ // no validation is done. [+-]?digit*+ //+ // Normalization of zeros *is* done...+ // 0004, 004, 04, 4 will all end up being equal+ // 0,-0 are normalized to '' (zero length)+ //+ // The value is written to the output buffer+ // from the end to the start. The return value+ // is the start of the Base100 int in the output buffer.+ //+ // As the output will be smaller than the input, arr and+ // out may refer to the same array if desired.+ //+ public static int base10toBase100SortableInt(char[] arr, int start, int end,+ char[] out, int outend+ )+ {+ int wpos=outend; // write position+ boolean neg=false;+ --end; // position end pointer *on* the last char++ // read signs and leading zeros+ while (start <= end) {+ char val = arr[start];+ if (val=='-') neg=!neg;+ else if (val>='1' && val<='9') break;+ start++;+ }++ // eat whitespace on RHS?+ outer: while (start <= end) {+ switch(arr[end]) {+ case ' ':+ case '\t':+ case '\n':+ case '\r': end--; break;+ default: break outer;+ }+ }++ int hundreds=0;+ /******************************************************+ * remove RHS zero normalization since it only helps 1 in 100+ * numbers and complicates both encoding and decoding.++ // remove pairs of zeros on the RHS and keep track of+ // the count.+ while (start <= end) {+ char val = arr[end];++ if (val=='0' && start <= end) {+ val=arr[end-1];+ if (val=='0') {+ hundreds++;+ end-=2;+ continue;+ }+ }++ break;+ }+ *************************************************************/+++ // now start at the end and work our way forward+ // encoding two base 10 digits into 1 base 100 digit+ while (start <= end) {+ int val = arr[end--];+ val = val - '0';+ if (start <= end) {+ int val2 = arr[end--];+ val = val + (val2 - '0')*10;+ }+ out[--wpos] = neg ? (char)(99-val) : (char)val;+ }++ /****** FUTURE: not needed for this implementation of exponent combined with sign+ // normalize all zeros to positive values+ if (wpos==outend) neg=false;+ ******/++ // adjust exponent by the number of base 100 chars written+ hundreds += outend - wpos;++ // write the exponent and sign combined+ out[--wpos] = neg ? (char)(ZERO_EXPONENT - hundreds) : (char)(ZERO_EXPONENT + hundreds);++ return outend-wpos; // the length of the base100 int+ }++ // Converts a base100 sortable number to base10 character form+// returns number of chars written.+// At least 1 char is always written.+ public static int base100SortableIntToBase10(char[] arr, int start, int end,+ char[] out, int offset)+ {+ // Take care of "0" case first. It's the only number that is represented+ // in one char.+ if (end-start == 1) {+ out[offset]='0';+ return 1;+ }++ int wpos = offset; // write position+ boolean neg = false;+ int exp = arr[start++];+ if (exp < ZERO_EXPONENT) {+ neg=true;+ exp = ZERO_EXPONENT - exp;+ out[wpos++]='-';+ }++ boolean firstDigit=true;+ while (start < end) {+ int val = arr[start++];+ if (neg) val = 99 - val;+ // opt - if we ever want a faster version we can avoid one integer+ // divide by using fixed point math to multiply by 1/10+ // http://www.cs.uiowa.edu/~jones/bcd/divide.html+ // TIP: write a small function in gcc or cl and see what+ // the optimized assemply output looks like (and which is fastest).+ // In C you can specify "unsigned" which gives the compiler more+ // info than the Java compiler has.+ char tens = (char)(val / 10 + '0');+ if (!firstDigit || tens!='0') { // skip leading 0+ out[wpos++] = tens; // write tens position+ }+ out[wpos++] = (char)(val % 10 + '0'); // write ones position+ firstDigit=false;+ }++ // OPTIONAL: if trailing zeros were truncated, then this is where+ // we would restore them (compare number of chars read vs exponent)++ return wpos-offset;+ }++ public static int base10toBase10kSortableInt(char[] arr, int start, int end,+ char[] out, int outend+ )+ {+ int wpos=outend; // write position+ boolean neg=false;+ --end; // position end pointer *on* the last char++ // read signs and leading zeros+ while (start <= end) {+ char val = arr[start];+ if (val=='-') neg=!neg;+ else if (val>='1' && val<='9') break;+ start++;+ }++ // eat whitespace on RHS?+ outer: while (start <= end) {+ switch(arr[end]) {+ case ' ': // fallthrough+ case '\t': // fallthrough+ case '\n': // fallthrough+ case '\r': end--; break;+ default: break outer;+ }+ }++ int exp=0;++ /******************************************************+ * remove RHS zero normalization since it only helps 1 in 100+ * numbers and complicates both encoding and decoding.++ // remove pairs of zeros on the RHS and keep track of+ // the count.+ while (start <= end) {+ char val = arr[end];++ if (val=='0' && start <= end) {+ val=arr[end-1];+ if (val=='0') {+ hundreds++;+ end-=2;+ continue;+ }+ }++ break;+ }+ *************************************************************/+++ // now start at the end and work our way forward+ // encoding two base 10 digits into 1 base 100 digit+ while (start <= end) {+ int val = arr[end--] - '0'; // ones+ if (start <= end) {+ val += (arr[end--] - '0')*10; // tens+ if (start <= end) {+ val += (arr[end--] - '0')*100; // hundreds+ if (start <= end) {+ val += (arr[end--] - '0')*1000; // thousands+ }+ }+ }+ out[--wpos] = neg ? (char)(9999-val) : (char)val;+ }+++ /****** FUTURE: not needed for this implementation of exponent combined with sign+ // normalize all zeros to positive values+ if (wpos==outend) neg=false;+ ******/++ // adjust exponent by the number of base 100 chars written+ exp += outend - wpos;++ // write the exponent and sign combined+ out[--wpos] = neg ? (char)(ZERO_EXPONENT - exp) : (char)(ZERO_EXPONENT + exp);++ return outend-wpos; // the length of the base100 int+ }++ // Converts a base100 sortable number to base10 character form+// returns number of chars written.+// At least 1 char is always written.+ public static int base10kSortableIntToBase10(char[] arr, int start, int end,+ char[] out, int offset)+ {+ // Take care of "0" case first. It's the only number that is represented+ // in one char since we don't chop trailing zeros.+ if (end-start == 1) {+ out[offset]='0';+ return 1;+ }++ int wpos = offset; // write position+ boolean neg;+ int exp = arr[start++];+ if (exp < ZERO_EXPONENT) {+ neg=true;+ // We don't currently use exp on decoding...+ // exp = ZERO_EXPONENT - exp;+ out[wpos++]='-';+ } else {+ neg=false;+ }++ // since so many values will fall in one char, pull it+ // out of the loop (esp since the first value must+ // be special-cased to not print leading zeros.+ // integer division is still expensive, so it's best to check+ // if you actually need to do it.+ //+ // TIP: write a small function in gcc or cl and see what+ // the optimized assemply output looks like (and which is fastest).+ // In C you can specify "unsigned" which gives the compiler more+ // info than the Java compiler has.+ int val = arr[start++];+ if (neg) val = 9999 - val;++ /***+ if (val < 10) {+ out[wpos++] = (char)(val + '0');+ } else if (val < 100) {+ out[wpos++] = (char)(val/10 + '0');+ out[wpos++] = (char)(val%10 + '0');+ } else if (val < 1000) {+ out[wpos++] = (char)(val/100 + '0');+ out[wpos++] = (char)((val/10)%10 + '0');+ out[wpos++] = (char)(val%10 + '0');+ } else {+ out[wpos++] = (char)(val/1000 + '0');+ out[wpos++] = (char)((val/100)%10 + '0');+ out[wpos++] = (char)((val/10)%10 + '0');+ out[wpos++] = (char)(val % 10 + '0');+ }+ ***/++ if (val < 10) {+ out[wpos++] = (char)(val + '0');+ } else if (val < 100) {+ int div = div10(val);+ int ones = val - mul10(div); // mod 10+ out[wpos++] = (char)(div + '0');+ out[wpos++] = (char)(ones + '0');+ } else if (val < 1000) {+ int div = div10(val);+ int ones = val - mul10(div); // mod 10+ val=div;+ div = div10(val);+ int tens = val - mul10(div); // mod 10+ out[wpos++] = (char)(div + '0');+ out[wpos++] = (char)(tens + '0');+ out[wpos++] = (char)(ones + '0');+ } else {+ int div = div10(val);+ int ones = val - mul10(div); // mod 10+ val=div;+ div = div10(val);+ int tens = val - mul10(div); // mod 10+ val=div;+ div = div10(val);+ int hundreds = val - mul10(div); // mod 10++ out[wpos++] = (char)(div + '0');+ out[wpos++] = (char)(hundreds + '0');+ out[wpos++] = (char)(tens + '0');+ out[wpos++] = (char)(ones + '0');+ }+++ while (start < end) {+ val = arr[start++];+ if (neg) val = 9999 - val;++ int div = div10(val);+ int ones = val - mul10(div); // mod 10+ val=div;+ div = div10(val);+ int tens = val - mul10(div); // mod 10+ val=div;+ div = div10(val);+ int hundreds = val - mul10(div); // mod 10++ /***+ int ones = val % 10;+ val /= 10;+ int tens = val!=0 ? val % 10 : 0;+ val /= 10;+ int hundreds = val!=0 ? val % 10 : 0;+ val /= 10;+ int thousands = val!=0 ? val % 10 : 0;+ ***/++ /***+ int thousands = val>=1000 ? val/1000 : 0;+ int hundreds = val>=100 ? (val/100)%10 : 0;+ int tens = val>=10 ? (val/10)%10 : 0;+ int ones = val % 10;+ ***/++ /***+ int thousands = val/1000;+ int hundreds = (val/100)%10;+ int tens = (val/10)%10;+ int ones = val % 10;+ ***/++ out[wpos++] = (char)(div + '0');+ out[wpos++] = (char)(hundreds + '0');+ out[wpos++] = (char)(tens + '0');+ out[wpos++] = (char)(ones + '0');+ }++ // OPTIONAL: if trailing zeros were truncated, then this is where+ // we would restore them (compare number of chars read vs exponent)++ return wpos-offset;+ }++++}diff --git a/src/java/org/apache/solr/util/DOMUtil.java b/src/java/org/apache/solr/util/DOMUtil.javanew file mode 100644index 00000000000..ec44b244747--- /dev/null+++ b/src/java/org/apache/solr/util/DOMUtil.java@@ -0,0 +1,152 @@+/**+ * 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.+ */++package org.apache.solr.util;++import org.w3c.dom.NamedNodeMap;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;++import java.util.Map;+import java.util.HashMap;+import java.util.List;+import java.util.ArrayList;++/**+ * @author yonik+ * @version $Id: DOMUtil.java,v 1.3 2005/12/01 16:50:11 yonik Exp $+ */+public class DOMUtil {++ public static Map<String,String> toMap(NamedNodeMap attrs) {+ return toMapExcept(attrs);+ }++ public static Map<String,String> toMapExcept(NamedNodeMap attrs, String... exclusions) {+ Map<String,String> args = new HashMap<String,String>();+ outer: for (int j=0; j<attrs.getLength(); j++) {+ Node attr = attrs.item(j);+ String attrName = attr.getNodeName();+ for (String ex : exclusions)+ if (ex.equals(attrName)) continue outer;+ String val = attr.getNodeValue();+ args.put(attrName, val);+ }+ return args;+ }++ public static Node getChild(Node node, String name) {+ if (!node.hasChildNodes()) return null;+ NodeList lst = node.getChildNodes();+ if (lst == null) return null;+ for (int i=0; i<lst.getLength(); i++) {+ Node child = lst.item(i);+ if (name.equals(child.getNodeName())) return child;+ }+ return null;+ }++ public static String getAttr(NamedNodeMap attrs, String name) {+ return getAttr(attrs,name,null);+ }++ public static String getAttr(Node nd, String name) {+ return getAttr(nd.getAttributes(), name);+ }++ public static String getAttr(NamedNodeMap attrs, String name, String missing_err) {+ Node attr = attrs==null? null : attrs.getNamedItem(name);+ if (attr==null) {+ if (missing_err==null) return null;+ throw new RuntimeException(missing_err + ": missing mandatory attribute '" + name + "'");+ }+ String val = attr.getNodeValue();+ return val;+ }++ public static String getAttr(Node node, String name, String missing_err) {+ return getAttr(node.getAttributes(), name, missing_err);+ }++ //////////////////////////////////////////////////////////+ // Routines to parse XML in the syntax of the Solr query+ // response schema.+ // Should these be moved to Config? Should all of these things?+ //////////////////////////////////////////////////////////+ public static NamedList childNodesToNamedList(Node nd) {+ return nodesToNamedList(nd.getChildNodes());+ }++ public static List childNodesToList(Node nd) {+ return nodesToList(nd.getChildNodes());+ }++ public static NamedList nodesToNamedList(NodeList nlst) {+ NamedList clst = new NamedList();+ for (int i=0; i<nlst.getLength(); i++) {+ addToNamedList(nlst.item(i), clst, null);+ }+ return clst;+ }++ public static List nodesToList(NodeList nlst) {+ List lst = new ArrayList();+ for (int i=0; i<nlst.getLength(); i++) {+ addToNamedList(nlst.item(i), null, lst);+ }+ return lst;+ }+++ public static void addToNamedList(Node nd, NamedList nlst, List arr) {+ // Nodes often include whitespace, etc... so just return if this+ // is not an Element.+ if (nd.getNodeType() != Node.ELEMENT_NODE) return;++ String type = nd.getNodeName();++ String name = null;+ if (nd.hasAttributes()) {+ NamedNodeMap attrs = nd.getAttributes();+ Node nameNd = attrs.getNamedItem("name");+ if (nameNd != null) name=nameNd.getNodeValue();+ }++ Object val=null;++ if ("str".equals(type)) {+ val = nd.getTextContent();+ } else if ("int".equals(type)) {+ val = Integer.valueOf(nd.getTextContent());+ } else if ("long".equals(type)) {+ val = Long.valueOf(nd.getTextContent());+ } else if ("float".equals(type)) {+ val = Float.valueOf(nd.getTextContent());+ } else if ("double".equals(type)) {+ val = Double.valueOf(nd.getTextContent());+ } else if ("bool".equals(type)) {+ val = Boolean.valueOf(nd.getTextContent());+ } else if ("lst".equals(type)) {+ val = childNodesToNamedList(nd);+ } else if ("arr".equals(type)) {+ val = childNodesToList(nd);+ }++ if (nlst != null) nlst.add(name,val);+ if (arr != null) arr.add(val);+ }++}diff --git a/src/java/org/apache/solr/util/NamedList.java b/src/java/org/apache/solr/util/NamedList.javanew file mode 100644index 00000000000..6e93f6bd3f1--- /dev/null+++ b/src/java/org/apache/solr/util/NamedList.java@@ -0,0 +1,143 @@+/**+ * 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.+ */++package org.apache.solr.util;++import java.util.*;+import java.io.Serializable;++/**+ * @author yonik+ * @version $Id$+ */+//+// A quick hack of a class to represent a list of name-value pairs.+// Unlike a map, order is maintained, and names may+// be repeated. Names and values may be null.+//+// In the future, it would be nice if this extended Map or Collection,+// had iterators, used java5 generics, had a faster lookup for+// large lists, etc...+// It could also have an interface, and multiple implementations.+// One might have indexed lookup, one might not.+//+public class NamedList implements Cloneable, Serializable {+ protected final List nvPairs;++ public NamedList() {+ nvPairs = new ArrayList();+ }++ public NamedList(List nameValuePairs) {+ nvPairs=nameValuePairs;+ }++ public int size() {+ return nvPairs.size() >> 1;+ }++ public String getName(int idx) {+ return (String)nvPairs.get(idx << 1);+ }++ public Object getVal(int idx) {+ return nvPairs.get((idx << 1) + 1);+ }++ public void add(String name, Object val) {+ nvPairs.add(name);+ nvPairs.add(val);+ }++ public void setName(int idx, String name) {+ nvPairs.set(idx<<1, name);+ }++ public void setVal(int idx, Object val) {+ nvPairs.set((idx<<1)+1, val);+ }++ public int indexOf(String name, int start) {+ int sz = size();+ for (int i=start; i<sz; i++) {+ String n = getName(i);+ if (name==null) {+ if (n==null) return i; // matched null+ } else if (name.equals(n)) {+ return i;+ }+ }+ return -1;+ }+++ // gets the value for the first specified name. returns null if not+ // found or if the value stored was null.+ public Object get(String name) {+ return get(name,0);+ }++ // gets the value for the first specified name starting start.+ // returns null if not found or if the value stored was null.+ public Object get(String name, int start) {+ int sz = size();+ for (int i=start; i<sz; i++) {+ String n = getName(i);+ if (name==null) {+ if (n==null) return getVal(i);+ } else if (name.equals(n)) {+ return getVal(i);+ }+ }+ return null;+ }++ public String toString() {+ StringBuffer sb = new StringBuffer();+ sb.append('{');+ int sz = size();+ for (int i=0; i<sz; i++) {+ if (i != 0) sb.append(',');+ sb.append(getName(i));+ sb.append('=');+ sb.append(getVal(i));+ }+ sb.append('}');++ return sb.toString();+ }+++ public boolean addAll(Map args) {+ Set eset = args.entrySet();+ Iterator iter = eset.iterator();+ while (iter.hasNext()) {+ Map.Entry entry = (Map.Entry)iter.next();+ add(entry.getKey().toString(), entry.getValue());+ }+ return false;+ }++ /**+ * Makes a *shallow copy* of the named list.+ */+ public NamedList clone() {+ ArrayList newList = new ArrayList(nvPairs.size());+ newList.addAll(nvPairs);+ return new NamedList(newList);+ }++}diff --git a/src/java/org/apache/solr/util/NumberUtils.java b/src/java/org/apache/solr/util/NumberUtils.javanew file mode 100644index 00000000000..78f313b1f19--- /dev/null+++ b/src/java/org/apache/solr/util/NumberUtils.java@@ -0,0 +1,159 @@+/**+ * 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.+ */++package org.apache.solr.util;++/**+ * @author yonik+ * @version $Id$+ */+public class NumberUtils {++++++ public static String int2sortableStr(int val) {+ char[] arr = new char[3];+ int2sortableStr(val,arr,0);+ return new String(arr,0,3);+ }++ public static String int2sortableStr(String val) {+ return int2sortableStr(Integer.parseInt(val));+ }++ public static String SortableStr2int(String val) {+ int ival = SortableStr2int(val,0,3);+ return Integer.toString(ival);+ }+++ public static String long2sortableStr(long val) {+ char[] arr = new char[5];+ long2sortableStr(val,arr,0);+ return new String(arr,0,5);+ }++ public static String long2sortableStr(String val) {+ return long2sortableStr(Long.parseLong(val));+ }++ public static String SortableStr2long(String val) {+ long ival = SortableStr2long(val,0,5);+ return Long.toString(ival);+ }++ //+ // IEEE floating point format is defined so that it sorts correctly+ // when interpreted as a signed integer (or signed long in the case+ // of a double) for positive values. For negative values, all the bits except+ // the sign bit must be inverted.+ // This correctly handles all possible float values including -Infinity and +Infinity.+ // Note that in float-space, NaN<x is false, NaN>x is false, NaN==x is false, NaN!=x is true+ // for all x (including NaN itself). Internal to Solr, NaN==NaN is true and NaN+ // sorts higher than Infinity, so a range query of [-Infinity TO +Infinity] will+ // exclude NaN values, but a query of "NaN" will find all NaN values.+ // Also, -0==0 in float-space but -0<0 after this transformation.+ //+ public static String float2sortableStr(float val) {+ int f = Float.floatToRawIntBits(val);+ if (f<0) f ^= 0x7fffffff;+ return int2sortableStr(f);+ }++ public static String float2sortableStr(String val) {+ return float2sortableStr(Float.parseFloat(val));+ }++ public static float SortableStr2float(String val) {+ int f = SortableStr2int(val,0,3);+ if (f<0) f ^= 0x7fffffff;+ return Float.intBitsToFloat(f);+ }++ public static String SortableStr2floatStr(String val) {+ return Float.toString(SortableStr2float(val));+ }+++ public static String double2sortableStr(double val) {+ long f = Double.doubleToRawLongBits(val);+ if (f<0) f ^= 0x7fffffffffffffffL;+ return long2sortableStr(f);+ }++ public static String double2sortableStr(String val) {+ return double2sortableStr(Double.parseDouble(val));+ }++ public static double SortableStr2double(String val) {+ long f = SortableStr2long(val,0,6);+ if (f<0) f ^= 0x7fffffffffffffffL;+ return Double.longBitsToDouble(f);+ }++ public static String SortableStr2doubleStr(String val) {+ return Double.toString(SortableStr2double(val));+ }++++ // uses binary representation of an int to build a string of+ // chars that will sort correctly. Only char ranges+ // less than 0xd800 will be used to avoid UCS-16 surrogates.+ public static int int2sortableStr(int val, char[] out, int offset) {+ val += Integer.MIN_VALUE;+ out[offset++] = (char)(val >>> 24);+ out[offset++] = (char)((val >>> 12) & 0x0fff);+ out[offset++] = (char)(val & 0x0fff);+ return 3;+ }++ public static int SortableStr2int(String sval, int offset, int len) {+ int val = sval.charAt(offset++) << 24;+ val |= sval.charAt(offset++) << 12;+ val |= sval.charAt(offset++);+ val -= Integer.MIN_VALUE;+ return val;+ }++ // uses binary representation of an int to build a string of+ // chars that will sort correctly. Only char ranges+ // less than 0xd800 will be used to avoid UCS-16 surrogates.+ // we can use the lowest 15 bits of a char, (or a mask of 0x7fff)+ public static int long2sortableStr(long val, char[] out, int offset) {+ val += Long.MIN_VALUE;+ out[offset++] = (char)(val >>>60);+ out[offset++] = (char)(val >>>45 & 0x7fff);+ out[offset++] = (char)(val >>>30 & 0x7fff);+ out[offset++] = (char)(val >>>15 & 0x7fff);+ out[offset] = (char)(val & 0x7fff);+ return 5;+ }++ public static long SortableStr2long(String sval, int offset, int len) {+ long val = (long)(sval.charAt(offset++)) << 60;+ val |= ((long)sval.charAt(offset++)) << 45;+ val |= ((long)sval.charAt(offset++)) << 30;+ val |= sval.charAt(offset++) << 15;+ val |= sval.charAt(offset);+ val -= Long.MIN_VALUE;+ return val;+ }+++}diff --git a/src/java/org/apache/solr/util/RefCounted.java b/src/java/org/apache/solr/util/RefCounted.javanew file mode 100644index 00000000000..8831730389f--- /dev/null+++ b/src/java/org/apache/solr/util/RefCounted.java@@ -0,0 +1,34 @@+/**+ * 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.+ */++package org.apache.solr.util;++import java.util.concurrent.atomic.AtomicInteger;++/**+ * @author yonik+ * @version $Id: RefCounted.java,v 1.2 2005/09/07 20:37:57 yonik Exp $+ */++public abstract class RefCounted<Type> {+ protected final Type resource;+ protected final AtomicInteger refcount= new AtomicInteger();+ public RefCounted(Type resource) { this.resource = resource; }+ public final RefCounted<Type> incref() { refcount.incrementAndGet(); return this; }+ public final Type get() { return resource; }+ public void decref() { if (refcount.decrementAndGet()==0) close(); }+ protected abstract void close();+}diff --git a/src/java/org/apache/solr/util/StrUtils.java b/src/java/org/apache/solr/util/StrUtils.javanew file mode 100644index 00000000000..637477d68f9--- /dev/null+++ b/src/java/org/apache/solr/util/StrUtils.java@@ -0,0 +1,202 @@+/**+ * 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.+ */++package org.apache.solr.util;++import java.util.List;+import java.util.ArrayList;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id$+ */+public class StrUtils {++ /**+ * Split a string based on a separator, but don't split if it's inside+ * a string. Assume '\' escapes the next char both inside and+ * outside strings.+ */+ public static List<String> splitSmart(String s, char separator) {+ ArrayList<String> lst = new ArrayList<String>(4);+ int pos=0, start=0, end=s.length();+ char inString=0;+ while (pos < end) {+ char ch = s.charAt(pos++);+ if (ch=='\\') { // skip escaped chars+ pos++;+ } else if (inString != 0 && ch==inString) {+ inString=0;+ } else if (ch=='\'' || ch=='"') {+ inString=ch;+ } else if (ch==separator && inString==0) {+ lst.add(s.substring(start,pos-1));+ start=pos;+ }+ }+ if (start < end) {+ lst.add(s.substring(start,end));+ }++ /***+ if (SolrCore.log.isLoggable(Level.FINEST)) {+ SolrCore.log.finest("splitCommand=" + lst);+ }+ ***/++ return lst;+ }++ /** Splits a backslash escaped string on the separator.+ * <p>+ * Current backslash escaping supported:+ * <br> \n \t \r \b \f are escaped the same as a Java String+ * <br> Other characters following a backslash are produced verbatim (\c => c)+ *+ * @param s the string to split+ * @param separator the separator to split on+ * @param decode decode backslash escaping+ */+ public static List<String> splitSmart(String s, String separator, boolean decode) {+ ArrayList<String> lst = new ArrayList<String>(2);+ StringBuilder sb = new StringBuilder();+ int pos=0, end=s.length();+ while (pos < end) {+ if (s.startsWith(separator,pos)) {+ if (sb.length() > 0) {+ lst.add(sb.toString());+ sb=new StringBuilder();+ }+ pos+=separator.length();+ continue;+ }++ char ch = s.charAt(pos++);+ if (ch=='\\') {+ if (!decode) sb.append(ch);+ if (pos>=end) break; // ERROR, or let it go?+ ch = s.charAt(pos++);+ if (decode) {+ switch(ch) {+ case 'n' : ch='\n';+ case 't' : ch='\t';+ case 'r' : ch='\r';+ case 'b' : ch='\b';+ case 'f' : ch='\f';+ }+ }+ }++ sb.append(ch);+ }++ if (sb.length() > 0) {+ lst.add(sb.toString());+ }++ return lst;+ }++++ public static List<String> splitWS(String s, boolean decode) {+ ArrayList<String> lst = new ArrayList<String>(2);+ StringBuilder sb = new StringBuilder();+ int pos=0, end=s.length();+ while (pos < end) {+ char ch = s.charAt(pos++);+ if (Character.isWhitespace(ch)) {+ if (sb.length() > 0) {+ lst.add(sb.toString());+ sb=new StringBuilder();+ }+ continue;+ }++ if (ch=='\\') {+ if (!decode) sb.append(ch);+ if (pos>=end) break; // ERROR, or let it go?+ ch = s.charAt(pos++);+ if (decode) {+ switch(ch) {+ case 'n' : ch='\n';+ case 't' : ch='\t';+ case 'r' : ch='\r';+ case 'b' : ch='\b';+ case 'f' : ch='\f';+ }+ }+ }++ sb.append(ch);+ }++ if (sb.length() > 0) {+ lst.add(sb.toString());+ }++ return lst;+ }++ public static List<String> toLower(List<String> strings) {+ ArrayList<String> ret = new ArrayList<String>(strings.size());+ for (String str : strings) {+ ret.add(str.toLowerCase());+ }+ return ret;+ }++++ /** Return if a string starts with '1', 't', or 'T'+ * and return false otherwise.+ */+ public static boolean parseBoolean(String s) {+ char ch = s.length()>0 ? s.charAt(0) : 0;+ return (ch=='1' || ch=='t' || ch=='T');+ }++ /**+ * URLEncodes a value, replacing only enough chars so that+ * the URL may be unambiguously pasted back into a browser.+ * <p>+ * Characters with a numeric value less than 32 are encoded.+ * &,=,%,+,space are encoded.+ * <p>+ */+ public static void partialURLEncodeVal(Appendable dest, String val) throws IOException {+ for (int i=0; i<val.length(); i++) {+ char ch = val.charAt(i);+ if (ch < 32) {+ dest.append('%');+ // Hmmm, if we used StringBuilder rather than Appendable, it+ // could add an integer more efficiently.+ dest.append(Integer.toString(ch));+ } else {+ switch (ch) {+ case ' ': dest.append('+'); break;+ case '&': dest.append("%26"); break;+ case '%': dest.append("%25"); break;+ case '=': dest.append("%3D"); break;+ case '+': dest.append("%2B"); break;+ default : dest.append(ch); break;+ }+ }+ }+ }++}diff --git a/src/java/org/apache/solr/util/XML.java b/src/java/org/apache/solr/util/XML.javanew file mode 100644index 00000000000..daf9d48a77b--- /dev/null+++ b/src/java/org/apache/solr/util/XML.java@@ -0,0 +1,144 @@+/**+ * 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.+ */++package org.apache.solr.util;++import java.io.Writer;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id$+ */+public class XML {++ //+ // copied from some of my personal code... -YCS+ // table created from python script.+ // only have to escape quotes in attribute values, and don't really have to escape '>'+ // many chars less than 0x20 are *not* valid XML, even when escaped!+ // for example, <foo>�<foo> is invalid XML.+ private static final String[] chardata_escapes=+ {"#0;","#1;","#2;","#3;","#4;","#5;","#6;","#7;","#8;",null,null,"#11;","#12;",null,"#14;","#15;","#16;","#17;","#18;","#19;","#20;","#21;","#22;","#23;","#24;","#25;","#26;","#27;","#28;","#29;","#30;","#31;",null,null,null,null,null,null,"&",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"<"};+++ /*****************************************+ #Simple python script used to generate the escape table above. -YCS+ #+ #use individual char arrays or one big char array for better efficiency+ # or byte array?+ #other={'&':'amp', '<':'lt', '>':'gt', "'":'apos', '"':'quot'}+ #+ other={'&':'amp', '<':'lt'}++ maxi=ord(max(other.keys()))+1+ table=[None] * maxi+ #NOTE: invalid XML chars are "escaped" as #nn; *not* &#nn; because+ #a real XML escape would cause many strict XML parsers to choke.+ for i in range(0x20): table[i]='#%d;' % i+ for i in '\n\r\t ': table[ord(i)]=None+ for k,v in other.items():+ table[ord(k)]='&%s;' % v++ result=""+ for i in range(maxi):+ val=table[i]+ if not val: val='null'+ else: val='"%s"' % val+ result += val + ','++ print result+ ****************************************/+++/*********+ *+ * @param str+ * @param out+ * @throws IOException+ */+ public static void escapeCharData(String str, Writer out) throws IOException {+ int start=0;+ // "n" was used for counting the chars added to out...+ // removed cause it wasn't really useful so far.+ // int n=0;++ for (int i=start; i<str.length(); i++) {+ char ch = str.charAt(i);+ // since I already received the char, what if I put it into+ // a char array and wrote that to the stream instead of the+ // string? (would cause extra GC though)+ String subst=null;+ if (ch<chardata_escapes.length) {+ subst=chardata_escapes[ch];+ }+ if (subst != null) {+ if (start<i) {+ // out.write(str.substring(start,i));+ out.write(str, start, i-start);+ // n+=i-start;+ }+ out.write(subst);+ // n+=subst.length();+ start=i+1;+ }+ }+ if (start==0) {+ out.write(str);+ // n += str.length();+ } else if (start<str.length()) {+ // out.write(str.substring(start));+ out.write(str, start, str.length()-start);+ // n += str.length()-start;+ }+ // return n;+ }++ public final static void writeXML(Writer out, String tag, String val) throws IOException {+ out.write('<');+ out.write(tag);+ if (val == null) {+ out.write("/>");+ } else {+ out.write('>');+ escapeCharData(val,out);+ out.write("</");+ out.write(tag);+ out.write('>');+ }+ }++ public final static void writeXML(Writer out, String tag, String val, Object... attrs) throws IOException {+ out.write('<');+ out.write(tag);+ for (int i=0; i<attrs.length; i++) {+ out.write(' ');+ out.write(attrs[i++].toString());+ out.write("=\"");+ out.write(attrs[i].toString());+ out.write("\"");+ }+ if (val == null) {+ out.write("/>");+ } else {+ out.write('>');+ escapeCharData(val,out);+ out.write("</");+ out.write(tag);+ out.write('>');+ }+ }+}diff --git a/src/java/org/apache/solr/util/test/TestNumberUtils.java b/src/java/org/apache/solr/util/test/TestNumberUtils.javanew file mode 100644index 00000000000..2c6ed743e4d--- /dev/null+++ b/src/java/org/apache/solr/util/test/TestNumberUtils.java@@ -0,0 +1,491 @@+/**+ * 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.+ */++package org.apache.solr.util.test;++import org.apache.solr.util.NumberUtils;+import org.apache.solr.util.BCDUtils;++import java.util.Random;++/**+ * @author yonik+ */++public class TestNumberUtils {++ private static String arrstr(char[] arr, int start, int end) {+ String str="[";+ for (int i=start; i<end; i++) str += arr[i]+"("+(int)arr[i]+"),";+ return str+"]";+ }++ static Random rng = new Random();++ static int[] special = {0,10,100,1000,10000,Integer.MAX_VALUE, Integer.MIN_VALUE};+ static int getSpecial() {+ int i = rng.nextInt();+ int j = rng.nextInt();+ if ((i & 0x10) != 0) return j;+ return special[(j&0x7fffffff) % special.length]* ((i & 0x20)==0?1:-1) + ((i&0x03)-1);+ }++ static long[] lspecial = {0,10,100,1000,10000,2,4,8,256,16384,32768,65536,+ Integer.MAX_VALUE, Integer.MIN_VALUE,+ Long.MAX_VALUE, Long.MIN_VALUE};+ static long getLongSpecial() {+ int i = rng.nextInt();+ long j = rng.nextLong();+ if ((i & 0x10) != 0) return j;+ return lspecial[((int)j&0x7fffffff) % special.length]* ((i & 0x20)==0?1:-1) + ((i&0x03)-1);+ }++ static float[] fspecial = {0,1,2,4,8,256,16384,32768,65536,.1f,.25f+ ,Float.NEGATIVE_INFINITY,Float.POSITIVE_INFINITY,Float.MIN_VALUE, Float.MAX_VALUE};+ static float getFloatSpecial() {+ int i = rng.nextInt();+ int j = rng.nextInt();+ float f = Float.intBitsToFloat(j);+ if (f!=f) f=0; // get rid of NaN for comparison purposes+ if ((i & 0x10) != 0) return f;+ return fspecial[(j&0x7fffffff) % fspecial.length]* ((i & 0x20)==0?1:-1) + ((i&0x03)-1);+ }++ static double[] dspecial = {0,1,2,4,8,256,16384,32768,65536,.1,.25+ ,Float.NEGATIVE_INFINITY,Float.POSITIVE_INFINITY,Float.MIN_VALUE, Float.MAX_VALUE+ ,Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY,Double.MIN_VALUE, Double.MAX_VALUE+ };+ static double getDoubleSpecial() {+ int i = rng.nextInt();+ long j = rng.nextLong();+ double f = Double.longBitsToDouble(j);+ if (f!=f) f=0; // get rid of NaN for comparison purposes+ if ((i & 0x10) != 0) return f;+ return dspecial[((int)j&0x7fffffff) % dspecial.length]* ((i & 0x20)==0?1:-1) + ((i&0x03)-1);+ }+++ public static void test(Comparable n1, Comparable n2, Converter conv) {+ String s1=n1.toString();+ String s2=n2.toString();+ String v1 = conv.toInternal(s1);+ String v2 = conv.toInternal(s2);+ String out1=conv.toExternal(v1);+ String out2=conv.toExternal(v2);++ int c1 = n1.compareTo(n2);+ int c2 = v1.compareTo(v2);+ if (c1==0 && !(c2==0) || c1 < 0 && !(c2<0) || c1>0 && !(c2>0)+ || !out1.equals(s1) || !out2.equals(s2))+ {+ System.out.println("Comparison error:"+s1+","+s2);+ System.out.print("v1=");+ for (int ii=0; ii<v1.length(); ii++) {+ System.out.print(" " + (int)v1.charAt(ii));+ }+ System.out.print("\nv2=");+ for (int ii=0; ii<v2.length(); ii++) {+ System.out.print(" " + (int)v2.charAt(ii));+ }+ System.out.println("\nout1='"+out1+"', out2='" + out2 + "'");+ }+ }+++ public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {+ int iter=1000000;+ int arrsz=100000;+ int ret=0;+ int num=0;++ String test="b100";+ String clazz="NoClass";++ for (int argnum=0; argnum<args.length; argnum++) {+ String arg = args[argnum];+ if ("-t".equals(arg)) { test=args[++argnum]; }+ if ("-i".equals(arg)) { iter=Integer.parseInt(args[++argnum]); }+ if ("-a".equals(arg)) { arrsz=Integer.parseInt(args[++argnum]); }+ if ("-c".equals(arg)) { clazz=args[++argnum]; }+ if ("-r".equals(arg)) { rng.setSeed(Long.parseLong(args[++argnum])); };+ if ("-n".equals(arg)) { num = Integer.parseInt(args[++argnum]); };++ }++ // Converter conv = (Converter)(Class.forName(clazz).newInstance());+ Class cls=null;+ try {+ cls = Class.forName(clazz);+ } catch (Exception e) {+ cls = Class.forName("solr.util.test." + clazz);+ }+ Converter conv = (Converter)cls.newInstance();++ long startTime = System.currentTimeMillis();++ if ("ispecial".equals(test)) {+ for (int i=0; i<iter; i++) {+ Integer i1 = getSpecial();+ Integer i2 = getSpecial();+ test(i1,i2,conv);+ }+ }+ else if ("lspecial".equals(test)) {+ for (int i=0; i<iter; i++) {+ Long f1 = getLongSpecial();+ Long f2 = getLongSpecial();+ test(f1,f2,conv);+ }+ }+ else if ("fspecial".equals(test)) {+ for (int i=0; i<iter; i++) {+ Float f1 = getFloatSpecial();+ Float f2 = getFloatSpecial();+ test(f1,f2,conv);+ }+ }+ else if ("dspecial".equals(test)) {+ for (int i=0; i<iter; i++) {+ Double f1 = getDoubleSpecial();+ Double f2 = getDoubleSpecial();+ test(f1,f2,conv);+ }+ }+ else if ("10kout".equals(test)) {+ String n = Integer.toString(num);+ char[] arr = new char[n.length()];+ char[] arr2 = new char[n.length()+1];+ n.getChars(0,n.length(),arr,0);+ for (int i=0; i<iter; i++) {+ ret += BCDUtils.base10toBase100SortableInt(arr,0,arr.length,arr2,arr2.length);+ }++ } else if ("internal".equals(test) || "external".equals(test)) {+ int min=-1000000; int max=1000000;+ String[] arr = new String[arrsz];+ String[] internal = new String[arrsz];++ if ("external".equals(test)) {+ for (int i=0; i<arrsz; i++) {+ int val = rng.nextInt();+ // todo - move to between min and max...+ arr[i] = Integer.toString(rng.nextInt());+ internal[i] = conv.toInternal(arr[i]);+ }+ for (int i=0; i<iter; i++) {+ int slot=i%arrsz;+ arr[slot] = conv.toExternal(internal[slot]);+ ret += arr[slot].length();+ }+ } else {+ for (int i=0; i<arrsz; i++) {+ int val = rng.nextInt();+ // todo - move to between min and max...+ arr[i] = Integer.toString(rng.nextInt());+ }+ for (int i=0; i<iter; i++) {+ int slot=i%arrsz;+ internal[slot] = conv.toInternal(arr[slot]);+ ret += internal[slot].length();+ }+ }+ } else if ("itest".equals(test) || "ltest".equals(test) || "ftest".equals(test)) {+ long internalLen=0;+ long externalLen=0;+ for (int i=0; i<iter; i++) {+ Comparable n1=null,n2=null;++ if ("itest".equals(test)) {+ Integer i1+ = rng.nextInt();+ Integer i2+ = rng.nextInt();++ // concentrate on small numbers for a while+ // to try and hit boundary cases 0,1,-1,100,-100,etc+ if (i < 10000) {+ i1 = (i1 % 250)-125;+ i2 = (i2 % 250)-125;+ } else if (i < 500000) {+ i1 = (i1 % 25000)-12500;+ i2 = (i2 % 25000)-12500;+ }++ n1=i1;+ n2=i2;+ } else if ("ltest".equals(test)) {+ Long i1 = rng.nextLong();+ Long i2 = rng.nextLong();++ // concentrate on small numbers for a while+ // to try and hit boundary cases 0,1,-1,100,-100,etc+ if (i < 10000) {+ i1 = (long)(i1 % 250)-125;+ i2 = (long)(i2 % 250)-125;+ } else if (i < 500000) {+ i1 = (long)(i1 % 25000)-12500;+ i2 = (long)(i2 % 25000)-12500;+ }++ n1=i1;+ n2=i2;+ } else if ("ftest".equals(test)) {+ Float i1;+ Float i2;+ if (i < 10000) {+ i1 = (float)(rng.nextInt() % 250)-125;+ i2 = (float)(rng.nextInt() % 250)-125;+ } else if (i < 300000) {+ i1 = (float)(rng.nextInt() % 2500)-1250;+ i2 = (float)(rng.nextInt() % 2500)-1250;+ } else if (i < 500000) {+ i1 = rng.nextFloat() / rng.nextFloat();+ i2 = rng.nextFloat() / rng.nextFloat();+ } else {+ i1 = Float.intBitsToFloat(rng.nextInt());+ i2 = Float.intBitsToFloat(rng.nextInt());+ }+ n1=i1;+ n2=i2;+ }+ String s1=n1.toString();+ String s2=n2.toString();+ String v1 = conv.toInternal(s1);+ String v2 = conv.toInternal(s2);+ String out1=conv.toExternal(v1);+ String out2=conv.toExternal(v2);++ externalLen += s1.length();+ internalLen += v1.length();++ int c1 = n1.compareTo(n2);+ int c2 = v1.compareTo(v2);+ if (c1==0 && !(c2==0) || c1 < 0 && !(c2<0) || c1>0 && !(c2>0)+ || !out1.equals(s1) || !out2.equals(s2))+ {+ System.out.println("Comparison error:"+s1+","+s2);+ System.out.print("v1=");+ for (int ii=0; ii<v1.length(); ii++) {+ System.out.print(" " + (int)v1.charAt(ii));+ }+ System.out.print("\nv2=");+ for (int ii=0; ii<v2.length(); ii++) {+ System.out.print(" " + (int)v2.charAt(ii));+ }+ System.out.println("\nout1='"+out1+"', out2='" + out2 + "'");++ }+ }+ }+++ /******************+ int sz=20;+ char[] arr1 = new char[sz];+ char[] arr2 = new char[sz];+ char[] arr3 = new char[sz];+ if ("noconv".equals(test)) {+ for (int i=0; i<iter; i++) {+ int val = rng.nextInt();+ String istr = Integer.toString(val);+ int n = istr.length();+ Integer.toString(val).getChars(0, n, arr1, 0);+ String nStr = new String(arr1,0,n);+ if (!nStr.equals(istr)) {+ System.out.println("ERROR! input="+istr+" output="+nStr);+ System.out.println(arrstr(arr1,0,n));+ }+ }+ } else if ("b100".equals(test)) {+ for (int i=0; i<iter; i++) {+ int val = rng.nextInt();+ String istr = Integer.toString(val);+ int n = istr.length();+ Integer.toString(val).getChars(0, n, arr1, 0);++ int b100_start = NumberUtils.base10toBase100(arr1,0,n,arr2,sz);+ int b10_len = NumberUtils.base100toBase10(arr2,b100_start,sz,arr3,0);++ String nStr = new String(arr3,0,b10_len);+ if (!nStr.equals(istr)) {+ System.out.println("ERROR! input="+istr+" output="+nStr);+ System.out.println(arrstr(arr1,0,n));+ System.out.println(arrstr(arr2,b100_start,sz));+ System.out.println(arrstr(arr3,0,b10_len));+ }++ }+ } else if ("b100sParse".equals(test)) {+ int min=-1000000; int max=1000000;+ String[] arr = new String[arrsz];+ String[] internal = new String[arrsz];+ for (int i=0; i<arrsz; i++) {+ int val = rng.nextInt();+ // todo - move to between min and max...+ arr[i] = Integer.toString(rng.nextInt());+ }+ for (int i=0; i<iter; i++) {+ int slot=i%arrsz;+ internal[slot] = NumberUtils.base10toBase100SortableInt(arr[i%arrsz]);+ ret += internal[slot].length();+ }+ } else if ("intParse".equals(test)) {+ int min=-1000000; int max=1000000;+ String[] arr = new String[arrsz];+ String[] internal = new String[arrsz];+ for (int i=0; i<arrsz; i++) {+ int val = rng.nextInt();+ // todo - move to between min and max...+ arr[i] = Integer.toString(rng.nextInt());+ }+ for (int i=0; i<iter; i++) {+ int slot=i%arrsz;+ int val = Integer.parseInt(arr[i%arrsz]);+ String sval = Integer.toString(val);+ internal[slot] = sval;+ ret += internal[slot].length();+ }+ } else if ("b100s".equals(test)) {+ for (int i=0; i<iter; i++) {+ Integer i1 = rng.nextInt();+ Integer i2 = rng.nextInt();++ // concentrate on small numbers for a while+ // to try and hit boundary cases 0,1,-1,100,-100,etc+ if (iter < 10000) {+ i1 = (i1 % 250)-125;+ i2 = (i2 % 250)-125;+ } else if (iter < 500000) {+ i1 = (i1 % 25000)-12500;+ i2 = (i2 % 25000)-12500;+ }++ String s1=Integer.toString(i1);+ String s2=Integer.toString(i2);+ String v1 = NumberUtils.base10toBase10kSortableInt(s1);+ String v2 = NumberUtils.base10toBase10kSortableInt(s2);+ String out1=NumberUtils.base10kSortableIntToBase10(v1);+ String out2=NumberUtils.base10kSortableIntToBase10(v2);++ int c1 = i1.compareTo(i2);+ int c2 = v1.compareTo(v2);+ if (c1==0 && c2 !=0 || c1 < 0 && c2 >= 0 || c1 > 0 && c2 <=0+ || !out1.equals(s1) || !out2.equals(s2))+ {+ System.out.println("Comparison error:"+s1+","+s2);+ System.out.print("v1=");+ for (int ii=0; ii<v1.length(); ii++) {+ System.out.print(" " + (int)v1.charAt(ii));+ }+ System.out.print("\nv2=");+ for (int ii=0; ii<v2.length(); ii++) {+ System.out.print(" " + (int)v2.charAt(ii));+ }+ System.out.println("\nout1='"+out1+"', out2='" + out2 + "'");++ }++++++ }+ }+ ****/++ long endTime = System.currentTimeMillis();+ System.out.println("time="+(endTime-startTime));+ System.out.println("ret="+ret);+ }+}+++interface Converter {+ String toInternal(String val);+ String toExternal(String val);+}++class Int2Int implements Converter {+ public String toInternal(String val) {+ return Integer.toString(Integer.parseInt(val));+ }+ public String toExternal(String val) {+ return Integer.toString(Integer.parseInt(val));+ }+}++class SortInt implements Converter {+ public String toInternal(String val) {+ return NumberUtils.int2sortableStr(val);+ }+ public String toExternal(String val) {+ return NumberUtils.SortableStr2int(val);+ }+}++class SortLong implements Converter {+ public String toInternal(String val) {+ return NumberUtils.long2sortableStr(val);+ }+ public String toExternal(String val) {+ return NumberUtils.SortableStr2long(val);+ }+}++class Float2Float implements Converter {+ public String toInternal(String val) {+ return Float.toString(Float.parseFloat(val));+ }+ public String toExternal(String val) {+ return Float.toString(Float.parseFloat(val));+ }+}++class SortFloat implements Converter {+ public String toInternal(String val) {+ return NumberUtils.float2sortableStr(val);+ }+ public String toExternal(String val) {+ return NumberUtils.SortableStr2floatStr(val);+ }+}++class SortDouble implements Converter {+ public String toInternal(String val) {+ return NumberUtils.double2sortableStr(val);+ }+ public String toExternal(String val) {+ return NumberUtils.SortableStr2doubleStr(val);+ }+}++class Base100S implements Converter {+ public String toInternal(String val) {+ return BCDUtils.base10toBase100SortableInt(val);+ }+ public String toExternal(String val) {+ return BCDUtils.base100SortableIntToBase10(val);+ }+}++class Base10kS implements Converter {+ public String toInternal(String val) {+ return BCDUtils.base10toBase10kSortableInt(val);+ }+ public String toExternal(String val) {+ return BCDUtils.base10kSortableIntToBase10(val);+ }+}diff --git a/src/lucene_extras/org/apache/lucene/analysis/SynonymFilter.java b/src/lucene_extras/org/apache/lucene/analysis/SynonymFilter.javanew file mode 100644index 00000000000..b9e3178254f--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/analysis/SynonymFilter.java@@ -0,0 +1,204 @@+/**+ * 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.+ */++package org.apache.lucene.analysis;++import java.io.IOException;+import java.util.*;++/** SynonymFilter handles multi-token synonyms with variable position increment offsets.+ * <p>+ * The matched tokens from the input stream may be optionally passed through (includeOrig=true)+ * or discarded. If the original tokens are included, the position increments may be modified+ * to retain absolute positions after merging with the synonym tokenstream.+ * <p>+ * Generated synonyms will start at the same position as the first matched source token.+ *+ * @author yonik+ * @version $Id: SynonymFilter.java,v 1.3 2005/12/13 05:14:52 yonik Exp $+ */+public class SynonymFilter extends TokenFilter {++ private final SynonymMap map; // Map<String, SynonymMap>+ private final boolean ignoreCase;+ private Iterator replacement; // iterator over generated tokens++ public SynonymFilter(TokenStream in, SynonymMap map, boolean ignoreCase) {+ super(in);+ this.map = map;+ this.ignoreCase = ignoreCase;+ }+++ /*+ * Need to worry about multiple scenarios:+ * - need to go for the longest match+ * a b => foo #shouldn't match if "a b" is followed by "c d"+ * a b c d => bar+ * - need to backtrack - retry matches for tokens already read+ * a b c d => foo+ * b c => bar+ * If the input stream is "a b c x", one will consume "a b c d"+ * trying to match the first rule... all but "a" should be+ * pushed back so a match may be made on "b c".+ * - don't try and match generated tokens (thus need separate queue)+ * matching is not recursive.+ * - handle optional generation of original tokens in all these cases,+ * merging token streams to preserve token positions.+ * - preserve original positionIncrement of first matched token+ */+++ public Token next() throws IOException {+ while (true) {+ // if there are any generated tokens, return them... don't try any+ // matches against them, as we specifically don't want recursion.+ if (replacement!=null && replacement.hasNext()) {+ return (Token)replacement.next();+ }++ // common case fast-path of first token not matching anything+ Token firstTok = nextTok();+ if (firstTok ==null) return null;+ String str = ignoreCase ? firstTok.termText.toLowerCase() : firstTok.termText;+ Object o = map.submap!=null ? map.submap.get(str) : null;+ if (o == null) return firstTok;++ // OK, we matched a token, so find the longest match.++ // since matched is only used for matches >= 2, defer creation until now+ if (matched==null) matched=new LinkedList();++ SynonymMap result = match((SynonymMap)o);++ if (result==null) {+ // no match, simply return the first token read.+ return firstTok;+ }++ // reuse, or create new one each time?+ ArrayList generated = new ArrayList(result.synonyms.length + matched.size() + 1);++ //+ // there was a match... let's generate the new tokens, merging+ // in the matched tokens (position increments need adjusting)+ //+ Token lastTok = matched.isEmpty() ? firstTok : (Token)matched.getLast();+ boolean includeOrig = result.includeOrig();++ Token origTok = includeOrig ? firstTok : null;+ int origPos = firstTok.getPositionIncrement(); // position of origTok in the original stream+ int repPos=0; // curr position in replacement token stream+ int pos=0; // current position in merged token stream++ for (int i=0; i<result.synonyms.length; i++) {+ Token repTok = result.synonyms[i];+ Token newTok = new Token(repTok.termText, firstTok.startOffset, lastTok.endOffset, firstTok.type);+ repPos += repTok.getPositionIncrement();+ if (i==0) repPos=origPos; // make position of first token equal to original++ // if necessary, insert original tokens and adjust position increment+ while (origTok != null && origPos <= repPos) {+ origTok.setPositionIncrement(origPos-pos);+ generated.add(origTok);+ pos += origTok.getPositionIncrement();+ origTok = matched.isEmpty() ? null : (Token)matched.removeFirst();+ if (origTok != null) origPos += origTok.getPositionIncrement();+ }++ newTok.setPositionIncrement(repPos - pos);+ generated.add(newTok);+ pos += newTok.getPositionIncrement();+ }++ // finish up any leftover original tokens+ while (origTok!=null) {+ origTok.setPositionIncrement(origPos-pos);+ generated.add(origTok);+ pos += origTok.getPositionIncrement();+ origTok = matched.isEmpty() ? null : (Token)matched.removeFirst();+ if (origTok != null) origPos += origTok.getPositionIncrement();+ }++ // what if we replaced a longer sequence with a shorter one?+ // a/0 b/5 => foo/0+ // should I re-create the gap on the next buffered token?++ replacement = generated.iterator();+ // Now return to the top of the loop to read and return the first+ // generated token.. The reason this is done is that we may have generated+ // nothing at all, and may need to continue with more matching logic.+ }+ }+++ //+ // Defer creation of the buffer until the first time it is used to+ // optimize short fields with no matches.+ //+ private LinkedList buffer;+ private LinkedList matched;++ // TODO: use ArrayList for better performance?++ private Token nextTok() throws IOException {+ if (buffer!=null && !buffer.isEmpty()) {+ return (Token)buffer.removeFirst();+ } else {+ return input.next();+ }+ }++ private void pushTok(Token t) {+ if (buffer==null) buffer=new LinkedList();+ buffer.addFirst(t);+ }++++ private SynonymMap match(SynonymMap map) throws IOException {+ SynonymMap result = null;++ if (map.submap != null) {+ Token tok = nextTok();+ if (tok != null) {+ // check for positionIncrement!=1? if>1, should not match, if==0, check multiple at this level?+ String str = ignoreCase ? tok.termText.toLowerCase() : tok.termText;++ SynonymMap subMap = (SynonymMap)map.submap.get(str);++ if (subMap !=null) {+ // recurse+ result = match(subMap);+ }+ if (result != null) {+ matched.addFirst(tok);+ } else {+ // push back unmatched token+ pushTok(tok);+ }+ }+ }++ // if no longer sequence matched, so if this node has synonyms, it's the match.+ if (result==null && map.synonyms!=null) {+ result = map;+ }++ return result;+ }++}diff --git a/src/lucene_extras/org/apache/lucene/analysis/SynonymMap.java b/src/lucene_extras/org/apache/lucene/analysis/SynonymMap.javanew file mode 100644index 00000000000..b560968f119--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/analysis/SynonymMap.java@@ -0,0 +1,143 @@+/**+ * 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.+ */++package org.apache.lucene.analysis;++import java.util.*;++/** Mapping rules for use with {@link SynonymFilter}+ *+ * @author yonik+ * @version $Id: SynonymMap.java,v 1.2 2005/12/13 05:15:08 yonik Exp $+ */+public class SynonymMap {+ Map submap; // recursive: Map<String, SynonymMap>+ Token[] synonyms;+ int flags;++ static final int INCLUDE_ORIG=0x01;++ public boolean includeOrig() { return (flags & INCLUDE_ORIG) != 0; }++ /**+ * @param singleMatch List<String>, the sequence of strings to match+ * @param replacement List<Token> the list of tokens to use on a match+ * @param includeOrig sets a flag on this mapping signaling the generation of matched tokens in addition to the replacement tokens+ * @param mergeExisting merge the replacement tokens with any other mappings that exist+ */+ public void add(List singleMatch, List replacement, boolean includeOrig, boolean mergeExisting) {+ SynonymMap currMap = this;+ for (Iterator iter = singleMatch.iterator(); iter.hasNext();) {+ String str = (String)iter.next();+ if (currMap.submap==null) {+ currMap.submap = new HashMap(1);+ }++ SynonymMap map = (SynonymMap)currMap.submap.get(str);+ if (map==null) {+ map = new SynonymMap();+ currMap.submap.put(str, map);+ }++ currMap = map;+ }++ if (currMap.synonyms != null && !mergeExisting) {+ throw new RuntimeException("SynonymFilter: there is already a mapping for " + singleMatch);+ }+ List superset = currMap.synonyms==null ? replacement :+ mergeTokens(Arrays.asList(currMap.synonyms), replacement);+ currMap.synonyms = (Token[])superset.toArray(new Token[superset.size()]);+ if (includeOrig) currMap.flags |= INCLUDE_ORIG;+ }+++ public String toString() {+ StringBuffer sb = new StringBuffer("<");+ if (synonyms!=null) {+ sb.append("[");+ for (int i=0; i<synonyms.length; i++) {+ if (i!=0) sb.append(',');+ sb.append(synonyms[i]);+ }+ if ((flags & INCLUDE_ORIG)!=0) {+ sb.append(",ORIG");+ }+ sb.append("],");+ }+ sb.append(submap);+ sb.append(">");+ return sb.toString();+ }++++ /** Produces a List<Token> from a List<String> */+ public static List makeTokens(List strings) {+ List ret = new ArrayList(strings.size());+ for (Iterator iter = strings.iterator(); iter.hasNext();) {+ Token newTok = new Token((String)iter.next(),0,0,"SYNONYM");+ ret.add(newTok);+ }+ return ret;+ }+++ /**+ * Merge two lists of tokens, producing a single list with manipulated positionIncrements so that+ * the tokens end up at the same position.+ *+ * Example: [a b] merged with [c d] produces [a/b c/d] ('/' denotes tokens in the same position)+ * Example: [a,5 b,2] merged with [c d,4 e,4] produces [c a,5/d b,2 e,2] (a,n means a has posInc=n)+ *+ */+ public static List mergeTokens(List lst1, List lst2) {+ ArrayList result = new ArrayList();+ if (lst1 ==null || lst2 ==null) {+ if (lst2 != null) result.addAll(lst2);+ if (lst1 != null) result.addAll(lst1);+ return result;+ }++ int pos=0;+ Iterator iter1=lst1.iterator();+ Iterator iter2=lst2.iterator();+ Token tok1 = iter1.hasNext() ? (Token)iter1.next() : null;+ Token tok2 = iter2.hasNext() ? (Token)iter2.next() : null;+ int pos1 = tok1!=null ? tok1.getPositionIncrement() : 0;+ int pos2 = tok2!=null ? tok2.getPositionIncrement() : 0;+ while(tok1!=null || tok2!=null) {+ while (tok1 != null && (pos1 <= pos2 || tok2==null)) {+ Token tok = new Token(tok1.termText, tok1.startOffset, tok1.endOffset, tok1.type);+ tok.setPositionIncrement(pos1-pos);+ result.add(tok);+ pos=pos1;+ tok1 = iter1.hasNext() ? (Token)iter1.next() : null;+ pos1 += tok1!=null ? tok1.getPositionIncrement() : 0;+ }+ while (tok2 != null && (pos2 <= pos1 || tok1==null)) {+ Token tok = new Token(tok2.termText, tok2.startOffset, tok2.endOffset, tok2.type);+ tok.setPositionIncrement(pos2-pos);+ result.add(tok);+ pos=pos2;+ tok2 = iter2.hasNext() ? (Token)iter2.next() : null;+ pos2 += tok2!=null ? tok2.getPositionIncrement() : 0;+ }+ }+ return result;+ }++}diff --git a/src/lucene_extras/org/apache/lucene/analysis/TestSynonymFilter.java b/src/lucene_extras/org/apache/lucene/analysis/TestSynonymFilter.javanew file mode 100644index 00000000000..eaebf836f08--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/analysis/TestSynonymFilter.java@@ -0,0 +1,279 @@+/**+ * 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.+ */++package org.apache.lucene.analysis;++import junit.framework.TestCase;++import java.util.*;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id: TestSynonymFilter.java,v 1.2 2005/12/12 18:07:23 yonik Exp $+ */+public class TestSynonymFilter extends TestCase {++ public List strings(String str) {+ String[] arr = str.split(" ");+ return Arrays.asList(arr);+ }++ /***+ * Return a list of tokens according to a test string format:+ * a b c => returns List<Token> [a,b,c]+ * a/b => tokens a and b share the same spot (b.positionIncrement=0)+ * a,3/b/c => a,b,c all share same position (a.positionIncrement=3, b.positionIncrement=0, c.positionIncrement=0)+ */+ public List tokens(String str) {+ String[] arr = str.split(" ");+ List result = new ArrayList();+ for (int i=0; i<arr.length; i++) {+ String[] toks = arr[i].split("/");+ String[] params = toks[0].split(",");+ Token t = new Token(params[0],0,0,"TEST");+ if (params.length > 1) t.setPositionIncrement(Integer.parseInt(params[1]));+ result.add(t);+ for (int j=1; j<toks.length; j++) {+ t = new Token(toks[j],0,0,"TEST");+ t.setPositionIncrement(0);+ result.add(t);+ }+ }+ return result;+ }++ public List getTokList(SynonymMap dict, String input, boolean includeOrig) throws IOException {+ ArrayList lst = new ArrayList();+ final List toks = tokens(input);+ TokenStream ts = new TokenStream() {+ Iterator iter = toks.iterator();+ public Token next() throws IOException {+ return iter.hasNext() ? (Token)iter.next() : null;+ }+ };++ SynonymFilter sf = new SynonymFilter(ts, dict, true);++ while(true) {+ Token t = sf.next();+ if (t==null) return lst;+ lst.add(t);+ }+ }++ public List tok2str(List tokLst) {+ ArrayList lst = new ArrayList();+ for (Iterator iter = tokLst.iterator(); iter.hasNext();) {+ lst.add(((Token)(iter.next())).termText());+ }+ return lst;+ }+++ public void assertTokEqual(List a, List b) {+ assertTokEq(a,b);+ assertTokEq(b,a);+ }++ private void assertTokEq(List a, List b) {+ int pos=0;+ for (Iterator iter = a.iterator(); iter.hasNext();) {+ Token tok = (Token)iter.next();+ pos += tok.getPositionIncrement();+ if (!tokAt(b, tok.termText(), pos)) {+ fail(a + "!=" + b);+ }+ }+ }++ public boolean tokAt(List lst, String val, int tokPos) {+ int pos=0;+ for (Iterator iter = lst.iterator(); iter.hasNext();) {+ Token tok = (Token)iter.next();+ pos += tok.getPositionIncrement();+ if (pos==tokPos && tok.termText().equals(val)) return true;+ }+ return false;+ }+++ public void testMatching() throws IOException {+ SynonymMap map = new SynonymMap();++ boolean orig = false;+ boolean merge = true;+ map.add(strings("a b"), tokens("ab"), orig, merge);+ map.add(strings("a c"), tokens("ac"), orig, merge);+ map.add(strings("a"), tokens("aa"), orig, merge);+ map.add(strings("b"), tokens("bb"), orig, merge);+ map.add(strings("z x c v"), tokens("zxcv"), orig, merge);+ map.add(strings("x c"), tokens("xc"), orig, merge);++ // System.out.println(map);+ // System.out.println(getTokList(map,"a",false));++ assertTokEqual(getTokList(map,"$",false), tokens("$"));+ assertTokEqual(getTokList(map,"a",false), tokens("aa"));+ assertTokEqual(getTokList(map,"a $",false), tokens("aa $"));+ assertTokEqual(getTokList(map,"$ a",false), tokens("$ aa"));+ assertTokEqual(getTokList(map,"a a",false), tokens("aa aa"));+ assertTokEqual(getTokList(map,"b",false), tokens("bb"));+ assertTokEqual(getTokList(map,"z x c v",false), tokens("zxcv"));+ assertTokEqual(getTokList(map,"z x c $",false), tokens("z xc $"));++ // repeats+ map.add(strings("a b"), tokens("ab"), orig, merge);+ map.add(strings("a b"), tokens("ab"), orig, merge);+ assertTokEqual(getTokList(map,"a b",false), tokens("ab"));++ // check for lack of recursion+ map.add(strings("zoo"), tokens("zoo"), orig, merge);+ assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo zoo $ zoo"));+ map.add(strings("zoo"), tokens("zoo zoo"), orig, merge);+ assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo zoo zoo zoo $ zoo zoo"));+ }++ public void testIncludeOrig() throws IOException {+ SynonymMap map = new SynonymMap();++ boolean orig = true;+ boolean merge = true;+ map.add(strings("a b"), tokens("ab"), orig, merge);+ map.add(strings("a c"), tokens("ac"), orig, merge);+ map.add(strings("a"), tokens("aa"), orig, merge);+ map.add(strings("b"), tokens("bb"), orig, merge);+ map.add(strings("z x c v"), tokens("zxcv"), orig, merge);+ map.add(strings("x c"), tokens("xc"), orig, merge);++ // System.out.println(map);+ // System.out.println(getTokList(map,"a",false));++ assertTokEqual(getTokList(map,"$",false), tokens("$"));+ assertTokEqual(getTokList(map,"a",false), tokens("a/aa"));+ assertTokEqual(getTokList(map,"a",false), tokens("a/aa"));+ assertTokEqual(getTokList(map,"$ a",false), tokens("$ a/aa"));+ assertTokEqual(getTokList(map,"a $",false), tokens("a/aa $"));+ assertTokEqual(getTokList(map,"$ a !",false), tokens("$ a/aa !"));+ assertTokEqual(getTokList(map,"a a",false), tokens("a/aa a/aa"));+ assertTokEqual(getTokList(map,"b",false), tokens("b/bb"));+ assertTokEqual(getTokList(map,"z x c v",false), tokens("z/zxcv x c v"));+ assertTokEqual(getTokList(map,"z x c $",false), tokens("z x/xc c $"));++ // check for lack of recursion+ map.add(strings("zoo zoo"), tokens("zoo"), orig, merge);+ assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo/zoo zoo/zoo $ zoo/zoo"));+ map.add(strings("zoo"), tokens("zoo zoo"), orig, merge);+ assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo/zoo zoo $ zoo/zoo zoo"));+ }+++ public void testMapMerge() throws IOException {+ SynonymMap map = new SynonymMap();++ boolean orig = false;+ boolean merge = true;+ map.add(strings("a"), tokens("a5,5"), orig, merge);+ map.add(strings("a"), tokens("a3,3"), orig, merge);+ // System.out.println(map);+ assertTokEqual(getTokList(map,"a",false), tokens("a3 a5,2"));++ map.add(strings("b"), tokens("b3,3"), orig, merge);+ map.add(strings("b"), tokens("b5,5"), orig, merge);+ //System.out.println(map);+ assertTokEqual(getTokList(map,"b",false), tokens("b3 b5,2"));+++ map.add(strings("a"), tokens("A3,3"), orig, merge);+ map.add(strings("a"), tokens("A5,5"), orig, merge);+ assertTokEqual(getTokList(map,"a",false), tokens("a3/A3 a5,2/A5"));++ map.add(strings("a"), tokens("a1"), orig, merge);+ assertTokEqual(getTokList(map,"a",false), tokens("a1 a3,2/A3 a5,2/A5"));++ map.add(strings("a"), tokens("a2,2"), orig, merge);+ map.add(strings("a"), tokens("a4,4 a6,2"), orig, merge);+ assertTokEqual(getTokList(map,"a",false), tokens("a1 a2 a3/A3 a4 a5/A5 a6"));+ }+++ public void testOverlap() throws IOException {+ SynonymMap map = new SynonymMap();++ boolean orig = false;+ boolean merge = true;+ map.add(strings("qwe"), tokens("qq/ww/ee"), orig, merge);+ map.add(strings("qwe"), tokens("xx"), orig, merge);+ map.add(strings("qwe"), tokens("yy"), orig, merge);+ map.add(strings("qwe"), tokens("zz"), orig, merge);+ assertTokEqual(getTokList(map,"$",false), tokens("$"));+ assertTokEqual(getTokList(map,"qwe",false), tokens("qq/ww/ee/xx/yy/zz"));++ // test merging within the map++ map.add(strings("a"), tokens("a5,5 a8,3 a10,2"), orig, merge);+ map.add(strings("a"), tokens("a3,3 a7,4 a9,2 a11,2 a111,100"), orig, merge);+ assertTokEqual(getTokList(map,"a",false), tokens("a3 a5,2 a7,2 a8 a9 a10 a11 a111,100"));+ }++ public void testOffsets() throws IOException {+ SynonymMap map = new SynonymMap();++ boolean orig = false;+ boolean merge = true;++ // test that generated tokens start at the same offset as the original+ map.add(strings("a"), tokens("aa"), orig, merge);+ assertTokEqual(getTokList(map,"a,5",false), tokens("aa,5"));+ assertTokEqual(getTokList(map,"a,0",false), tokens("aa,0"));++ // test that offset of first replacement is ignored (always takes the orig offset)+ map.add(strings("b"), tokens("bb,100"), orig, merge);+ assertTokEqual(getTokList(map,"b,5",false), tokens("bb,5"));+ assertTokEqual(getTokList(map,"b,0",false), tokens("bb,0"));++ // test that subsequent tokens are adjusted accordingly+ map.add(strings("c"), tokens("cc,100 c2,2"), orig, merge);+ assertTokEqual(getTokList(map,"c,5",false), tokens("cc,5 c2,2"));+ assertTokEqual(getTokList(map,"c,0",false), tokens("cc,0 c2,2"));++ }+++ public void testOffsetsWithOrig() throws IOException {+ SynonymMap map = new SynonymMap();++ boolean orig = true;+ boolean merge = true;++ // test that generated tokens start at the same offset as the original+ map.add(strings("a"), tokens("aa"), orig, merge);+ assertTokEqual(getTokList(map,"a,5",false), tokens("a,5/aa"));+ assertTokEqual(getTokList(map,"a,0",false), tokens("a,0/aa"));++ // test that offset of first replacement is ignored (always takes the orig offset)+ map.add(strings("b"), tokens("bb,100"), orig, merge);+ assertTokEqual(getTokList(map,"b,5",false), tokens("bb,5/b"));+ assertTokEqual(getTokList(map,"b,0",false), tokens("bb,0/b"));++ // test that subsequent tokens are adjusted accordingly+ map.add(strings("c"), tokens("cc,100 c2,2"), orig, merge);+ assertTokEqual(getTokList(map,"c,5",false), tokens("cc,5/c c2,2"));+ assertTokEqual(getTokList(map,"c,0",false), tokens("cc,0/c c2,2"));+ }+++}diff --git a/src/lucene_extras/org/apache/lucene/search/ConstantScorePrefixQuery.java b/src/lucene_extras/org/apache/lucene/search/ConstantScorePrefixQuery.javanew file mode 100644index 00000000000..bc95d350069--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/ConstantScorePrefixQuery.java@@ -0,0 +1,79 @@+/**+ * 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.+ */++package org.apache.lucene.search;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;++import java.io.IOException;++/**+ * @author yonik+ * @version $Id: ConstantScorePrefixQuery.java,v 1.2 2005/09/15 14:32:41 yonik Exp $+ */+public class ConstantScorePrefixQuery extends Query {+ private final Term prefix;++ public ConstantScorePrefixQuery(Term prefix) {+ this.prefix = prefix;+ }++ /** Returns the prefix for this query */+ public Term getPrefix() { return prefix; }++ public Query rewrite(IndexReader reader) throws IOException {+ // TODO: if number of terms are low enough, rewrite to a BooleanQuery+ // for potentially faster execution.+ // TODO: cache the bitset somewhere instead of regenerating it+ Query q = new ConstantScoreQuery(new PrefixFilter(prefix));+ q.setBoost(getBoost());+ return q;+ }++ /** Prints a user-readable version of this query. */+ public String toString(String field)+ {+ StringBuffer buffer = new StringBuffer();+ if (!prefix.field().equals(field)) {+ buffer.append(prefix.field());+ buffer.append(":");+ }+ buffer.append(prefix.text());+ buffer.append('*');+ if (getBoost() != 1.0f) {+ buffer.append("^");+ buffer.append(Float.toString(getBoost()));+ }+ return buffer.toString();+ }++ /** Returns true if <code>o</code> is equal to this. */+ public boolean equals(Object o) {+ if (this == o) return true;+ if (!(o instanceof ConstantScorePrefixQuery)) return false;+ ConstantScorePrefixQuery other = (ConstantScorePrefixQuery) o;+ return this.prefix.equals(other.prefix) && this.getBoost()==other.getBoost();+ }++ /** Returns a hash code value for this object.*/+ public int hashCode() {+ int h = prefix.hashCode() ^ Float.floatToIntBits(getBoost());+ h ^= (h << 14) | (h >>> 19); // reversible (1 to 1) transformation unique to ConstantScorePrefixQuery+ return h;+ }++}diff --git a/src/lucene_extras/org/apache/lucene/search/PrefixFilter.java b/src/lucene_extras/org/apache/lucene/search/PrefixFilter.javanew file mode 100644index 00000000000..363bc611581--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/PrefixFilter.java@@ -0,0 +1,95 @@+/**+ * 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.+ */++package org.apache.lucene.search;++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 java.util.BitSet;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id: PrefixFilter.java,v 1.1 2005/06/10 05:47:32 yonik Exp $+ */+public class PrefixFilter extends Filter {+ protected final Term prefix;++ PrefixFilter(Term prefix) {+ this.prefix = prefix;+ }++ Term getPrefix() { return prefix; }++ public BitSet bits(IndexReader reader) throws IOException {+ final BitSet bitSet = new BitSet(reader.maxDoc());+ new PrefixGenerator(prefix) {+ public void handleDoc(int doc) {+ bitSet.set(doc);+ }+ }.generate(reader);+ return bitSet;+ }+}+++// keep this protected until I decide if it's a good way+// to separate id generation from collection (or should+// I just reuse hitcollector???)+interface IdGenerator {+ public void generate(IndexReader reader) throws IOException;+ public void handleDoc(int doc);+}+++abstract class PrefixGenerator implements IdGenerator {+ protected final Term prefix;++ PrefixGenerator(Term prefix) {+ this.prefix = prefix;+ }++ public void generate(IndexReader reader) throws IOException {+ TermEnum enumerator = reader.terms(prefix);+ TermDocs termDocs = reader.termDocs();++ try {++ String prefixText = prefix.text();+ String prefixField = prefix.field();+ do {+ Term term = enumerator.term();+ if (term != null &&+ term.text().startsWith(prefixText) &&+ term.field() == prefixField)+ {+ termDocs.seek(term);+ while (termDocs.next()) {+ handleDoc(termDocs.doc());+ }+ } else {+ break;+ }+ } while (enumerator.next());+ } finally {+ termDocs.close();+ enumerator.close();+ }+ }+}diff --git a/src/lucene_extras/org/apache/lucene/search/PublicFieldSortedHitQueue.java b/src/lucene_extras/org/apache/lucene/search/PublicFieldSortedHitQueue.javanew file mode 100644index 00000000000..cc0b36f99d8--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/PublicFieldSortedHitQueue.java@@ -0,0 +1,41 @@+/**+ * 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.+ */++package org.apache.lucene.search;++/**+ * FieldSortedHitQueue that is public (can be created and accessed from other packages)+ *+ * @author yonik+ * @version $Id: PublicFieldSortedHitQueue.java,v 1.3 2005/11/11 21:57:56 yonik Exp $+ */++import org.apache.lucene.index.IndexReader;+import java.io.IOException;++public class PublicFieldSortedHitQueue extends FieldSortedHitQueue {+ public PublicFieldSortedHitQueue (IndexReader reader, SortField[] fields, int size) throws IOException {+ super(reader, fields, size);+ }++ int totalHits;+ public int getTotalHits() { return totalHits; }++ public boolean insert(FieldDoc element) {+ totalHits++;+ return super.insert(element);+ }+}\ No newline at end of filediff --git a/src/lucene_extras/org/apache/lucene/search/function/DocValues.java b/src/lucene_extras/org/apache/lucene/search/function/DocValues.javanew file mode 100644index 00000000000..21f62ababa7--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/DocValues.java@@ -0,0 +1,47 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.search.Explanation;++/**+ * Represents field values as different types.+ * Normally created via a {@link ValueSource} for a particular field and reader.+ * <br>+ * Often used by {@link FunctionFactory} implementations.+ *+ * @author yonik+ * @version $Id: DocValues.java,v 1.1 2005/11/22 05:23:20 yonik Exp $+ */++// DocValues is distinct from ValueSource because+// there needs to be an object created at query evaluation time that+// is not referenced by the query itself because:+// - Query objects should be MT safe+// - For caching, Query objects are often used as keys... you don't+// want the Query carrying around big objects+public abstract class DocValues {+ public float floatVal(int doc) { throw new UnsupportedOperationException(); }+ public int intVal(int doc) { throw new UnsupportedOperationException(); }+ public long longVal(int doc) { throw new UnsupportedOperationException(); }+ public double doubleVal(int doc) { throw new UnsupportedOperationException(); }+ public String strVal(int doc) { throw new UnsupportedOperationException(); }+ public abstract String toString(int doc);+ public Explanation explain(int doc) {+ return new Explanation(floatVal(doc), toString(doc));+ }+}diff --git a/src/lucene_extras/org/apache/lucene/search/function/FieldCacheSource.java b/src/lucene_extras/org/apache/lucene/search/function/FieldCacheSource.javanew file mode 100644index 00000000000..fe233b6d9da--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/FieldCacheSource.java@@ -0,0 +1,59 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.search.FieldCache;++/**+ * A base class for ValueSource implementations that retrieve values for+ * a single field from the {@link org.apache.lucene.search.FieldCache}.+ *+ * @author yonik+ * @version $Id: FieldCacheSource.java,v 1.1 2005/11/22 05:23:20 yonik Exp $+ */+public abstract class FieldCacheSource extends ValueSource {+ protected String field;+ protected FieldCache cache = FieldCache.DEFAULT;++ public FieldCacheSource(String field) {+ this.field=field;+ }++ public void setFieldCache(FieldCache cache) {+ this.cache = cache;+ }++ public FieldCache getFieldCache() {+ return cache;+ }++ public String description() {+ return field;+ }++ public boolean equals(Object o) {+ if (!(o instanceof FieldCacheSource)) return false;+ FieldCacheSource other = (FieldCacheSource)o;+ return this.field.equals(other.field)+ && this.cache == other.cache;+ }++ public int hashCode() {+ return cache.hashCode() + field.hashCode();+ };++}diff --git a/src/lucene_extras/org/apache/lucene/search/function/FloatFieldSource.java b/src/lucene_extras/org/apache/lucene/search/function/FloatFieldSource.javanew file mode 100644index 00000000000..88e35ab4d69--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/FloatFieldSource.java@@ -0,0 +1,96 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.FieldCache;++import java.io.IOException;++/**+ * Obtains float field values from the {@link org.apache.lucene.search.FieldCache}+ * using <code>getFloats()</code>+ * and makes those values available as other numeric types, casting as needed.+ *+ * @author yonik+ * @version $Id: FloatFieldSource.java,v 1.2 2005/11/22 05:23:20 yonik Exp $+ */++public class FloatFieldSource extends FieldCacheSource {+ protected FieldCache.FloatParser parser;++ public FloatFieldSource(String field) {+ this(field, null);+ }++ public FloatFieldSource(String field, FieldCache.FloatParser parser) {+ super(field);+ this.parser = parser;+ }++ public String description() {+ return "float(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final float[] arr = (parser==null) ?+ cache.getFloats(reader, field) :+ cache.getFloats(reader, field, parser);+ return new DocValues() {+ public float floatVal(int doc) {+ return arr[doc];+ }++ public int intVal(int doc) {+ return (int)arr[doc];+ }++ public long longVal(int doc) {+ return (long)arr[doc];+ }++ public double doubleVal(int doc) {+ return (double)arr[doc];+ }++ public String strVal(int doc) {+ return Float.toString(arr[doc]);+ }++ public String toString(int doc) {+ return description() + '=' + floatVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ if (o.getClass() != FloatFieldSource.class) return false;+ FloatFieldSource other = (FloatFieldSource)o;+ return super.equals(other)+ && this.parser==null ? other.parser==null :+ this.parser.getClass() == other.parser.getClass();+ }++ public int hashCode() {+ int h = parser==null ? Float.class.hashCode() : parser.getClass().hashCode();+ h += super.hashCode();+ return h;+ };++}\ No newline at end of filediff --git a/src/lucene_extras/org/apache/lucene/search/function/FunctionQuery.java b/src/lucene_extras/org/apache/lucene/search/function/FunctionQuery.javanew file mode 100644index 00000000000..8bf5bf84d55--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/FunctionQuery.java@@ -0,0 +1,173 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.*;+import java.io.IOException;+++/**+ * Returns a score for each document based on a ValueSource,+ * often some function of the value of a field.+ *+ * @author yonik+ * @version $Id: FunctionQuery.java,v 1.4 2005/11/23 04:22:20 yonik Exp $+ */+public class FunctionQuery extends Query {+ ValueSource func;++ /**+ *+ * @param func defines the function to be used for scoring+ */+ public FunctionQuery(ValueSource func) {+ this.func=func;+ }++ public Query rewrite(IndexReader reader) throws IOException {+ return this;+ }++ protected class FunctionWeight implements Weight {+ Searcher searcher;+ float queryNorm;+ float queryWeight;++ public FunctionWeight(Searcher searcher) {+ this.searcher = searcher;+ }++ public Query getQuery() {+ return FunctionQuery.this;+ }++ public float getValue() {+ return queryWeight;+ }++ public float sumOfSquaredWeights() throws IOException {+ queryWeight = getBoost();+ return queryWeight * queryWeight;+ }++ public void normalize(float norm) {+ this.queryNorm = norm;+ queryWeight *= this.queryNorm;+ }++ public Scorer scorer(IndexReader reader) throws IOException {+ return new AllScorer(getSimilarity(searcher), reader, this);+ }++ public Explanation explain(IndexReader reader, int doc) throws IOException {+ return scorer(reader).explain(doc);+ }+ }++ protected class AllScorer extends Scorer {+ final IndexReader reader;+ final FunctionWeight weight;+ final int maxDoc;+ final float qWeight;+ int doc=-1;+ final DocValues vals;++ public AllScorer(Similarity similarity, IndexReader reader, FunctionWeight w) throws IOException {+ super(similarity);+ this.weight = w;+ this.qWeight = w.getValue();+ this.reader = reader;+ this.maxDoc = reader.maxDoc();+ vals = func.getValues(reader);+ }++ // instead of matching all docs, we could also embed a query.+ // the score could either ignore the subscore, or boost it.+ // Containment: floatline(foo:myTerm, "myFloatField", 1.0, 0.0f)+ // Boost: foo:myTerm^floatline("myFloatField",1.0,0.0f)+ public boolean next() throws IOException {+ for(;;) {+ ++doc;+ if (doc>=maxDoc) {+ return false;+ }+ if (reader.isDeleted(doc)) continue;+ // todo: maybe allow score() to throw a specific exception+ // and continue on to the next document if it is thrown...+ // that may be useful, but exceptions aren't really good+ // for flow control.+ return true;+ }+ }++ public int doc() {+ return doc;+ }++ public float score() throws IOException {+ return qWeight * vals.floatVal(doc);+ }++ public boolean skipTo(int target) throws IOException {+ doc=target-1;+ return next();+ }++ public Explanation explain(int doc) throws IOException {+ float sc = qWeight * vals.floatVal(doc);++ Explanation result = new Explanation();+ result.setDescription("FunctionQuery(" + func+ + "), product of:");+ result.setValue(sc);+ result.addDetail(vals.explain(doc));+ result.addDetail(new Explanation(getBoost(), "boost"));+ result.addDetail(new Explanation(weight.queryNorm,"queryNorm"));+ return result;+ }+ }+++ protected Weight createWeight(Searcher searcher) {+ return new FunctionQuery.FunctionWeight(searcher);+ }+++ /** Prints a user-readable version of this query. */+ public String toString(String field)+ {+ float boost = getBoost();+ return (boost!=1.0?"(":"") + func.toString()+ + (getBoost()==0 ? "" : ")^"+getBoost());+ }+++ /** Returns true if <code>o</code> is equal to this. */+ public boolean equals(Object o) {+ if (FunctionQuery.class != o.getClass()) return false;+ FunctionQuery other = (FunctionQuery)o;+ return this.getBoost() == other.getBoost()+ && this.func.equals(other.func);+ }++ /** Returns a hash code value for this object. */+ public int hashCode() {+ return func.hashCode() ^ Float.floatToIntBits(getBoost());+ }++}diff --git a/src/lucene_extras/org/apache/lucene/search/function/IntFieldSource.java b/src/lucene_extras/org/apache/lucene/search/function/IntFieldSource.javanew file mode 100644index 00000000000..310346fbc92--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/IntFieldSource.java@@ -0,0 +1,96 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.FieldCache;++import java.io.IOException;++/**+ * Obtains int field values from the {@link org.apache.lucene.search.FieldCache}+ * using <code>getInts()</code>+ * and makes those values available as other numeric types, casting as needed. *+ * @author yonik+ * @version $Id: IntFieldSource.java,v 1.2 2005/11/22 05:23:20 yonik Exp $+ */++public class IntFieldSource extends FieldCacheSource {+ FieldCache.IntParser parser;++ public IntFieldSource(String field) {+ this(field, null);+ }++ public IntFieldSource(String field, FieldCache.IntParser parser) {+ super(field);+ this.parser = parser;+ }++ public String description() {+ return "int(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final int[] arr = (parser==null) ?+ cache.getInts(reader, field) :+ cache.getInts(reader, field, parser);+ return new DocValues() {+ public float floatVal(int doc) {+ return (float)arr[doc];+ }++ public int intVal(int doc) {+ return (int)arr[doc];+ }++ public long longVal(int doc) {+ return (long)arr[doc];+ }++ public double doubleVal(int doc) {+ return (double)arr[doc];+ }++ public String strVal(int doc) {+ return Float.toString(arr[doc]);+ }++ public String toString(int doc) {+ return description() + '=' + intVal(doc);+ }++ };+ }++ public boolean equals(Object o) {+ if (o.getClass() != IntFieldSource.class) return false;+ IntFieldSource other = (IntFieldSource)o;+ return super.equals(other)+ && this.parser==null ? other.parser==null :+ this.parser.getClass() == other.parser.getClass();+ }++ public int hashCode() {+ int h = parser==null ? Integer.class.hashCode() : parser.getClass().hashCode();+ h += super.hashCode();+ return h;+ };++}diff --git a/src/lucene_extras/org/apache/lucene/search/function/LinearFloatFunction.java b/src/lucene_extras/org/apache/lucene/search/function/LinearFloatFunction.javanew file mode 100644index 00000000000..df769fb8cc7--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/LinearFloatFunction.java@@ -0,0 +1,86 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;++import java.io.IOException;++/**+ * <code>LinearFloatFunction</code> implements a linear function over+ * another {@link ValueSource}.+ * <br>+ * Normally Used as an argument to a {@link FunctionQuery}+ *+ * @author yonik+ * @version $Id: LinearFloatFunction.java,v 1.2 2005/11/22 05:23:21 yonik Exp $+ */+public class LinearFloatFunction extends ValueSource {+ protected final ValueSource source;+ protected final float slope;+ protected final float intercept;++ public LinearFloatFunction(ValueSource source, float slope, float intercept) {+ this.source = source;+ this.slope = slope;+ this.intercept = intercept;+ }++ public String description() {+ return slope + "*float(" + source.description() + ")+" + intercept;+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final DocValues vals = source.getValues(reader);+ return new DocValues() {+ public float floatVal(int doc) {+ return vals.floatVal(doc) * slope + intercept;+ }+ public int intVal(int doc) {+ return (int)floatVal(doc);+ }+ public long longVal(int doc) {+ return (long)floatVal(doc);+ }+ public double doubleVal(int doc) {+ return (double)floatVal(doc);+ }+ public String strVal(int doc) {+ return Float.toString(floatVal(doc));+ }+ public String toString(int doc) {+ return slope + "*float(" + vals.toString(doc) + ")+" + intercept;+ }+ };+ }++ public int hashCode() {+ int h = Float.floatToIntBits(slope);+ h = (h >>> 2) | (h << 30);+ h += Float.floatToIntBits(intercept);+ h ^= (h << 14) | (h >>> 19);+ return h + source.hashCode();+ }++ public boolean equals(Object o) {+ if (LinearFloatFunction.class != o.getClass()) return false;+ LinearFloatFunction other = (LinearFloatFunction)o;+ return this.slope == other.slope+ && this.intercept == other.intercept+ && this.source.equals(other.source);+ }+}diff --git a/src/lucene_extras/org/apache/lucene/search/function/OrdFieldSource.java b/src/lucene_extras/org/apache/lucene/search/function/OrdFieldSource.javanew file mode 100644index 00000000000..c471ba7c1aa--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/OrdFieldSource.java@@ -0,0 +1,94 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.FieldCache;++import java.io.IOException;++/**+ * Obtains the ordinal of the field value from the default Lucene {@link org.apache.lucene.search.FieldCache} using getStringIndex().+ * <br>+ * The native lucene index order is used to assign an ordinal value for each field value.+ * <br>Field values (terms) are lexicographically ordered by unicode value, and numbered starting at 1.+ * <br>+ * Example:<br>+ * If there were only three field values: "apple","banana","pear"+ * <br>then ord("apple")=1, ord("banana")=2, ord("pear")=3+ * <p>+ * WARNING: ord() depends on the position in an index and can thus change when other documents are inserted or deleted,+ * or if a MultiSearcher is used.+ * @author yonik+ * @version $Id: OrdFieldSource.java,v 1.2 2005/11/22 05:23:21 yonik Exp $+ */++public class OrdFieldSource extends ValueSource {+ protected String field;++ public OrdFieldSource(String field) {+ this.field = field;+ }++ public String description() {+ return "ord(" + field + ')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final int[] arr = FieldCache.DEFAULT.getStringIndex(reader, field).order;+ return new DocValues() {+ public float floatVal(int doc) {+ return (float)arr[doc];+ }++ public int intVal(int doc) {+ return (int)arr[doc];+ }++ public long longVal(int doc) {+ return (long)arr[doc];+ }++ public double doubleVal(int doc) {+ return (double)arr[doc];+ }++ public String strVal(int doc) {+ // the string value of the ordinal, not the string itself+ return Integer.toString(arr[doc]);+ }++ public String toString(int doc) {+ return description() + '=' + intVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ if (o.getClass() != OrdFieldSource.class) return false;+ OrdFieldSource other = (OrdFieldSource)o;+ return this.field.equals(field);+ }++ private static final int hcode = OrdFieldSource.class.hashCode();+ public int hashCode() {+ return hcode + field.hashCode();+ };++}diff --git a/src/lucene_extras/org/apache/lucene/search/function/ReciprocalFloatFunction.java b/src/lucene_extras/org/apache/lucene/search/function/ReciprocalFloatFunction.javanew file mode 100644index 00000000000..a995776aa6e--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/ReciprocalFloatFunction.java@@ -0,0 +1,101 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;++import java.io.IOException;++/**+ * <code>ReciprocalFloatFunction</code> implements a reciprocal function f(x) = a/(mx+b), based on+ * the float value of a field as exported by {@link org.apache.lucene.search.function.ValueSource}.+ * <br>+ *+ * When a and b are equal, and x>=0, this function has a maximum value of 1 that drops as x increases.+ * Increasing the value of a and b together results in a movement of the entire function to a flatter part of the curve.+ * <br>These properties make this an idea function for boosting more recent documents.+ * <br>Example:<code>ReciprocalFloatFunction(new ReverseOrdFieldSource("my_date"),1,1000,1000)</code>+ *+ * @see FunctionQuery+ *+ *+ * @author yonik+ * @version $Id: ReciprocalFloatFunction.java,v 1.2 2005/11/22 05:23:21 yonik Exp $+ */+public class ReciprocalFloatFunction extends ValueSource {+ protected final ValueSource source;+ protected final float m;+ protected final float a;+ protected final float b;++ /**+ * f(source) = a/(m*float(source)+b)+ */+ public ReciprocalFloatFunction(ValueSource source, float m, float a, float b) {+ this.source=source;+ this.m=m;+ this.a=a;+ this.b=b;+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final DocValues vals = source.getValues(reader);+ return new DocValues() {+ public float floatVal(int doc) {+ return a/(m*vals.floatVal(doc) + b);+ }+ public int intVal(int doc) {+ return (int)floatVal(doc);+ }+ public long longVal(int doc) {+ return (long)floatVal(doc);+ }+ public double doubleVal(int doc) {+ return (double)floatVal(doc);+ }+ public String strVal(int doc) {+ return Float.toString(floatVal(doc));+ }+ public String toString(int doc) {+ return Float.toString(a) + "/("+ + m + "*float(" + vals.toString(doc) + ')'+ + '+' + b + ')';+ }+ };+ }++ public String description() {+ return Float.toString(a) + "/("+ + m + "*float(" + source.description() + ")"+ + "+" + b + ')';+ }++ public int hashCode() {+ int h = Float.floatToIntBits(a) + Float.floatToIntBits(m);+ h ^= (h << 13) | (h >>> 20);+ return h + (Float.floatToIntBits(b)) + source.hashCode();+ }++ public boolean equals(Object o) {+ if (ReciprocalFloatFunction.class != o.getClass()) return false;+ ReciprocalFloatFunction other = (ReciprocalFloatFunction)o;+ return this.m == other.m+ && this.a == other.a+ && this.b == other.b+ && this.source.equals(other.source);+ }+}diff --git a/src/lucene_extras/org/apache/lucene/search/function/ReverseOrdFieldSource.java b/src/lucene_extras/org/apache/lucene/search/function/ReverseOrdFieldSource.javanew file mode 100644index 00000000000..7f59e62f744--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/ReverseOrdFieldSource.java@@ -0,0 +1,99 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.function.DocValues;+import org.apache.lucene.search.function.ValueSource;+import org.apache.lucene.search.FieldCache;++import java.io.IOException;++/**+ * Obtains the ordinal of the field value from the default Lucene {@link org.apache.lucene.search.FieldCache} using getStringIndex()+ * and reverses the order.+ * <br>+ * The native lucene index order is used to assign an ordinal value for each field value.+ * <br>Field values (terms) are lexicographically ordered by unicode value, and numbered starting at 1.+ * <br>+ * Example of reverse ordinal (rord):<br>+ * If there were only three field values: "apple","banana","pear"+ * <br>then rord("apple")=3, rord("banana")=2, ord("pear")=1+ * <p>+ * WARNING: ord() depends on the position in an index and can thus change when other documents are inserted or deleted,+ * or if a MultiSearcher is used.+ * @author yonik+ * @version $Id: ReverseOrdFieldSource.java,v 1.2 2005/11/22 05:23:21 yonik Exp $+ */++public class ReverseOrdFieldSource extends ValueSource {+ public String field;++ public ReverseOrdFieldSource(String field) {+ this.field = field;+ }++ public String description() {+ return "rord("+field+')';+ }++ public DocValues getValues(IndexReader reader) throws IOException {+ final FieldCache.StringIndex sindex = FieldCache.DEFAULT.getStringIndex(reader, field);++ final int arr[] = sindex.order;+ final int end = sindex.lookup.length;++ return new DocValues() {+ public float floatVal(int doc) {+ return (float)(end - arr[doc]);+ }++ public int intVal(int doc) {+ return (int)(end - arr[doc]);+ }++ public long longVal(int doc) {+ return (long)(end - arr[doc]);+ }++ public double doubleVal(int doc) {+ return (double)(end - arr[doc]);+ }++ public String strVal(int doc) {+ // the string value of the ordinal, not the string itself+ return Integer.toString((end - arr[doc]));+ }++ public String toString(int doc) {+ return description() + '=' + strVal(doc);+ }+ };+ }++ public boolean equals(Object o) {+ if (o.getClass() != ReverseOrdFieldSource.class) return false;+ ReverseOrdFieldSource other = (ReverseOrdFieldSource)o;+ return this.field.equals(field);+ }++ private static final int hcode = ReverseOrdFieldSource.class.hashCode();+ public int hashCode() {+ return hcode + field.hashCode();+ };++}diff --git a/src/lucene_extras/org/apache/lucene/search/function/ValueSource.java b/src/lucene_extras/org/apache/lucene/search/function/ValueSource.javanew file mode 100644index 00000000000..312e11c461a--- /dev/null+++ b/src/lucene_extras/org/apache/lucene/search/function/ValueSource.java@@ -0,0 +1,48 @@+/**+ * 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.+ */++package org.apache.lucene.search.function;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.function.DocValues;++import java.io.IOException;+import java.io.Serializable;++/**+ * Instantiates {@link org.apache.lucene.search.function.DocValues} for a particular reader.+ * <br>+ * Often used when creating a {@link FunctionQuery}.+ *+ * @author yonik+ * @version $Id: ValueSource.java,v 1.2 2005/11/30 19:31:01 yonik Exp $+ */+public abstract class ValueSource implements Serializable {++ public abstract DocValues getValues(IndexReader reader) throws IOException;++ public abstract boolean equals(Object o);++ public abstract int hashCode();++ /** description of field, used in explain() */+ public abstract String description();++ public String toString() {+ return getClass().getName() + ":" + description();+ }++}diff --git a/src/lucene_extras/org/apache/lucene/search/function/function.zip b/src/lucene_extras/org/apache/lucene/search/function/function.zipnew file mode 100755index 00000000000..1f05cb810bcBinary files /dev/null and b/src/lucene_extras/org/apache/lucene/search/function/function.zip differdiff --git a/src/scripts/abc b/src/scripts/abcnew file mode 100755index 00000000000..a92ed607d07--- /dev/null+++ b/src/scripts/abc@@ -0,0 +1,132 @@+#!/bin/bash+#+# $Id: abc.template,v 1.5 2005/06/09 15:33:13 billa Exp $+# $Source: /cvs/main/searching/solar-tools/abc.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to make an Atomic Backup after Commit of+# a SOLAR Lucene collection.++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs++logMessage sending commit to Solar server at port 5051+rs=`curl http://localhost:5051/update -s -d "<commit/>"`+if [[ $? != 0 ]]+then+ logMessage failed to connect to SOLAR server at port 5051+ logMessage commit failed+ logExit failed 1+fi++# check status of commit request+rc=`echo $rs|cut -f2 -d'"'`+if [[ $? != 0 ]]+then+ logMessage commit request to SOLAR at port 5051 failed:+ logMessage $rs+ logExit failed 2+fi++# successful commit creates a snapshot file synchronously+lastsnap=`ls -drt1 snapshot.* 2> /dev/null | tail -1 `++if [[ $lastsnap == "" ]]+then+ logMessage commit did not create snapshot at port 5051; backup failed:+ logExit failed 3+fi++name=backup.${lastsnap##snapshot.}+temp=temp-${name}++if [[ -d ${name} ]]+then+ logMessage backup directory ${name} already exists+ logExit aborted 1+fi++if [[ -d ${temp} ]]+then+ logMessage backingup of ${name} in progress+ logExit aborted 1+fi+logMessage making backup ${name}++# clean up after INT/TERM+trap 'echo cleaning up, please wait ...;/bin/rm -rf ${name} ${temp};logExit aborted 13' INT TERM++# make a backup using hard links into temporary location+# then move it into place atomically+cp -lr ${lastsnap} ${temp}+mv ${temp} ${name}++logExit ended 0diff --git a/src/scripts/abo b/src/scripts/abonew file mode 100755index 00000000000..8ff5e6940ee--- /dev/null+++ b/src/scripts/abo@@ -0,0 +1,132 @@+#!/bin/bash+#+# $Id: abo.template,v 1.5 2005/06/09 15:33:13 billa Exp $+# $Source: /cvs/main/searching/solar-tools/abo.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to make an Atomic Backup after Optimize of+# a SOLAR Lucene collection.++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs++logMessage sending optimize to Solar server at port 5051+rs=`curl http://localhost:5051/update -s -d "<optimize/>"`+if [[ $? != 0 ]]+then+ logMessage failed to connect to SOLAR server at port 5051+ logMessage optimize failed+ logExit failed 1+fi++# check status of optimize request+rc=`echo $rs|cut -f2 -d'"'`+if [[ $? != 0 ]]+then+ logMessage optimize request to SOLAR at port 5051 failed:+ logMessage $rs+ logExit failed 2+fi++# successful optimize creates a snapshot file synchronously+lastsnap=`ls -drt1 snapshot.* | tail -1 `++if [[ $lastsnap == "" ]]+then+ logMessage commit did not create snapshot at port 5051; backup failed:+ logExit failed 3+fi++name=backup.${lastsnap##snapshot.}+temp=temp-${name}++if [[ -d ${name} ]]+then+ logMessage backup directory ${name} already exists+ logExit aborted 1+fi++if [[ -d ${temp} ]]+then+ logMessage backingup of ${name} in progress+ logExit aborted 1+fi+logMessage making backup ${name}++# clean up after INT/TERM+trap 'echo cleaning up, please wait ...;/bin/rm -rf ${name} ${temp};logExit aborted 13' INT TERM++# make a backup using hard links into temporary location+# then move it into place atomically+cp -lr ${lastsnap} ${temp}+mv ${temp} ${name}++logExit ended 0diff --git a/src/scripts/backup b/src/scripts/backupnew file mode 100755index 00000000000..be33505f715--- /dev/null+++ b/src/scripts/backup@@ -0,0 +1,105 @@+#!/bin/bash+#+# $Id: backup.template,v 1.4 2005/06/09 15:33:13 billa Exp $+# $Source: /cvs/main/searching/solar-tools/backup.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to make a backup of a SOLAR Lucene collection.++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs+name=backup.`date +"%Y%m%d%H%M%S"`+temp=temp-${name}++if [[ -d ${name} ]]+then+ logMessage backup directory ${name} already exists+ logExit aborted 1+fi++if [[ -d ${temp} ]]+then+ logMessage backingup of ${name} in progress+ logExit aborted 1+fi++# clean up after INT/TERM+trap 'echo cleaning up, please wait ...;/bin/rm -rf ${name} ${temp};logExit aborted 13' INT TERM++logMessage making backup ${name}++# make a backup using hard links into temporary location+# then move it into place atomically+cp -lr index ${temp}+mv ${temp} ${name}++logExit ended 0+diff --git a/src/scripts/commit b/src/scripts/commitnew file mode 100755index 00000000000..71f12f8c7f9--- /dev/null+++ b/src/scripts/commit@@ -0,0 +1,99 @@+#!/bin/bash+#+# $Id: commit.template,v 1.4 2005/06/09 15:33:13 billa Exp $+# $Source: /cvs/main/searching/solar-tools/commit.template,v $+# $Name: r20050725_standardized_server_enabled $++#+# Shell script to force a commit of all changes since last commit+# for a SOLAR server++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs++rs=`curl http://localhost:5051/update -s -d "<commit/>"`+if [[ $? != 0 ]]+then+ logMessage failed to connect to SOLAR server at port 5051+ logMessage commit failed+ logExit failed 1+fi++# check status of commit request+rc=`echo $rs|cut -f2 -d'"'`+if [[ $? != 0 ]]+then+ logMessage commit request to SOLAR at port 5051 failed:+ logMessage $rs+ logExit failed 2+fi++logExit ended 0diff --git a/src/scripts/optimize b/src/scripts/optimizenew file mode 100755index 00000000000..547fb1fb7a7--- /dev/null+++ b/src/scripts/optimize@@ -0,0 +1,99 @@+#!/bin/bash+#+# $Id: optimize.template,v 1.3 2005/06/09 15:34:06 billa Exp $+# $Source: /cvs/main/searching/solar-tools/optimize.template,v $+# $Name: r20050725_standardized_server_enabled $++#+# Shell script to force a optimized commit of all changes since last commit+# for a SOLAR server++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+ fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs++rs=`curl http://localhost:5051/update -s -d "<optimize/>"`+if [[ $? != 0 ]]+then+ logMessage failed to connect to SOLAR server at port 5051+ logMessage optimize failed+ logExit failed 1+fi++# check status of optimize request+rc=`echo $rs|cut -f2 -d'"'`+if [[ $? != 0 ]]+then+ logMessage optimize request to SOLAR at port 5051 failed:+ logMessage $rs+ logExit failed 2+fi++logExit ended 0diff --git a/src/scripts/readercycle b/src/scripts/readercyclenew file mode 100755index 00000000000..28375513bd1--- /dev/null+++ b/src/scripts/readercycle@@ -0,0 +1,99 @@+#!/bin/bash+#+# $Id: readercycle.template,v 1.3 2005/06/09 15:34:06 billa Exp $+# $Source: /cvs/main/searching/solar-tools/readercycle.template,v $+# $Name: r20050725_standardized_server_enabled $++#+# Shell script to force all old readers closed and a new reader to be opened+# for a SOLAR server++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs++rs=`curl http://localhost:5051/update -s -d "<commit/>"`+if [[ $? != 0 ]]+then+ logMessage failed to connect to SOLAR server at port 5051+ logMessage reader cycle failed+ logExit failed 1+fi++# check status of commit request+rc=`echo $rs|cut -f2 -d'"'`+if [[ $? != 0 ]]+then+ logMessage reader cycle request to SOLAR at port 5051 failed:+ logMessage $rs+ logExit failed 2+fi++logExit ended 0diff --git a/src/scripts/rsyncd-disable b/src/scripts/rsyncd-disablenew file mode 100755index 00000000000..523f67acfe0--- /dev/null+++ b/src/scripts/rsyncd-disable@@ -0,0 +1,89 @@+#!/bin/bash+#+# $Id: rsyncd-disable.template,v 1.1 2005/06/20 20:43:29 billa Exp $+# $Source: /cvs/main/searching/solar-tools/rsyncd-disable.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to disable rsyncd++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/rsyncd.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y/%m/%d %H:%M:%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage disabled by $oldwhoami+logMessage command: $0 $originalargs+name=rsyncd-enabled++if [[ -f ${name} ]]+then+ rm -f ${name}+else+ logMessage rsyncd not currently enabled+ logExit exited 1+fi++logExit ended 0diff --git a/src/scripts/rsyncd-enable b/src/scripts/rsyncd-enablenew file mode 100755index 00000000000..18eb6795721--- /dev/null+++ b/src/scripts/rsyncd-enable@@ -0,0 +1,89 @@+#!/bin/bash+#+# $Id: rsyncd-enable.template,v 1.1 2005/06/20 20:43:29 billa Exp $+# $Source: /cvs/main/searching/solar-tools/rsyncd-enable.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to enable rsyncd++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/rsyncd.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y/%m/%d %H:%M:%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage enabled by $oldwhoami+logMessage command: $0 $originalargs+name=rsyncd-enabled++if [[ -f ${name} ]]+then+ logMessage rsyncd already currently enabled+ logExit exited 1+else+ touch ${name}+fi++logExit ended 0diff --git a/src/scripts/rsyncd-start b/src/scripts/rsyncd-startnew file mode 100755index 00000000000..6c3401c9bf5--- /dev/null+++ b/src/scripts/rsyncd-start@@ -0,0 +1,101 @@+#!/bin/bash+#+# $Id: rsyncd-start.template,v 1.3 2005/06/20 20:43:55 billa Exp $+# $Source: /cvs/main/searching/solar-tools/rsyncd-start.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to start rsyncd on master SOLAR server++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++prog=${0##*/}+log=logs/rsyncd.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++resin_port=5051+rsyncd_port=`expr 10000 + ${resin_port}`++cd ${0%/*}/../..++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++function timeStamp+{+ date +'%Y/%m/%d %H:%M:%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++logMessage started by $oldwhoami+logMessage command: $0 $originalargs++if [[ ! -f rsyncd-enabled ]]+then+ logMessage rsyncd disabled+ exit 1+fi++if \+ rsync rsync://localhost:${rsyncd_port} >/dev/null 2>&1+then+ logMessage "rsyncd already running at port ${rsyncd_port}"+ exit 1+fi++rsync --daemon --port=${rsyncd_port} --config=conf/rsyncd.conf++# first make sure rsyncd is accepting connections+i=1+while \+ ! rsync rsync://localhost:${rsyncd_port} >/dev/null 2>&1+do+ if (( i++ > 15 ))+ then+ logMessage "rsyncd not accepting connections, exiting" >&2+ exit 2+ fi+ sleep 1+done++logMessage rsyncd started and accepting requests\ No newline at end of filediff --git a/src/scripts/rsyncd-stop b/src/scripts/rsyncd-stopnew file mode 100755index 00000000000..bfddab34805--- /dev/null+++ b/src/scripts/rsyncd-stop@@ -0,0 +1,100 @@+#!/bin/bash+#+# $Id: rsyncd-stop.template,v 1.3 2005/06/20 20:43:55 billa Exp $+# $Source: /cvs/main/searching/solar-tools/rsyncd-stop.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to stop rsyncd on master SOLAR server++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++prog=${0##*/}+log=logs/rsyncd.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++cd ${0%/*}/../..+SERVER_ROOT=$(pwd)++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++function timeStamp+{+ date +'%Y/%m/%d %H:%M:%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++logMessage stopped by $oldwhoami+logMessage command: $0 $originalargs++# get PID from file+pid=$(<$SERVER_ROOT/logs/rsyncd.pid)+if [[ -z $pid ]]+then+ logMessage "unable to get rsyncd's PID"+ exit 2+fi++kill $pid++# wait until rsyncd dies or we time out+dead=0+timer=0+timeout=300+while (( ! dead && timer < timeout ))+do+ if ps -eo pid | grep -q $pid+ then+ kill $pid+ (( timer++ ))+ sleep 1+ else+ dead=1+ fi+done+if ps -eo pid | grep -q $pid+then+ logMessage rsyncd failed to stop after $timeout seconds+ exit 3+fidiff --git a/src/scripts/snapcleaner b/src/scripts/snapcleanernew file mode 100755index 00000000000..b3a98dd4a51--- /dev/null+++ b/src/scripts/snapcleaner@@ -0,0 +1,137 @@+#!/bin/bash+#+# $Id: snapcleaner.template,v 1.7 2005/06/09 15:34:06 billa Exp $+# $Source: /cvs/main/searching/solar-tools/snapcleaner.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to clean up snapshots of a SOLAR Lucene collection.++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog -d <days> | -n <num> [ -v ]+ -d <days> cleanup snapshots more than <days> days old+ -n <num> keep the most most recent <num> number of snapshots and+ cleanup up the remaining ones that are not being pulled+ -v increase verbosity+"++unset days num verbose++# parse args+originalargs="$@"+while getopts d:n:v OPTION+do+ case $OPTION in+ d)+ days="$OPTARG"+ ;;+ n)+ num="$OPTARG"+ ;;+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++if [[ -z ${days} && -z ${num} ]]+then+ echo "$USAGE"+ exit 1+fi++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++function remove+{+ syncing=`ps -fwwwu app|grep rsync|grep -v grep|cut -f6 -d"/"|grep $1`+ if [[ -n $syncing ]]+ then+ logMessage $1 not removed - rsync in progress+ else+ logMessage removing snapshot $1+ /bin/rm -rf $1+ fi+}++cd ${0%/*}/../..+logMessage started by $oldwhoami+logMessage command: $0 $originalargs+start=`date +"%s"`++# trap control-c+trap 'echo "caught INT/TERM, exiting now but partial cleanup may have already occured";logExit aborted 13' INT TERM++if [[ -n ${days} ]]+then+ logMessage cleaning up snapshots more than ${days} days old+ for i in `find . -name "snapshot.*" -maxdepth 1 -mtime +${days} -print`+ do+ remove `basename $i`+ done+elif [[ -n ${num} ]]+then+ logMessage cleaning up all snapshots except for the most recent ${num} ones+ unset snapshots count+ snapshots=`ls -cd snapshot.* 2>/dev/null`+ if [[ $? == 0 ]]+ then+ count=`echo $snapshots|wc -w`+ startpos=`expr $num + 1`+ if [[ $count -gt $num ]]+ then+ for i in `echo $snapshots|cut -f${startpos}- -d" "`+ do+ remove $i+ done+ fi+ fi+fi++logExit ended 0++diff --git a/src/scripts/snapinstaller b/src/scripts/snapinstallernew file mode 100755index 00000000000..5a948933fa7--- /dev/null+++ b/src/scripts/snapinstaller@@ -0,0 +1,171 @@+#!/bin/bash+#+# $Id: snapinstaller.template,v 1.12 2005/06/09 17:19:34 billa Exp $+# $Source: /cvs/main/searching/solar-tools/snapinstaller.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to install a snapshot into place as the Lucene collection+# for a SOLAR server++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog -m master -p port [ -v ]+ -m master hostname of master server where snapshot stats are posted+ -p port port number of master server where snapshot stats are posted+ -v increase verbosity+"++cd ${0%/*}/../..+SERVER_ROOT=$(pwd)++unset masterHost masterPort verbose++# check for config file+confFile=${SERVER_ROOT}/conf/distribution.conf+if+ [[ ! -f $confFile ]]+then+ echo "unable to find configuration file: $confFile" >&2+ exit 1+fi+# source the config file+. $confFile++# parse args+originalargs="$@"+while getopts m:p:v OPTION+do+ case $OPTION in+ m)+ masterHost="$OPTARG"+ ;;+ p)+ masterPort="$OPTARG"+ ;;+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++MASTER_ROOT=/var/opt/resin3/${masterPort}++if [[ -z ${masterHost} ]]+then+ echo "name of master server missing in $confFile or command line."+ echo "$USAGE"+ exit 1+fi++if [[ -z ${masterPort} ]]+then+ echo "port number of master server missing in $confFile or command line."+ echo "$USAGE"+ exit 1+fi++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++logMessage started by $oldwhoami+logMessage command: $0 $originalargs+start=`date +"%s"`++# get directory name of latest snapshot+name=`ls -d snapshot.*|grep -v wip|sort -r|head -1`++# clean up after INT/TERM+trap 'echo "caught INT/TERM, exiting now but partial installation may have already occured";/bin/rm -rf index.tmp$$;logExit aborted 13' INT TERM++# is there a snapshot+if [[ "${name}" == "" ]]+then+ logMessage no shapshot available+ logExit ended 0+fi++# has snapshot already been installed+if [[ ${name} == `cat logs/snapshot.current 2>/dev/null` ]]+then+ logMessage latest snapshot ${name} already installed+ logExit ended 0+fi++# make sure master has directory for hold slaves stats/state+if+ ! ssh -o StrictHostKeyChecking=no ${masterHost} mkdir -p ${MASTER_ROOT}/logs/clients+then+ logMessage failed to ssh to master ${masterHost}, snapshot status not updated on master+fi++# install using hard links into temporary directory+# remove original index and then atomically copy new one into place+logMessage installing snapshot ${name}+cp -lr ${name}/ index.tmp$$+/bin/rm -rf index+mv -f index.tmp$$ index++# update distribution stats+echo ${name} > logs/snapshot.current++# push stats/state to master+if+ ! scp -q -o StrictHostKeyChecking=no logs/snapshot.current ${masterHost}:${MASTER_ROOT}/logs/clients/snapshot.current.`uname -n`+then+ logMessage failed to ssh to master ${masterHost}, snapshot status not updated on master+fi++# notify SOLAR to open a new Searcher+logMessage notifing SOLAR to open a new Searcher+scripts/solar/commit+if [[ $? != 0 ]]+then+ logMessage failed to connect to SOLAR server at port 5051+ logMessage snapshot installed but SOLAR server has not open a new Searcher+ logExit failed 1+fi++logExit ended 0diff --git a/src/scripts/snappuller b/src/scripts/snappullernew file mode 100755index 00000000000..2514c47f8c2--- /dev/null+++ b/src/scripts/snappuller@@ -0,0 +1,212 @@+#!/bin/bash+#+# $Id: snappuller.template,v 1.13 2005/07/20 18:38:49 billa Exp $+# $Source: /cvs/main/searching/solar-tools/snappuller.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to copy snapshots of a SOLAR Lucene collection from the master++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog -m master -p port [-n snapshot] [ -svz ]+ -m master hostname of master server from where to pull index snapshot+ -p port port number of master server from where to pull index snapshot+ -n snapshot pull a specific snapshot by name+ -s use the --size-only option with rsync+ -v increase verbosity (-vv show file transfer stats also)+ -z enable compression of data+"++unset masterHost masterPort name sizeonly stats verbose compress startStatus++cd ${0%/*}/../..+SERVER_ROOT=$(pwd)++# check for config file+confFile=${SERVER_ROOT}/conf/distribution.conf+if+ [[ ! -f $confFile ]]+then+ echo "unable to find configuration file: $confFile" >&2+ exit 1+fi+# source the config file+. $confFile++# parse args+originalargs="$@"+while getopts m:p:n:svz OPTION+do+ case $OPTION in+ m)+ masterHost="$OPTARG"+ ;;+ p)+ masterPort="$OPTARG"+ ;;+ n)+ name="$OPTARG"+ ;;+ s)+ sizeonly="--size-only"+ ;;+ v)+ [[ -n $verbose ]] && stats="--stats" || verbose=v+ ;;+ z)+ compress="z"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++MASTER_ROOT=/var/opt/resin3/${masterPort}++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+# push stats/state to master if necessary+ if [[ -n ${startStatus} ]]+ then+ scp -q -o StrictHostKeyChecking=no logs/snappuller.status ${masterHost}:${MASTER_ROOT}/logs/clients/snapshot.status.`uname -n`+ fi+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++if [[ -z ${masterHost} ]]+then+ echo "name of master server missing in $confFile or command line."+ echo "$USAGE"+ exit 1+fi++if [[ -z ${masterPort} ]]+then+ echo "port number of master server missing in $confFile or command line."+ echo "$USAGE"+ exit 1++fi+rsyncd_port=`expr 10000 + ${masterPort}`++logMessage started by $oldwhoami+logMessage command: $0 $originalargs+start=`date +"%s"`++if [[ ! -f ${prog}-enabled ]]+then+ logMessage snappuller disabled+ exit 1+fi++# make sure we can ssh to master+if+ ! ssh -o StrictHostKeyChecking=no ${masterHost} id 1>/dev/null 2>&1+then+ logMessage failed to ssh to master ${masterHost}+ exit 1+fi++# get directory name of latest snapshot if not specified on command line+if [[ -z ${name} ]]+then+ name=`ssh -o StrictHostKeyChecking=no ${masterHost} "ls -d ${MASTER_ROOT}/snapshot.* 2>/dev/null"|tail -1`+fi++# clean up after INT/TERM+trap 'echo cleaning up, please wait ...;/bin/rm -rf ${name} ${name}-wip;echo ${startStatus} aborted:$(timeStamp)>logs/snappuller.status;logExit aborted 13' INT TERM++if [[ -d ${name} || -d ${name}-wip || "${name}" == "" ]]+then+ logMessage no new snapshot available on ${masterHost}:${masterPort}+ logExit ended 0+fi++# take a snapshot of current index so that only modified files will be rsync-ed+# put the snapshot in the 'work-in-progress" directory to prevent it from+# being installed while the copying is still in progress+cp -lr index ${name}-wip+# force rsync of segments and .del files since we are doing size-only+if [[ -n ${sizeonly} ]]+then+ rm -f ${name}-wip/segments+ rm -f ${name}-wip/*.del+fi++logMessage pulling snapshot ${name}++# make sure master has directory for hold slaves stats/state+ssh -o StrictHostKeyChecking=no ${masterHost} mkdir -p ${MASTER_ROOT}/logs/clients++# start new distribution stats+rsyncStart=`date`+startTimestamp=`date -d "$rsyncStart" +'%Y%m%d-%H%M%S'`+rsyncStartSec=`date -d "$rsyncStart" +'%s'`+startStatus="rsync of `basename ${name}` started:$startTimestamp"+echo ${startStatus} > logs/snappuller.status+# push stats/state to master+scp -q -o StrictHostKeyChecking=no logs/snappuller.status ${masterHost}:${MASTER_ROOT}/logs/clients/snapshot.status.`uname -n`++# rsync over files that have changed+rsync -Wa${verbose}${compress} --delete ${sizeonly} \+${stats} rsync://${masterHost}:${rsyncd_port}/solar/`basename ${name}`/ `basename ${name}-wip`++rc=$?+rsyncEnd=`date`+endTimestamp=`date -d "$rsyncEnd" +'%Y%m%d-%H%M%S'`+rsyncEndSec=`date -d "$rsyncEnd" +'%s'`+elapsed=`expr $rsyncEndSec - $rsyncStartSec`+if [[ $rc != 0 ]]+then+ logMessage rsync failed+ /bin/rm -rf ${name}-wip+ echo ${startStatus} failed:$endTimestamp > logs/snappuller.status+ logExit failed 1+fi++# move into place atomically+mv ${name}-wip ${name}++# finish new distribution stats`+echo ${startStatus} ended:$endTimestamp rsync-elapsed:${elapsed} > logs/snappuller.status++logExit ended 0diff --git a/src/scripts/snappuller-disable b/src/scripts/snappuller-disablenew file mode 100755index 00000000000..fed1f965760--- /dev/null+++ b/src/scripts/snappuller-disable@@ -0,0 +1,89 @@+#!/bin/bash+#+# $Id: snappuller-disable.template,v 1.4 2005/06/20 20:43:55 billa Exp $+# $Source: /cvs/main/searching/solar-tools/snappuller-disable.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to disable snappuller++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/snappuller.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage disabled by $oldwhoami+logMessage command: $0 $originalargs+name=snappuller-enabled++if [[ -f ${name} ]]+then+ rm -f ${name}+else+ logMessage snappuller not currently enabled+ logExit exited 1+fi++logExit ended 0diff --git a/src/scripts/snappuller-enable b/src/scripts/snappuller-enablenew file mode 100755index 00000000000..b9f16c8d2b5--- /dev/null+++ b/src/scripts/snappuller-enable@@ -0,0 +1,89 @@+#!/bin/bash+#+# $Id: snappuller-enable.template,v 1.4 2005/06/20 20:43:56 billa Exp $+# $Source: /cvs/main/searching/solar-tools/snappuller-enable.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to enable snappuller++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/snappuller.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++unset verbose++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++start=`date +"%s"`++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++cd ${0%/*}/../..+logMessage enabled by $oldwhoami+logMessage command: $0 $originalargs+name=snappuller-enabled++if [[ -f ${name} ]]+then+ logMessage snappuller already currently enabled+ logExit exited 1+else+ touch ${name}+fi++logExit ended 0diff --git a/src/scripts/snapshooter b/src/scripts/snapshooternew file mode 100755index 00000000000..cb3175fd754--- /dev/null+++ b/src/scripts/snapshooter@@ -0,0 +1,124 @@+#!/bin/bash+#+# $Id: snapshooter.template,v 1.9 2005/06/09 15:34:07 billa Exp $+# $Source: /cvs/main/searching/solar-tools/snapshooter.template,v $+# $Name: r20050725_standardized_server_enabled $+#+# Shell script to take a snapshot of a SOLAR Lucene collection.++export PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH++# sudo to app user if necessary+if [[ $(whoami) != app ]]+then+ sudo -u app $0 "$@"+ exit $?+fi++oldwhoami=$(who -m | cut -d' ' -f1 | sed -e's/^.*!//')++if [[ "${oldwhoami}" == "" ]]+then+ oldwhoami=`ps h -Hfp $(pgrep -g0 ${0##*/}) | tail -1|cut -f1 -d" "`+fi++# set up variables+prog=${0##*/}+log=logs/${prog}.log++# define usage string+USAGE="\+usage: $prog [ -v ]+ -v increase verbosity+"++cd ${0%/*}/../..+SERVER_ROOT=$(pwd)++unset verbose++# check for config file+confFile=${SERVER_ROOT}/conf/distribution.conf+if+ [[ ! -f $confFile ]]+then+ echo "unable to find configuration file: $confFile" >&2+ exit 1+fi+# source the config file+. $confFile++if [[ "${solar_role}" == "slave" ]]+then+ echo "$prog disabled on slave server" >&2+ exit 1+fi++# parse args+originalargs="$@"+while getopts v OPTION+do+ case $OPTION in+ v)+ verbose="v"+ ;;+ *)+ echo "$USAGE"+ exit 1+ esac+done+shift $(( OPTIND - 1 ))++function timeStamp+{+ date +'%Y%m%d-%H%M%S'+}++function logMessage+{+ echo $(timeStamp) $@>>$log+ if [[ -n ${verbose} ]]+ then+ echo $@+ fi+}++function logExit+{+ end=`date +"%s"`+ diff=`expr $end - $start`+ echo "$(timeStamp) $1 (elapsed time: $diff sec)">>$log+ exit $2+}++logMessage started by $oldwhoami+logMessage command: $0 $originalargs+start=`date +"%s"`++name=snapshot.`date +"%Y%m%d%H%M%S"`+temp=temp-${name}++if [[ -d ${name} ]]+then+ logMessage snapshot directory ${name} already exists+ logExit aborted 1+fi++if [[ -d ${temp} ]]+then+ logMessage snapshoting of ${name} in progress+ logExit aborted 1+fi++# clean up after INT/TERM+trap 'echo cleaning up, please wait ...;/bin/rm -rf ${name} ${temp};logExit aborted 13' INT TERM++logMessage taking snapshot ${name}++# take a snapshot using hard links into temporary location+# then move it into place atomically+cp -lr index ${temp}+mv ${temp} ${name}++logExit ended 0+diff --git a/src/webapp/WEB-INF/web.xml b/src/webapp/WEB-INF/web.xmlnew file mode 100644index 00000000000..5620e5de0dc--- /dev/null+++ b/src/webapp/WEB-INF/web.xml@@ -0,0 +1,62 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- Tomcat fails if it can't find the DTD+<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN+" "http://java.sun.com/dtd/web-app_2_3.dtd" [+ <!ENTITY web.external.xml SYSTEM "../../../conf/solar/WEB-INF/web.external.xml">+]>+-->++<web-app>+ <!-- resin specific way to add to the webapps classpath -->+ <classpath id="../../conf/solar/WEB-INF/classes" />+ <classpath id="../../conf/solar/WEB-INF/lib" library-dir="true" />++ <!-- Use the default JDK5 XML implementation...+ Resin3 has some missing/incompatible xpath features. -->+ <system-property javax.xml.xpath.XPathFactory=+ "com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl"/>+ <system-property javax.xml.parsers.DocumentBuilderFactory=+ "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"/>+ <system-property javax.xml.parsers.SAXParserFactory=+ "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"/>++ <servlet>++ <servlet-name>SolrServer</servlet-name>+ <display-name>SOLR</display-name>+ <description>SOLR Server</description>+ <servlet-class>org.apache.solr.servlet.SolrServlet</servlet-class>+ <load-on-startup>0</load-on-startup>+ </servlet>+ <servlet-mapping>+ <servlet-name>SolrServer</servlet-name>+ <url-pattern>/select/*</url-pattern>+ </servlet-mapping>+ <servlet-mapping>+ <servlet-name>SolrServer</servlet-name>+ <url-pattern>/update/*</url-pattern>+ </servlet-mapping>++ <servlet>+ <servlet-name>solar-status</servlet-name>+ <jsp-file>/admin/solar-status.jsp</jsp-file>+ </servlet>+ <servlet-mapping>+ <servlet-name>solar-status</servlet-name>+ <url-pattern>/admin/solar-status</url-pattern>+ </servlet-mapping>++ <servlet>+ <servlet-name>ping</servlet-name>+ <jsp-file>/admin/ping.jsp</jsp-file>+ </servlet>+ <servlet-mapping>+ <servlet-name>ping</servlet-name>+ <url-pattern>/admin/ping</url-pattern>+ </servlet-mapping>++ <!-- doesn't seem to work with tomcat+ &web.external.xml;+ -->++</web-app>diff --git a/src/webapp/resources/admin/action.jsp b/src/webapp/resources/admin/action.jspnew file mode 100644index 00000000000..aabe11891dc--- /dev/null+++ b/src/webapp/resources/admin/action.jsp@@ -0,0 +1,156 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.File,+ java.net.InetAddress,+ java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<%@ page import="java.util.logging.Level"%>+<%@ page import="java.util.logging.Logger"%>+<%+ SolrCore core = SolrCore.getSolrCore();+ IndexSchema schema = core.getSchema();+ String collectionName = schema!=null ? schema.getName():"unknown";++ String action = request.getParameter("action");+ String logging = request.getParameter("log");+ String enableActionStatus = "";+ boolean isValid = false;+ boolean wasOk = true;++ String rootdir = "/var/opt/resin3/"+request.getServerPort();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ File enableFile = new File(rootdir + "/logs/server-enabled");++ if (action != null) {+ // Validate fname+ if ("Enable".compareTo(action) == 0) isValid = true;+ if ("Disable".compareTo(action) == 0) isValid = true;+ }+ if (logging != null) {+ action = "Set Log Level";+ isValid = true;+ }+ if (isValid) {+ if ("Enable".compareTo(action) == 0) {+ try {+ if (enableFile.createNewFile()) {+ enableActionStatus += "Enable Succeeded";+ } else {+ enableActionStatus += "Already Enabled";+ }+ } catch(Exception e) {+ enableActionStatus += "Enable Failed: " + e.toString();+ wasOk = false;+ }+ }+ if ("Disable".compareTo(action) == 0) {+ try {+ if (enableFile.delete()) {+ enableActionStatus = "Disable Succeeded";+ } else {+ enableActionStatus = "Already Disabled";+ }+ } catch(Exception e) {+ enableActionStatus += "Disable Failed: " + e.toString();+ wasOk = false;+ }+ }+ if (logging != null) {+ try {+ Logger log = SolrCore.log;+ Logger parent = log.getParent();+ while (parent != null) {+ log = parent;+ parent = log.getParent();+ }+ log.setLevel(Level.parse(logging));+ enableActionStatus = "Set Log Level (" + logging + ") Succeeded";+ } catch(Exception e) {+ enableActionStatus += "Set Log Level (" + logging + ") Failed: "+ + e.toString();+ wasOk = false;+ }+ }+ } else {+ enableActionStatus = "Illegal Action";+ }++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>+<%+ if (wasOk) {+%>+<meta http-equiv="refresh" content="4;url=index.jsp">+<%+ }+%>+<html>+<head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+ <link rel="icon" href="/favicon.ico" type="image/ico">+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico">+</head>+<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Action (<%= collectionName %>) - <%= action %></h1>+<%= hostname %> : <%= request.getServerPort() %>+<br clear="all">+<table>+ <tr>+ <td>+ <H3>Action:</H3>+ </td>+ <td>+ <%= action %><br>+ </td>+ </tr>+ <tr>+ <td>+ <H4>Result:</H4>+ </td>+ <td>+ <%= enableActionStatus %><br>+ </td>+ </tr>+</table>+<br>+<table>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <%= new Date().toString() %>+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start At: <%= startTime %>+ </td>+ </tr>+</table>+<br><br>+ <a href="/admin">Return to Admin Page</a>+</body>+</html>diff --git a/src/webapp/resources/admin/analysis.jsp b/src/webapp/resources/admin/analysis.jspnew file mode 100644index 00000000000..b592ddc094a--- /dev/null+++ b/src/webapp/resources/admin/analysis.jsp@@ -0,0 +1,451 @@+<%@ page import="org.apache.lucene.analysis.Analyzer,+ org.apache.lucene.analysis.Token,+ org.apache.lucene.analysis.TokenStream,+ org.apache.solr.analysis.TokenFilterFactory,+ org.apache.solr.analysis.TokenizerChain,+ org.apache.solr.analysis.TokenizerFactory,+ org.apache.solr.core.SolrConfig,+ org.apache.solr.core.SolrCore,+ org.apache.solr.schema.FieldType,+ org.apache.solr.schema.IndexSchema,org.apache.solr.schema.SchemaField+ "%>+<%@ page import="org.apache.solr.util.XML"%>+<%@ page import="javax.servlet.jsp.JspWriter"%>+<%@ page import="java.io.File"%>+<%@ page import="java.io.IOException"%>+<%@ page import="java.io.Reader"%>+<%@ page import="java.io.StringReader"%>+<%@ page import="java.net.InetAddress"%>+<%@ page import="java.net.UnknownHostException"%>+<%@ page import="java.util.*"%>+<!-- $Id: analysis.jsp,v 1.2 2005/09/20 18:23:30 yonik Exp $ -->+<!-- $Source: /cvs/main/searching/org.apache.solrolarServer/resources/admin/analysis.jsp,v $ -->+<!-- $Name: $ -->++<%+ SolrCore core = SolrCore.getSolrCore();+ IndexSchema schema = core.getSchema();++ String rootdir = "/var/opt/resin3/"+request.getServerPort();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ File enableFile = new File(rootdir + "/logs/server-enabled");+ boolean isEnabled = false;+ String enabledStatus = "";+ String enableActionStatus = "";+ String makeEnabled = "";+ String action = request.getParameter("action");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }+++ try {+ isEnabled = (enableFile.lastModified() > 0);+ enabledStatus = (isEnabled)+ ? "Enabled"+ : "Disabled";+ makeEnabled = (isEnabled)+ ? "Disable"+ : "Enable";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't check server-enabled file:" + e.toString());+ out.println("</ERROR>");+ }++ String collectionName = schema!=null ? schema.getName():"unknown";+ String hostname="localhost";+ String defaultSearch= SolrConfig.config.get("admin/defaultQuery","");+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>++<%+ String name = request.getParameter("name");+ if (name==null || name.length()==0) name="";+ String val = request.getParameter("val");+ if (val==null || val.length()==0) val="";+ String qval = request.getParameter("qval");+ if (qval==null || qval.length()==0) qval="";+ String verboseS = request.getParameter("verbose");+ boolean verbose = verboseS!=null && verboseS.equalsIgnoreCase("on");+ String qverboseS = request.getParameter("qverbose");+ boolean qverbose = qverboseS!=null && qverboseS.equalsIgnoreCase("on");+ String highlightS = request.getParameter("highlight");+ boolean highlight = highlightS!=null && highlightS.equalsIgnoreCase("on");+%>+++<html>+<head>+<link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+<link rel="icon" href="/favicon.ico" type="image/ico">+<link rel="shortcut icon" href="/favicon.ico" type="image/ico">+<title>SOLR Interface</title>+</head>++<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Interface (<%= collectionName %>) - <%= enabledStatus %></h1>+<%= hostname %> : <%= request.getServerPort() %>+<br clear="all">+++<h2>Field Analysis</h2>++<form method="GET" action="/admin/analysis.jsp">+<table>+<tr>+ <td>+ <strong>Field name</strong>+ </td>+ <td>+ <input name="name" type="text" value="<%= name %>">+ </td>+</tr>+<tr>+ <td>+ <strong>Field value (Index)</strong>+ <br/>+ verbose output+ <input name="verbose" type="checkbox"+ <%= verbose ? "checked=\"true\"" : "" %> >+ <br/>+ highlight matches+ <input name="highlight" type="checkbox"+ <%= highlight ? "checked=\"true\"" : "" %> >+ </td>+ <td>+ <textarea rows="3" cols="70" name="val"><%= val %></textarea>+ </td>+</tr>+<tr>+ <td>+ <strong>Field value (Query)</strong>+ <br/>+ verbose output+ <input name="qverbose" type="checkbox"+ <%= qverbose ? "checked=\"true\"" : "" %> >+ </td>+ <td>+ <textarea rows="1" cols="70" name="qval"><%= qval %></textarea>+ </td>+</tr>+<tr>++ <td>+ </td>++ <td>+ <input type="submit" value="analyze">+ </td>++</tr>+</table>+</form>+++<%+ SchemaField field=null;++ if (name!="") {+ try {+ field = schema.getField(name);+ } catch (Exception e) {+ out.println("<strong>Unknown Field " + name + "</strong>");+ }+ }++ if (field!=null) {+ HashSet<Tok> matches = null;+ if (qval!="" && highlight) {+ Reader reader = new StringReader(qval);+ Analyzer analyzer = field.getType().getQueryAnalyzer();+ TokenStream tstream = analyzer.tokenStream(field.getName(),reader);+ List<Token> tokens = getTokens(tstream);+ matches = new HashSet<Tok>();+ for (Token t : tokens) { matches.add( new Tok(t,0)); }+ }++ if (val!="") {+ out.println("<h3>Index Analyzer</h3>");+ doAnalyzer(out, field, val, false, verbose,matches);+ }+ if (qval!="") {+ out.println("<h3>Query Analyzer</h3>");+ doAnalyzer(out, field, qval, true, qverbose,null);+ }+ }++%>+++</body>+</html>+++<%!+ private static void doAnalyzer(JspWriter out, SchemaField field, String val, boolean queryAnalyser, boolean verbose, Set<Tok> match) throws Exception {+ Reader reader = new StringReader(val);++ FieldType ft = field.getType();+ Analyzer analyzer = queryAnalyser ?+ ft.getQueryAnalyzer() : ft.getAnalyzer();+ if (analyzer instanceof TokenizerChain) {+ TokenizerChain tchain = (TokenizerChain)analyzer;+ TokenizerFactory tfac = tchain.getTokenizerFactory();+ TokenFilterFactory[] filtfacs = tchain.getTokenFilterFactories();++ TokenStream tstream = tfac.create(reader);+ List<Token> tokens = getTokens(tstream);+ tstream = tfac.create(reader);+ if (verbose) {+ writeHeader(out, tfac.getClass(), tfac.getArgs());+ }++ writeTokens(out, tokens, ft, verbose, match);++ for (TokenFilterFactory filtfac : filtfacs) {+ if (verbose) {+ writeHeader(out, filtfac.getClass(), filtfac.getArgs());+ }++ final Iterator<Token> iter = tokens.iterator();+ tstream = filtfac.create( new TokenStream() {+ public Token next() throws IOException {+ return iter.hasNext() ? iter.next() : null;+ }+ }+ );+ tokens = getTokens(tstream);++ writeTokens(out, tokens, ft, verbose, match);+ }++ } else {+ TokenStream tstream = analyzer.tokenStream(field.getName(),reader);+ List<Token> tokens = getTokens(tstream);+ if (verbose) {+ writeHeader(out, analyzer.getClass(), new HashMap<String,String>());+ }+ writeTokens(out, tokens, ft, verbose, match);+ }+ }+++ static List<Token> getTokens(TokenStream tstream) throws IOException {+ List<Token> tokens = new ArrayList<Token>();+ while (true) {+ Token t = tstream.next();+ if (t==null) break;+ tokens.add(t);+ }+ return tokens;+ }+++ private static class Tok {+ Token token;+ int pos;+ Tok(Token token, int pos) {+ this.token=token;+ this.pos=pos;+ }++ public boolean equals(Object o) {+ return ((Tok)o).token.termText().equals(token.termText());+ }+ public int hashCode() {+ return token.termText().hashCode();+ }+ public String toString() {+ return token.termText();+ }+ }++ private static interface ToStr {+ public String toStr(Object o);+ }++ private static void printRow(JspWriter out, String header, List[] arrLst, ToStr converter, boolean multival, boolean verbose, Set<Tok> match) throws IOException {+ // find the maximum number of terms for any position+ int maxSz=1;+ if (multival) {+ for (List lst : arrLst) {+ maxSz = Math.max(lst.size(), maxSz);+ }+ }+++ for (int idx=0; idx<maxSz; idx++) {+ out.println("<tr>");+ if (idx==0 && verbose) {+ if (header != null) {+ out.print("<th NOWRAP rowspan=\""+maxSz+"\">");+ XML.escapeCharData(header,out);+ out.println("</th>");+ }+ }++ for (List<Tok> lst : arrLst) {+ if (lst.size() <= idx) continue;+ if (match!=null && match.contains(lst.get(idx))) {+ out.print("<td name=\"highlight\"");+ } else {+ out.print("<td name=\"debugdata\"");+ }++ if (idx==0 && lst.size()==1 && maxSz > 1) {+ out.print("rowspan=\""+maxSz+'"');+ }++ out.print('>');++ XML.escapeCharData(converter.toStr(lst.get(idx)), out);+ out.print("</td>");+ }++ out.println("</tr>");+ }++ }++++ static void writeHeader(JspWriter out, Class clazz, Map<String,String> args) throws IOException {+ out.print("<h4>");+ out.print(clazz.getName());+ XML.escapeCharData(" "+args,out);+ out.println("</h4>");+ }++++ // readable, raw, pos, type, start/end+ static void writeTokens(JspWriter out, List<Token> tokens, final FieldType ft, boolean verbose, Set<Tok> match) throws IOException {++ // Use a map to tell what tokens are in what positions+ // because some tokenizers/filters may do funky stuff with+ // very large increments, or negative increments.+ HashMap<Integer,List<Tok>> map = new HashMap<Integer,List<Tok>>();+ boolean needRaw=false;+ int pos=0;+ for (Token t : tokens) {+ if (!t.termText().equals(ft.indexedToReadable(t.termText()))) {+ needRaw=true;+ }++ pos += t.getPositionIncrement();+ List lst = map.get(pos);+ if (lst==null) {+ lst = new ArrayList(1);+ map.put(pos,lst);+ }+ Tok tok = new Tok(t,pos);+ lst.add(tok);+ }++ List<Tok>[] arr = (List<Tok>[])map.values().toArray(new ArrayList[map.size()]);++ /***+ // This generics version works fine with Resin, but fails with Tomcat 5.5+ // with java.lang.AbstractMethodError+ // at java.util.Arrays.mergeSort(Arrays.java:1284)+ // at java.util.Arrays.sort(Arrays.java:1223)+ Arrays.sort(arr, new Comparator<List<Tok>>() {+ public int compare(List<Tok> toks, List<Tok> toks1) {+ return toks.get(0).pos - toks1.get(0).pos;+ }+ }+ ***/+ Arrays.sort(arr, new Comparator() {+ public int compare(Object a, Object b) {+ List<Tok> toks = (List<Tok>)a;+ List<Tok> toks1 = (List<Tok>)b;+ return toks.get(0).pos - toks1.get(0).pos;+ }+ }++ );++ out.println("<table width=\"auto\" name=\"table\" border=\"1\">");++ if (verbose) {+ printRow(out,"term position", arr, new ToStr() {+ public String toStr(Object o) {+ return Integer.toString(((Tok)o).pos);+ }+ }+ ,false+ ,verbose+ ,null);+ }+++ printRow(out,"term text", arr, new ToStr() {+ public String toStr(Object o) {+ return ft.indexedToReadable( ((Tok)o).token.termText() );+ }+ }+ ,true+ ,verbose+ ,match+ );++ if (needRaw) {+ printRow(out,"raw text", arr, new ToStr() {+ public String toStr(Object o) {+ // todo: output in hex or something?+ // check if it's all ascii or not?+ return ((Tok)o).token.termText();+ }+ }+ ,true+ ,verbose+ ,match+ );+ }++ if (verbose) {+ printRow(out,"term type", arr, new ToStr() {+ public String toStr(Object o) {+ return ((Tok)o).token.type();+ }+ }+ ,true+ ,verbose,+ null+ );+ }++ if (verbose) {+ printRow(out,"source start,end", arr, new ToStr() {+ public String toStr(Object o) {+ Token t = ((Tok)o).token;+ return Integer.toString(t.startOffset()) + ',' + t.endOffset() ;+ }+ }+ ,true+ ,verbose+ ,null+ );+ }++ out.println("</table>");+ }++%>diff --git a/src/webapp/resources/admin/distributiondump.jsp b/src/webapp/resources/admin/distributiondump.jspnew file mode 100644index 00000000000..b710fc9c46e--- /dev/null+++ b/src/webapp/resources/admin/distributiondump.jsp@@ -0,0 +1,141 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.BufferedReader,+ java.io.File,+ java.io.FileReader,+ java.net.InetAddress,+ java.net.UnknownHostException,+ java.util.Date"%>+<%+ SolrCore core = SolrCore.getSolrCore();+ Integer port = new Integer(request.getServerPort());+ IndexSchema schema = core.getSchema();+ String collectionName = schema!=null ? schema.getName():"unknown";++ String rootdir = "/var/opt/resin3/"+port.toString();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}++ File slaveinfo = new File(rootdir + "/logs/snappuller.status");++ StringBuffer buffer = new StringBuffer();+ String mode = "";++ if (slaveinfo.canRead()) {+ // Slave instance+ mode = "Slave";+ File slavevers = new File(rootdir + "/logs/snapshot.current");+ BufferedReader inforeader = new BufferedReader(new FileReader(slaveinfo));+ BufferedReader versreader = new BufferedReader(new FileReader(slavevers));+ buffer.append("<tr>\n" ++ "<td>\n" ++ "Version:" ++ "</td>\n" ++ "<td>\n")+ .append( versreader.readLine())+ .append( "<td>\n" ++ "</td>\n" ++ "</tr>\n" ++ "<tr>\n" ++ "<td>\n" ++ "Status:" ++ "</td>\n" ++ "<td>\n")+ .append( inforeader.readLine())+ .append( "</td>\n" ++ "</tr>\n");+ } else {+ // Master instance+ mode = "Master";+ File masterdir = new File(rootdir + "/logs/clients");+ File[] clients = masterdir.listFiles();+ if (clients == null) {+ buffer.append("<tr>\n" ++ "<td>\n" ++ "</td>\n" ++ "<td>\n" ++ "No distribution info present" ++ "</td>\n" ++ "</tr>\n");+ } else {+ int i = 0;+ while (i < clients.length) {+ BufferedReader reader = new BufferedReader(new FileReader(clients[i]));+ buffer.append("<tr>\n" ++ "<td>\n" ++ "Client:" ++ "</td>\n" ++ "<td>\n")+ .append( clients[i].toString())+ .append( "</td>\n" ++ "</tr>\n" ++ "<tr>\n" ++ "<td>\n" ++ "</td>\n" ++ "<td>\n")+ .append( reader.readLine())+ .append( "</td>\n" ++ "</tr>\n" ++ "<tr>\n" ++ "</tr>\n");+ i++;+ }+ }+ }+%>+<html>+<head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+ <link rel="icon" href="/favicon.ico" type="image/ico">+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico">+</head>+<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Distribution Info (<%= collectionName %>)</h1>+<%= hostname %> : <%= port.toString() %>+<br clear="all">+<table>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <%= new Date().toString() %>+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start At: <%= startTime %>+ </td>+ </tr>+</table>+<br>+<h3><%= mode %> Status</h3>+<table>+<%= buffer %>+</table>+<br><br>+ <a href="/admin">Return to Admin Page</a>+</body>+</html>diff --git a/src/webapp/resources/admin/form.jsp b/src/webapp/resources/admin/form.jspnew file mode 100644index 00000000000..4d8ff74dfd3--- /dev/null+++ b/src/webapp/resources/admin/form.jsp@@ -0,0 +1,207 @@+<%@ page import="org.apache.solr.core.SolrConfig,+ org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.File+"%>+<%@ page import="java.net.InetAddress"%>+<%@ page import="java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<!-- $Id: form.jsp,v 1.6 2005/09/16 21:45:54 yonik Exp $ -->+<%+ SolrCore core = SolrCore.getSolrCore();+ Integer port = new Integer(request.getServerPort());+ IndexSchema schema = core.getSchema();++ String rootdir = "/var/opt/resin3/"+port.toString();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ File enableFile = new File(rootdir + "/logs/server-enabled");+ boolean isEnabled = false;+ String enabledStatus = "";+ String enableActionStatus = "";+ String makeEnabled = "";+ String action = request.getParameter("action");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ try {+ if (action != null) {+ if ("Enable".compareTo(action) == 0) {+ if (enableFile.createNewFile()) {+ enableActionStatus += "Enable Succeeded";+ } else {+ enableActionStatus += "Already Enabled)";+ }+ }+ if ("Disable".compareTo(action) == 0) {+ if (enableFile.delete()) {+ enableActionStatus = "Disable Succeeded";+ } else {+ enableActionStatus = "Already Disabled";+ }+ }+ }+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't "+action+" server-enabled file:" + e.toString());+ out.println("</ERROR>");+ }++ try {+ isEnabled = (enableFile.lastModified() > 0);+ enabledStatus = (isEnabled)+ ? "Enabled"+ : "Disabled";+ makeEnabled = (isEnabled)+ ? "Disable"+ : "Enable";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't check server-enabled file:" + e.toString());+ out.println("</ERROR>");+ }++ String collectionName = schema!=null ? schema.getName():"unknown";+ String hostname="localhost";+ String defaultSearch= SolrConfig.config.get("admin/defaultQuery","");+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>+++<html>+<head>+<link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+<link rel="icon" href="/favicon.ico" type="image/ico">+<link rel="shortcut icon" href="/favicon.ico" type="image/ico">+<title>SOLR Interface</title>+</head>++<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Interface (<%= collectionName %>) - <%= enabledStatus %></h1>+<%= hostname %> : <%= port.toString() %>+<br clear="all">+++<h2>/select mode</h2>++<form method="GET" action="/select/">+<table>+<tr>+ <td>+ <strong>SOLR/Lucene Statement</strong>+ </td>+ <td>+ <textarea rows="5" cols="60" name="q"></textarea>+ </td>+</tr>+<tr>+ <td>+ <strong>Return Number Found</strong>+ </td>+ <td>+ <input name="getnumfound" type="checkbox" > <em><font size="-1">(Option ignored by SOLR... the number of matching documents is always returned)</font></em>+ </td>+</tr>+<tr>+ <td>+ <strong>Protocol Version</strong>+ </td>+ <td>+ <input name="version" type="text" value="2.0">+ </td>+</tr>+<tr>+ <td>+ <strong>Start Row</strong>+ </td>+ <td>+ <input name="start" type="text" value="0">+ </td>+</tr>+<tr>+ <td>+ <strong>Maximum Rows Returned</strong>+ </td>+ <td>+ <input name="rows" type="text" value="10">+ </td>+</tr>+<tr>+ <td>+ <strong>Fields to Return</strong>+ </td>+ <td>+ <input name="fl" type="text" value="">+ </td>+</tr>+<tr>+ <td>+ <strong>Query Type</strong>+ </td>+ <td>+ <input name="qt" type="text" value="standard">+ </td>+</tr>+<tr>+ <td>+ <strong>Style Sheet</strong>+ </td>+ <td>+ <input name="stylesheet" type="text" value="">+ </td>+</tr>+<tr>+ <td>+ <strong>Indent XML</strong>+ </td>+ <td>+ <input name="indent" type="checkbox" checked="true">+ </td>+</tr>+<tr>+ <td>+ <strong>Debug: enable</strong>+ </td>+ <td>+ <input name="debugQuery" type="checkbox" >+ <em><font size="-1"> Note: do "view source" in your browser to see explain() correctly indented</font></em>+ </td>+</tr>+<tr>+ <td>+ <strong>Debug: explain others</strong>+ </td>+ <td>+ <input name="explainOther" type="text" >+ <em><font size="-1"> apply original query scoring to matches of this query</font></em>+ </td>+</tr>+<tr>+ <td>+ </td>+ <td>+ <input type="submit" value="search">+ </td>+</tr>+</table>+</form>+++</body>+</html>diff --git a/src/webapp/resources/admin/get-file.jsp b/src/webapp/resources/admin/get-file.jspnew file mode 100644index 00000000000..1e6c806be99--- /dev/null+++ b/src/webapp/resources/admin/get-file.jsp@@ -0,0 +1,45 @@+<%@ page import="org.apache.solr.core.Config,+ org.apache.solr.core.SolrConfig,+ java.io.FileInputStream,+ java.io.InputStream,+ java.io.InputStreamReader,+ java.io.Reader,+ java.util.StringTokenizer"%>+<%@ page contentType="text/plain;charset=UTF-8" language="java" %>+<%+ String fname = request.getParameter("file");+ String cloader = request.getParameter("classloader");+ String binary = request.getParameter("binary");+ String gettableFiles = SolrConfig.config.get("admin/gettableFiles","");+ StringTokenizer st = new StringTokenizer(gettableFiles);+ InputStream is;+ boolean isValid = false;+ if (fname != null) {+ // Validate fname+ while(st.hasMoreTokens()) {+ if (st.nextToken().compareTo(fname) == 0) isValid = true;+ }+ }+ if (isValid) {+ if (cloader!=null) {+ is= Config.openResource(fname);+ } else {+ is=new FileInputStream(fname);+ }+ if (binary != null) {+ // not implemented yet...+ } else {+ Reader input = new InputStreamReader(is);+ char[] buf = new char[4096];+ while (true) {+ int len = input.read(buf);+ if (len<=0) break;+ out.write(buf,0,len);+ }+ }+ } else {+ out.println("<ERROR>");+ out.println("Permission denied for file "+ fname);+ out.println("</ERROR>");+ }+%>diff --git a/src/webapp/resources/admin/get-properties.jsp b/src/webapp/resources/admin/get-properties.jspnew file mode 100644index 00000000000..3895b7d0fb4--- /dev/null+++ b/src/webapp/resources/admin/get-properties.jsp@@ -0,0 +1,9 @@+<%@ page import=""%>+<%@ page contentType="text/plain;charset=UTF-8" language="java" %>+<%+ java.util.Enumeration e = System.getProperties().propertyNames();+ while(e.hasMoreElements()) {+ String prop = (String)e.nextElement();+ out.println(prop + " = " + System.getProperty(prop));+ }+%>\ No newline at end of filediff --git a/src/webapp/resources/admin/index.jsp b/src/webapp/resources/admin/index.jspnew file mode 100644index 00000000000..184dd68897b--- /dev/null+++ b/src/webapp/resources/admin/index.jsp@@ -0,0 +1,220 @@+<%@ page import="org.apache.solr.core.SolrConfig,+ org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.File"%>+<%@ page import="java.net.InetAddress"%>+<%@ page import="java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<!-- $Id: index.jsp,v 1.26 2005/09/20 18:23:30 yonik Exp $ -->+<!-- $Source: /cvs/main/searching/SolrServer/resources/admin/index.jsp,v $ -->+<!-- $Name: $ -->++<%+ SolrCore core = SolrCore.getSolrCore();+ Integer port = new Integer(request.getServerPort());+ IndexSchema schema = core.getSchema();++ String rootdir = "/var/opt/resin3/"+port.toString();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ File enableFile = new File(rootdir + "/logs/server-enabled");+ boolean isEnabled = false;+ String enabledStatus = "";+ String enableActionStatus = "";+ String makeEnabled = "";+ String action = request.getParameter("action");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ try {+ if (action != null) {+ if ("Enable".compareTo(action) == 0) {+ if (enableFile.createNewFile()) {+ enableActionStatus += "Enable Succeeded";+ } else {+ enableActionStatus += "Already Enabled)";+ }+ }+ if ("Disable".compareTo(action) == 0) {+ if (enableFile.delete()) {+ enableActionStatus = "Disable Succeeded";+ } else {+ enableActionStatus = "Already Disabled";+ }+ }+ }+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't "+action+" server-enabled file:" + e.toString());+ out.println("</ERROR>");+ }++ try {+ isEnabled = (enableFile.lastModified() > 0);+ enabledStatus = (isEnabled)+ ? "Enabled"+ : "Disabled";+ makeEnabled = (isEnabled)+ ? "Disable"+ : "Enable";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't check server-enabled file:" + e.toString());+ out.println("</ERROR>");+ }++ String collectionName = schema!=null ? schema.getName():"unknown";+ String hostname="localhost";+ String defaultSearch= SolrConfig.config.get("admin/defaultQuery","");+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>+++<html>+<head>+<link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+<link rel="icon" href="/favicon.ico" type="image/ico"></link>+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico"></link>+<title>SOLR admin page</title>+</head>++<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Admin (<%= collectionName %>) - <%= enabledStatus %></h1>+<%= hostname %> : <%= port.toString() %>+<br clear="all">+<table>++<tr>+ <td>+ <h3>SOLR</h3>+ </td>+ <td>+ [<a href="/admin/solar-status">Status</a>]+ [<a href="/admin/get-file.jsp?file=solarconfig.xml&classloader=true">Config</a>]+ [<a href="/admin/get-file.jsp?file=conf/solar/WEB-INF/web.external.xml">web.external.xml</a>]+ [<a href="/admin/get-properties.jsp">Properties</a>]+ [<a href="/admin/raw-schema.jsp">Schema</a>]+ [<a href="/admin/analysis.jsp?highlight=on">Analysis</a>]+ <br>+ [<a href="/admin/registry.jsp">Info</a>]+ [<a href="/admin/stats.jsp">Statistics</a>]+ [<a href="/admin/distributiondump.jsp">Distribution</a>]+ [<a href="/admin/ping">Ping</a>]+ [<a href="/admin/logging.jsp">Logging</a>]+ </td>+</tr>++<tr>+ <td>+ <strong>Resin server:</strong><br>+ </td>+ <td>+ [<a href="/server-status">Status</a>]+ [<a href="/admin/get-file.jsp?file=conf/resin.conf">Config</a>]+ [<a href="/admin/threaddump.jsp">Thread Dump</a>]+ <%+ if (isEnabled) {+ %>+ [<a href="/admin/action.jsp?action=Disable">Disable</a>]+ <%+ } else {+ %>+ [<a href="/admin/action.jsp?action=Enable">Enable</a>]+ <%+ }+ %>+ </td>+</tr>++<tr>+ <td>+ <strong>Hardware:</strong><br>+ </td>+ <td>+ [<a href="http://playground.cnet.com/db/machines-match.php3?searchterm=<%= hostname %>&searchfield=hostorserial">Status</a>]+ [<a href="http://playground.cnet.com/db/machines-match.php3?searchterm=<%= hostname %>/t&searchfield=hostorserial">Traffic</a>]+ [<a href="http://monitor.cnet.com/orca_mon/?mgroup=prob&hours=48&hostname=<%= hostname %>">Problems</a>]+ </td>+</tr>++</table><P>+++<table>+<tr>+ <td>+ <h3>Make a Query</he>+ </td>+ <td>++ <td>+ [<a href="/admin/form.jsp">Full Interface</a>]+ </td>+</tr>+<tr>+ <td>+ StyleSheet:<br>Query:+ </td>+ <td colspan=2>+ <form method="GET" action="/select/">+ <input name="stylesheet" type="text" value=""><br>+ <textarea rows="4" cols="40" name="q"><%= defaultSearch %></textarea>+ <input name="version" type="hidden" value="2.0">+ <input name="start" type="hidden" value="0">+ <input name="rows" type="hidden" value="10">+ <input name="indent" type="hidden" value="on">+ <br><input type="submit" value="search">+ </form>+ </td>+</tr>+</table><p>++<table>+<tr>+ <td>+ <h3>Assistance</h3>+ </td>+ <td>+ [<a href="http://pi.cnet.com/solar/">Documentation</a>]+ [<a href="http://bugzilla.cnet.com/enter_bug.cgi?op_sys=All&product=PI-Solr&component=Operational">File a Bugzilla</a>]+ [<a href="mailto:[email protected]">Send Email</a>]+ <br>+ [<a href="http://lucene.apache.org/java/docs/queryparsersyntax.html">Lucene Query Syntax</a>]+ </td>+ <td rowspan="3">+ <a href="http://pi.cnet.com/"><img align="right" border=0 height="107" width="148" src="power.png"></a>+ </td>+</tr>+<tr>+ <td>+ </td>+ <td>+ Current Time: <%= new Date().toString() %>+ </td>+</tr>+<tr>+ <td>+ </td>+ <td>+ Server Start At: <%= startTime %>+ </td>+</tr>+</table>+</body>+</html>diff --git a/src/webapp/resources/admin/logging.jsp b/src/webapp/resources/admin/logging.jspnew file mode 100644index 00000000000..3050c9e098c--- /dev/null+++ b/src/webapp/resources/admin/logging.jsp@@ -0,0 +1,106 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.File,+ java.net.InetAddress,+ java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<%@ page import="java.util.logging.Level"%>+<%@ page import="java.util.logging.LogManager"%>+<%@ page import="java.util.logging.Logger"%>+<%+ SolrCore core = SolrCore.getSolrCore();+ Integer port = new Integer(request.getServerPort());+ IndexSchema schema = core.getSchema(); String collectionName = schema!=null ? schema.getName():"unknown";++ String rootdir = "/var/opt/resin3/"+port.toString();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ LogManager mgr = LogManager.getLogManager();+ Logger log = SolrCore.log;++ Logger parent = log.getParent();+ while(parent != null) {+ log = parent;+ parent = log.getParent();+ }+ Level lvl = log.getLevel();++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>+<html>+<head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+ <link rel="icon" href="/favicon.ico" type="image/ico">+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico">+</head>+<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Logging (<%= collectionName %>)</h1>+<%= hostname %> : <%= port.toString() %>+<br clear="all">+<table>+ <tr>+ <td>+ <H3>Log Level:</H3>+ </td>+ <td>+ <%= lvl.toString() %><br>+ </td>+ </tr>+ <tr>+ <td>+ Set Level+ </td>+ <td>+ [<a href=action.jsp?log=ALL>ALL</a>]+ [<a href=action.jsp?log=CONFIG>CONFIG</a>]+ [<a href=action.jsp?log=FINE>FINE</a>]+ [<a href=action.jsp?log=FINER>FINER</a>]+ [<a href=action.jsp?log=FINEST>FINEST</a>]+ [<a href=action.jsp?log=INFO>INFO</a>]+ [<a href=action.jsp?log=OFF>OFF</a>]+ [<a href=action.jsp?log=SEVERE>SEVERE</a>]+ [<a href=action.jsp?log=WARNING>WARNING</a>]+ </td>+ </tr>+</table>+<br>+<table>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <%= new Date().toString() %>+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start At: <%= startTime %>+ </td>+ </tr>+</table>+<br><br>+ <a href="/admin">Return to Admin Page</a>+</body>+</html>diff --git a/src/webapp/resources/admin/ping.jsp b/src/webapp/resources/admin/ping.jspnew file mode 100644index 00000000000..7c35c77aff3--- /dev/null+++ b/src/webapp/resources/admin/ping.jsp@@ -0,0 +1,34 @@+<%@ page import="org.apache.solr.core.SolrConfig,+ org.apache.solr.core.SolrCore,+ org.apache.solr.core.SolrException"%>+<%@ page import="org.apache.solr.request.LocalSolrQueryRequest"%>+<%@ page import="org.apache.solr.request.SolrQueryResponse"%>+<%@ page import="java.util.StringTokenizer"%>+<%+ SolrCore core = SolrCore.getSolrCore();++ String queryArgs = (request.getQueryString() == null) ?+ SolrConfig.config.get("admin/pingQuery","") : request.getQueryString();+ StringTokenizer qtokens = new StringTokenizer(queryArgs,"&");+ String tok;+ String query = null;+ while (qtokens.hasMoreTokens()) {+ tok = qtokens.nextToken();+ String[] split = tok.split("=");+ if (split[0].startsWith("q")) {+ query = split[1];+ }+ }+ LocalSolrQueryRequest req = new LocalSolrQueryRequest(core, query,null,0,1,LocalSolrQueryRequest.emptyArgs);+ SolrQueryResponse resp = new SolrQueryResponse();+ try {+ core.execute(req,resp);+ if (resp.getException() != null) {+ response.sendError(500, SolrException.toStr(resp.getException()));+ }+ } catch (Throwable t) {+ response.sendError(500, SolrException.toStr(t));+ } finally {+ req.close();+ }+%>diff --git a/src/webapp/resources/admin/raw-schema.jsp b/src/webapp/resources/admin/raw-schema.jspnew file mode 100644index 00000000000..1a3941c65d0--- /dev/null+++ b/src/webapp/resources/admin/raw-schema.jsp@@ -0,0 +1,16 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema"%>+<%@ page import="java.io.InputStreamReader"%>+<%@ page import="java.io.Reader"%>+<%@ page contentType="text/plain;charset=UTF-8" language="java" %>+<%+ SolrCore core = SolrCore.getSolrCore();+ IndexSchema schema = core.getSchema();+ Reader input = new InputStreamReader(schema.getInputStream());+ char[] buf = new char[4096];+ while (true) {+ int len = input.read(buf);+ if (len<=0) break;+ out.write(buf,0,len);+ }+%>\ No newline at end of filediff --git a/src/webapp/resources/admin/registry.jsp b/src/webapp/resources/admin/registry.jspnew file mode 100644index 00000000000..df97b724851--- /dev/null+++ b/src/webapp/resources/admin/registry.jsp@@ -0,0 +1,123 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.core.SolrInfoMBean,+ org.apache.solr.core.SolrInfoRegistry,+ org.apache.solr.schema.IndexSchema,+ java.io.File,+ java.net.InetAddress,+ java.net.URL"%>+<%@ page import="java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<%@ page import="java.util.Map"%>++<%@ page contentType="text/xml;charset=UTF-8" language="java" %>+<?xml-stylesheet type="text/xsl" href="/admin/registry.xsl"?>++<%+ SolrCore core = SolrCore.getSolrCore();+ IndexSchema schema = core.getSchema();+ String collectionName = schema!=null ? schema.getName():"unknown";+ Map<String, SolrInfoMBean> reg = SolrInfoRegistry.getRegistry();++ String rootdir = "/var/opt/resin3/"+request.getServerPort();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>++<solr>+ <schema><%= collectionName %></schema>+ <host><%= hostname %></host>+ <now><%= new Date().toString() %></now>+ <start><%= startTime %></start>+ <solr-info>+<%+for (SolrInfoMBean.Category cat : SolrInfoMBean.Category.values()) {+%>+ <<%= cat.toString() %>>+<%+ synchronized(reg) {+ for (Map.Entry<String,SolrInfoMBean> entry : reg.entrySet()) {+ String key = entry.getKey();+ SolrInfoMBean m = entry.getValue();++ if (m.getCategory() != cat) continue;++ String na = "None Provided";+ String name = (m.getName()!=null ? m.getName() : na);+ String vers = (m.getVersion()!=null ? m.getVersion() : na);+ String desc = (m.getDescription()!=null ? m.getDescription() : na);+ String cvsId = (m.getCvsId()!=null ? m.getCvsId() : na);+ String cvsSrc = (m.getCvsSource()!=null ? m.getCvsSource() : na);+ String cvsTag = (m.getCvsName()!=null ? m.getCvsName() : na);+%>+ <entry>+ <name>+ <%= key %>+ </name>+ <class>+ <%= name %>+ </class>+ <version>+ <%= vers %>+ </version>+ <description>+ <%= desc %>+ </description>+ <cvsid>+ <%= cvsId %>+ </cvsid>+ <cvssrc>+ <%= cvsSrc %>+ </cvssrc>+ <cvstag>+ <%= cvsTag %>+ </cvstag>+<%+ URL[] urls = m.getDocs();+ if ((urls != null) && (urls.length != 0)) {+%>+ <urls>+<%+ for (URL u : urls) {+%>+ <url>+ <%= u.toString() %>+ </url>+<%+ }+%>+ </urls>+<%+ }+%>+ </entry>+<%+ }+ }+%>+ </<%= cat.toString() %>>+<%+}+%>+ </solr-info>+</solr>diff --git a/src/webapp/resources/admin/registry.xsl b/src/webapp/resources/admin/registry.xslnew file mode 100644index 00000000000..04bc86b61e9--- /dev/null+++ b/src/webapp/resources/admin/registry.xsl@@ -0,0 +1,257 @@+<?xml version="1.0" encoding="utf-8"?>++<!-- $Id: registry.xsl,v 1.6 2005/06/07 15:53:35 ronp Exp $ -->+<!-- $Source: /cvs/main/searching/org.apache.solrSolarServer/resources/admin/registry.xsl,v $ -->+<!-- $Name: $ -->++<xsl:stylesheet+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"+ version="1.0">+++ <xsl:output+ method="html"+ indent="yes"+ doctype-public="-//W3C//DTD HTML 4.01//EN"+ doctype-system="http://www.w3.org/TR/html4/strict.dtd" />+++ <xsl:template match="/">+ <html>+ <head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css"></link>+ <link rel="icon" href="/favicon.ico" type="image/ico"></link>+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico"></link>+ <title>SOLR Info</title>+ </head>+ <body>+ <a href="/admin/">+ <img border="0" align="right" height="88" width="215" src="/admin/solr-head.gif" alt="SOLR">+ </img>+ </a>+ <h1>SOLR Info (<xsl:value-of select="solr/schema" />)</h1>+ <xsl:value-of select="solr/host" />+ <br clear="all" />+ <xsl:apply-templates/>+ <br /><br />+ <a href="/admin">Return to Admin Page</a>+ </body>+ </html>+ </xsl:template>++ <xsl:template match="solr">+ <table>+ <tr>+ <td>+ <H3>Category</H3>+ </td>+ <td>+ [<a href="#core">Core</a>]+ [<a href="#cache">Cache</a>]+ [<a href="#query">Query</a>]+ [<a href="#update">Update</a>]+ [<a href="#other">Other</a>]+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <xsl:value-of select="now" />+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start Time:<xsl:value-of select="start" />+ </td>+ </tr>+ </table>+ <xsl:apply-templates/>+ </xsl:template>++ <xsl:template match="solr/schema" />++ <xsl:template match="solr/host" />++ <xsl:template match="solr/now" />++ <xsl:template match="solr/start" />++ <xsl:template match="solr/solr-info">+ <xsl:apply-templates/>+ </xsl:template>++ <xsl:template match="solr/solr-info/CORE">+ <br />+ <a name="core"><h2>Core</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/CORE/entry">+ <xsl:for-each select="*">+ <tr>+ <td align="right">+ <strong><xsl:value-of select="name()"/>: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="."/> </tt>+ </td>+ </tr>+ </xsl:for-each>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/CACHE">+ <br />+ <a name="cache"><h2>Cache</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/CACHE/entry">+ <xsl:for-each select="*">+ <tr>+ <td align="right">+ <strong><xsl:value-of select="name()"/>: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="."/> </tt>+ </td>+ </tr>+ </xsl:for-each>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/QUERYHANDLER">+ <br />+ <a name="query"><h2>Query Handlers</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/QUERYHANDLER/entry">+ <xsl:for-each select="*">+ <tr>+ <td align="right">+ <strong><xsl:value-of select="name()"/>: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="."/> </tt>+ </td>+ </tr>+ </xsl:for-each>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/UPDATEHANDLER">+ <br />+ <a name="update"><h2>Update Handlers</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/UPDATEHANDLER/entry">+ <xsl:for-each select="*">+ <tr>+ <td align="right">+ <strong><xsl:value-of select="name()"/>: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="."/> </tt>+ </td>+ </tr>+ </xsl:for-each>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/OTHER">+ <br />+ <a name="other"><h2>Other</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/OTHER/entry">+ <xsl:for-each select="*">+ <tr>+ <td align="right">+ <strong><xsl:value-of select="name()"/>: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="."/> </tt>+ </td>+ </tr>+ </xsl:for-each>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>+++</xsl:stylesheet>diff --git a/src/webapp/resources/admin/solar-status.jsp b/src/webapp/resources/admin/solar-status.jspnew file mode 100644index 00000000000..ae9548ac1c2--- /dev/null+++ b/src/webapp/resources/admin/solar-status.jsp@@ -0,0 +1,62 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.File,+ java.net.InetAddress,+ java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<%--+ Created by IntelliJ IDEA.+ User: yonik+ Date: Oct 14, 2004+ Time: 2:40:56 PM+ To change this template use File | Settings | File Templates.+--%>+<%@ page contentType="text/xml;charset=UTF-8" language="java" %>++<?xml-stylesheet type="text/xsl" href="/admin/status.xsl"?>++<%+ SolrCore core = SolrCore.getSolrCore();+ IndexSchema schema = core.getSchema();+ String collectionName = schema!=null ? schema.getName():"unknown";++ String rootdir = "/var/opt/resin3/"+request.getServerPort();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>+<solr>+ <schema><%= collectionName %></schema>+ <host><%= hostname %> : <%= request.getServerPort() %></host>+ <now><%= new Date().toString() %></now>+ <start><%= startTime %></start>+ <status>+ <cvsId><%= core.cvsId %></cvsId>+ <cvsSource><%= core.cvsSource %></cvsSource>+ <cvsTag><%= core.cvsTag %></cvsTag>+ <state>IN_SERVICE</state>+ <schemaFile>schema.xml</schemaFile>+ <schemaName><%= schema.getName() %></schemaName>+ <indexDir><%= core.getDir() %></indexDir>+ <maxDoc><%= core.maxDoc() %></maxDoc>+ </status>+</solr>diff --git a/src/webapp/resources/admin/solr-admin.css b/src/webapp/resources/admin/solr-admin.cssnew file mode 100644index 00000000000..c2ecc92c4ac--- /dev/null+++ b/src/webapp/resources/admin/solr-admin.css@@ -0,0 +1,133 @@+++h1, h2, h3, h4, h5 {+ display: block;+ font-family: ITC Officina Sans Book, Terminator Two, Helvetica, Arial, sans-serif;+ font-style: bold;+ margin: 0;+}++strong {+ font-family: ITC Officina Sans Book, Terminator Two, Helvetica, Arial, sans-serif;+ font-style: bold;+ margin: 0;+}++input[type="text"], textarea {+ color: black;+ border: 2px inset #ff9933;+ background-color: #ffffff;+}++input[type="submit"] {+ font-family: ITC Officina Sans Book, Helvetica, Arial, sans-serif;+ font-style: bold;+ font-size: 11;+ text-transform: capitalize;+ color: black;+ background-color: #dddddd;+ border: groove #ff9933;+}++input[type="submit"]:hover {+ color: #0000ff;+ border: groove #0000ff;+}+++body {+ background-color: #bbbbbb;+}++table {+ display: table;+ background-color: #FAF7E4;+ width: 100%;+ border-top: 4px solid #666666;+ border-left: 2px solid #666666;+ text-align: left;+ vertical-align: top;+ cellpadding-right: 8px;+}++table[name="responseHeader"] {+ width: auto;+}++table[name="table"] {+ width: auto;+}++table {+ border-collapse: collapse+}++tr {+ border-bottom: 1px solid #ff9933;+}+++tr > td:first-child {+ width: 30%;+}++tr > td[name="debugdata"] {+ width: auto;+}++tr > td[name="highlight"]:first-child {+ width: auto;+ background: #ccccff;+}++tr > td[name="responseHeader"]:first-child {+ width: auto;+ text-align: right;+}++tr > td[name="responseHeader"] + td {+ text-align: left;+ font-family: Courier;+}+++td {+ text-align: left;+ vertical-align: top;+}++td[name="highlight"] {+ width: auto;+ background: #ccccff;+}+++a {+ text-decoration: none;+ font-weight: bold;+ font-size: 11px;+ background: #FAF7E4;+ text-transform: uppercase;+}++a:link {+ color: #0000aa;+}++a:visited {+ color: #0000ff;+}++a:active {+ color: #4444ff;+}++a:hover {+ color: #0000ff;+ background: #ccccff;+}++a:offsite {+ color: #0000aa;+}+diff --git a/src/webapp/resources/admin/solr-head.gif b/src/webapp/resources/admin/solr-head.gifnew file mode 100644index 00000000000..4660ecb0030Binary files /dev/null and b/src/webapp/resources/admin/solr-head.gif differdiff --git a/src/webapp/resources/admin/solr-head.png b/src/webapp/resources/admin/solr-head.pngnew file mode 100644index 00000000000..103c9ea1ea8Binary files /dev/null and b/src/webapp/resources/admin/solr-head.png differdiff --git a/src/webapp/resources/admin/solr-lowercase.gif b/src/webapp/resources/admin/solr-lowercase.gifnew file mode 100644index 00000000000..6822920a343Binary files /dev/null and b/src/webapp/resources/admin/solr-lowercase.gif differdiff --git a/src/webapp/resources/admin/solr-lowercase.png b/src/webapp/resources/admin/solr-lowercase.pngnew file mode 100644index 00000000000..0fe4e94cc3cBinary files /dev/null and b/src/webapp/resources/admin/solr-lowercase.png differdiff --git a/src/webapp/resources/admin/stats.jsp b/src/webapp/resources/admin/stats.jspnew file mode 100644index 00000000000..607140374e6--- /dev/null+++ b/src/webapp/resources/admin/stats.jsp@@ -0,0 +1,109 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.core.SolrInfoMBean,+ org.apache.solr.core.SolrInfoRegistry,+ org.apache.solr.schema.IndexSchema,+ org.apache.solr.util.NamedList,+ java.io.File"%>+<%@ page import="java.net.InetAddress"%>+<%@ page import="java.net.UnknownHostException"%>+<%@ page import="java.util.Date"%>+<%@ page import="java.util.Map"%>++<%@ page contentType="text/xml;charset=UTF-8" language="java" %>+<?xml-stylesheet type="text/xsl" href="/admin/stats.xsl"?>++<%+ SolrCore core = SolrCore.getSolrCore();+ Integer port = new Integer(request.getServerPort());+ IndexSchema schema = core.getSchema();+ String collectionName = schema!=null ? schema.getName():"unknown";+ Map<String, SolrInfoMBean> reg = SolrInfoRegistry.getRegistry();++ String rootdir = "/var/opt/resin3/"+port.toString();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}+%>++<solr>+ <schema><%= collectionName %></schema>+ <host><%= hostname %></host>+ <now><%= new Date().toString() %></now>+ <start><%= startTime %></start>+ <solr-info>+<%+for (SolrInfoMBean.Category cat : SolrInfoMBean.Category.values()) {+%>+ <<%= cat.toString() %>>+<%+ synchronized(reg) {+ for (Map.Entry<String,SolrInfoMBean> entry : reg.entrySet()) {+ String key = entry.getKey();+ SolrInfoMBean m = entry.getValue();++ if (m.getCategory() != cat) continue;++ NamedList nl = m.getStatistics();+ if ((nl != null) && (nl.size() != 0)) {+ String na = "None Provided";+ String name = (m.getName()!=null ? m.getName() : na);+ String vers = (m.getVersion()!=null ? m.getVersion() : na);+ String desc = (m.getDescription()!=null ? m.getDescription() : na);+%>+ <entry>+ <name>+ <%= key %>+ </name>+ <class>+ <%= name %>+ </class>+ <version>+ <%= vers %>+ </version>+ <description>+ <%= desc %>+ </description>+ <stats>+<%+ for (int i = 0; i < nl.size() ; i++) {+%>+ <stat name="<%= nl.getName(i) %>" >+ <%= nl.getVal(i).toString() %>+ </stat>+<%+ }+%>+ </stats>+ </entry>+<%+ }+%>+<%+ }+ }+%>+ </<%= cat.toString() %>>+<%+}+%>+ </solr-info>+</solr>diff --git a/src/webapp/resources/admin/stats.xsl b/src/webapp/resources/admin/stats.xslnew file mode 100644index 00000000000..b0188c2c38f--- /dev/null+++ b/src/webapp/resources/admin/stats.xsl@@ -0,0 +1,431 @@+<?xml version="1.0" encoding="utf-8"?>++<!-- $Id: stats.xsl,v 1.6 2005/06/13 15:38:45 ronp Exp $ -->+<!-- $Source: /cvs/main/searching/org.apache.solrSolarServer/resources/admin/stats.xsl,v $ -->+<!-- $Name: $ -->++<xsl:stylesheet+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"+ version="1.0">+++ <xsl:output+ method="html"+ indent="yes"+ doctype-public="-//W3C//DTD HTML 4.01//EN"+ doctype-system="http://www.w3.org/TR/html4/strict.dtd" />+++ <xsl:template match="/">+ <html>+ <head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css"></link>+ <link rel="icon" href="/favicon.ico" type="image/ico"></link>+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico"></link>+ <title>SOLR Statistics</title>+ </head>+ <body>+ <a href="/admin/">+ <img border="0" align="right" height="88" width="215" src="/admin/solr-head.gif" alt="SOLR">+ </img>+ </a>+ <h1>SOLR Statistics (<xsl:value-of select="solr/schema" />)</h1>+ <xsl:value-of select="solr/host" />+ <br clear="all" />+ <xsl:apply-templates/>+ <br /><br />+ <a href="/admin">Return to Admin Page</a>+ </body>+ </html>+ </xsl:template>++ <xsl:template match="solr">+ <table>+ <tr>+ <td>+ <H3>Category</H3>+ </td>+ <td>+ [<a href="#core">Core</a>]+ [<a href="#cache">Cache</a>]+ [<a href="#query">Query</a>]+ [<a href="#update">Update</a>]+ [<a href="#other">Other</a>]+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <xsl:value-of select="now" />+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start Time: <xsl:value-of select="start" />+ </td>+ </tr>+ </table>+ <xsl:apply-templates/>+ </xsl:template>++ <xsl:template match="solr/schema" />++ <xsl:template match="solr/host" />++ <xsl:template match="solr/now" />++ <xsl:template match="solr/start" />++ <xsl:template match="solr/solr-info">+ <xsl:apply-templates/>+ </xsl:template>++ <xsl:template match="solr/solr-info/CORE">+ <br />+ <a name="core"><h2>Core</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/CORE/entry">+ <tr>+ <td align="right">+ <strong>name: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="name"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>class: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="class"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>version: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="version"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>description: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="description"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>stats: </strong>+ </td>+ <td>+ <xsl:for-each select="stats/stat[@name]">+ <xsl:value-of select="@name"/>+ <xsl:text> : </xsl:text>+ <xsl:variable name="name" select="@name" />+ <xsl:value-of select="." /><br />+ </xsl:for-each>+ </td>+ </tr>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/CACHE">+ <br />+ <a name="cache"><h2>Cache</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/CACHE/entry">+ <tr>+ <td align="right">+ <strong>name: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="name"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>class: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="class"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>version: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="version"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>description: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="description"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>stats: </strong>+ </td>+ <td>+ <xsl:for-each select="stats/stat[@name]">+ <xsl:value-of select="@name"/>+ <xsl:text> : </xsl:text>+ <xsl:variable name="name" select="@name" />+ <xsl:value-of select="." /><br />+ </xsl:for-each>+ </td>+ </tr>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/QUERYHANDLER">+ <br />+ <a name="query"><h2>Query Handlers</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/QUERYHANDLER/entry">+ <tr>+ <td align="right">+ <strong>name: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="name"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>class: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="class"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>version: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="version"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>description: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="description"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>stats: </strong>+ </td>+ <td>+ <xsl:for-each select="stats/stat[@name]">+ <xsl:value-of select="@name"/>+ <xsl:text> : </xsl:text>+ <xsl:variable name="name" select="@name" />+ <xsl:value-of select="." /><br />+ </xsl:for-each>+ </td>+ </tr>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/UPDATEHANDLER">+ <br />+ <a name="update"><h2>Update Handlers</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/UPDATEHANDLER/entry">+ <tr>+ <td align="right">+ <strong>name: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="name"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>class: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="class"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>version: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="version"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>description: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="description"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>stats: </strong>+ </td>+ <td>+ <xsl:for-each select="stats/stat[@name]">+ <xsl:value-of select="@name"/>+ <xsl:text> : </xsl:text>+ <xsl:variable name="name" select="@name" />+ <xsl:value-of select="." /><br />+ </xsl:for-each>+ </td>+ </tr>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++ <xsl:template match="solr/solr-info/OTHER">+ <br />+ <a name="other"><h2>Other</h2></a>+ <table>+ <tr>+ <td align="right">+  + </td>+ <td>+ </td>+ </tr>+ <xsl:apply-templates/>+ </table>+ </xsl:template>++ <xsl:template match="solr/solr-info/OTHER/entry">+ <tr>+ <td align="right">+ <strong>name: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="name"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>class: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="class"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>version: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="version"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>description: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="description"/> </tt>+ </td>+ </tr>+ <tr>+ <td align="right">+ <strong>stats: </strong>+ </td>+ <td>+ <xsl:for-each select="stats/stat[@name]">+ <xsl:value-of select="@name"/>+ <xsl:text> : </xsl:text>+ <xsl:variable name="name" select="@name" />+ <xsl:value-of select="." /><br />+ </xsl:for-each>+ </td>+ </tr>+ <tr>+ <td align="right">+ </td>+ <td>+ </td>+ </tr>+ </xsl:template>++</xsl:stylesheet>diff --git a/src/webapp/resources/admin/status.xsl b/src/webapp/resources/admin/status.xslnew file mode 100644index 00000000000..e0794c1e011--- /dev/null+++ b/src/webapp/resources/admin/status.xsl@@ -0,0 +1,87 @@+<?xml version="1.0" encoding="utf-8"?>++<!-- $Id: status.xsl,v 1.4 2005/05/31 20:34:42 ronp Exp $ -->+<!-- $Source: /cvs/main/searching/org.apache.solrSolarServer/resources/admin/status.xsl,v $ -->+<!-- $Name: $ -->++<xsl:stylesheet+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"+ version="1.0">+++ <xsl:output+ method="html"+ indent="yes"+ doctype-public="-//W3C//DTD HTML 4.01//EN"+ doctype-system="http://www.w3.org/TR/html4/strict.dtd" />++ <xsl:template match="/">+ <html>+ <head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css"></link>+ <link rel="icon" href="/favicon.ico" type="image/ico"></link>+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico"></link>+ <title>SOLR Status</title>+ </head>+ <body>+ <a href="/admin/">+ <img border="0" align="right" height="88" width="215" src="/admin/solr-head.gif" alt="SOLR">+ </img>+ </a>+ <h1>SOLR Status (<xsl:value-of select="solr/schema" />)</h1>+ <xsl:value-of select="solr/host" />+ <br clear="all" />+ <xsl:apply-templates/>+ <br /><br />+ <a href="/admin">Return to Admin Page</a>+ </body>+ </html>+ </xsl:template>++ <xsl:template match="solr">+ <table>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <xsl:value-of select="now" />+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start Time: <xsl:value-of select="start" />+ </td>+ </tr>+ </table>+ <xsl:apply-templates/>+ </xsl:template>++ <xsl:template match="solr/schema" />++ <xsl:template match="solr/host" />++ <xsl:template match="solr/now" />++ <xsl:template match="solr/start" />++ <xsl:template match="solr/status">+ <br clear="all" />+ <h2>status</h2>+ <table>+ <xsl:for-each select="*">+ <tr>+ <td align="right">+ <strong><xsl:value-of select="name()"/>: </strong>+ </td>+ <td>+ <tt><xsl:value-of select="."/> </tt>+ </td>+ </tr>+ </xsl:for-each>+ </table>+ </xsl:template>+++</xsl:stylesheet>diff --git a/src/webapp/resources/admin/tabular.xsl b/src/webapp/resources/admin/tabular.xslnew file mode 100644index 00000000000..c11ddd80c91--- /dev/null+++ b/src/webapp/resources/admin/tabular.xsl@@ -0,0 +1,125 @@+<?xml version="1.0" encoding="utf-8"?>++<!-- $Id: tabular.xsl,v 1.2 2005/05/31 20:35:18 ronp Exp $ -->+<!-- $Source: /cvs/main/searching/org.apache.solrSolarServer/resources/admin/tabular.xsl,v $ -->+<!-- $Name: $ -->+++<xsl:stylesheet+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"+ version="1.0">+++ <xsl:output+ method="html"+ indent="yes"+ doctype-public="-//W3C//DTD HTML 4.01//EN"+ doctype-system="http://www.w3.org/TR/html4/strict.dtd" />+++ <xsl:template match="/">+ <html>+ <head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css"></link>+ <link rel="icon" href="/favicon.ico" type="image/ico"></link>+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico"></link>+ <title>SOLR Search Results</title>+ </head>+ <body>+ <a href="/admin/">+ <img border="0" align="right" height="88" width="215" src="/admin/solr-head.gif" alt="SOLR">+ </img>+ </a>+ <h1>SOLR Search Results</h1>+ <br clear="all" />+ <xsl:apply-templates/>+ <br /><br />+ <a href="/admin">Return to Admin Page</a>+ </body>+ </html>+ </xsl:template>+++ <xsl:template match="responseHeader">+ <table name="responseHeader">+ <xsl:apply-templates/>+ </table>+ </xsl:template>+++ <xsl:template match="status">+ <tr>+ <td name="responseHeader"><strong>Status: </strong></td>+ <td><xsl:value-of select="."></xsl:value-of></td>+ </tr>+ </xsl:template>+++ <xsl:template match="numFields">+ <tr>+ <td name="responseHeader"><strong>Number of Fields: </strong></td>+ <td><xsl:value-of select="."></xsl:value-of></td>+ </tr>+ </xsl:template>+++ <xsl:template match="numRecords">+ <tr>+ <td name="responseHeader"><strong>Records Returned: </strong></td>+ <td><xsl:value-of select="."></xsl:value-of></td>+ </tr>+ </xsl:template>+++ <xsl:template match="numFound">+ <tr>+ <td name="responseHeader"><strong>Records Found: </strong></td>+ <td><xsl:value-of select="."></xsl:value-of></td>+ </tr>+ </xsl:template>+++ <xsl:template match="QTime">+ <tr>+ <td name="responseHeader"><strong>Query time: </strong></td>+ <td><xsl:value-of select="."></xsl:value-of>(ms)</td>+ </tr>+ </xsl:template>++ <!-- YCS.. match everything. How to match only what is not+ matched above???+ -->+ <xsl:template match="responseHeader/*">+ <tr>+ <td name="responseHeader"><strong><xsl:value-of select="name(.)"></xsl:value-of>: </strong></td>+ <td><xsl:value-of select="."></xsl:value-of></td>+ </tr>+ </xsl:template>++ <xsl:template match="responseBody">+ <br></br><br></br>+ <table border="2">++ <!-- table headers -->+ <tr>+ <xsl:for-each select="record[1]/field">+ <th><xsl:value-of select="name"></xsl:value-of></th>+ </xsl:for-each>+ </tr>++ <!-- table rows -->+ <xsl:for-each select="record">+ <tr>+ <xsl:for-each select="field">+ <td><xsl:value-of select="value"></xsl:value-of> </td>+ </xsl:for-each>+ </tr>+ </xsl:for-each>++ </table>+++ </xsl:template>+++</xsl:stylesheet>diff --git a/src/webapp/resources/admin/threaddump.jsp b/src/webapp/resources/admin/threaddump.jspnew file mode 100644index 00000000000..51df1de7c12--- /dev/null+++ b/src/webapp/resources/admin/threaddump.jsp@@ -0,0 +1,118 @@+<%@ page import="org.apache.solr.core.SolrCore,+ org.apache.solr.schema.IndexSchema,+ java.io.BufferedReader,+ java.io.File,+ java.io.FileReader,+ java.net.InetAddress,+ java.net.UnknownHostException,+ java.util.Date"%>+<%+ SolrCore core = SolrCore.getSolrCore();+ Integer port = new Integer(request.getServerPort());+ IndexSchema schema = core.getSchema();+ String collectionName = schema!=null ? schema.getName():"unknown";++ String rootdir = "/var/opt/resin3/"+port.toString();+ File pidFile = new File(rootdir + "/logs/resin.pid");+ String startTime = "";++ try {+ startTime = (pidFile.lastModified() > 0)+ ? new Date(pidFile.lastModified()).toString()+ : "No Resin Pid found (logs/resin.pid)";+ } catch (Exception e) {+ out.println("<ERROR>");+ out.println("Couldn't open Solr pid file:" + e.toString());+ out.println("</ERROR>");+ }++ String hostname="localhost";+ try {+ InetAddress addr = InetAddress.getLocalHost();+ // Get IP Address+ byte[] ipAddr = addr.getAddress();+ // Get hostname+ // hostname = addr.getHostName();+ hostname = addr.getCanonicalHostName();+ } catch (UnknownHostException e) {}++ File getinfo = new File(rootdir + "/logs/jvm.log");+%>+<html>+<head>+ <link rel="stylesheet" type="text/css" href="/admin/solr-admin.css">+ <link rel="icon" href="/favicon.ico" type="image/ico">+ <link rel="shortcut icon" href="/favicon.ico" type="image/ico">+</head>+<body>+<a href="/admin/"><img border="0" align="right" height="88" width="215" src="solr-head.gif" alt="SOLR"></a>+<h1>SOLR Thread Dump (<%= collectionName %>)</h1>+<%= hostname %> : <%= port.toString() %>+<br clear="all">+<%+ Runtime rt = Runtime.getRuntime();+ Process p = rt.exec(rootdir + "/getinfo");+ p.waitFor();+%>+<table>+ <tr>+ <td>+ <H3>Exit Value:</H3>+ </td>+ <td>+ <%= p.exitValue() %>+ </td>+ </tr>+</table>+<br>+<table>+ <tr>+ <td>+ </td>+ <td>+ Current Time: <%= new Date().toString() %>+ </td>+ </tr>+ <tr>+ <td>+ </td>+ <td>+ Server Start At: <%= startTime %>+ </td>+ </tr>+</table>+<%+ BufferedReader in = new BufferedReader(new FileReader(getinfo));+ StringBuffer buf = new StringBuffer();+ String line;++ while((line = in.readLine()) != null) {+ if (line.startsWith("taking thread dump")) {+ buf = new StringBuffer();+ }+ buf.append(line).append("<br>");+ }+%>+<br>+Thread Dumps+<table>+ <tr>+ <td>+ </td>+ <td>+ [<a href=/admin/get-file.jsp?file=logs/jvm.log>All Entries</a>]+ </td>+ </tr>+ <tr>+ <td>+ Last Entry+ </td>+ <td>+ <%= buf.toString() %>+ </td>+ </tr>+</table>+<br><br>+ <a href="/admin">Return to Admin Page</a>+</body>+</html>diff --git a/src/webapp/resources/favicon.ico b/src/webapp/resources/favicon.iconew file mode 100755index 00000000000..8a77d4f6477Binary files /dev/null and b/src/webapp/resources/favicon.ico differdiff --git a/src/webapp/src/org/apache/solr/servlet/SolrServlet.java b/src/webapp/src/org/apache/solr/servlet/SolrServlet.javanew file mode 100644index 00000000000..c9cef2836e9--- /dev/null+++ b/src/webapp/src/org/apache/solr/servlet/SolrServlet.java@@ -0,0 +1,192 @@+/**+ * 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.+ */++package org.apache.solr.servlet;++import org.apache.solr.core.*;+import org.apache.solr.request.*;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.util.StrUtils;++import javax.servlet.ServletException;+import javax.servlet.http.HttpServlet;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;+import java.io.IOException;+import java.io.PrintWriter;+import java.io.BufferedReader;+import java.util.logging.Logger;+import java.util.Map;+import java.util.Set;++/**+ * @author yonik+ */++public class SolrServlet extends HttpServlet {+ public static Logger log = Logger.getLogger(SolrServlet.class.getName());+ public SolrCore core;+ private static String CONTENT_TYPE="text/xml;charset=UTF-8";+++ XMLResponseWriter xmlResponseWriter;++ public void init() throws ServletException+ {+ /***+ luceneDir=getServletContext().getInitParameter("solr.indexdir");+ schemaFile=getServletContext().getInitParameter("solr.schema");+ if (schemaFile == null) schemaFile="schema.xml";+ ***/++ log.info("user.dir=" + System.getProperty("user.dir"));++ IndexSchema schema = new IndexSchema("schema.xml");+ core = SolrCore.getSolrCore();++ xmlResponseWriter=new XMLResponseWriter();++ getServletContext().setAttribute("SolrServlet",this);++ log.info("SolrServlet.init() done");+ }++ public void destroy() {+ core.close();+ getServletContext().removeAttribute("SolrServlet");+ super.destroy();+ }++ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {+ // log.finer("Solr doPost()");+ // InputStream is = request.getInputStream();+ BufferedReader requestReader = request.getReader();++ response.setContentType(CONTENT_TYPE);+ PrintWriter responseWriter = response.getWriter();++ core.update(requestReader, responseWriter);+ }++++ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {+ // log.finer("Solr doGet: getQueryString:" + request.getQueryString());++ SolrServletRequest solrReq =null;+ SolrQueryResponse solrRsp =null;+ try {+ solrRsp = new SolrQueryResponse();+ solrReq = new SolrServletRequest(core, request);+ // log.severe("REQUEST PARAMS:" + solrReq.getParamString());+ core.execute(solrReq, solrRsp);+ if (solrRsp.getException() == null) {+ response.setContentType(CONTENT_TYPE);+ PrintWriter writer = response.getWriter();+ // if (solrReq.getStrParam("version","2").charAt(0) == '1')+ xmlResponseWriter.write(writer, solrReq, solrRsp);+ } else {+ Exception e = solrRsp.getException();+ int rc=500;+ if (e instanceof SolrException) {+ rc=((SolrException)e).code();+ }+ sendErr(rc, SolrException.toStr(e), request, response);+ }+ } catch (SolrException e) {+ if (!e.logged) SolrException.log(log,e);+ sendErr(e.code(), SolrException.toStr(e), request, response);+ } catch (Throwable e) {+ SolrException.log(log,e);+ sendErr(500, SolrException.toStr(e), request, response);+ } finally {+ // This releases the IndexReader associated with the request+ solrReq.close();+ }++ }++ final void sendErr(int rc, String msg, HttpServletRequest request, HttpServletResponse response) {+ try {+ // hmmm, what if this was already set to text/xml?+ try{+ response.setContentType(CONTENT_TYPE);+ // response.setCharacterEncoding("UTF-8");+ } catch (Exception e) {}+ try{response.setStatus(rc);} catch (Exception e) {}+ PrintWriter writer = response.getWriter();+ writer.write(msg);+ } catch (IOException e) {+ SolrException.log(log,e);+ }+ }++ final int getParam(HttpServletRequest request, String param, int defval) {+ final String pval = request.getParameter(param);+ return (pval==null) ? defval : Integer.parseInt(pval);+ }++ final boolean paramExists(HttpServletRequest request, String param) {+ return request.getParameter(param)!=null ? true : false;+ }++}++++class SolrServletRequest extends SolrQueryRequestBase {++ final HttpServletRequest req;++ public SolrServletRequest(SolrCore core, HttpServletRequest req) {+ super(core);+ this.req = req;+ }++ public String getParam(String name) {+ return req.getParameter(name);+ }+++ public String getParamString() {+ StringBuilder sb = new StringBuilder(128);+ try {+ boolean first=true;++ for (Map.Entry<String,String[]> entry : (Set<Map.Entry<String,String[]>>)req.getParameterMap().entrySet()) {+ String key = entry.getKey();+ String[] valarr = entry.getValue();++ for (String val : valarr) {+ if (!first) sb.append('&');+ first=false;+ sb.append(key);+ sb.append('=');+ StrUtils.partialURLEncodeVal(sb, val);+ }+ }+ }+ catch (Exception e) {+ // should never happen... we only needed this because+ // partialURLEncodeVal can throw an IOException, but it+ // never will when adding to a StringBuilder.+ throw new RuntimeException(e);+ }++ return sb.toString();+ }++}\ No newline at end of file