Apache Solr open-source search software
SOLR-20: Adding a java client. The client includes two implementaions: CommonsHttpSolrServer.java and EmbeddedSolrServer.java
Ryan McKinley9a9d11385c24
diff --git a/build.xml b/build.xmlindex f6dd57cf408..1ad9a6d0524 100644--- a/build.xml+++ b/build.xml@@ -228,7 +228,6 @@</solr-javac></target>-<target name="javadoc" depends="compile"description="Generates javadoc documentation.">@@ -269,7 +268,57 @@<classpath refid="javadoc.classpath"/></javadoc></target>-++ <!-- ========================================================================= -->+ <!-- ===================== CLIENT: solrj ============================= -->+ <!-- ========================================================================= -->++ <property name="solrj-dir" value="client/java/solrj" />++ <path id="compile.classpath.solrj">+ <fileset dir="${solrj-dir}/lib">+ <include name="*.jar" />+ </fileset>+ <fileset dir="${lib}">+ <include name="commons-io-*.jar" />+ </fileset>+ <pathelement location="${dest}/common"/>+ </path>++ <!-- This depend on all of solr -->+ <path id="compile.classpath.solrj-embedded">+ <path refid="compile.classpath.solrj" />+ <path refid="compile.classpath" />+ <pathelement location="${dest}/core"/>++ <!-- jetty -->+ <fileset dir="example/lib">+ <include name="*.jar" />+ </fileset>+ </path>++ <target name="compile-solrj-core"+ description="Compile the java client."+ depends="compile-common">++ <solr-javac destdir="${dest}/client/solrj"+ classpathref="compile.classpath.solrj">+ <src path="${solrj-dir}/src" />+ <exclude name="org/apache/solr/client/solrj/embedded/**" />+ </solr-javac>+ </target>++ <!-- solrj includes the embedded app -->+ <target name="compile-solrj"+ description="Compile the java client."+ depends="compile,compile-solrj-core">++ <solr-javac destdir="${dest}/client/solrj"+ classpathref="compile.classpath.solrj-embedded">+ <src path="${solrj-dir}/src/org/apache/solr/client/solrj/embedded" />+ </solr-javac>+ </target>+<!-- ========================================================================= --><!-- ===================== TESTING-RELATED TASKS ============================= -->@@ -280,13 +329,19 @@<!-- For now, it's the same as main classpath. Later it will have JUnit, Clover, etc. --><path id="test.compile.classpath"><path refid="compile.classpath" />+ <path refid="compile.classpath.solrj-embedded" />+<pathelement location="${dest}/common"/><pathelement location="${dest}/core"/>+ <pathelement location="${dest}/client/solrj"/> <!-- include solrj --></path><path id="test.run.classpath"><path refid="test.compile.classpath" />- <pathelement location="${dest}/tests"/>+ <pathelement location="${dest}/tests"/>++ <!-- include the solrj classpath and jetty files included in example -->+ <path refid="compile.classpath.solrj" /></path><!-- Check that JUnit is present. -->@@ -304,13 +359,14 @@<!-- Compile unit tests. --><target name="compileTests"description="Compile unit tests."- depends="compile,checkJunitPresence">+ depends="compile,compile-solrj,checkJunitPresence"><mkdir dir="${dest}/tests" /><solr-javacdestdir="${dest}/tests"classpathref="test.compile.classpath"><src path="${src}/test" />+ <src path="${solrj-dir}/test" /></solr-javac></target>@@ -340,6 +396,8 @@<formatter type="xml"/><batchtest fork="yes" todir="${junit.output.dir}" unless="testcase"><fileset dir="src/test" includes="${junit.includes}"/>+ <!-- this will start jetty and run some tests through HTTP -->+ <fileset dir="${solrj-dir}/test/" includes="${junit.includes}" /></batchtest><batchtest fork="yes" todir="${junit.output.dir}" if="testcase"><fileset dir="src/test" includes="**/${testcase}.java"/>@@ -348,7 +406,7 @@<fail if="tests.failed">Tests failed!</fail></target>-+<target name="test-reports"description="Generates HTML test reports."><mkdir dir="${junit.reports}"/>@@ -369,7 +427,7 @@<!-- Creates the Solr distribution files. --><target name="dist"description="Creates the Solr distribution files."- depends="init-forrest-entities, dist-war, dist-jar" />+ depends="init-forrest-entities, dist-war, dist-solrj, dist-jar" /><!-- Creates a Manifest file for Jars and WARs --><target name="make-manifest" >@@ -462,6 +520,29 @@</target>+ <!-- Creates the solr jar. -->+ <target name="dist-solrj"+ description="Creates the Solr JAR Distribution file."+ depends="compile-solrj, dist-jar">+ <mkdir dir="${dist}" />+ <solr-jar+ destfile="${dist}/${fullnamever}-solrj.jar"+ basedir="${dest}/client/solrj" />++ <mkdir dir="${dist}/solrj-lib" />+ <copy todir="${dist}/solrj-lib">+ <fileset dir="${lib}">+ <include name="commons-codec-*.jar"/>+ <include name="commons-io-*.jar"/>+ <include name="stax-*.jar"/>+ </fileset>+ <fileset dir="${solrj-dir}/lib">+ <include name="*.jar" />+ </fileset>+ </copy>++ </target>+<target name="example"description="Creates a runnable example configuration."depends="init-forrest-entities,dist-war">diff --git a/client/java/solrj/LICENSE.txt b/client/java/solrj/LICENSE.txtnew file mode 100644index 00000000000..213149bd60a--- /dev/null+++ b/client/java/solrj/LICENSE.txt@@ -0,0 +1,294 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ 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.++==========================================================================+The following license applies only to the xpp3 jar included with Solr+--------------------------------------------------------------------------+Indiana University Extreme! Lab Software License++Version 1.1.1++Copyright (c) 2002 Extreme! Lab, Indiana University. All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:++1. Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in+ the documentation and/or other materials provided with the distribution.++3. The end-user documentation included with the redistribution, if any,+ must include the following acknowledgment:++ "This product includes software developed by the Indiana University+ Extreme! Lab (http://www.extreme.indiana.edu/)."++Alternately, this acknowledgment may appear in the software itself,+if and wherever such third-party acknowledgments normally appear.++4. The names "Indiana Univeristy" and "Indiana Univeristy Extreme! Lab"+must not be used to endorse or promote products derived from this+software without prior written permission. For written permission,+please contact http://www.extreme.indiana.edu/.++5. Products derived from this software may not use "Indiana Univeristy"+name nor may "Indiana Univeristy" appear in their name, without prior+written permission of the Indiana University.++THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.+IN NO EVENT SHALL THE AUTHORS, COPYRIGHT HOLDERS OR ITS CONTRIBUTORS+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR+OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF+ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++==========================================================================+Portions of Jetty 5.1 are bundled in the Solr example server.+The following licenses are part of the Jetty 5.1 distribution, which+as a whole is licensed under The Apache License version 2.0.+ - example/etc/LICENSE.javax.servlet.txt+ - example/etc/LICENSE.javax.xml.html+ - example/etc/LICENSE.jsse.txt++==========================================================================+The following license applies to parts of the lucene-snowball jar+that are generated from the snowball sources at http://snowball.tartarus.org/+--------------------------------------------------------------------------+The BSD License++Copyright (c) 2001, Dr Martin Porter, Copyright (c) 2002, Richard Boulton+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++ * Neither the name of the <ORGANIZATION> nor the names of its contributors+ may be used to endorse or promote products derived from this software+ without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+diff --git a/client/java/solrj/lib/commons-httpclient-3.0.1.jar b/client/java/solrj/lib/commons-httpclient-3.0.1.jarnew file mode 100644index 00000000000..684f8310b23--- /dev/null+++ b/client/java/solrj/lib/commons-httpclient-3.0.1.jar@@ -0,0 +1,2 @@+AnyObjectId[cfc777c71d600a90001b7b2dcd68993d0977b0cb] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/client/java/solrj/lib/commons-logging-1.0.4.jar b/client/java/solrj/lib/commons-logging-1.0.4.jarnew file mode 100644index 00000000000..f330fde2131--- /dev/null+++ b/client/java/solrj/lib/commons-logging-1.0.4.jar@@ -0,0 +1,2 @@+AnyObjectId[b73a80fab641131e6fbe3ae833549efb3c540d17] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/client/java/solrj/src/org/apache/solr/client/solrj/ResponseParser.java b/client/java/solrj/src/org/apache/solr/client/solrj/ResponseParser.javanew file mode 100644index 00000000000..053e9db1938--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/ResponseParser.java@@ -0,0 +1,34 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import java.io.Reader;++import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public interface ResponseParser+{+ String getWriterType(); // for example: wt=XML, JSON, etc+ NamedList<Object> processResponse( Reader body );+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/SolrQuery.java b/client/java/solrj/src/org/apache/solr/client/solrj/SolrQuery.javanew file mode 100644index 00000000000..e1fc7e0a77d--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/SolrQuery.java@@ -0,0 +1,435 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import org.apache.solr.common.params.HighlightParams;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.SolrParams;+++/**+ * This is an augmented SolrParams with get/set/add fields for common fields used+ * in the Standard and Dismax request handlers+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class SolrQuery extends ModifiableSolrParams+{+ public enum ORDER { desc, asc;+ public ORDER reverse() {+ return (this == asc) ? desc : asc;+ }+ }++ public SolrQuery() {+ super();+ }++ /** Create a new SolrQuery+ *+ * @param q query string+ */+ public SolrQuery(String q) {+ this();+ this.set(SolrParams.Q, q);+ }+++ /** add a field for facet computation+ *+ * @param f the field name from the IndexSchema+ */+ public void addFacetField(String f) {+ this.add(SolrParams.FACET_FIELD, f);+ this.set(SolrParams.FACET, true);+ this.setFacetMinCount(1);+ }++ /** get the facet fields+ *+ * @return string array of facet fields or null if not set/empty+ */+ public String[] getFacetFields() {+ return this.getParams(SolrParams.FACET_FIELD);+ }++ /** remove a facet field+ *+ */+ public boolean removeFacetField(String name) {+ boolean b = this.remove(SolrParams.FACET_FIELD, name);+ if (this.get(SolrParams.FACET_FIELD) == null && this.get(SolrParams.FACET_QUERY) == null) {+ this.setFacet(false);+ }+ return b;+ }++ /** enable/disable faceting.+ *+ * @param b flag to indicate faceting should be enabled. if b==false removes all other faceting parameters+ */+ public void setFacet(boolean b) {+ if (b) {+ this.set(SolrParams.FACET, true);+ } else {+ this.remove(SolrParams.FACET);+ this.remove(SolrParams.FACET_MINCOUNT);+ this.remove(SolrParams.FACET_FIELD);+ this.remove(SolrParams.FACET_LIMIT);+ this.remove(SolrParams.FACET_MISSING);+ this.remove(SolrParams.FACET_OFFSET);+ this.remove(SolrParams.FACET_PREFIX);+ this.remove(SolrParams.FACET_QUERY);+ this.remove(SolrParams.FACET_SORT);+ this.remove(SolrParams.FACET_ZEROS);+ this.remove(SolrParams.FACET_PREFIX); // does not include the individual fields...+ }+ }++ public void setFacetPrefix( String prefix )+ {+ this.set( SolrParams.FACET_PREFIX, prefix );+ }++ public void setFacetPrefix( String field, String prefix )+ {+ this.set( "f."+field+"."+SolrParams.FACET_PREFIX, prefix );+ }++ /** add a faceting query+ *+ * @param f facet query+ */+ public void addFacetQuery(String f) {+ this.add(SolrParams.FACET_QUERY, f);+ }++ /** get facet queries+ *+ * @return all facet queries or null if not set/empty+ */+ public String[] getFacetQuery() {+ return this.getParams(SolrParams.FACET_QUERY);+ }++ /** remove a facet query+ *+ * @param q the facet query to remove+ * @return true if the facet query was removed false otherwise+ */+ public boolean removeFacetQuery(String q) {+ boolean b = this.remove(SolrParams.FACET_QUERY, q);+ if (this.get(SolrParams.FACET_FIELD) == null && this.get(SolrParams.FACET_QUERY) == null) {+ this.setFacet(false);+ }+ return b;+ }++ /** se the facet limit+ *+ * @param lim number facet items to return+ */+ public void setFacetLimit(int lim) {+ this.set(SolrParams.FACET_LIMIT, lim);+ }++ /** get current facet limit+ *+ * @return facet limit or default of 25+ */+ public int getFacetLimit() {+ return this.getInt(SolrParams.FACET_LIMIT, 25);+ }++ /** set facet minimum count+ *+ * @param cnt facets having less that cnt hits will be excluded from teh facet list+ */+ public void setFacetMinCount(int cnt) {+ this.set(SolrParams.FACET_MINCOUNT, cnt);+ }++ /** get facet minimum count+ *+ * @return facet minimum count or default of 1+ */+ public int getFacetMinCount() {+ return this.getInt(SolrParams.FACET_LIMIT, 1);+ }++ public void setMissing(String fld) {+ this.set(SolrParams.FACET_MISSING, fld);+ }++ /** get facet sort+ *+ * @return facet sort or default of true+ */+ public boolean getFacetSort() {+ return this.getBool(SolrParams.FACET_SORT, false);+ }++ /** set facet sort+ *+ * @param sort sort facets+ */+ public void setFacetSort(Boolean sort) {+ this.set(SolrParams.FACET_SORT, sort);+ }++ /** add highlight field+ *+ * @param f field to enable for highlighting+ */+ public void addHighlightField(String f) {+ this.add(HighlightParams.FIELDS, f);+ this.set(HighlightParams.HIGHLIGHT, true);+ }++ /** remove a field for highlighting+ *+ * @param f field name to not highlight+ * @return true if removed, false otherwise+ */+ public boolean removeHighlightField(String f) {+ boolean b = this.remove(HighlightParams.FIELDS, f);+ if (this.get(HighlightParams.FIELDS) == null) {+ this.setHighlight(false);+ }+ return b;+ }++ /** get list of hl fields+ *+ * @return highlight fields or null if not set/empty+ */+ public String[] getHighlightFields() {+ return this.getParams(HighlightParams.FIELDS);+ }++ public void setHighlightSnippets(int num) {+ this.set(HighlightParams.SNIPPETS, num);+ }++ public int getHighlightSnippets() {+ return this.getInt(HighlightParams.SNIPPETS, 1);+ }++ public void setHighlightFragsize(int num) {+ this.set(HighlightParams.FRAGSIZE, num);+ }++ public int getHighlightFragsize() {+ return this.getInt(HighlightParams.FRAGSIZE, 100);+ }++ public void setHighlightRequireFieldMatch(boolean flag) {+ this.set(HighlightParams.FIELD_MATCH, flag);+ }++ public boolean setHighlightRequireFieldMatch() {+ return this.getBool(HighlightParams.FIELD_MATCH, false);+ }++ public void setHighlightSimplePre(String f) {+ this.set(HighlightParams.SIMPLE_PRE, f);+ }++ public String getHighlightSimplePre() {+ return this.get(HighlightParams.SIMPLE_PRE, "");+ }++ public void setHighlightSimplePost(String f) {+ this.set(HighlightParams.SIMPLE_POST, f);+ }++ public String getHighlightSimplePost() {+ return this.get(HighlightParams.SIMPLE_POST, "");+ }++ public void addSortField(String field, ORDER order) {+ addValueToParam(SolrParams.SORT, toSortString(field, order));+ }++ public void removeSortField(String field, ORDER order) {+ String s = this.get(SolrParams.SORT);+ String removeSort = toSortString(field, order);+ if (s != null) {+ String[] sorts = s.split(",");+ s = join(sorts, ", ", removeSort);+ if (s.length()==0) s=null;+ this.set(SolrParams.SORT, s);+ }+ }++ public String[] getSortFields() {+ String s = getSortField();+ if (s==null) return null;+ return s.split(",");+ }++ public String getSortField() {+ return this.get(SolrParams.SORT);+ }++ public void setFilterQueries(String ... fq) {+ this.set(SolrParams.FQ, fq);+ }++ public void addFilterQuery(String ... fq) {+ this.add(SolrParams.FQ, fq);+ }++ public boolean removeFilterQuery(String fq) {+ return this.remove(SolrParams.FQ, fq);+ }++ public String[] getFilterQueries() {+ return this.getParams(SolrParams.FQ);+ }++ public boolean getHighlight() {+ return this.getBool(HighlightParams.HIGHLIGHT, false);+ }++ public void setHighlight(boolean b) {+ if (b) {+ this.set(HighlightParams.HIGHLIGHT, true);+ } else {+ this.remove(HighlightParams.HIGHLIGHT);+ this.remove(HighlightParams.FIELD_MATCH);+ this.remove(HighlightParams.FIELDS);+ this.remove(HighlightParams.FORMATTER);+ this.remove(HighlightParams.FRAGSIZE);+ this.remove(HighlightParams.SIMPLE_POST);+ this.remove(HighlightParams.SIMPLE_PRE);+ this.remove(HighlightParams.SNIPPETS);+ }+ }++ public void setFields(String ... fields) {+ this.set(SolrParams.FL, fields);+ }++ public void addField(String field) {+ addValueToParam(SolrParams.FL, field);+ }++ public String getFields() {+ String fields = this.get(SolrParams.FL);+ if (fields!=null && fields.equals("score")) {+ fields = "*, score";+ }+ return fields;+ }++ public void setIncludeScore(boolean includeScore) {+ if (includeScore) {+ this.add(SolrParams.FL, "score");+ } else {+ this.remove(SolrParams.FL, "score");+ }+ }++ public void setQuery(String query) {+ this.set(SolrParams.Q, query);+ }++ public void setRows(Integer rows) {+ this.set(SolrParams.ROWS, rows);+ }++ public void setShowDebugInfo(boolean showDebugInfo) {+ this.set(SolrParams.DEBUG_QUERY, String.valueOf(showDebugInfo));+ }++// use addSortField( sort, order+// public void setSort(String ... sort) {+// this.set(SolrParams.SORT, sort);+// }++ public void setStart(Integer start) {+ this.set(SolrParams.START, start);+ }++ public void setQueryType(String qt) {+ this.set(SolrParams.QT, qt);+ }++ public String getQueryType() {+ return this.get(SolrParams.QT);+ }++ public void setParam(String name, String ... values) {+ this.set(name, values);+ }++ public void setParam(String name, boolean value) {+ this.set(name, value);+ }++ /** get a deep copy of this object * */+ public SolrQuery getCopy() {+ SolrQuery q = new SolrQuery();+ for (String name : this.getParameterNames()) {+ q.setParam(name, this.getParams(name));+ }+ return q;+ }++ ///////////////////////+ // Utility functions+ ///////////////////////++ private String toSortString(String field, ORDER order) {+ return field.trim() + ' ' + String.valueOf(order).trim();+ }++ private String join(String a, String b, String sep) {+ StringBuilder sb = new StringBuilder();+ if (a!=null && a.length()>0) {+ sb.append(a);+ sb.append(sep);+ }+ if (b!=null && b.length()>0) {+ sb.append(b);+ }+ return sb.toString().trim();+ }++ private void addValueToParam(String name, String value) {+ String tmp = this.get(name);+ tmp = join(tmp, value, ",");+ this.set(name, tmp);+ }++ private String join(String[] vals, String sep, String removeVal) {+ StringBuilder sb = new StringBuilder();+ for (int i=0; i<vals.length; i++) {+ if (removeVal==null || !vals[i].equals(removeVal)) {+ sb.append(vals[i]);+ if (i<vals.length-1) {+ sb.append(sep);+ }+ }+ }+ return sb.toString().trim();+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/SolrRequest.java b/client/java/solrj/src/org/apache/solr/client/solrj/SolrRequest.javanew file mode 100644index 00000000000..c1e8197b915--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/SolrRequest.java@@ -0,0 +1,44 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import java.io.IOException;+import java.util.Collection;++import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.ContentStream;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public interface SolrRequest+{+ public enum METHOD {+ GET,+ POST+ };++ public String getPath();+ public METHOD getMethod();+ public SolrParams getParams();+ public Collection<ContentStream> getContentStreams() throws IOException;+ public SolrResponse process( SolrServer server ) throws SolrServerException, IOException;+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/SolrResponse.java b/client/java/solrj/src/org/apache/solr/client/solrj/SolrResponse.javanew file mode 100644index 00000000000..38716a7c06a--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/SolrResponse.java@@ -0,0 +1,33 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import org.apache.solr.common.util.NamedList;+++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public interface SolrResponse+{+ long getElapsedTime();+ NamedList<Object> getResponse();+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/SolrServer.java b/client/java/solrj/src/org/apache/solr/client/solrj/SolrServer.javanew file mode 100644index 00000000000..c4927e07de4--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/SolrServer.java@@ -0,0 +1,54 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import java.io.IOException;+import java.util.Collection;++import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.client.solrj.response.SolrPingResponse;+import org.apache.solr.client.solrj.response.UpdateResponse;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public interface SolrServer+{+ // A general method to allow various methods+ NamedList<Object> request( final SolrRequest request ) throws SolrServerException, IOException;++ // Standard methods+ UpdateResponse add( SolrInputDocument doc ) throws SolrServerException, IOException;+ UpdateResponse add( Collection<SolrInputDocument> docs ) throws SolrServerException, IOException;+ UpdateResponse add( SolrInputDocument doc, boolean overwrite ) throws SolrServerException, IOException;+ UpdateResponse add( Collection<SolrInputDocument> docs, boolean overwrite ) throws SolrServerException, IOException;+ UpdateResponse deleteById( String id ) throws SolrServerException, IOException;+ UpdateResponse deleteByQuery( String query ) throws SolrServerException, IOException;+ UpdateResponse commit( boolean waitFlush, boolean waitSearcher ) throws SolrServerException, IOException;+ UpdateResponse optimize( boolean waitFlush, boolean waitSearcher ) throws SolrServerException, IOException;+ UpdateResponse commit( ) throws SolrServerException, IOException;+ UpdateResponse optimize( ) throws SolrServerException, IOException;+ QueryResponse query( SolrParams params ) throws SolrServerException, IOException;+ SolrPingResponse ping() throws SolrServerException, IOException;+}\ No newline at end of filediff --git a/client/java/solrj/src/org/apache/solr/client/solrj/SolrServerException.java b/client/java/solrj/src/org/apache/solr/client/solrj/SolrServerException.javanew file mode 100644index 00000000000..eeed7c20b34--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/SolrServerException.java@@ -0,0 +1,55 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++/** Exception to catch all types of communication / parsing issues associated with talking to SOLR+ *+ * @author wjohnson+ * @version $Id$+ * @since solr 1.3+ */+public class SolrServerException extends Exception {++ private static final long serialVersionUID = -3371703521752000294L;++ public SolrServerException(String message, Throwable cause) {+ super(message, cause);+ }++ public SolrServerException(String message) {+ super(message);+ }++ public SolrServerException(Throwable cause) {+ super(cause);+ }++ public Throwable getRootCause() {+ Throwable t = this;+ while (true) {+ Throwable cause = t.getCause();+ if (cause!=null) {+ t = cause;+ } else {+ break;+ }+ }+ return t;+ }++}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.java b/client/java/solrj/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.javanew file mode 100644index 00000000000..378457d9497--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.java@@ -0,0 +1,126 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.embedded;++import java.io.IOException;+import java.io.StringReader;+import java.io.StringWriter;++import org.apache.solr.client.solrj.ResponseParser;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.impl.BaseSolrServer;+import org.apache.solr.client.solrj.impl.XMLResponseParser;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.params.DefaultSolrParams;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.SolrCore;+import org.apache.solr.request.QueryResponseWriter;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.request.SolrQueryResponse;+import org.apache.solr.request.SolrRequestHandler;+import org.apache.solr.servlet.SolrRequestParsers;++/**+ * SolrServer that connects directly to SolrCore+ *+ * TODO -- this implementation sends the response to XML and then parses it.+ * It *should* be able to convert the response directly into a named list.+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class EmbeddedSolrServer extends BaseSolrServer+{+ protected ModifiableSolrParams _invariantParams;+ protected ResponseParser _processor;++ protected final SolrCore core;+ protected final SolrRequestParsers parser;++ public EmbeddedSolrServer( SolrCore core )+ {+ this.core = core;+ this.parser = new SolrRequestParsers( core, SolrConfig.config );++ // by default use the XML one+ _processor = new XMLResponseParser();++ _invariantParams = new ModifiableSolrParams();+ _invariantParams.set( SolrParams.WT, _processor.getWriterType() );+ _invariantParams.set( SolrParams.VERSION, "2.2" );+ }++ public NamedList<Object> request(SolrRequest request) throws SolrServerException, IOException+ {+ String path = request.getPath();+ if( path == null || !path.startsWith( "/" ) ) {+ path = "/select";+ }++ SolrParams params = request.getParams();+ if( params == null ) {+ params = new ModifiableSolrParams();+ }+ if( _invariantParams != null ) {+ params = new DefaultSolrParams( _invariantParams, params );+ }++ // Extract the handler from the path or params+ SolrRequestHandler handler = core.getRequestHandler( path );+ if( handler == null ) {+ if( "/select".equals( path ) || "/select/".equalsIgnoreCase( path) ) {+ String qt = params.get( SolrParams.QT );+ handler = core.getRequestHandler( qt );+ if( handler == null ) {+ throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "unknown handler: "+qt);+ }+ }+ }+ if( handler == null ) {+ throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "unknown handler: "+path );+ }++ try {+ SolrQueryRequest req = parser.buildRequestFrom( params, request.getContentStreams() );+ req.getContext().put( "path", path );+ SolrQueryResponse rsp = new SolrQueryResponse();+ core.execute( handler, req, rsp );+ if( rsp.getException() != null ) {+ throw new SolrServerException( rsp.getException() );+ }++ // Now write it out+ QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);+ StringWriter out = new StringWriter();+ responseWriter.write(out, req, rsp);++ return _processor.processResponse( new StringReader( out.toString() ) );+ }+ catch( IOException iox ) {+ throw iox;+ }+ catch( Exception ex ) {+ throw new SolrServerException( ex );+ }+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/embedded/JettySolrRunner.java b/client/java/solrj/src/org/apache/solr/client/solrj/embedded/JettySolrRunner.javanew file mode 100644index 00000000000..f7254896bbd--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/embedded/JettySolrRunner.java@@ -0,0 +1,162 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.embedded;++import java.io.IOException;++import javax.servlet.http.HttpServlet;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;++import org.apache.solr.core.Config;+import org.apache.solr.core.SolrCore;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.servlet.SolrDispatchFilter;+import org.apache.solr.servlet.SolrServlet;+import org.apache.solr.servlet.SolrUpdateServlet;+import org.mortbay.jetty.Handler;+import org.mortbay.jetty.Server;+import org.mortbay.jetty.servlet.Context;+import org.mortbay.jetty.servlet.FilterHolder;+import org.mortbay.log.Logger;++/**+ * Run solr using jetty+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class JettySolrRunner+{+ Server server;+ FilterHolder dispatchFilter;++ public JettySolrRunner( String context, int port )+ {+ this.init( context, port );+ }++// public JettySolrRunner( String context, String home, String dataDir, int port, boolean log )+// {+// if(!log) {+// System.setProperty("org.mortbay.log.class", NoLog.class.getName() );+// System.setProperty("java.util.logging.config.file", home+"/conf/logging.properties");+// NoLog noLogger = new NoLog();+// org.mortbay.log.Log.setLog(noLogger);+// }+//+// // Initalize JNDI+// Config.setInstanceDir(home);+// new SolrCore(dataDir, new IndexSchema(home+"/conf/schema.xml"));+// this.init( context, port );+// }++ private void init( String context, int port )+ {+ server = new Server( port );++ // Initialize the servlets+ Context root = new Context( server, context, Context.SESSIONS );+ root.addServlet( SolrServlet.class, "/select" );+ root.addServlet( SolrUpdateServlet.class, "/update" );++ // for some reason, there must be a servlet for this to get applied+ root.addServlet( Servlet404.class, "/*" );+ dispatchFilter = root.addFilter( SolrDispatchFilter.class, "*", Handler.REQUEST );+ }++ //------------------------------------------------------------------------------------------------+ //------------------------------------------------------------------------------------------------++ public void start() throws Exception+ {+ if(!server.isRunning() ) {+ server.start();+ }+ }++ public void stop() throws Exception+ {+ if( server.isRunning() ) {+ server.stop();+ }+ }++ //--------------------------------------------------------------+ //--------------------------------------------------------------++ /**+ * This is a stupid hack to give jetty something to attach to+ */+ public static class Servlet404 extends HttpServlet+ {+ @Override+ public void service(HttpServletRequest req, HttpServletResponse res ) throws IOException+ {+ res.sendError( 404, "Can not find: "+req.getRequestURI() );+ }+ }+}+++class NoLog implements Logger+{+ private static boolean debug = System.getProperty("DEBUG",null)!=null;+ private final String name;++ public NoLog()+ {+ this(null);+ }++ public NoLog(String name)+ {+ this.name=name==null?"":name;+ }++ public boolean isDebugEnabled()+ {+ return debug;+ }++ public void setDebugEnabled(boolean enabled)+ {+ debug=enabled;+ }++ public void info(String msg,Object arg0, Object arg1) {}+ public void debug(String msg,Throwable th){}+ public void debug(String msg,Object arg0, Object arg1){}+ public void warn(String msg,Object arg0, Object arg1){}+ public void warn(String msg, Throwable th){}++ public Logger getLogger(String name)+ {+ if ((name==null && this.name==null) ||+ (name!=null && name.equals(this.name)))+ return this;+ return new NoLog(name);+ }++ @Override+ public String toString()+ {+ return "NOLOG["+name+"]";+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/impl/BaseSolrServer.java b/client/java/solrj/src/org/apache/solr/client/solrj/impl/BaseSolrServer.javanew file mode 100644index 00000000000..861e2c200e7--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/impl/BaseSolrServer.java@@ -0,0 +1,102 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.impl;++import java.io.IOException;+import java.util.Collection;++import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.client.solrj.request.SolrPing;+import org.apache.solr.client.solrj.request.UpdateRequest;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.client.solrj.response.SolrPingResponse;+import org.apache.solr.client.solrj.response.UpdateResponse;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.SolrParams;++/**+ * Base class that converts the server request into the more verbose general request framework.+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public abstract class BaseSolrServer implements SolrServer {++ public UpdateResponse add(Collection<SolrInputDocument> docs, boolean overwrite ) throws SolrServerException, IOException {+ UpdateRequest req = new UpdateRequest();+ req.add(docs);+ req.setOverwrite(overwrite);+ return req.process(this);+ }++ public UpdateResponse add(SolrInputDocument doc, boolean overwrite ) throws SolrServerException, IOException {+ UpdateRequest req = new UpdateRequest();+ req.add(doc);+ req.setOverwrite(overwrite);+ return req.process(this);+ }++ public UpdateResponse add(SolrInputDocument doc) throws SolrServerException, IOException {+ return add(doc, true);+ }++ public UpdateResponse add(Collection<SolrInputDocument> docs) throws SolrServerException, IOException {+ return add(docs, true);+ }++ /** waitFlush=true and waitSearcher=true to be inline with the defaults for plain HTTP access+ * @throws IOException+ */+ public UpdateResponse commit( ) throws SolrServerException, IOException {+ return commit(true, true);+ }++ /** waitFlush=true and waitSearcher=true to be inline with the defaults for plain HTTP access+ * @throws IOException+ */+ public UpdateResponse optimize( ) throws SolrServerException, IOException {+ return optimize(true, true);+ }++ public UpdateResponse commit( boolean waitFlush, boolean waitSearcher ) throws SolrServerException, IOException {+ return new UpdateRequest().setAction( UpdateRequest.ACTION.COMMIT, waitFlush, waitSearcher ).process( this );+ }++ public UpdateResponse optimize( boolean waitFlush, boolean waitSearcher ) throws SolrServerException, IOException {+ return new UpdateRequest().setAction( UpdateRequest.ACTION.OPTIMIZE, waitFlush, waitSearcher ).process( this );+ }++ public UpdateResponse deleteById(String id) throws SolrServerException, IOException {+ return new UpdateRequest().deleteById( id ).process( this );+ }++ public UpdateResponse deleteByQuery(String query) throws SolrServerException, IOException {+ return new UpdateRequest().deleteByQuery( query ).process( this );+ }++ public SolrPingResponse ping() throws SolrServerException, IOException {+ return new SolrPing().process( this );+ }++ public QueryResponse query(SolrParams params) throws SolrServerException {+ return new QueryRequest( params ).process( this );+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/impl/CommonsHttpSolrServer.java b/client/java/solrj/src/org/apache/solr/client/solrj/impl/CommonsHttpSolrServer.javanew file mode 100644index 00000000000..dc24ff0c28d--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/impl/CommonsHttpSolrServer.java@@ -0,0 +1,294 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.impl;++import java.io.IOException;+import java.io.InputStreamReader;+import java.io.OutputStream;+import java.io.Reader;+import java.net.MalformedURLException;+import java.net.URL;+import java.util.Collection;+import java.util.Iterator;++import org.apache.commons.httpclient.HttpClient;+import org.apache.commons.httpclient.HttpException;+import org.apache.commons.httpclient.HttpMethod;+import org.apache.commons.httpclient.HttpMethodBase;+import org.apache.commons.httpclient.HttpStatus;+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;+import org.apache.commons.httpclient.methods.GetMethod;+import org.apache.commons.httpclient.methods.InputStreamRequestEntity;+import org.apache.commons.httpclient.methods.PostMethod;+import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;+import org.apache.commons.httpclient.methods.multipart.Part;+import org.apache.commons.httpclient.methods.multipart.PartBase;+import org.apache.commons.io.IOUtils;+import org.apache.solr.client.solrj.ResponseParser;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.util.ClientUtils;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.params.DefaultSolrParams;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.ContentStream;+import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class CommonsHttpSolrServer extends BaseSolrServer+{+ public static final String AGENT = "Solr["+CommonsHttpSolrServer.class.getName()+"] 1.0";++ /**+ * The URL of the Solr server.+ */+ protected String _baseURL;+ protected ModifiableSolrParams _invariantParams;+ protected ResponseParser _processor;+ MultiThreadedHttpConnectionManager _connectionManager = new MultiThreadedHttpConnectionManager();++ /**+ * @param solrServerUrl The URL of the Solr server. For+ * example, "<code>http://localhost:8983/solr/</code>"+ * if you are using the standard distribution Solr webapp+ * on your local machine.+ */+ public CommonsHttpSolrServer(String solrServerUrl) throws MalformedURLException {+ this(new URL(solrServerUrl));+ }++ /**+ * @param baseURL The URL of the Solr server. For+ * example, "<code>http://localhost:8983/solr/</code>"+ * if you are using the standard distribution Solr webapp+ * on your local machine.+ */+ public CommonsHttpSolrServer(URL baseURL)+ {+ this._baseURL = baseURL.toExternalForm();+ if( this._baseURL.endsWith( "/" ) ) {+ this._baseURL = this._baseURL.substring( 0, this._baseURL.length()-1 );+ }++ // by default use the XML one+ _processor = new XMLResponseParser();++ // TODO -- expose these so that people can add things like 'u' & 'p'+ _invariantParams = new ModifiableSolrParams();+ _invariantParams.set( SolrParams.WT, _processor.getWriterType() );+ _invariantParams.set( SolrParams.VERSION, "2.2" );+ }++ //------------------------------------------------------------------------+ //------------------------------------------------------------------------++ public NamedList<Object> request( final SolrRequest request ) throws SolrServerException, IOException+ {+ // TODO -- need to set the WRITER TYPE!!!+ // params.set( SolrParams.WT, wt );++ HttpMethod method = null;+ SolrParams params = request.getParams();+ Collection<ContentStream> streams = request.getContentStreams();+ String path = request.getPath();+ if( path == null || !path.startsWith( "/" ) ) {+ path = "/select";+ }++ if( params == null ) {+ params = new ModifiableSolrParams();+ }+ if( _invariantParams != null ) {+ params = new DefaultSolrParams( _invariantParams, params );+ }++ try {+ if( SolrRequest.METHOD.GET == request.getMethod() ) {+ if( streams != null ) {+ throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!" );+ }+ method = new GetMethod( _baseURL + path + ClientUtils.toQueryString( params, false ) );+ }+ else if( SolrRequest.METHOD.POST == request.getMethod() ) {++ String url = _baseURL + path;+ boolean isMultipart = ( streams != null && streams.size() > 1 );++ if( streams == null || isMultipart ) {+ // Without streams, just post the parameters+ PostMethod post = new PostMethod( url );++ Iterator<String> iter = params.getParameterNamesIterator();+ while( iter.hasNext() ) {+ String p = iter.next();+ String[] vals = params.getParams( p );+ if( vals != null && vals.length > 0 ) {+ for( String v : vals ) {+ post.addParameter( p, (v==null)?null:v );+ }+ }+ else {+ post.addParameter( p, null );+ }+ }++ post.getParams().setContentCharset("UTF-8");++ if( isMultipart ) {+ int i=0;+ Part[] parts = new Part[streams.size()];++ for( ContentStream content : streams ) {+ final ContentStream c = content;++ String charSet = null;+ String transferEncoding = null;+ parts[i++] = new PartBase( c.getName(), c.getContentType(), charSet, transferEncoding ) {+ @Override+ protected long lengthOfData() throws IOException {+ return c.getSize();+ }++ @Override+ protected void sendData(OutputStream out) throws IOException {+ IOUtils.copy( c.getReader(), out );+ }+ };+ }++ // Set the multi-part request+ post.setRequestEntity(+ new MultipartRequestEntity(+ parts,+ post.getParams() )+ );+ method = post;+ }++ method = post;+ }+ // It is has one stream, it is the post body, put the params in the URL+ else {+ String pstr = ClientUtils.toQueryString( params, false );+ PostMethod post = new PostMethod( url+pstr );++ // Single stream as body+ // Using a loop just to get the first one+ for( ContentStream content : streams ) {+ post.setRequestEntity(+ new InputStreamRequestEntity(+ content.getStream(),+ content.getContentType()) );+ break;+ }+ method = post;+ }+ }+ else {+ throw new SolrServerException("Unsupported method: "+request.getMethod() );+ }+ }+ catch( IOException ex ) {+ throw new SolrServerException("error reading streams", ex );+ }++ method.addRequestHeader( "User-Agent", AGENT );++ try {+ // Execute the method.+ //System.out.println( "EXECUTE:"+method.getURI() );++ int statusCode = getHttpConnection().executeMethod(method);+ if (statusCode != HttpStatus.SC_OK) {+ StringBuilder msg = new StringBuilder();+ msg.append( method.getStatusLine().getReasonPhrase() );+ msg.append( "\n\n" );+ msg.append( method.getStatusText() );+ msg.append( "\n\n" );+ msg.append( "request: "+method.getURI() );+ throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8") );+ }++ // Read the contents+ String charset = "UTF-8";+ if( method instanceof HttpMethodBase ) {+ charset = ((HttpMethodBase)method).getResponseCharSet();+ }+ Reader reader = new InputStreamReader( method.getResponseBodyAsStream(), charset );+ return _processor.processResponse( reader );+ }+ catch (HttpException e) {+ throw new SolrServerException( e );+ }+ catch (IOException e) {+ throw new SolrServerException( e );+ }+ finally {+ method.releaseConnection();+ }+ }++ //-------------------------------------------------------------------+ //-------------------------------------------------------------------++ public String getBaseURL() {+ return _baseURL;+ }++ public void setBaseURL(String baseURL) {+ this._baseURL = baseURL;+ }++ public ResponseParser getProcessor() {+ return _processor;+ }++ public void setProcessor(ResponseParser processor) {+ _processor = processor;+ }++ protected HttpClient getHttpConnection() {+ return new HttpClient(_connectionManager);+ }++ public MultiThreadedHttpConnectionManager getConnectionManager() {+ return _connectionManager;+ }++ /** set connectionTimeout on the underlying MultiThreadedHttpConnectionManager */+ public void setConnectionTimeout(int timeout) {+ _connectionManager.getParams().setConnectionTimeout(timeout);+ }++ /** set maxConnectionsPerHost on the underlying MultiThreadedHttpConnectionManager */+ public void setDefaultMaxConnectionsPerHost(int connections) {+ _connectionManager.getParams().setDefaultMaxConnectionsPerHost(connections);+ }++ /** set maxTotalConnection on the underlying MultiThreadedHttpConnectionManager */+ public void setMaxTotalConnections(int connections) {+ _connectionManager.getParams().setMaxTotalConnections(connections);+ }++}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/impl/XMLResponseParser.java b/client/java/solrj/src/org/apache/solr/client/solrj/impl/XMLResponseParser.javanew file mode 100644index 00000000000..16eb4f73439--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/impl/XMLResponseParser.java@@ -0,0 +1,394 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.impl;++import java.io.Reader;+import java.util.ArrayList;+import java.util.Date;+import java.util.List;++import javax.xml.stream.XMLInputFactory;+import javax.xml.stream.XMLStreamConstants;+import javax.xml.stream.XMLStreamException;+import javax.xml.stream.XMLStreamReader;++import org.apache.solr.client.solrj.ResponseParser;+import org.apache.solr.client.solrj.util.ClientUtils;+import org.apache.solr.common.SolrDocument;+import org.apache.solr.common.SolrDocumentList;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class XMLResponseParser implements ResponseParser+{+ XMLInputFactory factory;++ public XMLResponseParser()+ {+ factory = XMLInputFactory.newInstance();+ }++ public String getWriterType()+ {+ return "xml";+ }++ /**+ * parse the text into a named list...+ */+ public NamedList<Object> processResponse( Reader in )+ {+ XMLStreamReader parser = null;+ try {+// String txt = IOUtils.toString( in );+// in = new StringReader( txt );+// System.out.println( "TEXT:"+txt );++ parser = factory.createXMLStreamReader(in);++ NamedList<Object> response = null;+ for (int event = parser.next();+ event != XMLStreamConstants.END_DOCUMENT;+ event = parser.next())+ {+ switch (event) {+ case XMLStreamConstants.START_ELEMENT:++ if( response != null ) {+ throw new Exception( "already read the response!" );+ }++ // only top-level element is "response+ String name = parser.getLocalName();+ if( name.equals( "response" ) || name.equals( "result" ) ) {+ response = readNamedList( parser );+ }+ else {+ throw new Exception( "really needs to be response or result. " ++ "not:"+parser.getLocalName() );+ }+ break;+ }+ }+ return response;+ }+ catch( Exception ex ) {+ throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, "parsing error", ex );+ }+ finally {+ try {+ parser.close();+ }+ catch( Exception ex ){}+ }+ }+++ protected enum KnownType {+ STR (true) { @Override public String read( String txt ) { return txt; } },+ INT (true) { @Override public Integer read( String txt ) { return Integer.valueOf(txt); } },+ FLOAT (true) { @Override public Float read( String txt ) { return Float.valueOf(txt); } },+ DOUBLE (true) { @Override public Double read( String txt ) { return Double.valueOf(txt); } },+ LONG (true) { @Override public Long read( String txt ) { return Long.valueOf(txt); } },+ BOOL (true) { @Override public Boolean read( String txt ) { return Boolean.valueOf(txt); } },+ NULL (true) { @Override public Object read( String txt ) { return null; } },+ DATE (true) {+ @Override+ public Date read( String txt ) {+ try {+ return ClientUtils.parseDate(txt);+ }+ catch( Exception ex ) {+ ex.printStackTrace();+ }+ return null;+ }+ },++ ARR (false) { @Override public Object read( String txt ) { return null; } },+ LST (false) { @Override public Object read( String txt ) { return null; } },+ RESULT (false) { @Override public Object read( String txt ) { return null; } },+ DOC (false) { @Override public Object read( String txt ) { return null; } };++ final boolean isLeaf;++ KnownType( boolean isLeaf )+ {+ this.isLeaf = isLeaf;+ }++ public abstract Object read( String txt );++ public static KnownType get( String v )+ {+ if( v != null ) {+ try {+ return KnownType.valueOf( v.toUpperCase() );+ }+ catch( Exception ex ) {}+ }+ return null;+ }+ };++ protected NamedList<Object> readNamedList( XMLStreamReader parser ) throws XMLStreamException+ {+ if( XMLStreamConstants.START_ELEMENT != parser.getEventType() ) {+ throw new RuntimeException( "must be start element, not: "+parser.getEventType() );+ }++ StringBuilder builder = new StringBuilder();+ NamedList<Object> nl = new NamedList<Object>();+ KnownType type = null;+ String name = null;++ // just eat up the events...+ int depth = 0;+ while( true )+ {+ switch (parser.next()) {+ case XMLStreamConstants.START_ELEMENT:+ depth++;+ builder.setLength( 0 ); // reset the text+ type = KnownType.get( parser.getLocalName() );+ if( type == null ) {+ throw new RuntimeException( "this must be known type! not: "+parser.getLocalName() );+ }++ name = null;+ int cnt = parser.getAttributeCount();+ for( int i=0; i<cnt; i++ ) {+ if( "name".equals( parser.getAttributeLocalName( i ) ) ) {+ name = parser.getAttributeValue( i );+ break;+ }+ }++ if( name == null ) {+ throw new XMLStreamException( "requires 'name' attribute: "+parser.getLocalName(), parser.getLocation() );+ }++ if( !type.isLeaf ) {+ switch( type ) {+ case LST: nl.add( name, readNamedList( parser ) ); depth--; continue;+ case ARR: nl.add( name, readArray( parser ) ); depth--; continue;+ case RESULT: nl.add( name, readDocuments( parser ) ); depth--; continue;+ case DOC: nl.add( name, readDocument( parser ) ); depth--; continue;+ }+ throw new XMLStreamException( "branch element not handled!", parser.getLocation() );+ }+ break;++ case XMLStreamConstants.END_ELEMENT:+ if( --depth < 0 ) {+ return nl;+ }+ //System.out.println( "NL:ELEM:"+type+"::"+name+"::"+builder );+ nl.add( name, type.read( builder.toString().trim() ) );+ break;++ case XMLStreamConstants.SPACE: // TODO? should this be trimmed? make sure it only gets one/two space?+ case XMLStreamConstants.CDATA:+ case XMLStreamConstants.CHARACTERS:+ builder.append( parser.getText() );+ break;+ }+ }+ }++ protected List<Object> readArray( XMLStreamReader parser ) throws XMLStreamException+ {+ if( XMLStreamConstants.START_ELEMENT != parser.getEventType() ) {+ throw new RuntimeException( "must be start element, not: "+parser.getEventType() );+ }+ if( !"arr".equals( parser.getLocalName().toLowerCase() ) ) {+ throw new RuntimeException( "must be 'arr', not: "+parser.getLocalName() );+ }++ StringBuilder builder = new StringBuilder();+ KnownType type = null;++ List<Object> vals = new ArrayList<Object>();++ int depth = 0;+ while( true )+ {+ switch (parser.next()) {+ case XMLStreamConstants.START_ELEMENT:+ depth++;+ KnownType t = KnownType.get( parser.getLocalName() );+ if( t == null ) {+ throw new RuntimeException( "this must be known type! not: "+parser.getLocalName() );+ }+ if( type == null ) {+ type = t;+ }+ else if( type != t ) {+ throw new RuntimeException( "arrays must have the same type! ("+type+"!="+t+") "+parser.getLocalName() );+ }++ builder.setLength( 0 ); // reset the text++ if( !type.isLeaf ) {+ switch( type ) {+ case LST: vals.add( readNamedList( parser ) ); continue;+ case ARR: vals.add( readArray( parser ) ); continue;+ case RESULT: vals.add( readDocuments( parser ) ); continue;+ case DOC: vals.add( readDocument( parser ) ); continue;+ }+ throw new XMLStreamException( "branch element not handled!", parser.getLocation() );+ }+ break;++ case XMLStreamConstants.END_ELEMENT:+ if( --depth < 0 ) {+ return vals; // the last element is itself+ }+ //System.out.println( "ARR:"+type+"::"+builder );+ Object val = type.read( builder.toString().trim() );+ if( val == null ) {+ throw new XMLStreamException( "error reading value:"+type, parser.getLocation() );+ }+ vals.add( val );+ break;++ case XMLStreamConstants.SPACE: // TODO? should this be trimmed? make sure it only gets one/two space?+ case XMLStreamConstants.CDATA:+ case XMLStreamConstants.CHARACTERS:+ builder.append( parser.getText() );+ break;+ }+ }+ }++ protected SolrDocumentList readDocuments( XMLStreamReader parser ) throws XMLStreamException+ {+ SolrDocumentList docs = new SolrDocumentList();++ // Parse the attributes+ for( int i=0; i<parser.getAttributeCount(); i++ ) {+ String n = parser.getAttributeLocalName( i );+ String v = parser.getAttributeValue( i );+ if( "numFound".equals( n ) ) {+ docs.setNumFound( Integer.parseInt( v ) );+ }+ else if( "start".equals( n ) ) {+ docs.setStart( Integer.parseInt( v ) );+ }+ else if( "maxScore".equals( n ) ) {+ docs.setMaxScore( Float.parseFloat( v ) );+ }+ }++ // Read through each document+ int event;+ while( true ) {+ event = parser.next();+ if( XMLStreamConstants.START_ELEMENT == event ) {+ if( !"doc".equals( parser.getLocalName() ) ) {+ throw new RuntimeException( "shoudl be doc! "+parser.getLocalName() + " :: " + parser.getLocation() );+ }+ docs.add( readDocument( parser ) );+ }+ else if ( XMLStreamConstants.END_ELEMENT == event ) {+ return docs; // only happens once+ }+ }+ }++ protected SolrDocument readDocument( XMLStreamReader parser ) throws XMLStreamException+ {+ if( XMLStreamConstants.START_ELEMENT != parser.getEventType() ) {+ throw new RuntimeException( "must be start element, not: "+parser.getEventType() );+ }+ if( !"doc".equals( parser.getLocalName().toLowerCase() ) ) {+ throw new RuntimeException( "must be 'lst', not: "+parser.getLocalName() );+ }++ SolrDocument doc = new SolrDocument();+ StringBuilder builder = new StringBuilder();+ KnownType type = null;+ String name = null;++ // just eat up the events...+ int depth = 0;+ while( true )+ {+ switch (parser.next()) {+ case XMLStreamConstants.START_ELEMENT:+ depth++;+ builder.setLength( 0 ); // reset the text+ type = KnownType.get( parser.getLocalName() );+ if( type == null ) {+ throw new RuntimeException( "this must be known type! not: "+parser.getLocalName() );+ }++ name = null;+ int cnt = parser.getAttributeCount();+ for( int i=0; i<cnt; i++ ) {+ if( "name".equals( parser.getAttributeLocalName( i ) ) ) {+ name = parser.getAttributeValue( i );+ break;+ }+ }++ if( name == null ) {+ throw new XMLStreamException( "requires 'name' attribute: "+parser.getLocalName(), parser.getLocation() );+ }++ // Handle multi-valued fields+ if( type == KnownType.ARR ) {+ for( Object val : readArray( parser ) ) {+ doc.addField( name, val );+ }+ depth--; // the array reading clears out the 'endElement'+ }+ else if( !type.isLeaf ) {+ throw new XMLStreamException( "must be value or array", parser.getLocation() );+ }+ break;++ case XMLStreamConstants.END_ELEMENT:+ if( --depth < 0 ) {+ return doc;+ }+ //System.out.println( "FIELD:"+type+"::"+name+"::"+builder );+ Object val = type.read( builder.toString().trim() );+ if( val == null ) {+ throw new XMLStreamException( "error reading value:"+type, parser.getLocation() );+ }+ doc.addField( name, val );+ break;++ case XMLStreamConstants.SPACE: // TODO? should this be trimmed? make sure it only gets one/two space?+ case XMLStreamConstants.CDATA:+ case XMLStreamConstants.CHARACTERS:+ builder.append( parser.getText() );+ break;+ }+ }+ }+++}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/request/LukeRequest.java b/client/java/solrj/src/org/apache/solr/client/solrj/request/LukeRequest.javanew file mode 100644index 00000000000..70d4d873d21--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/request/LukeRequest.java@@ -0,0 +1,90 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.request;++import java.io.IOException;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;++import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.response.LukeResponse;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.ContentStream;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class LukeRequest extends RequestBase+{+ private List<String> fields;+ private int count = -1;++ public LukeRequest()+ {+ super( METHOD.GET, "/admin/luke" );+ }++ public LukeRequest( String path )+ {+ super( METHOD.GET, path );+ }++ //---------------------------------------------------------------------------------+ //---------------------------------------------------------------------------------++ public void addField( String f )+ {+ if( fields == null ) {+ fields = new ArrayList<String>();+ }+ fields.add( f );+ }++ //---------------------------------------------------------------------------------+ //---------------------------------------------------------------------------------++ public Collection<ContentStream> getContentStreams() {+ return null;+ }++ public SolrParams getParams() {+ ModifiableSolrParams params = new ModifiableSolrParams();+ if( fields != null && fields.size() > 0 ) {+ params.add( SolrParams.FL, fields.toArray( new String[fields.size()] ) );+ }+ if( count >= 0 ) {+ params.add( "count", count+"" );+ }+ return params;+ }++ public LukeResponse process( SolrServer server ) throws SolrServerException, IOException+ {+ long startTime = System.currentTimeMillis();+ LukeResponse res = new LukeResponse( server.request( this ) );+ res.setElapsedTime( System.currentTimeMillis()-startTime );+ return res;+ }+}+diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/request/QueryRequest.java b/client/java/solrj/src/org/apache/solr/client/solrj/request/QueryRequest.javanew file mode 100644index 00000000000..1cdb0dabf19--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/request/QueryRequest.java@@ -0,0 +1,90 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.request;++import java.util.Collection;++import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.ContentStream;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class QueryRequest extends RequestBase+{+ private SolrParams query;++ public QueryRequest()+ {+ super( METHOD.GET, null );+ }++ public QueryRequest( SolrParams q )+ {+ super( METHOD.GET, null );+ query = q;+ }++ /**+ * Use the params 'QT' parameter if it exists+ */+ @Override+ public String getPath() {+ String qt = query.get( SolrParams.QT );+ if( qt == null ) {+ qt = super.getPath();+ }+ if( qt != null && qt.startsWith( "/" ) ) {+ return qt;+ }+ return "/select";+ }++ //---------------------------------------------------------------------------------+ //---------------------------------------------------------------------------------++ public Collection<ContentStream> getContentStreams() {+ return null;+ }++ public SolrParams getParams() {+ return query;+ }++ public QueryResponse process( SolrServer server ) throws SolrServerException+ {+ try+ {+ long startTime = System.currentTimeMillis();+ QueryResponse res = new QueryResponse( server.request( this ) );+ res.setElapsedTime( System.currentTimeMillis()-startTime );+ return res;+ }+ catch (Exception e)+ {+ throw new SolrServerException("Error executing query", e);+ }+ }+}+diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/request/RequestBase.java b/client/java/solrj/src/org/apache/solr/client/solrj/request/RequestBase.javanew file mode 100644index 00000000000..1bbf7f19a6d--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/request/RequestBase.java@@ -0,0 +1,58 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.request;++import org.apache.solr.client.solrj.SolrRequest;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public abstract class RequestBase implements SolrRequest+{+ private METHOD method = METHOD.GET;+ private String path = null;++ //---------------------------------------------------------+ //---------------------------------------------------------++ public RequestBase( METHOD m, String path )+ {+ this.method = m;+ this.path = path;+ }++ //---------------------------------------------------------+ //---------------------------------------------------------++ public METHOD getMethod() {+ return method;+ }+ public void setMethod(METHOD method) {+ this.method = method;+ }++ public String getPath() {+ return path;+ }+ public void setPath(String path) {+ this.path = path;+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/request/SolrPing.java b/client/java/solrj/src/org/apache/solr/client/solrj/request/SolrPing.javanew file mode 100644index 00000000000..d2b02686efc--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/request/SolrPing.java@@ -0,0 +1,57 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.request;++import java.io.IOException;+import java.util.Collection;++import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.response.SolrPingResponse;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.ContentStream;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class SolrPing extends RequestBase+{+ public SolrPing()+ {+ super( METHOD.GET, "/admin/ping" );+ }++ public Collection<ContentStream> getContentStreams() {+ return null;+ }++ public SolrParams getParams() {+ return null;+ }++ public SolrPingResponse process( SolrServer server ) throws SolrServerException, IOException+ {+ long startTime = System.currentTimeMillis();+ SolrPingResponse res = new SolrPingResponse( server.request( this ) );+ res.setElapsedTime( System.currentTimeMillis()-startTime );+ return res;+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/request/UpdateRequest.java b/client/java/solrj/src/org/apache/solr/client/solrj/request/UpdateRequest.javanew file mode 100644index 00000000000..c3392172f59--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/request/UpdateRequest.java@@ -0,0 +1,271 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.request;++import java.io.IOException;+import java.io.StringWriter;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;++import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.response.UpdateResponse;+import org.apache.solr.client.solrj.util.ClientUtils;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.params.UpdateParams;+import org.apache.solr.common.util.ContentStream;+import org.apache.solr.common.util.XML;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class UpdateRequest extends RequestBase+{+ public enum ACTION {+ COMMIT,+ OPTIMIZE+ };++ private boolean waitFlush = true;+ private boolean waitSearcher = true;+ private boolean allowDups = false;+ private boolean overwriteCommitted = false;+ private boolean overwritePending = false;+ private ACTION action = null;++ private List<SolrInputDocument> documents = null;+ private List<String> deleteById = null;+ private List<String> deleteQuery = null;++ public UpdateRequest()+ {+ super( METHOD.POST, "/update" );+ }++ //---------------------------------------------------------------------------+ //---------------------------------------------------------------------------++ public UpdateRequest add( final SolrInputDocument doc )+ {+ if( documents == null ) {+ documents = new ArrayList<SolrInputDocument>( 2 );+ }+ documents.add( doc );+ return this;+ }++ public UpdateRequest add( final Collection<SolrInputDocument> docs )+ {+ if( documents == null ) {+ documents = new ArrayList<SolrInputDocument>( docs.size()+1 );+ }+ documents.addAll( docs );+ return this;+ }++ public UpdateRequest deleteById( String id )+ {+ if( deleteById == null ) {+ deleteById = new ArrayList<String>();+ }+ deleteById.add( id );+ return this;+ }++ public UpdateRequest deleteByQuery( String q )+ {+ if( deleteQuery == null ) {+ deleteQuery = new ArrayList<String>();+ }+ deleteQuery.add( q );+ return this;+ }++ public UpdateRequest setAction(ACTION action, boolean waitFlush, boolean waitSearcher ) {+ this.action = action;+ this.waitFlush = waitFlush;+ this.waitSearcher = waitSearcher;+ return this;+ }++ //--------------------------------------------------------------------------+ //--------------------------------------------------------------------------++ public Collection<ContentStream> getContentStreams() throws IOException {+ return ClientUtils.toContentStreams( getXML(), ClientUtils.TEXT_XML );+ }++ public String getXML() throws IOException {+ StringWriter writer = new StringWriter();+ if( documents != null && documents.size() > 0 ) {+ writer.write("<add ");+ writer.write("allowDups=\"" + allowDups + "\" ");+ writer.write("overwriteCommitted=\"" + overwriteCommitted + "\" ");+ writer.write("overwritePending=\"" + overwritePending + "\">");+ for (SolrInputDocument doc : documents ) {+ if( doc != null ) {+ ClientUtils.writeXML( doc, writer );+ }+ }+ writer.write("</add>");+ }++ // Add the delete commands+ if( deleteById != null || deleteQuery != null ) {+ writer.append( "<delete>" );+ if( deleteById != null ) {+ for( String id : deleteById ) {+ writer.append( "<id>" );+ XML.escapeCharData( id, writer );+ writer.append( "</id>" );+ }+ }+ if( deleteQuery != null ) {+ for( String q : deleteQuery ) {+ writer.append( "<query>" );+ XML.escapeCharData( q, writer );+ writer.append( "</query>" );+ }+ }+ writer.append( "</delete>" );+ }++ // add the commits+ if (action == ACTION.COMMIT) {+ writer.append("<commit ");+ writer.append("waitFlush=\"" + waitFlush + "\" ");+ writer.append("waitSearcher=\"" + waitSearcher + "\" ");+ writer.append(">");+ writer.append("</commit>");+ }++ // add the optimizes+ if (action == ACTION.OPTIMIZE) {+ writer.append("<optimize ");+ writer.append("waitFlush=\"" + waitFlush + "\" ");+ writer.append("waitSearcher=\"" + waitSearcher + "\" ");+ writer.append(">");+ writer.append("</optimize>");+ }+ return writer.toString();+ }++ //--------------------------------------------------------------------------+ //--------------------------------------------------------------------------++ public SolrParams getParams() {+ if( action != null ) {+ ModifiableSolrParams params = new ModifiableSolrParams();+ if( action == ACTION.OPTIMIZE ) {+ params.set( UpdateParams.OPTIMIZE, "true" );+ }+ else if( action == ACTION.COMMIT ) {+ params.set( UpdateParams.COMMIT, "true" );+ }+ params.set( UpdateParams.WAIT_FLUSH, waitFlush+"" );+ params.set( UpdateParams.WAIT_SEARCHER, waitSearcher+"" );+ return params;+ }+ return null;+ }++ public UpdateResponse process( SolrServer server ) throws SolrServerException, IOException+ {+ long startTime = System.currentTimeMillis();+ UpdateResponse res = new UpdateResponse( server.request( this ) );+ res.setElapsedTime( System.currentTimeMillis()-startTime );+ return res;+ }++ //--------------------------------------------------------------------------+ //+ //--------------------------------------------------------------------------++ public void setOverwrite( boolean v )+ {+ allowDups = !v;+ overwriteCommitted = v;+ overwritePending = v;+ }++ //--------------------------------------------------------------------------+ //+ //--------------------------------------------------------------------------++ public boolean isWaitFlush() {+ return waitFlush;+ }++ public boolean isWaitSearcher() {+ return waitSearcher;+ }++ public ACTION getAction() {+ return action;+ }++ public boolean isAllowDups() {+ return allowDups;+ }++ /**+ * Use setOverwrite()+ */+ @Deprecated+ public void setAllowDups(boolean allowDups) {+ this.allowDups = allowDups;+ }++ public boolean isOverwriteCommitted() {+ return overwriteCommitted;+ }++ /**+ * Use setOverwrite()+ */+ @Deprecated+ public void setOverwriteCommitted(boolean overwriteCommitted) {+ this.overwriteCommitted = overwriteCommitted;+ }++ public boolean isOverwritePending() {+ return overwritePending;+ }++ /**+ * Use setOverwrite()+ */+ @Deprecated+ public void setOverwritePending(boolean overwritePending) {+ this.overwritePending = overwritePending;+ }++ public void setWaitFlush(boolean waitFlush) {+ this.waitFlush = waitFlush;+ }++ public void setWaitSearcher(boolean waitSearcher) {+ this.waitSearcher = waitSearcher;+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/response/FacetField.java b/client/java/solrj/src/org/apache/solr/client/solrj/response/FacetField.javanew file mode 100644index 00000000000..85ac33570ba--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/response/FacetField.java@@ -0,0 +1,146 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.response;++import java.util.ArrayList;+import java.util.List;++ /**+ * A utility class to hold the facet response. It could use the NamedList container,+ * but for JSTL, it is nice to have something that implements List so it can be iterated+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+ public class FacetField+ {+ public static class Count+ {+ private String _name = null;+ private int _count = 0;+ // hang onto the FacetField for breadcrumb creation convenience+ private FacetField _ff = null;++ public Count( FacetField ff, String n, int c )+ {+ _name = n;+ _count = c;+ _ff = ff;+ }++ public String getName() {+ return _name;+ }++ public void setName( String n )+ {+ _name = n;+ }++ public int getCount() {+ return _count;+ }++ public void setCount( int c )+ {+ _count = c;+ }++ public FacetField getFacetField() {+ return _ff;+ }++ @Override+ public String toString()+ {+ return _name+" ("+_count+")";+ }++ public String getAsFilterQuery() {+ if (_ff.getName().equals("facet_queries")) {+ return _name;+ } else {+ return _ff._name+":\""+_name+"\"";+ }+ }+ }++ private String _name = null;+ private List<Count> _values = null;++ public FacetField( final String n )+ {+ _name = n;+ }++ /**+ * Insert at the end of the list+ */+ public void add( String name, int cnt )+ {+ if( _values == null ) {+ _values = new ArrayList<Count>( 30 );+ }+ _values.add( new Count( this, name, cnt ) );+ }++ /**+ * Insert at the beginning of the list.+ */+ public void insert( String name, int cnt )+ {+ if( _values == null ) {+ _values = new ArrayList<Count>( 30 );+ }+ _values.add( 0, new Count( this, name, cnt ) );+ }++ public String getName() {+ return _name;+ }++ public List<Count> getValues() {+ return _values;+ }++ public int getValueCount()+ {+ return _values == null ? 0 : _values.size();+ }++ public FacetField getLimitingFields(int max)+ {+ FacetField ff = new FacetField( _name );+ if( _values != null ) {+ ff._values = new ArrayList<Count>( _values.size() );+ for( Count c : _values ) {+ if( c._count < max ) { // !equal to+ ff._values.add( c );+ }+ }+ }+ return ff;+ }++ @Override+ public String toString()+ {+ return _name + ":" + _values;+ }+ }diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/response/LukeResponse.java b/client/java/solrj/src/org/apache/solr/client/solrj/response/LukeResponse.javanew file mode 100644index 00000000000..b5d92931301--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/response/LukeResponse.java@@ -0,0 +1,161 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.response;++import java.util.HashMap;+import java.util.Map;++import org.apache.solr.common.util.NamedList;+++/**+ * This is an incomplete representation of the data returned from Luke+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class LukeResponse extends SolrResponseBase+{+ public static class FieldInfo {+ String name;+ String type;+ String schema;+ int docs;+ int distinct;+ boolean cacheableFaceting;+ NamedList<Integer> topTerms;++ public FieldInfo( String n )+ {+ name = n;+ }++ @SuppressWarnings("unchecked")+ public void read( NamedList<Object> nl )+ {+ for( Map.Entry<String, Object> entry : nl ) {+ if( "type".equals( entry.getKey() ) ) {+ type = (String)entry.getValue();+ }+ else if( "schema".equals( entry.getKey() ) ) {+ schema = (String)entry.getValue();+ }+ else if( "docs".equals( entry.getKey() ) ) {+ docs = (Integer)entry.getValue();+ }+ else if( "distinct".equals( entry.getKey() ) ) {+ distinct = (Integer)entry.getValue();+ }+ else if( "cacheableFaceting".equals( entry.getKey() ) ) {+ cacheableFaceting = (Boolean)entry.getValue();+ }+ else if( "topTerms".equals( entry.getKey() ) ) {+ topTerms = (NamedList<Integer>)entry.getValue();+ }+ }+ }++ public boolean isCacheableFaceting() {+ return cacheableFaceting;+ }++ public int getDistinct() {+ return distinct;+ }++ public int getDocs() {+ return docs;+ }++ public String getName() {+ return name;+ }++ public String getSchema() {+ return schema;+ }++ public NamedList<Integer> getTopTerms() {+ return topTerms;+ }++ public String getType() {+ return type;+ }+ };++ private NamedList<Object> indexInfo;+ private Map<String,FieldInfo> fieldInfo;++ @SuppressWarnings("unchecked")+ public LukeResponse(NamedList<Object> res) {+ super(res);++ // Parse indexinfo+ indexInfo = (NamedList<Object>)res.get( "index" );++ NamedList<Object> flds = (NamedList<Object>)res.get( "fields" );+ if( flds != null ) {+ fieldInfo = new HashMap<String,FieldInfo>( );+ for( Map.Entry<String, Object> field : flds ) {+ FieldInfo f = new FieldInfo( field.getKey() );+ f.read( (NamedList<Object>)field.getValue() );+ fieldInfo.put( field.getKey(), f );+ }+ }+ }++ //----------------------------------------------------------------+ //----------------------------------------------------------------++ public String getIndexDirectory()+ {+ if( indexInfo == null ) return null;+ return (String)indexInfo.get( "directory" );+ }++ public Integer getNumDocs()+ {+ if( indexInfo == null ) return null;+ return (Integer)indexInfo.get( "numDocs" );+ }++ public Integer getMaxDoc()+ {+ if( indexInfo == null ) return null;+ return (Integer)indexInfo.get( "maxDoc" );+ }++ public Integer getNumTerms()+ {+ if( indexInfo == null ) return null;+ return (Integer)indexInfo.get( "numTerms" );+ }++ public Map<String,FieldInfo> getFieldInfo() {+ return fieldInfo;+ }++ public FieldInfo getFieldInfo( String f ) {+ return fieldInfo.get( f );+ }++ //----------------------------------------------------------------+ //----------------------------------------------------------------+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/response/QueryResponse.java b/client/java/solrj/src/org/apache/solr/client/solrj/response/QueryResponse.javanew file mode 100644index 00000000000..039615923c2--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/response/QueryResponse.java@@ -0,0 +1,224 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.response;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++import org.apache.solr.common.SolrDocumentList;+import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+@SuppressWarnings("unchecked")+public class QueryResponse extends SolrResponseBase+{+ // Direct pointers to known types+ private NamedList<Object> _header = null;+ private SolrDocumentList _results = null;+ private NamedList<Object> _facetInfo = null;+ private NamedList<Object> _debugInfo = null;+ private NamedList<Object> _highlightingInfo = null;++ // Facet stuff+ private Map<String,Integer> _facetQuery = null;+ private List<FacetField> _facetFields = null;+ private List<FacetField> _limitingFacets = null;++ // Highlight Info+ private Map<String,Map<String,List<String>>> _highlighting = null;++ // Debug Info+ private Map<String,Object> _debugMap = null;+ private Map<String,Integer> _docIdMap = null;+ private Map<String,String> _explainMap = null;++ public QueryResponse( NamedList<Object> res )+ {+ super( res );++ // Look for known things+ for( int i=0; i<res.size(); i++ ) {+ String n = res.getName( i );+ if( "responseHeader".equals( n ) ) {+ _header = (NamedList<Object>) res.getVal( i );+ }+ else if( "response".equals( n ) ) {+ _results = (SolrDocumentList) res.getVal( i );+ }+ else if( "facet_counts".equals( n ) ) {+ _facetInfo = (NamedList<Object>) res.getVal( i );+ extractFacetInfo( _facetInfo );+ }+ else if( "debug".equals( n ) ) {+ _debugInfo = (NamedList<Object>) res.getVal( i );+ extractDebugInfo( _debugInfo );+ }+ else if( "highlighting".equals( n ) ) {+ _highlightingInfo = (NamedList<Object>) res.getVal( i );+ extractHighlightingInfo( _highlightingInfo );+ }+ }+ }++ private static final String DKEY = ",internal_docid=";++ private void extractDebugInfo( NamedList<Object> debug )+ {+ _debugMap = new LinkedHashMap<String, Object>(); // keep the order+ for( Map.Entry<String, Object> info : debug ) {+ _debugMap.put( info.getKey(), info.getValue() );+ }++ // Parse out interisting bits from the debug info+ _explainMap = new HashMap<String, String>();+ _docIdMap = new HashMap<String, Integer>();+ NamedList<String> explain = (NamedList<String>)_debugMap.get( "explain" );+ if( explain != null ) {+ for( Map.Entry<String, String> info : explain ) {+ String key = info.getKey();+ int idx0 = key.indexOf( '=' )+1;+ int idx1 = info.getKey().indexOf( DKEY );+ int idx2 = idx1 + DKEY.length();++ String id = key.substring( idx0, idx1 );+ String docID = key.substring( idx2 );++ _explainMap.put( id, info.getValue() );+ _docIdMap.put( id, Integer.valueOf( docID ) );+ }+ }+ }++ private void extractHighlightingInfo( NamedList<Object> info )+ {+ _highlighting = new HashMap<String,Map<String,List<String>>>();+ for( Map.Entry<String, Object> doc : info ) {+ Map<String,List<String>> fieldMap = new HashMap<String, List<String>>();+ _highlighting.put( doc.getKey(), fieldMap );++ NamedList<List<String>> fnl = (NamedList<List<String>>)doc.getValue();+ for( Map.Entry<String, List<String>> field : fnl ) {+ fieldMap.put( field.getKey(), field.getValue() );+ }+ }+ }++ private void extractFacetInfo( NamedList<Object> info )+ {+ // Parse the queries+ _facetQuery = new HashMap<String, Integer>();+ NamedList<Integer> fq = (NamedList<Integer>) info.get( "facet_queries" );+ for( Map.Entry<String, Integer> entry : fq ) {+ _facetQuery.put( entry.getKey(), entry.getValue() );+ }++ // Parse the facet info into fields+ NamedList<NamedList<Integer>> ff = (NamedList<NamedList<Integer>>) info.get( "facet_fields" );+ if( ff != null ) {+ _facetFields = new ArrayList<FacetField>( ff.size() );+ _limitingFacets = new ArrayList<FacetField>( ff.size() );++ int minsize = _results.getNumFound();+ for( Map.Entry<String,NamedList<Integer>> facet : ff ) {+ FacetField f = new FacetField( facet.getKey() );+ for( Map.Entry<String, Integer> entry : facet.getValue() ) {+ f.add( entry.getKey(), entry.getValue() );+ }++ _facetFields.add( f );+ FacetField nl = f.getLimitingFields( minsize );+ if( nl.getValueCount() > 0 ) {+ _limitingFacets.add( nl );+ }+ }+ }+ }++ //------------------------------------------------------+ //------------------------------------------------------++ /**+ * Remove the field facet info+ */+ public void removeFacets() {+ _facetFields = new ArrayList<FacetField>();+ }++ //------------------------------------------------------+ //------------------------------------------------------++ public NamedList<Object> getHeader() {+ return _header;+ }++ public SolrDocumentList getResults() {+ return _results;+ }++ public Map<String, Object> getDebugMap() {+ return _debugMap;+ }++ public Map<String, Integer> getDocIdMap() {+ return _docIdMap;+ }++ public Map<String, String> getExplainMap() {+ return _explainMap;+ }++ public Map<String,Integer> getFacetQuery() {+ return _facetQuery;+ }++ public Map<String, Map<String, List<String>>> getHighlighting() {+ return _highlighting;+ }++ public List<FacetField> getFacetFields() {+ return _facetFields;+ }++ /** get+ *+ * @param name the name of the+ * @return the FacetField by name or null if it does not exist+ */+ public FacetField getFacetField(String name) {+ if (_facetFields==null) return null;+ for (FacetField f : _facetFields) {+ if (f.getName().equals(name)) return f;+ }+ return null;+ }++ public List<FacetField> getLimitingFacets() {+ return _limitingFacets;+ }+}+++diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/response/SolrPingResponse.java b/client/java/solrj/src/org/apache/solr/client/solrj/response/SolrPingResponse.javanew file mode 100644index 00000000000..3e24f68bf3f--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/response/SolrPingResponse.java@@ -0,0 +1,33 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.response;++import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class SolrPingResponse extends SolrResponseBase+{+ public SolrPingResponse(NamedList<Object> res) {+ super(res);+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/response/SolrResponseBase.java b/client/java/solrj/src/org/apache/solr/client/solrj/response/SolrResponseBase.javanew file mode 100644index 00000000000..82a615c8982--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/response/SolrResponseBase.java@@ -0,0 +1,82 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.response;++import org.apache.solr.client.solrj.SolrResponse;+import org.apache.solr.common.util.NamedList;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public abstract class SolrResponseBase implements SolrResponse+{+ private long elapsedTime = -1;+ private NamedList<Object> response = null;+ private String requestUrl = null;++ public SolrResponseBase( NamedList<Object> res )+ {+ response = res;+ }++ public long getElapsedTime() {+ return elapsedTime;+ }++ public void setElapsedTime(long elapsedTime) {+ this.elapsedTime = elapsedTime;+ }++ public NamedList<Object> getResponse() {+ return response;+ }++ public void setResponse(NamedList<Object> response) {+ this.response = response;+ }++ @Override+ public String toString() {+ return response.toString();+ }++ public NamedList getResponseHeader() {+ return (NamedList) response.get("responseHeader");+ }++ // these two methods are based on the logic in SolrCore.setResponseHeaderValues(...)+ public int getStatus() {+ return (Integer) getResponseHeader().get("status");+ }++ public int getQTime() {+ return (Integer) getResponseHeader().get("QTime");+ }++ public String getRequestUrl() {+ return requestUrl;+ }++ public void setRequestUrl(String requestUrl) {+ this.requestUrl = requestUrl;+ }++}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/response/UpdateResponse.java b/client/java/solrj/src/org/apache/solr/client/solrj/response/UpdateResponse.javanew file mode 100644index 00000000000..0762ec54b07--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/response/UpdateResponse.java@@ -0,0 +1,35 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.response;++import org.apache.solr.common.util.NamedList;+++/**+ * TODO -- mostly a stub until we have a defined output format+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class UpdateResponse extends SolrResponseBase+{+ public UpdateResponse(NamedList<Object> res) {+ super(res);+ }+}diff --git a/client/java/solrj/src/org/apache/solr/client/solrj/util/ClientUtils.java b/client/java/solrj/src/org/apache/solr/client/solrj/util/ClientUtils.javanew file mode 100644index 00000000000..71d4c47660d--- /dev/null+++ b/client/java/solrj/src/org/apache/solr/client/solrj/util/ClientUtils.java@@ -0,0 +1,226 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.util;++import java.io.IOException;+import java.io.StringWriter;+import java.io.Writer;+import java.net.URLEncoder;+import java.text.DateFormat;+import java.text.ParseException;+import java.text.SimpleDateFormat;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Date;+import java.util.Iterator;+import java.util.TimeZone;++import org.apache.commons.httpclient.util.DateParseException;+import org.apache.commons.httpclient.util.DateUtil;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.ContentStream;+import org.apache.solr.common.util.ContentStreamBase;+import org.apache.solr.common.util.XML;+++/**+ * TODO? should this go in common?+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class ClientUtils+{+ // Standard Content types+ public static final String TEXT_XML = "text/xml; charset=utf-8";++ /**+ * Take a string and make it an iterable ContentStream+ */+ public static Collection<ContentStream> toContentStreams( final String str, final String contentType )+ {+ ContentStreamBase ccc = new ContentStreamBase.StringStream( str );+ ccc.setContentType( contentType );+ ArrayList<ContentStream> streams = new ArrayList<ContentStream>();+ streams.add( ccc );+ return streams;+ }++ //------------------------------------------------------------------------+ //------------------------------------------------------------------------++ private static void writeFieldValue(Writer writer, String fieldName, Float boost, Object fieldValue) throws IOException+ {+ if (fieldValue instanceof Date) {+ fieldValue = fmtThreadLocal.get().format( (Date)fieldValue );+ }+ if( boost != null ) {+ XML.writeXML(writer, "field", fieldValue.toString(), "name", fieldName, "boost", boost );+ }+ else if( fieldValue != null ){+ XML.writeXML(writer, "field", fieldValue.toString(), "name", fieldName);+ }+ }++ public static void writeXML( SolrInputDocument doc, Writer writer ) throws IOException+ {+ if( doc.getBoost( null ) != null ) {+ writer.write("<doc boost=\""+doc.getBoost( null )+"\">");+ }+ else {+ writer.write("<doc>");+ }++ for( String name : doc.getFieldNames() ) {+ Float boost = doc.getBoost( name );+ for( Object o : doc.getFieldValues( name ) ) {+ writeFieldValue(writer, name, boost, o );+ }+ }+ writer.write("</doc>");+ }+++ public static String toXML( SolrInputDocument doc )+ {+ StringWriter str = new StringWriter();+ try {+ writeXML( doc, str );+ }+ catch( Exception ex ){}+ return str.toString();+ }++ //---------------------------------------------------------------------------------------++ public static final Collection<String> fmts = new ArrayList<String>();+ static {+ fmts.add( "yyyy-MM-dd'T'HH:mm:ss'Z'" );+ fmts.add( "yyyy-MM-dd'T'HH:mm:ss" );+ fmts.add( "yyyy-MM-dd" );+ }++ /**+ * Returns a formatter that can be use by the current thread if needed to+ * convert Date objects to the Internal representation.+ * @throws ParseException+ * @throws DateParseException+ */+ public static Date parseDate( String d ) throws ParseException, DateParseException+ {+ // 2007-04-26T08:05:04Z+ if( d.endsWith( "Z" ) && d.length() > 20 ) {+ return getThreadLocalDateFormat().parse( d );+ }+ return DateUtil.parseDate( d, fmts );+ }++ /**+ * Returns a formatter that can be use by the current thread if needed to+ * convert Date objects to the Internal representation.+ */+ public static DateFormat getThreadLocalDateFormat() {++ return fmtThreadLocal.get();+ }++ public static TimeZone UTC = TimeZone.getTimeZone("UTC");+ private static ThreadLocalDateFormat fmtThreadLocal = new ThreadLocalDateFormat();++ private static class ThreadLocalDateFormat extends ThreadLocal<DateFormat> {+ DateFormat proto;+ public ThreadLocalDateFormat() {+ super();+ //2007-04-26T08:05:04Z+ SimpleDateFormat tmp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");+ tmp.setTimeZone(UTC);+ proto = tmp;+ }++ @Override+ protected DateFormat initialValue() {+ return (DateFormat) proto.clone();+ }+ }+++ /**+ * See: http://lucene.apache.org/java/docs/queryparsersyntax.html#Escaping Special Characters+ */+ public static String escapeQueryChars( String input )+ {+ char buff[] = input.toCharArray();+ StringBuilder str = new StringBuilder( buff.length+5 );+ for( char c : buff ) {+ switch( c ) {+ case '+':+ case '-':+ case '&':+ case '|':+ case '(':+ case ')':+ case '{':+ case '}':+ case '[':+ case ']':+ case '^':+ case '"':+ case '*':+ case ':':+ case '\\':+ str.append( '\\' );+ }+ str.append( c );+ }+ return str.toString();+ }+++ public static String toQueryString( SolrParams params, boolean xml ) {+ StringBuilder sb = new StringBuilder(128);+ try {+ String amp = xml ? "&" : "&";+ boolean first=true;+ Iterator<String> names = params.getParameterNamesIterator();+ while( names.hasNext() ) {+ String key = names.next();+ String[] valarr = params.getParams( key );+ if( valarr == null ) {+ sb.append( first?"?":amp );+ sb.append(key);+ first=false;+ }+ else {+ for (String val : valarr) {+ sb.append( first? "?":amp );+ sb.append(key);+ if( val != null ) {+ sb.append('=');+ sb.append( URLEncoder.encode( val, "UTF-8" ) );+ }+ first=false;+ }+ }+ }+ }+ catch (IOException e) {throw new RuntimeException(e);} // can't happen+ return sb.toString();+ }+}diff --git a/client/java/solrj/test/org/apache/solr/client/solrj/SolrExampleTestBase.java b/client/java/solrj/test/org/apache/solr/client/solrj/SolrExampleTestBase.javanew file mode 100644index 00000000000..db359bf6028--- /dev/null+++ b/client/java/solrj/test/org/apache/solr/client/solrj/SolrExampleTestBase.java@@ -0,0 +1,151 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;+++import java.util.ArrayList;+import java.util.List;++import junit.framework.Assert;++import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.client.solrj.response.UpdateResponse;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.util.AbstractSolrTestCase;++/**+ * This should include tests against the example solr config+ *+ * This lets us try various SolrServer implementations with the same tests.+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+abstract public class SolrExampleTestBase extends AbstractSolrTestCase+{+ @Override public String getSchemaFile() { return "../../../example/solr/conf/schema.xml"; }+ @Override public String getSolrConfigFile() { return "../../../example/solr/conf/solrconfig.xml"; }++ /**+ * Subclasses need to initalize the server impl+ */+ protected abstract SolrServer getSolrServer();++ /**+ * query the example+ */+ public void testExampleConfig() throws Exception+ {+ SolrServer server = getSolrServer();++ // Empty the database...+ server.deleteByQuery( "*:*" );// delete everything!++ // Now add something...+ SolrInputDocument doc = new SolrInputDocument();+ String docID = "1112211111";+ doc.addField( "id", docID );+ doc.addField( "name", "my name!" );++ Assert.assertEquals( null, doc.getFieldValue("foo"));+ Assert.assertTrue(doc.getFieldValue("name") != null );++ UpdateResponse upres = server.add( doc );+ System.out.println( "ADD:"+upres.getResponse() );+ Assert.assertEquals(0, upres.getStatus());++ upres = server.commit( true, true );+ System.out.println( "COMMIT:"+upres.getResponse() );+ Assert.assertEquals(0, upres.getStatus());++ upres = server.optimize( true, true );+ System.out.println( "OPTIMIZE:"+upres.getResponse() );+ Assert.assertEquals(0, upres.getStatus());++ SolrQuery query = new SolrQuery();+ query.setQuery( "id:"+docID );+ QueryResponse response = server.query( query );++ Assert.assertEquals(docID, response.getResults().get(0).getFieldValue("id") );++ // Now add a few docs for facet testing...+ List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();+ SolrInputDocument doc2 = new SolrInputDocument();+ doc2.addField( "id", "2" );+ doc2.addField( "inStock", true );+ doc2.addField( "price", 2 );+ doc2.addField( "timestamp", new java.util.Date() );+ docs.add(doc2);+ SolrInputDocument doc3 = new SolrInputDocument();+ doc3.addField( "id", "3" );+ doc3.addField( "inStock", false );+ doc3.addField( "price", 3 );+ doc3.addField( "timestamp", new java.util.Date() );+ docs.add(doc3);+ SolrInputDocument doc4 = new SolrInputDocument();+ doc4.addField( "id", "4" );+ doc4.addField( "inStock", true );+ doc4.addField( "price", 4 );+ doc4.addField( "timestamp", new java.util.Date() );+ docs.add(doc4);+ SolrInputDocument doc5 = new SolrInputDocument();+ doc5.addField( "id", "5" );+ doc5.addField( "inStock", false );+ doc5.addField( "price", 5 );+ doc5.addField( "timestamp", new java.util.Date() );+ docs.add(doc5);++ upres = server.add( docs );+ System.out.println( "ADD:"+upres.getResponse() );+ Assert.assertEquals(0, upres.getStatus());++ upres = server.commit( true, true );+ System.out.println( "COMMIT:"+upres.getResponse() );+ Assert.assertEquals(0, upres.getStatus());++ upres = server.optimize( true, true );+ System.out.println( "OPTIMIZE:"+upres.getResponse() );+ Assert.assertEquals(0, upres.getStatus());++ query = new SolrQuery("*:*");+ query.addFacetQuery("price:[* TO 2]");+ query.addFacetQuery("price:[2 TO 4]");+ query.addFacetQuery("price:[5 TO *]");+ query.addFacetField("inStock");+ query.addFacetField("price");+ query.addFacetField("timestamp");+ query.removeFilterQuery("inStock:true");++ response = server.query( query );+ Assert.assertEquals(0, response.getStatus());+ Assert.assertEquals(5, response.getResults().getNumFound() );+ Assert.assertEquals(3, response.getFacetQuery().size());+ Assert.assertEquals(2, response.getFacetField("inStock").getValueCount());+ Assert.assertEquals(4, response.getFacetField("price").getValueCount());++ // test a second query, test making a copy of the main query+ SolrQuery query2 = query.getCopy();+ query2.addFilterQuery("inStock:true");+ response = server.query( query2 );+ Assert.assertEquals(1, query2.getFilterQueries().length);+ Assert.assertEquals(0, response.getStatus());+ Assert.assertEquals(2, response.getResults().getNumFound() );+ Assert.assertFalse(query.getFilterQueries() == query2.getFilterQueries());+ }+}diff --git a/client/java/solrj/test/org/apache/solr/client/solrj/SolrExceptionTest.java b/client/java/solrj/test/org/apache/solr/client/solrj/SolrExceptionTest.javanew file mode 100644index 00000000000..8d52cdf06ac--- /dev/null+++ b/client/java/solrj/test/org/apache/solr/client/solrj/SolrExceptionTest.java@@ -0,0 +1,50 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import java.net.UnknownHostException;++import junit.framework.TestCase;++import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class SolrExceptionTest extends TestCase {++ public void testSolrException() throws Throwable {+ // test a connection to a solr server that probably doesn't exist+ // this is a very simple test and most of the test should be considered verified+ // if the compiler won't let you by without the try/catch+ boolean gotExpectedError = false;+ try {+ SolrServer client = new CommonsHttpSolrServer("http://333.333.333.333:8080/solr/");+ SolrQuery query = new SolrQuery("test123");+ client.query(query);+ } catch (SolrServerException sse) {+ gotExpectedError = true;+ assertTrue(UnknownHostException.class == sse.getRootCause().getClass());+ }+ assertTrue(gotExpectedError);+ }++}diff --git a/client/java/solrj/test/org/apache/solr/client/solrj/SolrQueryTest.java b/client/java/solrj/test/org/apache/solr/client/solrj/SolrQueryTest.javanew file mode 100644index 00000000000..108759fb787--- /dev/null+++ b/client/java/solrj/test/org/apache/solr/client/solrj/SolrQueryTest.java@@ -0,0 +1,86 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj;++import junit.framework.Assert;+import junit.framework.TestCase;++/**+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class SolrQueryTest extends TestCase {++ public void testSolrQueryMethods() {+ SolrQuery q = new SolrQuery("dog");+ boolean b = false;++ q.setFacetLimit(10);+ q.addFacetField("price");+ q.addFacetField("state");+ Assert.assertEquals(q.getFacetFields().length, 2);+ q.addFacetQuery("instock:true");+ q.addFacetQuery("instock:false");+ q.addFacetQuery("a:b");+ Assert.assertEquals(q.getFacetQuery().length, 3);++ b = q.removeFacetField("price");+ Assert.assertEquals(b, true);+ b = q.removeFacetField("price2");+ Assert.assertEquals(b, false);+ b = q.removeFacetField("state");+ Assert.assertEquals(b, true);+ Assert.assertEquals(null, q.getFacetFields());++ b = q.removeFacetQuery("instock:true");+ Assert.assertEquals(b, true);+ b = q.removeFacetQuery("instock:false");+ b = q.removeFacetQuery("a:c");+ Assert.assertEquals(b, false);+ b = q.removeFacetQuery("a:b");+ Assert.assertEquals(null, q.getFacetQuery());++ q.addSortField("price", SolrQuery.ORDER.asc);+ q.addSortField("date", SolrQuery.ORDER.desc);+ q.addSortField("qty", SolrQuery.ORDER.desc);+ q.removeSortField("date", SolrQuery.ORDER.desc);+ Assert.assertEquals(2, q.getSortFields().length);+ q.removeSortField("price", SolrQuery.ORDER.asc);+ q.removeSortField("qty", SolrQuery.ORDER.desc);+ Assert.assertEquals(null, q.getSortFields());++ q.addHighlightField("hl1");+ q.addHighlightField("hl2");+ q.setHighlightSnippets(2);+ Assert.assertEquals(2, q.getHighlightFields().length);+ Assert.assertEquals(100, q.getHighlightFragsize());+ Assert.assertEquals(q.getHighlightSnippets(), 2);+ q.removeHighlightField("hl1");+ q.removeHighlightField("hl3");+ Assert.assertEquals(1, q.getHighlightFields().length);+ q.removeHighlightField("hl2");+ Assert.assertEquals(null, q.getHighlightFields());++ // check to see that the removes are properly clearing the cgi params+ Assert.assertEquals(q.toString(), "q=dog");++ System.out.println(q);+ }+}diff --git a/client/java/solrj/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServer.java b/client/java/solrj/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServer.javanew file mode 100644index 00000000000..a314515a611--- /dev/null+++ b/client/java/solrj/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServer.java@@ -0,0 +1,48 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.embedded;++import org.apache.solr.client.solrj.SolrExampleTestBase;+import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.core.SolrCore;++/**+ * This runs SolrServer test using+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class TestEmbeddedSolrServer extends SolrExampleTestBase {++ SolrServer server;++ @Override public void setUp() throws Exception+ {+ super.setUp();++ // setup the server...+ server = new EmbeddedSolrServer( SolrCore.getSolrCore() );+ }++ @Override+ protected SolrServer getSolrServer()+ {+ return server;+ }+}diff --git a/client/java/solrj/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java b/client/java/solrj/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.javanew file mode 100644index 00000000000..e3d85660e8b--- /dev/null+++ b/client/java/solrj/test/org/apache/solr/client/solrj/embedded/TestJettySolrRunner.java@@ -0,0 +1,61 @@+/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.client.solrj.embedded;++import org.apache.solr.client.solrj.SolrExampleTestBase;+import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;++/**+ * TODO? perhaps use:+ * http://docs.codehaus.org/display/JETTY/ServletTester+ * rather then open a real connection?+ *+ * @author ryan+ * @version $Id$+ * @since solr 1.3+ */+public class TestJettySolrRunner extends SolrExampleTestBase {++ SolrServer server;+ JettySolrRunner jetty;++ @Override public void setUp() throws Exception+ {+ super.setUp();++ int port = 8983;+ String context = "/example";++ jetty = new JettySolrRunner( context, port );+ jetty.start();++ // setup the server...+ String url = "http://localhost:"+port+context;+ server = new CommonsHttpSolrServer( url );+ ((CommonsHttpSolrServer)server).setConnectionTimeout(5);+ ((CommonsHttpSolrServer)server).setDefaultMaxConnectionsPerHost(100);+ ((CommonsHttpSolrServer)server).setMaxTotalConnections(100);+ }++ @Override+ protected SolrServer getSolrServer()+ {+ return server;+ }+}diff --git a/lib/stax-1.2.0-dev.jar b/lib/stax-1.2.0-dev.jarnew file mode 100644index 00000000000..a25126c506e--- /dev/null+++ b/lib/stax-1.2.0-dev.jar@@ -0,0 +1,2 @@+AnyObjectId[2cf1ca4881b24623fb64cbb0f470de65a23cd1fe] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/lib/stax-api-1.0.jar b/lib/stax-api-1.0.jarnew file mode 100644index 00000000000..6b279c3d9b5--- /dev/null+++ b/lib/stax-api-1.0.jar@@ -0,0 +1,2 @@+AnyObjectId[8687bd31b95deb498c091ef91cdff390d8cce017] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/lib/stax-utils.jar b/lib/stax-utils.jarnew file mode 100644index 00000000000..0582965060a--- /dev/null+++ b/lib/stax-utils.jar@@ -0,0 +1,2 @@+AnyObjectId[cd0573d31467410867251dad9df12ebeb97443ab] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/src/test/test-files/solr/conf/solrconfig.xml b/src/test/test-files/solr/conf/solrconfig.xmlindex 410bfb7894f..ebd63fec17f 100644--- a/src/test/test-files/solr/conf/solrconfig.xml+++ b/src/test/test-files/solr/conf/solrconfig.xml@@ -262,8 +262,8 @@</lst></requestHandler>- <requestHandler name="/update/csv" class="solr.CSVRequestHandler" startup="lazy">- </requestHandler>+ <requestHandler name="/update" class="solr.XmlUpdateRequestHandler" />+ <requestHandler name="/update/csv" class="solr.CSVRequestHandler" startup="lazy" /><!-- enable streaming for testing... --><requestDispatcher handleSelect="true" >