Apache Lucene open-source search software
SOLR-2020: migrate to Java client that uses Apache Http Components http client (4.x)
Sami Sirenb5f8deb7959b
diff --git a/dev-tools/eclipse/dot.classpath b/dev-tools/eclipse/dot.classpathindex 32c485b18b2..b8c8dfb4858 100644--- a/dev-tools/eclipse/dot.classpath+++ b/dev-tools/eclipse/dot.classpath@@ -104,7 +104,9 @@<classpathentry kind="lib" path="solr/lib/apache-solr-noggit-r1211150.jar"/><classpathentry kind="lib" path="solr/lib/apache-solr-commons-csv-1.0-SNAPSHOT-r966014.jar"/><classpathentry kind="lib" path="solr/lib/commons-fileupload-1.2.1.jar"/>- <classpathentry kind="lib" path="solr/lib/commons-httpclient-3.1.jar"/>+ <classpathentry kind="lib" path="solr/lib/httpclient-4.1.3.jar"/>+ <classpathentry kind="lib" path="solr/lib/httpcore-4.1.4.jar"/>+ <classpathentry kind="lib" path="solr/lib/httpmime-4.1.3.jar"/><classpathentry kind="lib" path="solr/lib/commons-io-2.1.jar"/><classpathentry kind="lib" path="solr/lib/commons-lang-2.6.jar"/><classpathentry kind="lib" path="solr/lib/easymock-2.2.jar"/>diff --git a/dev-tools/maven/pom.xml.template b/dev-tools/maven/pom.xml.templateindex 8905c163cc0..36219102d02 100644--- a/dev-tools/maven/pom.xml.template+++ b/dev-tools/maven/pom.xml.template@@ -45,6 +45,7 @@<jetty.version>8.1.2.v20120308</jetty.version><slf4j.version>1.6.1</slf4j.version><tika.version>1.0</tika.version>+ <httpcomponents.version>4.1.3</httpcomponents.version></properties><issueManagement><system>JIRA</system>@@ -150,9 +151,14 @@<version>2.1</version></dependency><dependency>- <groupId>commons-httpclient</groupId>- <artifactId>commons-httpclient</artifactId>- <version>3.1</version>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpclient</artifactId>+ <version>${httpcomponents.version}</version>+ </dependency>+ <dependency>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpmime</artifactId>+ <version>${httpcomponents.version}</version></dependency><dependency><groupId>commons-lang</groupId>diff --git a/dev-tools/maven/solr/core/pom.xml.template b/dev-tools/maven/solr/core/pom.xml.templateindex 75fe98de4ff..bcffb16d102 100644--- a/dev-tools/maven/solr/core/pom.xml.template+++ b/dev-tools/maven/solr/core/pom.xml.template@@ -151,14 +151,8 @@<artifactId>commons-fileupload</artifactId></dependency><dependency>- <groupId>commons-httpclient</groupId>- <artifactId>commons-httpclient</artifactId>- <exclusions>- <exclusion>- <groupId>commons-logging</groupId>- <artifactId>commons-logging</artifactId>- </exclusion>- </exclusions>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpmime</artifactId></dependency><dependency><groupId>org.slf4j</groupId>@@ -213,6 +207,20 @@<artifactId>easymock</artifactId><scope>test</scope></dependency>+ <dependency>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpclient</artifactId>+ <exclusions>+ <exclusion>+ <groupId>commons-logging</groupId>+ <artifactId>commons-logging</artifactId>+ </exclusion>+ </exclusions>+ </dependency>+ <dependency>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpmime</artifactId>+ </dependency></dependencies><build><directory>${build-directory}</directory>diff --git a/dev-tools/maven/solr/solrj/pom.xml.template b/dev-tools/maven/solr/solrj/pom.xml.templateindex e150b6f43cb..a68a1bde234 100644--- a/dev-tools/maven/solr/solrj/pom.xml.template+++ b/dev-tools/maven/solr/solrj/pom.xml.template@@ -84,14 +84,8 @@<artifactId>log4j-over-slf4j</artifactId></dependency><dependency>- <groupId>commons-httpclient</groupId>- <artifactId>commons-httpclient</artifactId>- <exclusions>- <exclusion>- <groupId>commons-logging</groupId>- <artifactId>commons-logging</artifactId>- </exclusion>- </exclusions>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpmime</artifactId></dependency><dependency><groupId>org.slf4j</groupId>@@ -101,6 +95,22 @@<groupId>commons-io</groupId><artifactId>commons-io</artifactId></dependency>+ <dependency>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpclient</artifactId>+ <!-- HttpSolrServer requires this dependency. -->+ <exclusions>+ <exclusion>+ <groupId>commons-logging</groupId>+ <artifactId>commons-logging</artifactId>+ </exclusion>+ </exclusions>+ </dependency>+ <dependency>+ <groupId>org.apache.httpcomponents</groupId>+ <artifactId>httpmime</artifactId>+ <!-- HttpSolrServer requires this dependency. -->+ </dependency><!-- Technically, this is optional in SolrJ; but it's fast. SOLR-2852 --><dependency><groupId>org.codehaus.woodstox</groupId>diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex a298be5bdf0..560ec60eade 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -508,6 +508,9 @@ Upgrading from Solr 3.5New Features----------------------+* SOLR-2020: Add Java client that uses Apache Http Components http client (4.x).+ (Chantal Ackermann, Ryan McKinley, Yonik Seeley, siren)+* SOLR-2854: Now load URL content stream data (via stream.url) when called for during request handling,rather than loading URL content streams automatically regardless of use.(David Smiley and Ryan McKinley via ehatcher)diff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/SolrEntityProcessor.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/SolrEntityProcessor.javaindex 56f7499bd4b..6e5bf9accbc 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/SolrEntityProcessor.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/SolrEntityProcessor.java@@ -17,12 +17,13 @@ package org.apache.solr.handler.dataimport;* limitations under the License.*/-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;+import org.apache.http.client.HttpClient;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.impl.XMLResponseParser;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;@@ -82,7 +83,7 @@ public class SolrEntityProcessor extends EntityProcessorBase {* @return a {@link HttpClient} instance used for interfacing with a source Solr service*/protected HttpClient getHttpClient() {- return new HttpClient(new MultiThreadedHttpConnectionManager());+ return new DefaultHttpClient(new ThreadSafeClientConnManager());}@Override@@ -100,10 +101,10 @@ public class SolrEntityProcessor extends EntityProcessorBase {URL url = new URL(serverPath);// (wt="javabin|xml") default is javabinif ("xml".equals(context.getResolvedEntityAttribute(CommonParams.WT))) {- solrServer = new CommonsHttpSolrServer(url, client, new XMLResponseParser(), false);+ solrServer = new HttpSolrServer(url.toExternalForm(), client, new XMLResponseParser());LOG.info("using XMLResponseParser");} else {- solrServer = new CommonsHttpSolrServer(url, client);+ solrServer = new HttpSolrServer(url.toExternalForm(), client);LOG.info("using BinaryResponseParser");}} catch (MalformedURLException e) {diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContentStreamDataSource.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContentStreamDataSource.javaindex 3098875f351..c41a4358873 100644--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContentStreamDataSource.java+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContentStreamDataSource.java@@ -18,7 +18,7 @@ package org.apache.solr.handler.dataimport;import org.apache.commons.io.FileUtils;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.DirectXmlRequest;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;@@ -69,7 +69,7 @@ public class TestContentStreamDataSource extends AbstractDataImportHandlerTestCaparams.set("clean", "false");req.setParams(params);String url = "http://localhost:" + jetty.getLocalPort() + "/solr";- CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(url);+ HttpSolrServer solrServer = new HttpSolrServer(url);solrServer.request(req);ModifiableSolrParams qparams = new ModifiableSolrParams();qparams.add("q", "*:*");@@ -89,7 +89,7 @@ public class TestContentStreamDataSource extends AbstractDataImportHandlerTestCaUpdateParams.COMMIT_WITHIN, "1000");req.setParams(params);String url = "http://localhost:" + jetty.getLocalPort() + "/solr";- CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(url);+ HttpSolrServer solrServer = new HttpSolrServer(url);solrServer.request(req);Thread.sleep(100);ModifiableSolrParams queryAll = params("q", "*");diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.javaindex ad611d64d2f..ed515e73280 100644--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestSolrEntityProcessorEndToEnd.java@@ -26,12 +26,12 @@ import java.util.List;import java.util.Map;import java.util.Map.Entry;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;import org.apache.commons.io.FileUtils;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.common.SolrInputDocument;import org.junit.After;import org.junit.AfterClass;@@ -274,9 +274,9 @@ public class TestSolrEntityProcessorEndToEnd extends AbstractDataImportHandlerTesidl.add(sd);}- HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());+ DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());URL url = new URL(getSourceUrl(jetty.getLocalPort()));- CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(url, client);+ HttpSolrServer solrServer = new HttpSolrServer(url.toExternalForm(), client);solrServer.add(sidl);solrServer.commit(true, true);}diff --git a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.javaindex 0ba5b363838..944c9335001 100644--- a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java+++ b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java@@ -28,8 +28,8 @@ import javax.servlet.http.HttpServletResponse;import org.apache.solr.servlet.SolrDispatchFilter;import org.eclipse.jetty.server.*;-import org.eclipse.jetty.server.Server;import org.eclipse.jetty.server.bio.SocketConnector;+import org.eclipse.jetty.server.handler.GzipHandler;import org.eclipse.jetty.server.session.HashSessionIdManager;import org.eclipse.jetty.servlet.FilterHolder;import org.eclipse.jetty.servlet.ServletContextHandler;@@ -124,6 +124,7 @@ public class JettySolrRunner {// Initialize the servletsfinal ServletContextHandler root = new ServletContextHandler(server,context,ServletContextHandler.SESSIONS);+ root.setHandler(new GzipHandler());server.addLifeCycleListener(new LifeCycle.Listener() {public void lifeCycleStopping(LifeCycle arg0) {diff --git a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.javaindex 6e539e4700e..98f6c1f3d98 100644--- a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java+++ b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java@@ -26,7 +26,7 @@ import java.util.concurrent.Future;import java.util.concurrent.TimeoutException;import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.AbstractUpdateRequest;import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState;import org.apache.solr.client.solrj.request.UpdateRequest;@@ -159,7 +159,7 @@ public class RecoveryStrategy extends Thread implements SafeStopThread {private void commitOnLeader(String leaderUrl) throws MalformedURLException,SolrServerException, IOException {- CommonsHttpSolrServer server = new CommonsHttpSolrServer(leaderUrl);+ HttpSolrServer server = new HttpSolrServer(leaderUrl);server.setConnectionTimeout(30000);server.setSoTimeout(30000);UpdateRequest ureq = new UpdateRequest();@@ -174,7 +174,7 @@ public class RecoveryStrategy extends Thread implements SafeStopThread {private void sendPrepRecoveryCmd(String leaderBaseUrl,String leaderCoreName) throws MalformedURLException, SolrServerException,IOException {- CommonsHttpSolrServer server = new CommonsHttpSolrServer(leaderBaseUrl);+ HttpSolrServer server = new HttpSolrServer(leaderBaseUrl);server.setConnectionTimeout(45000);server.setSoTimeout(45000);WaitForState prepCmd = new WaitForState();diff --git a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.javaindex 308066eadcb..9ca9eecfeac 100644--- a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java+++ b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java@@ -23,12 +23,12 @@ import java.util.ArrayList;import java.util.List;import java.util.Map;-import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;-import org.apache.commons.httpclient.params.HttpMethodParams;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.http.params.CoreConnectionPNames;import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery;import org.apache.solr.common.SolrException;import org.apache.solr.common.cloud.CloudState;@@ -55,17 +55,16 @@ public class SyncStrategy {private ShardHandler shardHandler;- private static MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();- private static HttpClient client = new HttpClient(mgr);+ private static ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager();+ private static DefaultHttpClient client = new DefaultHttpClient(mgr);static {- mgr.getParams().setDefaultMaxConnectionsPerHost(20);- mgr.getParams().setMaxTotalConnections(10000);- mgr.getParams().setConnectionTimeout(30000);- mgr.getParams().setSoTimeout(30000);-+ mgr.setDefaultMaxPerRoute(20);+ mgr.setMaxTotal(10000);+ client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);+ client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// prevent retries (note: this didn't work when set on mgr.. needed to be set on client)- DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);- client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);+ DefaultHttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(0, false);+ client.setHttpRequestRetryHandler(retryhandler);}public SyncStrategy() {@@ -241,7 +240,7 @@ public class SyncStrategy {recoverRequestCmd.setAction(CoreAdminAction.REQUESTRECOVERY);recoverRequestCmd.setCoreName(((SyncShardRequest)srsp.getShardRequest()).coreName);- CommonsHttpSolrServer server = new CommonsHttpSolrServer(zkLeader.getBaseUrl());+ HttpSolrServer server = new HttpSolrServer(zkLeader.getBaseUrl());server.request(recoverRequestCmd);} catch (Exception e) {log.info("Could not tell a replica to recover", e);diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex 83d400a8899..67310c31fb8 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -20,7 +20,6 @@ package org.apache.solr.cloud;import java.io.File;import java.io.IOException;import java.net.InetAddress;-import java.net.MalformedURLException;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;@@ -33,7 +32,7 @@ import java.util.concurrent.TimeoutException;import java.util.regex.Matcher;import java.util.regex.Pattern;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;@@ -1119,13 +1118,8 @@ public final class ZkController {boolean isLeader = leaderProps.getCoreUrl().equals(ourUrl);if (!isLeader && !SKIP_AUTO_RECOVERY) {- CommonsHttpSolrServer server = null;- try {- server = new CommonsHttpSolrServer(leaderBaseUrl);- } catch (MalformedURLException e) {- throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "",- e);- }+ HttpSolrServer server = null;+ server = new HttpSolrServer(leaderBaseUrl);server.setConnectionTimeout(45000);server.setSoTimeout(45000);WaitForState prepCmd = new WaitForState();diff --git a/solr/core/src/java/org/apache/solr/handler/SnapPuller.java b/solr/core/src/java/org/apache/solr/handler/SnapPuller.javaindex 21f5e97f9e2..e23a4a1fa07 100644--- a/solr/core/src/java/org/apache/solr/handler/SnapPuller.java+++ b/solr/core/src/java/org/apache/solr/handler/SnapPuller.java@@ -16,10 +16,21 @@*/package org.apache.solr.handler;-import org.apache.commons.httpclient.*;-import org.apache.commons.httpclient.auth.AuthScope;-import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.io.IOUtils;+import org.apache.http.Header;+import org.apache.http.HttpResponse;+import org.apache.http.HttpStatus;+import org.apache.http.auth.AuthScope;+import org.apache.http.auth.UsernamePasswordCredentials;+import org.apache.http.client.HttpClient;+import org.apache.http.client.entity.UrlEncodedFormEntity;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.http.message.AbstractHttpMessage;+import org.apache.http.message.BasicNameValuePair;+import org.apache.http.params.CoreConnectionPNames;+import org.apache.http.util.EntityUtils;import org.apache.lucene.index.IndexCommit;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.ModifiableSolrParams;@@ -109,17 +120,23 @@ public class SnapPuller {// HttpClient for this instance if connectionTimeout or readTimeout has been specifiedprivate final HttpClient myHttpClient;- private static synchronized HttpClient createHttpClient(String connTimeout, String readTimeout) {+ private static synchronized HttpClient createHttpClient(String connTimeout, String readTimeout, String httpBasicAuthUser, String httpBasicAuthPassword) {if (connTimeout == null && readTimeout == null && client != null) return client;- MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();+ ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager();// Keeping a very high number so that if you have a large number of cores// no requests are kept waiting for an idle connection.- mgr.getParams().setDefaultMaxConnectionsPerHost(10000);- mgr.getParams().setMaxTotalConnections(10000);- mgr.getParams().setSoTimeout(readTimeout == null ? 20000 : Integer.parseInt(readTimeout)); //20 secs- mgr.getParams().setConnectionTimeout(connTimeout == null ? 5000 : Integer.parseInt(connTimeout)); //5 secs- HttpClient httpClient = new HttpClient(mgr);+ mgr.setDefaultMaxPerRoute(10000);+ mgr.setMaxTotal(10000);+ DefaultHttpClient httpClient = new DefaultHttpClient(mgr);+ httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout == null ? 20000 : Integer.parseInt(readTimeout)); //20 secs+ httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connTimeout == null ? 5000 : Integer.parseInt(connTimeout)); //5 secsif (client == null && connTimeout == null && readTimeout == null) client = httpClient;++ if (httpBasicAuthUser != null && httpBasicAuthPassword != null) {+ httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,+ new UsernamePasswordCredentials(httpBasicAuthUser, httpBasicAuthPassword));+ }+return httpClient;}@@ -139,11 +156,7 @@ public class SnapPuller {String readTimeout = (String) initArgs.get(HTTP_READ_TIMEOUT);String httpBasicAuthUser = (String) initArgs.get(HTTP_BASIC_AUTH_USER);String httpBasicAuthPassword = (String) initArgs.get(HTTP_BASIC_AUTH_PASSWORD);- myHttpClient = createHttpClient(connTimeout, readTimeout);- if (httpBasicAuthUser != null && httpBasicAuthPassword != null) {- myHttpClient.getState().setCredentials(AuthScope.ANY,- new UsernamePasswordCredentials(httpBasicAuthUser, httpBasicAuthPassword));- }+ myHttpClient = createHttpClient(connTimeout, readTimeout, httpBasicAuthUser, httpBasicAuthPassword);if (pollInterval != null && pollInterval > 0) {startExecutorService();} else {@@ -177,45 +190,66 @@ public class SnapPuller {*/@SuppressWarnings("unchecked")NamedList getLatestVersion() throws IOException {- PostMethod post = new PostMethod(masterUrl);- post.addParameter(COMMAND, CMD_INDEX_VERSION);- post.addParameter("wt", "javabin");+ HttpPost post = new HttpPost(masterUrl);+ List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();+ formparams.add(new BasicNameValuePair("wt", "javabin"));+ formparams.add(new BasicNameValuePair(COMMAND, CMD_INDEX_VERSION));+ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");+ post.setEntity(entity);return getNamedListResponse(post);}NamedList getCommandResponse(NamedList<String> commands) throws IOException {- PostMethod post = new PostMethod(masterUrl);++ HttpPost post = new HttpPost(masterUrl);++ List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();+ formparams.add(new BasicNameValuePair("wt", "javabin"));+for (Map.Entry<String, String> c : commands) {- post.addParameter(c.getKey(),c.getValue());+ formparams.add(new BasicNameValuePair(c.getKey(), c.getValue()));}- post.addParameter("wt", "javabin");+ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");+ post.setEntity(entity);return getNamedListResponse(post);}- private NamedList<?> getNamedListResponse(PostMethod method) throws IOException {+ private NamedList<?> getNamedListResponse(HttpPost method) throws IOException {+ InputStream input = null;+ NamedList<?> result = null;try {- int status = myHttpClient.executeMethod(method);+ HttpResponse response = myHttpClient.execute(method);+ int status = response.getStatusLine().getStatusCode();if (status != HttpStatus.SC_OK) {throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE,"Request failed for the url " + method);}- return (NamedList<?>) new JavaBinCodec().unmarshal(method.getResponseBodyAsStream());+ input = response.getEntity().getContent();+ result = (NamedList<?>)new JavaBinCodec().unmarshal(input);} finally {try {- method.releaseConnection();+ if (input != null) {+ input.close();+ }} catch (Exception e) {}}+ return result;}/*** Fetches the list of files in a given index commit point*/void fetchFileList(long gen) throws IOException {- PostMethod post = new PostMethod(masterUrl);- post.addParameter(COMMAND, CMD_GET_FILE_LIST);- post.addParameter(GENERATION, String.valueOf(gen));- post.addParameter("wt", "javabin");+ HttpPost post = new HttpPost(masterUrl);++ List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();+ formparams.add(new BasicNameValuePair("wt", "javabin"));+ formparams.add(new BasicNameValuePair(COMMAND, CMD_GET_FILE_LIST));+ formparams.add(new BasicNameValuePair(GENERATION, String.valueOf(gen)));++ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");+ post.setEntity(entity);@SuppressWarnings("unchecked")NamedList<List<Map<String, Object>>> nl@@ -907,7 +941,7 @@ public class SnapPuller {private boolean isConf;- private PostMethod post;+ private HttpPost post;private boolean aborted = false;@@ -1064,10 +1098,6 @@ public class SnapPuller {} catch (Exception e) {/* noop */LOG.error("Error closing the file stream: "+ this.saveAs ,e);}- try {- post.releaseConnection();- } catch (Exception e) {- }if (bytesDownloaded != size) {//if the download is not complete then//delete the file being downloaded@@ -1088,35 +1118,43 @@ public class SnapPuller {* Open a new stream using HttpClient*/FastInputStream getStream() throws IOException {- post = new PostMethod(masterUrl);+ post = new HttpPost(masterUrl);//the method is command=filecontent- post.addParameter(COMMAND, CMD_GET_FILE);++ List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();++ formparams.add(new BasicNameValuePair(COMMAND, CMD_GET_FILE));+//add the version to download. This is used to reserve the download- post.addParameter(GENERATION, indexGen.toString());+ formparams.add(new BasicNameValuePair(GENERATION, indexGen.toString()));if (isConf) {//set cf instead of file for config file- post.addParameter(CONF_FILE_SHORT, fileName);+ formparams.add(new BasicNameValuePair(CONF_FILE_SHORT, fileName));} else {- post.addParameter(FILE, fileName);+ formparams.add(new BasicNameValuePair(FILE, fileName));}if (useInternal) {- post.addParameter(COMPRESSION, "true");+ formparams.add(new BasicNameValuePair(COMPRESSION, "true"));}if (useExternal) {- post.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));+ formparams.add(new BasicNameValuePair("Accept-Encoding", "gzip,deflate"));}//use checksumif (this.includeChecksum)- post.addParameter(CHECKSUM, "true");+ formparams.add(new BasicNameValuePair(CHECKSUM, "true"));//wt=filestream this is a custom protocol- post.addParameter("wt", FILE_STREAM);+ formparams.add(new BasicNameValuePair("wt", FILE_STREAM));// This happen if there is a failure there is a retry. the offset=<sizedownloaded> ensures that// the server starts from the offsetif (bytesDownloaded > 0) {- post.addParameter(OFFSET, "" + bytesDownloaded);+ formparams.add(new BasicNameValuePair(OFFSET, "" + bytesDownloaded));}- myHttpClient.executeMethod(post);- InputStream is = post.getResponseBodyAsStream();++ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");+ post.setEntity(entity);++ HttpResponse response = myHttpClient.execute(post);+ InputStream is = response.getEntity().getContent();//wrap it using FastInputStreamif (useInternal) {is = new InflaterInputStream(is);@@ -1130,8 +1168,8 @@ public class SnapPuller {/** This is copied from CommonsHttpSolrServer*/- private InputStream checkCompressed(HttpMethod method, InputStream respBody) throws IOException {- Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");+ private InputStream checkCompressed(AbstractHttpMessage method, InputStream respBody) throws IOException {+ Header contentEncodingHeader = method.getFirstHeader("Content-Encoding");if (contentEncodingHeader != null) {String contentEncoding = contentEncodingHeader.getValue();if (contentEncoding.contains("gzip")) {@@ -1140,7 +1178,7 @@ public class SnapPuller {respBody = new InflaterInputStream(respBody);}} else {- Header contentTypeHeader = method.getResponseHeader("Content-Type");+ Header contentTypeHeader = method.getFirstHeader("Content-Type");if (contentTypeHeader != null) {String contentType = contentTypeHeader.getValue();if (contentType != null) {diff --git a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.java b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.javaindex 19f3fce45f0..9daebb43a88 100644--- a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.java@@ -16,11 +16,24 @@ package org.apache.solr.handler.component;* limitations under the License.*/-import org.apache.commons.httpclient.HttpClient;+import java.net.ConnectException;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.Callable;+import java.util.concurrent.CompletionService;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.ExecutorCompletionService;+import java.util.concurrent.Future;++import org.apache.http.client.HttpClient;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrResponse;import org.apache.solr.client.solrj.SolrServer;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.impl.LBHttpSolrServer;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.client.solrj.util.ClientUtils;@@ -42,10 +55,6 @@ import org.apache.solr.common.util.StrUtils;import org.apache.solr.core.CoreDescriptor;import org.apache.solr.request.SolrQueryRequest;-import java.net.ConnectException;-import java.util.*;-import java.util.concurrent.*;-public class HttpShardHandler extends ShardHandler {private HttpShardHandlerFactory httpShardHandlerFactory;@@ -152,7 +161,7 @@ public class HttpShardHandler extends ShardHandler {if (urls.size() <= 1) {String url = urls.get(0);srsp.setShardAddress(url);- SolrServer server = new CommonsHttpSolrServer(url, httpClient == null ? httpShardHandlerFactory.client : httpClient);+ SolrServer server = new HttpSolrServer(url, httpClient == null ? httpShardHandlerFactory.client : httpClient);ssr.nl = server.request(req);} else {LBHttpSolrServer.Rsp rsp = httpShardHandlerFactory.loadbalancer.request(new LBHttpSolrServer.Req(req, urls));diff --git a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.java b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.javaindex 3b5ad013355..596f08b4bc2 100644--- a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.java+++ b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.java@@ -16,10 +16,15 @@ package org.apache.solr.handler.component;* limitations under the License.*/-import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;-import org.apache.commons.httpclient.params.HttpMethodParams;+import java.net.MalformedURLException;+import java.util.Random;+import java.util.concurrent.*;++import org.apache.http.client.HttpClient;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.http.params.CoreConnectionPNames;import org.apache.solr.client.solrj.impl.LBHttpSolrServer;import org.apache.solr.common.SolrException;import org.apache.solr.common.util.NamedList;@@ -29,10 +34,6 @@ import org.apache.solr.util.plugin.PluginInfoInitialized;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import java.net.MalformedURLException;-import java.util.Random;-import java.util.concurrent.*;-public class HttpShardHandlerFactory extends ShardHandlerFactory implements PluginInfoInitialized {protected static Logger log = LoggerFactory.getLogger(HttpShardHandlerFactory.class);@@ -64,7 +65,7 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements Plugpublic String scheme = "http://"; //current default values- private MultiThreadedHttpConnectionManager mgr;+ private ThreadSafeClientConnManager mgr;// socket timeout measured in ms, closes a socket if read// takes longer than x ms to complete. throws// java.net.SocketTimeoutException: Read timed out exception@@ -100,7 +101,7 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements Plugreturn getShardHandler(null);}- public ShardHandler getShardHandler(HttpClient httpClient) {+ public ShardHandler getShardHandler(DefaultHttpClient httpClient){return new HttpShardHandler(this, httpClient);}@@ -130,18 +131,20 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements Plugnew DefaultSolrThreadFactory("httpShardExecutor"));- mgr = new MultiThreadedHttpConnectionManager();- mgr.getParams().setDefaultMaxConnectionsPerHost(this.maxConnectionsPerHost);- mgr.getParams().setMaxTotalConnections(10000);- mgr.getParams().setConnectionTimeout(this.connectionTimeout);- mgr.getParams().setSoTimeout(this.soTimeout);+ mgr = new ThreadSafeClientConnManager();+ mgr.setDefaultMaxPerRoute(256);+ mgr.setMaxTotal(10000);+ DefaultHttpClient client = new DefaultHttpClient(mgr);++ client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);+ client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);// mgr.getParams().setStaleCheckingEnabled(false);- client = new HttpClient(mgr);// prevent retries (note: this didn't work when set on mgr.. needed to be set on client)- DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);- client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);+ DefaultHttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(0, false);+ client.setHttpRequestRetryHandler(retryhandler);+ this.client = client;try {loadbalancer = new LBHttpSolrServer(client);diff --git a/solr/core/src/java/org/apache/solr/update/PeerSync.java b/solr/core/src/java/org/apache/solr/update/PeerSync.javaindex c182908b065..b068b8690e7 100644--- a/solr/core/src/java/org/apache/solr/update/PeerSync.java+++ b/solr/core/src/java/org/apache/solr/update/PeerSync.java@@ -26,11 +26,11 @@ import java.util.HashSet;import java.util.List;import java.util.Set;-import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;-import org.apache.commons.httpclient.NoHttpResponseException;-import org.apache.commons.httpclient.params.HttpMethodParams;+import org.apache.http.NoHttpResponseException;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.http.params.CoreConnectionPNames;import org.apache.lucene.util.BytesRef;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.cloud.ZkController;@@ -77,17 +77,17 @@ public class PeerSync {private Set<Long> requestedUpdateSet;private long ourLowThreshold; // 20th percentileprivate long ourHighThreshold; // 80th percentile- private static MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();- private static HttpClient client = new HttpClient(mgr);+ private static ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager();+ private static DefaultHttpClient client = new DefaultHttpClient(mgr);static {- mgr.getParams().setDefaultMaxConnectionsPerHost(20);- mgr.getParams().setMaxTotalConnections(10000);- mgr.getParams().setConnectionTimeout(30000);- mgr.getParams().setSoTimeout(30000);+ mgr.setDefaultMaxPerRoute(20);+ mgr.setMaxTotal(10000);+ client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);+ client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// prevent retries (note: this didn't work when set on mgr.. needed to be set on client)- DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);- client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);+ DefaultHttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(0, false);+ client.setHttpRequestRetryHandler(retryhandler);}// comparator that sorts by absolute value, putting highest firstdiff --git a/solr/core/src/java/org/apache/solr/update/SolrCmdDistributor.java b/solr/core/src/java/org/apache/solr/update/SolrCmdDistributor.javaindex 9f98eb52f05..b0a82bd26a2 100644--- a/solr/core/src/java/org/apache/solr/update/SolrCmdDistributor.java+++ b/solr/core/src/java/org/apache/solr/update/SolrCmdDistributor.java@@ -33,9 +33,10 @@ import java.util.concurrent.SynchronousQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.http.client.HttpClient;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.AbstractUpdateRequest;import org.apache.solr.client.solrj.request.UpdateRequestExt;import org.apache.solr.common.SolrException;@@ -58,10 +59,10 @@ public class SolrCmdDistributor {static HttpClient client;static {- MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();- mgr.getParams().setDefaultMaxConnectionsPerHost(8);- mgr.getParams().setMaxTotalConnections(200);- client = new HttpClient(mgr);+ ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager();+ mgr.setDefaultMaxPerRoute(8);+ mgr.setMaxTotal(200);+ client = new DefaultHttpClient(mgr);}CompletionService<Request> completionService;@@ -313,7 +314,7 @@ public class SolrCmdDistributor {fullUrl = url;}- CommonsHttpSolrServer server = new CommonsHttpSolrServer(fullUrl,+ HttpSolrServer server = new HttpSolrServer(fullUrl,client);clonedRequest.ursp = server.request(clonedRequest.ureq);diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.javaindex 4ef01214cb8..c406b53e99a 100644--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java@@ -25,7 +25,7 @@ import java.util.Map.Entry;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CharsRef;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery;import org.apache.solr.cloud.CloudDescriptor;import org.apache.solr.cloud.ZkController;@@ -333,10 +333,10 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {// TODO: what if its is already recovering? Right now recoveries queue up -// should they?String recoveryUrl = error.node.getBaseUrl();- CommonsHttpSolrServer server;+ HttpSolrServer server;log.info("try and ask " + recoveryUrl + " to recover");try {- server = new CommonsHttpSolrServer(recoveryUrl);+ server = new HttpSolrServer(recoveryUrl);server.setSoTimeout(5000);server.setConnectionTimeout(5000);diff --git a/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.java b/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.javaindex 17ac58a1397..518fe178eef 100644--- a/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.java+++ b/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.java@@ -19,10 +19,10 @@ package org.apache.solr;import org.apache.lucene.util.LuceneTestCase;import org.apache.solr.util.AbstractSolrTestCase;import org.apache.solr.client.solrj.embedded.JettySolrRunner;+import org.apache.solr.client.solrj.impl.HttpSolrServer;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.client.solrj.impl.CommonsHttpSolrServer;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.commons.io.IOUtils;@@ -51,7 +51,7 @@ public class TestSolrCoreProperties extends LuceneTestCase {solrJetty.start();String url = "http://localhost:" + solrJetty.getLocalPort() + "/solr";- client = new CommonsHttpSolrServer(url);+ client = new HttpSolrServer(url);}diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.javaindex 5a2880d81dd..18f8e5ba920 100644--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java@@ -38,7 +38,7 @@ import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.impl.CloudSolrServer;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.AbstractUpdateRequest;import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;import org.apache.solr.client.solrj.request.CoreAdminRequest.Create;@@ -288,7 +288,7 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {private void testNumberOfCommitsWithCommitAfterAdd()throws MalformedURLException, SolrServerException, IOException {- long startCommits = getNumCommits((CommonsHttpSolrServer) clients.get(0));+ long startCommits = getNumCommits((HttpSolrServer) clients.get(0));ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/csv");up.addFile(getFile("books_numeric_ids.csv"));@@ -296,14 +296,14 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);NamedList<Object> result = clients.get(0).request(up);- long endCommits = getNumCommits((CommonsHttpSolrServer) clients.get(0));+ long endCommits = getNumCommits((HttpSolrServer) clients.get(0));assertEquals(startCommits + 1L, endCommits);}- private Long getNumCommits(CommonsHttpSolrServer solrServer) throws MalformedURLException,+ private Long getNumCommits(HttpSolrServer solrServer) throws MalformedURLException,SolrServerException, IOException {- CommonsHttpSolrServer server = new CommonsHttpSolrServer(solrServer.getBaseURL());+ HttpSolrServer server = new HttpSolrServer(solrServer.getBaseURL());ModifiableSolrParams params = new ModifiableSolrParams();params.set("qt", "/admin/mbeans?key=updateHandler&stats=true");// use generic request to avoid extra processing of queries@@ -322,7 +322,7 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {List<SolrServer> collectionClients = new ArrayList<SolrServer>();SolrServer client = clients.get(0);otherCollectionClients.put(oneInstanceCollection2, collectionClients);- String baseUrl = ((CommonsHttpSolrServer) client).getBaseURL();+ String baseUrl = ((HttpSolrServer) client).getBaseURL();createCollection(oneInstanceCollection2, collectionClients, baseUrl, 1, "slice1");createCollection(oneInstanceCollection2, collectionClients, baseUrl, 2, "slice2");createCollection(oneInstanceCollection2, collectionClients, baseUrl, 3, "slice2");@@ -386,7 +386,7 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {private void testSearchByCollectionName() throws SolrServerException {SolrServer client = clients.get(0);- String baseUrl = ((CommonsHttpSolrServer) client).getBaseURL();+ String baseUrl = ((HttpSolrServer) client).getBaseURL();// the cores each have different names, but if we add the collection name to the url// we should get mapped to the right core@@ -400,7 +400,7 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {List<SolrServer> collectionClients = new ArrayList<SolrServer>();SolrServer client = clients.get(0);otherCollectionClients.put(oneInstanceCollection , collectionClients);- String baseUrl = ((CommonsHttpSolrServer) client).getBaseURL();+ String baseUrl = ((HttpSolrServer) client).getBaseURL();createCollection(oneInstanceCollection, collectionClients, baseUrl, 1);createCollection(oneInstanceCollection, collectionClients, baseUrl, 2);createCollection(oneInstanceCollection, collectionClients, baseUrl, 3);@@ -458,9 +458,9 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {IOException, InterruptedException {Callable call = new Callable() {public Object call() {- CommonsHttpSolrServer server;+ HttpSolrServer server;try {- server = new CommonsHttpSolrServer(baseUrl);+ server = new HttpSolrServer(baseUrl);Create createCmd = new Create();createCmd.setRoles("none");@@ -570,10 +570,10 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {final int frozeUnique = unique;Callable call = new Callable() {public Object call() {- CommonsHttpSolrServer server;+ HttpSolrServer server;try {- server = new CommonsHttpSolrServer(- ((CommonsHttpSolrServer) client).getBaseURL());+ server = new HttpSolrServer(+ ((HttpSolrServer) client).getBaseURL());Create createCmd = new Create();createCmd.setCoreName(collection);@@ -590,7 +590,7 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {};collectionClients.add(createNewSolrServer(collection,- ((CommonsHttpSolrServer) client).getBaseURL()));+ ((HttpSolrServer) client).getBaseURL()));pending.add(completionService.submit(call));while (pending != null && pending.size() > 0) {@@ -604,7 +604,7 @@ public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {protected SolrServer createNewSolrServer(String collection, String baseUrl) {try {// setup the server...- CommonsHttpSolrServer s = new CommonsHttpSolrServer(baseUrl + "/" + collection);+ HttpSolrServer s = new HttpSolrServer(baseUrl + "/" + collection);s.setConnectionTimeout(100); // 1/10th secs.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);diff --git a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.javaindex 3a3dbbe5bc7..a655439af30 100644--- a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java@@ -25,12 +25,12 @@ import java.util.ArrayList;import java.util.List;import java.util.Set;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;-import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;+import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.common.SolrInputDocument;import org.apache.zookeeper.KeeperException;import org.junit.After;@@ -206,11 +206,11 @@ public class ChaosMonkeyNothingIsSafeTest extends FullSolrCloudTest {}class FullThrottleStopableIndexingThread extends StopableIndexingThread {- MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager();- private HttpClient httpClient = new HttpClient(cm) ;+ ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();+ private DefaultHttpClient httpClient = new DefaultHttpClient(cm) ;private volatile boolean stop = false;int clientIndex = 0;- private StreamingUpdateSolrServer suss;+ private ConcurrentUpdateSolrServer suss;private List<SolrServer> clients;public FullThrottleStopableIndexingThread(List<SolrServer> clients,@@ -219,8 +219,8 @@ public class ChaosMonkeyNothingIsSafeTest extends FullSolrCloudTest {setName("FullThrottleStopableIndexingThread");setDaemon(true);this.clients = clients;- suss = new StreamingUpdateSolrServer(- ((CommonsHttpSolrServer) clients.get(0)).getBaseURL(), httpClient, 8,+ suss = new ConcurrentUpdateSolrServer(+ ((HttpSolrServer) clients.get(0)).getBaseURL(), httpClient, 8,2) {public void handleError(Throwable ex) {log.warn("suss error", ex);@@ -288,8 +288,8 @@ public class ChaosMonkeyNothingIsSafeTest extends FullSolrCloudTest {}try {suss.shutdownNow();- suss = new StreamingUpdateSolrServer(- ((CommonsHttpSolrServer) clients.get(clientIndex)).getBaseURL(),+ suss = new ConcurrentUpdateSolrServer(+ ((HttpSolrServer) clients.get(clientIndex)).getBaseURL(),httpClient, 30, 3) {public void handleError(Throwable ex) {log.warn("suss error", ex);diff --git a/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java b/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.javaindex 1c77138e8f1..5478ce2b89c 100644--- a/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java@@ -24,8 +24,8 @@ import java.util.concurrent.TimeoutException;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;-import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;+import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;import org.apache.solr.client.solrj.request.UpdateRequest;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;@@ -40,7 +40,6 @@ import org.apache.solr.update.processor.DistributedUpdateProcessor;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.junit.BeforeClass;-import org.junit.Ignore;/*** Super basic testing, no shard restarting or anything.@@ -239,8 +238,8 @@ public class FullSolrCloudDistribCmdsTest extends FullSolrCloudTest {}private void testIndexingWithSuss() throws MalformedURLException, Exception {- StreamingUpdateSolrServer suss = new StreamingUpdateSolrServer(- ((CommonsHttpSolrServer) clients.get(0)).getBaseURL(), 3, 1);+ ConcurrentUpdateSolrServer suss = new ConcurrentUpdateSolrServer(+ ((HttpSolrServer) clients.get(0)).getBaseURL(), 3, 1);for (int i=100; i<150; i++) {index_specific(suss, id, i);diff --git a/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudTest.java b/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudTest.javaindex 729316641ea..fb3a551ec78 100644--- a/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudTest.java@@ -25,12 +25,13 @@ import java.util.*;import java.util.concurrent.TimeoutException;import java.util.concurrent.atomic.AtomicInteger;+import org.apache.http.params.CoreConnectionPNames;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.embedded.JettySolrRunner;import org.apache.solr.client.solrj.impl.CloudSolrServer;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.UpdateRequest;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;@@ -206,8 +207,9 @@ public class FullSolrCloudTest extends AbstractDistributedZkTestCase {CloudSolrServer server = new CloudSolrServer(zkServer.getZkAddress());server.setDefaultCollection(DEFAULT_COLLECTION);server.getLbServer().getHttpClient().getParams()- .setConnectionManagerTimeout(5000);- server.getLbServer().getHttpClient().getParams().setSoTimeout(15000);+ .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);+ server.getLbServer().getHttpClient().getParams()+ .setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);cloudClient = server;} catch (MalformedURLException e) {throw new RuntimeException(e);@@ -348,7 +350,7 @@ public class FullSolrCloudTest extends AbstractDistributedZkTestCase {for (Map.Entry<String,Slice> slice : slices.entrySet()) {Map<String,ZkNodeProps> theShards = slice.getValue().getShards();for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) {- int port = new URI(((CommonsHttpSolrServer) client).getBaseURL())+ int port = new URI(((HttpSolrServer) client).getBaseURL()).getPort();if (shard.getKey().contains(":" + port + "_")) {@@ -475,7 +477,7 @@ public class FullSolrCloudTest extends AbstractDistributedZkTestCase {}controlClient.add(doc);- CommonsHttpSolrServer client = (CommonsHttpSolrServer) clients+ HttpSolrServer client = (HttpSolrServer) clients.get(serverNumber);UpdateRequest ureq = new UpdateRequest();@@ -1207,7 +1209,7 @@ public class FullSolrCloudTest extends AbstractDistributedZkTestCase {Map<String,ZkNodeProps> theShards = slice.getValue().getShards();for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) {String shardName = new URI(- ((CommonsHttpSolrServer) client).getBaseURL()).getPort()+ ((HttpSolrServer) client).getBaseURL()).getPort()+ "_solr_";if (verbose && shard.getKey().endsWith(shardName)) {System.err.println("shard:" + slice.getKey());@@ -1317,7 +1319,7 @@ public class FullSolrCloudTest extends AbstractDistributedZkTestCase {if (VERBOSE || printLayoutOnTearDown) {super.printLayout();}- ((CommonsHttpSolrServer) controlClient).shutdown();+ ((HttpSolrServer) controlClient).shutdown();if (cloudClient != null) {cloudClient.close();}@@ -1353,7 +1355,7 @@ public class FullSolrCloudTest extends AbstractDistributedZkTestCase {// setup the server...String url = "http://localhost:" + port + context + "/"+ DEFAULT_COLLECTION;- CommonsHttpSolrServer s = new CommonsHttpSolrServer(url);+ HttpSolrServer s = new HttpSolrServer(url);s.setConnectionTimeout(100); // 1/10th secs.setSoTimeout(15000);s.setDefaultMaxConnectionsPerHost(100);diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.javaindex b766ab9288a..f501c7fa88f 100644--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java@@ -41,7 +41,7 @@ import org.apache.solr.TestDistributedSearch;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;@@ -131,7 +131,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {try {// setup the server...String url = "http://localhost:" + port + context;- CommonsHttpSolrServer s = new CommonsHttpSolrServer(url);+ HttpSolrServer s = new HttpSolrServer(url);s.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);return s;diff --git a/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.java b/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.javaindex 0f0795f49e6..d04b4b2b42d 100644--- a/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.java+++ b/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.java@@ -22,7 +22,7 @@ import org.apache.solr.SolrJettyTestBase;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrException;@@ -68,7 +68,7 @@ public class TestRemoteStreaming extends SolrJettyTestBase {@Testpublic void testStreamUrl() throws Exception {- CommonsHttpSolrServer solrServer = (CommonsHttpSolrServer) getSolrServer();+ HttpSolrServer solrServer = (HttpSolrServer) getSolrServer();String streamUrl = solrServer.getBaseURL()+"/select?q=*:*&fl=id&wt=csv";String getUrl = solrServer.getBaseURL()+"/debug/dump?wt=xml&stream.url="+URLEncoder.encode(streamUrl,"UTF-8");@@ -127,7 +127,7 @@ public class TestRemoteStreaming extends SolrJettyTestBase {/** Compose a url that if you get it, it will delete all the data. */private String makeDeleteAllUrl() throws UnsupportedEncodingException {- CommonsHttpSolrServer solrServer = (CommonsHttpSolrServer) getSolrServer();+ HttpSolrServer solrServer = (HttpSolrServer) getSolrServer();String deleteQuery = "<delete><query>*:*</query></delete>";return solrServer.getBaseURL()+"/update?commit=true&stream.body="+ URLEncoder.encode(deleteQuery, "UTF-8");}diff --git a/solr/core/src/test/org/apache/solr/schema/TestBinaryField.java b/solr/core/src/test/org/apache/solr/schema/TestBinaryField.javaindex 8293c4eca7f..ec1f6300e0b 100644--- a/solr/core/src/test/org/apache/solr/schema/TestBinaryField.java+++ b/solr/core/src/test/org/apache/solr/schema/TestBinaryField.java@@ -27,18 +27,19 @@ import org.apache.lucene.util.SystemPropertiesRestoreRule;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.beans.Field;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.core.SolrResourceLoader;+import org.apache.commons.io.IOUtils;import org.junit.Rule;import org.junit.rules.RuleChain;import org.junit.rules.TestRule;public class TestBinaryField extends LuceneTestCase {- CommonsHttpSolrServer server;+ HttpSolrServer server;JettySolrRunner jetty;int port = 0;@@ -83,7 +84,7 @@ public class TestBinaryField extends LuceneTestCase {port = jetty.getLocalPort();String url = "http://localhost:" + jetty.getLocalPort() + context;- server = new CommonsHttpSolrServer(url);+ server = new HttpSolrServer(url);}public void testSimple() throws Exception {diff --git a/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.java b/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.javaindex 76b92c082c3..effd99d68ba 100644--- a/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.java+++ b/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.java@@ -20,12 +20,13 @@ import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;+import java.util.Arrays;import java.util.Date;-import org.apache.commons.httpclient.Header;-import org.apache.commons.httpclient.HttpMethodBase;-import org.apache.commons.httpclient.NameValuePair;-import org.apache.commons.httpclient.util.DateUtil;+import org.apache.http.Header;+import org.apache.http.HttpResponse;+import org.apache.http.client.methods.HttpRequestBase;+import org.apache.http.impl.cookie.DateUtils;import org.junit.BeforeClass;import org.junit.Test;@@ -46,39 +47,35 @@ public class CacheHeaderTest extends CacheHeaderTestBase {@Testpublic void testCacheVetoHandler() throws Exception {File f=makeFile(CONTENTS);- HttpMethodBase m=getUpdateMethod("GET");- m.setQueryString(new NameValuePair[] { new NameValuePair("stream.file",f.getCanonicalPath())});- getClient().executeMethod(m);- assertEquals(200, m.getStatusCode());- checkVetoHeaders(m, true);+ HttpRequestBase m=getUpdateMethod("GET", "stream.file", f.getCanonicalPath());+ HttpResponse response = getClient().execute(m);+ assertEquals(200, response.getStatusLine().getStatusCode());+ checkVetoHeaders(response, true);}@Testpublic void testCacheVetoException() throws Exception {- HttpMethodBase m = getSelectMethod("GET");+ HttpRequestBase m = getSelectMethod("GET", "q", "xyz_ignore_exception:solr", "qt", "standard");// We force an exception from Solr. This should emit "no-cache" HTTP headers- m.setQueryString(new NameValuePair[] { new NameValuePair("q", "xyz_ignore_exception:solr"),- new NameValuePair("qt", "standard") });- getClient().executeMethod(m);- assertFalse(m.getStatusCode() == 200);- checkVetoHeaders(m, false);+ HttpResponse response = getClient().execute(m);+ assertFalse(response.getStatusLine().getStatusCode() == 200);+ checkVetoHeaders(response, false);}-- protected void checkVetoHeaders(HttpMethodBase m, boolean checkExpires) throws Exception {- Header head = m.getResponseHeader("Cache-Control");+ protected void checkVetoHeaders(HttpResponse response, boolean checkExpires) throws Exception {+ Header head = response.getFirstHeader("Cache-Control");assertNotNull("We got no Cache-Control header", head);assertTrue("We got no no-cache in the Cache-Control header", head.getValue().contains("no-cache"));assertTrue("We got no no-store in the Cache-Control header", head.getValue().contains("no-store"));- head = m.getResponseHeader("Pragma");+ head = response.getFirstHeader("Pragma");assertNotNull("We got no Pragma header", head);assertEquals("no-cache", head.getValue());if (checkExpires) {- head = m.getResponseHeader("Expires");- assertNotNull("We got no Expires header:" + m.getResponseHeaders(), head);- Date d = DateUtil.parseDate(head.getValue());+ head = response.getFirstHeader("Expires");+ assertNotNull("We got no Expires header:" + Arrays.asList(response.getAllHeaders()), head);+ Date d = DateUtils.parseDate(head.getValue());assertTrue("We got no Expires header far in the past", System.currentTimeMillis()- d.getTime() > 100000);@@ -89,68 +86,67 @@ public class CacheHeaderTest extends CacheHeaderTestBase {protected void doLastModified(String method) throws Exception {// We do a first request to get the last modified// This must result in a 200 OK response- HttpMethodBase get = getSelectMethod(method);- getClient().executeMethod(get);- checkResponseBody(method, get);+ HttpRequestBase get = getSelectMethod(method);+ HttpResponse response = getClient().execute(get);+ checkResponseBody(method, response);- assertEquals("Got no response code 200 in initial request", 200, get- .getStatusCode());+ assertEquals("Got no response code 200 in initial request", 200, response.+ getStatusLine().getStatusCode());- Header head = get.getResponseHeader("Last-Modified");+ Header head = response.getFirstHeader("Last-Modified");assertNotNull("We got no Last-Modified header", head);- Date lastModified = DateUtil.parseDate(head.getValue());+ Date lastModified = DateUtils.parseDate(head.getValue());// If-Modified-Since testsget = getSelectMethod(method);- get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date()));+ get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date()));- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 304 NotModified response with current date", 304,- get.getStatusCode());+ response.getStatusLine().getStatusCode());get = getSelectMethod(method);- get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(+ get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date(lastModified.getTime() - 10000)));- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 200 OK response with If-Modified-Since in the past",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());// If-Unmodified-Since testsget = getSelectMethod(method);- get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(+ get.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date(lastModified.getTime() - 10000)));- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 412 Precondition failed with If-Unmodified-Since in the past",- 412, get.getStatusCode());+ 412, response.getStatusLine().getStatusCode());get = getSelectMethod(method);- get- .addRequestHeader("If-Unmodified-Since", DateUtil+ get.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date()));- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 200 OK response with If-Unmodified-Since and current date",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());}// test ETag@Overrideprotected void doETag(String method) throws Exception {- HttpMethodBase get = getSelectMethod(method);- getClient().executeMethod(get);- checkResponseBody(method, get);+ HttpRequestBase get = getSelectMethod(method);+ HttpResponse response = getClient().execute(get);+ checkResponseBody(method, response);- assertEquals("Got no response code 200 in initial request", 200, get- .getStatusCode());+ assertEquals("Got no response code 200 in initial request", 200, response+ .getStatusLine().getStatusCode());- Header head = get.getResponseHeader("ETag");+ Header head = response.getFirstHeader("ETag");assertNotNull("We got no ETag in the response", head);assertTrue("Not a valid ETag", head.getValue().startsWith("\"")&& head.getValue().endsWith("\""));@@ -160,80 +156,80 @@ public class CacheHeaderTest extends CacheHeaderTestBase {// If-None-Match tests// we set a non matching ETagget = getSelectMethod(method);- get.addRequestHeader("If-None-Match", "\"xyz123456\"");- getClient().executeMethod(get);- checkResponseBody(method, get);+ get.addHeader("If-None-Match", "\"xyz123456\"");+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("If-None-Match: Got no response code 200 in response to non matching ETag",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());// now we set matching ETagsget = getSelectMethod(method);- get.addRequestHeader("If-None-Match", "\"xyz1223\"");- get.addRequestHeader("If-None-Match", "\"1231323423\", \"1211211\", "+ get.addHeader("If-None-Match", "\"xyz1223\"");+ get.addHeader("If-None-Match", "\"1231323423\", \"1211211\", "+ etag);- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("If-None-Match: Got no response 304 to matching ETag", 304,- get.getStatusCode());+ response.getStatusLine().getStatusCode());// we now set the special star ETagget = getSelectMethod(method);- get.addRequestHeader("If-None-Match", "*");- getClient().executeMethod(get);- checkResponseBody(method, get);- assertEquals("If-None-Match: Got no response 304 for star ETag", 304, get- .getStatusCode());+ get.addHeader("If-None-Match", "*");+ response = getClient().execute(get);+ checkResponseBody(method, response);+ assertEquals("If-None-Match: Got no response 304 for star ETag", 304,+ response.getStatusLine().getStatusCode());// If-Match tests// we set a non matching ETagget = getSelectMethod(method);- get.addRequestHeader("If-Match", "\"xyz123456\"");- getClient().executeMethod(get);- checkResponseBody(method, get);+ get.addHeader("If-Match", "\"xyz123456\"");+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("If-Match: Got no response code 412 in response to non matching ETag",- 412, get.getStatusCode());+ 412, response.getStatusLine().getStatusCode());// now we set matching ETagsget = getSelectMethod(method);- get.addRequestHeader("If-Match", "\"xyz1223\"");- get.addRequestHeader("If-Match", "\"1231323423\", \"1211211\", " + etag);- getClient().executeMethod(get);- checkResponseBody(method, get);- assertEquals("If-Match: Got no response 200 to matching ETag", 200, get- .getStatusCode());+ get.addHeader("If-Match", "\"xyz1223\"");+ get.addHeader("If-Match", "\"1231323423\", \"1211211\", " + etag);+ response = getClient().execute(get);+ checkResponseBody(method, response);+ assertEquals("If-Match: Got no response 200 to matching ETag", 200,+ response.getStatusLine().getStatusCode());// now we set the special star ETagget = getSelectMethod(method);- get.addRequestHeader("If-Match", "*");- getClient().executeMethod(get);- checkResponseBody(method, get);- assertEquals("If-Match: Got no response 200 to star ETag", 200, get- .getStatusCode());+ get.addHeader("If-Match", "*");+ response = getClient().execute(get);+ checkResponseBody(method, response);+ assertEquals("If-Match: Got no response 200 to star ETag", 200, response+ .getStatusLine().getStatusCode());}@Overrideprotected void doCacheControl(String method) throws Exception {if ("POST".equals(method)) {- HttpMethodBase m = getSelectMethod(method);- getClient().executeMethod(m);- checkResponseBody(method, m);+ HttpRequestBase m = getSelectMethod(method);+ HttpResponse response = getClient().execute(m);+ checkResponseBody(method, response);- Header head = m.getResponseHeader("Cache-Control");+ Header head = response.getFirstHeader("Cache-Control");assertNull("We got a cache-control header in response to POST", head);- head = m.getResponseHeader("Expires");+ head = response.getFirstHeader("Expires");assertNull("We got an Expires header in response to POST", head);} else {- HttpMethodBase m = getSelectMethod(method);- getClient().executeMethod(m);- checkResponseBody(method, m);+ HttpRequestBase m = getSelectMethod(method);+ HttpResponse response = getClient().execute(m);+ checkResponseBody(method, response);- Header head = m.getResponseHeader("Cache-Control");+ Header head = response.getFirstHeader("Cache-Control");assertNotNull("We got no cache-control header", head);- head = m.getResponseHeader("Expires");+ head = response.getFirstHeader("Expires");assertNotNull("We got no Expires header in response", head);}}diff --git a/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTestBase.java b/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTestBase.javaindex ff176057a29..1f550ba9fdc 100644--- a/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTestBase.java+++ b/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTestBase.java@@ -16,58 +16,94 @@*/package org.apache.solr.servlet;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.HttpMethodBase;-import org.apache.commons.httpclient.NameValuePair;-import org.apache.commons.httpclient.methods.GetMethod;-import org.apache.commons.httpclient.methods.HeadMethod;-import org.apache.commons.httpclient.methods.PostMethod;+import java.net.URI;+import java.net.URISyntaxException;+import java.util.ArrayList;++import org.apache.http.HttpResponse;+import org.apache.http.client.HttpClient;+import org.apache.http.client.methods.HttpGet;+import org.apache.http.client.methods.HttpHead;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.client.methods.HttpRequestBase;+import org.apache.http.client.utils.URIUtils;+import org.apache.http.client.utils.URLEncodedUtils;+import org.apache.http.message.BasicNameValuePair;+import org.apache.http.util.EntityUtils;import org.apache.solr.SolrJettyTestBase;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.junit.Test;public abstract class CacheHeaderTestBase extends SolrJettyTestBase {- protected HttpMethodBase getSelectMethod(String method) {- CommonsHttpSolrServer httpserver = (CommonsHttpSolrServer)getSolrServer();- HttpMethodBase m = null;+ protected HttpRequestBase getSelectMethod(String method, String... params) throws URISyntaxException {+ HttpSolrServer httpserver = (HttpSolrServer)getSolrServer();+ HttpRequestBase m = null;++ ArrayList<BasicNameValuePair> qparams = new ArrayList<BasicNameValuePair>();+ if(params.length==0) {+ qparams.add(new BasicNameValuePair("q", "solr"));+ qparams.add(new BasicNameValuePair("qt", "standard"));+ }+ for (int i = 0; i < params.length / 2; i++) {+ qparams.add(new BasicNameValuePair(params[i * 2], params[i * 2 + 1]));+ }++ java.net.URI uri = URIUtils.createURI("http",+ new URI(httpserver.getBaseURL()).getHost(),+ new URI(httpserver.getBaseURL()).getPort(), "/solr/select",+ URLEncodedUtils.format(qparams, "UTF-8"), null);+if ("GET".equals(method)) {- m = new GetMethod(httpserver.getBaseURL() + "/select");+ m = new HttpGet(uri);} else if ("HEAD".equals(method)) {- m = new HeadMethod(httpserver.getBaseURL() + "/select");+ m = new HttpHead(uri);} else if ("POST".equals(method)) {- m = new PostMethod(httpserver.getBaseURL() + "/select");+ m = new HttpPost(uri);}- m.setQueryString(new NameValuePair[] { new NameValuePair("q", "solr"),- new NameValuePair("qt", "standard") });+return m;}- protected HttpMethodBase getUpdateMethod(String method) {- CommonsHttpSolrServer httpserver = (CommonsHttpSolrServer)getSolrServer();- HttpMethodBase m = null;+ protected HttpRequestBase getUpdateMethod(String method, String... params) throws URISyntaxException {+ HttpSolrServer httpserver = (HttpSolrServer)getSolrServer();+ HttpRequestBase m = null;++ ArrayList<BasicNameValuePair> qparams = new ArrayList<BasicNameValuePair>();+ for(int i=0;i<params.length/2;i++) {+ qparams.add(new BasicNameValuePair(params[i*2], params[i*2+1]));+ }+ java.net.URI uri = URIUtils.createURI("http",+ new URI(httpserver.getBaseURL()).getHost(),+ new URI(httpserver.getBaseURL()).getPort(), "/solr/update/csv",+ URLEncodedUtils.format(qparams, "UTF-8"), null);if ("GET".equals(method)) {- m=new GetMethod(httpserver.getBaseURL()+"/update/csv");+ m=new HttpGet(uri);} else if ("POST".equals(method)) {- m=new PostMethod(httpserver.getBaseURL()+"/update/csv");+ m=new HttpPost(uri);} else if ("HEAD".equals(method)) {- m=new HeadMethod(httpserver.getBaseURL()+"/update/csv");+ m=new HttpHead(uri);}-+return m;}protected HttpClient getClient() {- CommonsHttpSolrServer httpserver = (CommonsHttpSolrServer)getSolrServer();+ HttpSolrServer httpserver = (HttpSolrServer)getSolrServer();return httpserver.getHttpClient();}- protected void checkResponseBody(String method, HttpMethodBase resp)+ protected void checkResponseBody(String method, HttpResponse resp)throws Exception {- String responseBody = resp.getResponseBodyAsString();+ String responseBody ="";++ if (resp.getEntity() != null) {+ responseBody = EntityUtils.toString(resp.getEntity());+ }+if ("GET".equals(method)) {- switch (resp.getStatusCode()) {+ switch (resp.getStatusLine().getStatusCode()) {case 200:assertTrue("Response body was empty for method " + method,responseBody != null && responseBody.length() > 0);@@ -82,7 +118,7 @@ public abstract class CacheHeaderTestBase extends SolrJettyTestBase {break;default:System.err.println(responseBody);- assertEquals("Unknown request response", 0, resp.getStatusCode());+ assertEquals("Unknown request response", 0, resp.getStatusLine().getStatusCode());}}if ("HEAD".equals(method)) {diff --git a/solr/core/src/test/org/apache/solr/servlet/NoCacheHeaderTest.java b/solr/core/src/test/org/apache/solr/servlet/NoCacheHeaderTest.javaindex c016fe3fbda..c0a5ad07a8f 100644--- a/solr/core/src/test/org/apache/solr/servlet/NoCacheHeaderTest.java+++ b/solr/core/src/test/org/apache/solr/servlet/NoCacheHeaderTest.java@@ -18,13 +18,13 @@ package org.apache.solr.servlet;import java.util.Date;-import org.apache.commons.httpclient.Header;-import org.apache.commons.httpclient.HttpMethodBase;-import org.apache.commons.httpclient.util.DateUtil;+import org.apache.http.Header;+import org.apache.http.HttpResponse;+import org.apache.http.client.methods.HttpRequestBase;+import org.apache.http.impl.cookie.DateUtils;import org.junit.BeforeClass;import org.junit.Test;-/*** A test case for the several HTTP cache headers emitted by Solr*/@@ -63,113 +63,111 @@ public class NoCacheHeaderTest extends CacheHeaderTestBase {protected void doLastModified(String method) throws Exception {// We do a first request to get the last modified// This must result in a 200 OK response- HttpMethodBase get = getSelectMethod(method);- getClient().executeMethod(get);- checkResponseBody(method, get);+ HttpRequestBase get = getSelectMethod(method);+ HttpResponse response = getClient().execute(get);+ checkResponseBody(method, response);- assertEquals("Got no response code 200 in initial request", 200, get- .getStatusCode());+ assertEquals("Got no response code 200 in initial request", 200, response+ .getStatusLine().getStatusCode());- Header head = get.getResponseHeader("Last-Modified");+ Header head = response.getFirstHeader("Last-Modified");assertNull("We got a Last-Modified header", head);// If-Modified-Since testsget = getSelectMethod(method);- get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date()));+ get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date()));- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 200 with If-Modified-Since header. We should never get a 304 here", 200,- get.getStatusCode());+ response.getStatusLine().getStatusCode());get = getSelectMethod(method);- get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(System.currentTimeMillis()-10000)));- getClient().executeMethod(get);- checkResponseBody(method, get);+ get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date(System.currentTimeMillis()-10000)));+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 200 with If-Modified-Since header. We should never get a 304 here",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());// If-Unmodified-Since testsget = getSelectMethod(method);- get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(System.currentTimeMillis()-10000)));+ get.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date(System.currentTimeMillis()-10000)));- getClient().executeMethod(get);- checkResponseBody(method, get);+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 200 with If-Unmodified-Since header. We should never get a 304 here",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());get = getSelectMethod(method);- get- .addRequestHeader("If-Unmodified-Since", DateUtil- .formatDate(new Date()));- getClient().executeMethod(get);- checkResponseBody(method, get);+ get.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date()));+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("Expected 200 with If-Unmodified-Since header. We should never get a 304 here",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());}// test ETag@Overrideprotected void doETag(String method) throws Exception {- HttpMethodBase get = getSelectMethod(method);- getClient().executeMethod(get);- checkResponseBody(method, get);+ HttpRequestBase get = getSelectMethod(method);+ HttpResponse response = getClient().execute(get);+ checkResponseBody(method, response);- assertEquals("Got no response code 200 in initial request", 200, get- .getStatusCode());+ assertEquals("Got no response code 200 in initial request", 200, response+ .getStatusLine().getStatusCode());- Header head = get.getResponseHeader("ETag");+ Header head = response.getFirstHeader("ETag");assertNull("We got an ETag in the response", head);// If-None-Match tests// we set a non matching ETagget = getSelectMethod(method);- get.addRequestHeader("If-None-Match", "\"xyz123456\"");- getClient().executeMethod(get);- checkResponseBody(method, get);+ get.addHeader("If-None-Match", "\"xyz123456\"");+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("If-None-Match: Got no response code 200 in response to non matching ETag",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());// we now set the special star ETagget = getSelectMethod(method);- get.addRequestHeader("If-None-Match", "*");- getClient().executeMethod(get);- checkResponseBody(method, get);- assertEquals("If-None-Match: Got no response 200 for star ETag", 200, get- .getStatusCode());+ get.addHeader("If-None-Match", "*");+ response = getClient().execute(get);+ checkResponseBody(method, response);+ assertEquals("If-None-Match: Got no response 200 for star ETag", 200,+ response.getStatusLine().getStatusCode());// If-Match tests// we set a non matching ETagget = getSelectMethod(method);- get.addRequestHeader("If-Match", "\"xyz123456\"");- getClient().executeMethod(get);- checkResponseBody(method, get);+ get.addHeader("If-Match", "\"xyz123456\"");+ response = getClient().execute(get);+ checkResponseBody(method, response);assertEquals("If-Match: Got no response code 200 in response to non matching ETag",- 200, get.getStatusCode());+ 200, response.getStatusLine().getStatusCode());// now we set the special star ETagget = getSelectMethod(method);- get.addRequestHeader("If-Match", "*");- getClient().executeMethod(get);- checkResponseBody(method, get);- assertEquals("If-Match: Got no response 200 to star ETag", 200, get- .getStatusCode());+ get.addHeader("If-Match", "*");+ response = getClient().execute(get);+ checkResponseBody(method, response);+ assertEquals("If-Match: Got no response 200 to star ETag", 200, response+ .getStatusLine().getStatusCode());}@Overrideprotected void doCacheControl(String method) throws Exception {- HttpMethodBase m = getSelectMethod(method);- getClient().executeMethod(m);- checkResponseBody(method, m);+ HttpRequestBase m = getSelectMethod(method);+ HttpResponse response = getClient().execute(m);+ checkResponseBody(method, response);- Header head = m.getResponseHeader("Cache-Control");+ Header head = response.getFirstHeader("Cache-Control");assertNull("We got a cache-control header in response", head);- head = m.getResponseHeader("Expires");+ head = response.getFirstHeader("Expires");assertNull("We got an Expires header in response", head);}}\ No newline at end of filediff --git a/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java b/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.javaindex 2da5ebb3c2a..ba76747eff8 100644--- a/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java@@ -88,7 +88,7 @@ public class DirectUpdateHandlerTest extends SolrTestCaseJ4 {assertU(adoc("id","5"));// search - not committed - "5" should not be found.- assertQ(req("q","id:5"), "//*[@numFound='0']");+ assertQ(req("qt","standard","q","id:5"), "//*[@numFound='0']");assertU(commit());diff --git a/solr/core/src/test/org/apache/solr/update/PeerSyncTest.java b/solr/core/src/test/org/apache/solr/update/PeerSyncTest.javaindex 351395f5549..25a418c372f 100644--- a/solr/core/src/test/org/apache/solr/update/PeerSyncTest.java+++ b/solr/core/src/test/org/apache/solr/update/PeerSyncTest.java@@ -17,30 +17,16 @@ package org.apache.solr.update;* limitations under the License.*/+import java.io.IOException;+import java.util.Arrays;+import org.apache.solr.BaseDistributedSearchTestCase;-import org.apache.solr.client.solrj.SolrQuery;-import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;import org.apache.solr.client.solrj.request.QueryRequest;-import org.apache.solr.common.SolrDocumentList;-import org.apache.solr.common.cloud.ZkCoreNodeProps;-import org.apache.solr.common.cloud.ZkNodeProps;-import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.StrUtils;-import org.apache.solr.update.SolrCmdDistributor.Node;-import org.apache.solr.update.SolrCmdDistributor.Response;-import org.apache.solr.update.SolrCmdDistributor.StdNode;--import java.io.IOException;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.Collections;-import java.util.List;public class PeerSyncTest extends BaseDistributedSearchTestCase {private static int numVersions = 100; // number of versions to use when syncingdiff --git a/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java b/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.javaindex 811f06e18e9..ae29e0d7e3f 100644--- a/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java+++ b/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java@@ -24,7 +24,7 @@ import java.util.List;import org.apache.solr.BaseDistributedSearchTestCase;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.common.SolrDocumentList;import org.apache.solr.common.cloud.ZkCoreNodeProps;import org.apache.solr.common.cloud.ZkNodeProps;@@ -87,7 +87,7 @@ public class SolrCmdDistributorTest extends BaseDistributedSearchTestCase {List<Node> nodes = new ArrayList<Node>();ZkNodeProps nodeProps = new ZkNodeProps(ZkStateReader.BASE_URL_PROP,- ((CommonsHttpSolrServer) controlClient).getBaseURL(),+ ((HttpSolrServer) controlClient).getBaseURL(),ZkStateReader.CORE_NAME_PROP, "");nodes.add(new StdNode(new ZkCoreNodeProps(nodeProps)));@@ -109,7 +109,7 @@ public class SolrCmdDistributorTest extends BaseDistributedSearchTestCase {.getNumFound();assertEquals(1, numFound);- CommonsHttpSolrServer client = (CommonsHttpSolrServer) clients.get(0);+ HttpSolrServer client = (HttpSolrServer) clients.get(0);nodeProps = new ZkNodeProps(ZkStateReader.BASE_URL_PROP,client.getBaseURL(), ZkStateReader.CORE_NAME_PROP, "");nodes.add(new StdNode(new ZkCoreNodeProps(nodeProps)));diff --git a/solr/lib/commons-httpclient-3.1.jar b/solr/lib/commons-httpclient-3.1.jardeleted file mode 100644index 3c261e7b419..00000000000--- a/solr/lib/commons-httpclient-3.1.jar+++ /dev/null@@ -1,2 +0,0 @@-AnyObjectId[7c59774aed4f5dd08778489aaad565690ff7c132] was removed in git history.-Apache SVN contains full history.\ No newline at end of filediff --git a/solr/lib/commons-httpclient-NOTICE.txt b/solr/lib/commons-httpclient-NOTICE.txtdeleted file mode 100644index 152a7800c41..00000000000--- a/solr/lib/commons-httpclient-NOTICE.txt+++ /dev/null@@ -1,5 +0,0 @@-Apache Jakarta HttpClient-Copyright 1999-2007 The Apache Software Foundation--This product includes software developed by-The Apache Software Foundation (http://www.apache.org/).diff --git a/solr/lib/httpclient-4.1.3.jar b/solr/lib/httpclient-4.1.3.jarnew file mode 100644index 00000000000..9f5317a4ac0--- /dev/null+++ b/solr/lib/httpclient-4.1.3.jar@@ -0,0 +1,2 @@+AnyObjectId[dfa8793c26a659666a62472d476956bd21ab9460] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/solr/lib/commons-httpclient-LICENSE-ASL.txt b/solr/lib/httpclient-LICENSE-ASL.txtsimilarity index 97%rename from solr/lib/commons-httpclient-LICENSE-ASL.txtrename to solr/lib/httpclient-LICENSE-ASL.txtindex d9a10c0d8e8..2c41ec88f61 100644--- a/solr/lib/commons-httpclient-LICENSE-ASL.txt+++ b/solr/lib/httpclient-LICENSE-ASL.txt@@ -174,3 +174,9 @@of your accepting any such warranty or additional liability.END OF TERMS AND CONDITIONS++This project contains annotations derived from JCIP-ANNOTATIONS+Copyright (c) 2005 Brian Goetz and Tim Peierls.+See http://www.jcip.net and the Creative Commons Attribution License+(http://creativecommons.org/licenses/by/2.5)+diff --git a/solr/lib/httpclient-NOTICE.txt b/solr/lib/httpclient-NOTICE.txtnew file mode 100644index 00000000000..3a98f4542f5--- /dev/null+++ b/solr/lib/httpclient-NOTICE.txt@@ -0,0 +1,8 @@+Apache HttpComponents Client+Copyright 1999-2011 The Apache Software Foundation++This product includes software developed by+The Apache Software Foundation (http://www.apache.org/).++This project contains annotations derived from JCIP-ANNOTATIONS+Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net\ No newline at end of filediff --git a/solr/lib/httpcore-4.1.4.jar b/solr/lib/httpcore-4.1.4.jarnew file mode 100644index 00000000000..23b15a16147--- /dev/null+++ b/solr/lib/httpcore-4.1.4.jar@@ -0,0 +1,2 @@+AnyObjectId[1606a2e3f93423450a7c985673e6c7c633959abe] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/solr/lib/httpcore-LICENSE-ASL.txt b/solr/lib/httpcore-LICENSE-ASL.txtnew file mode 100644index 00000000000..2c41ec88f61--- /dev/null+++ b/solr/lib/httpcore-LICENSE-ASL.txt@@ -0,0 +1,182 @@+ 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++This project contains annotations derived from JCIP-ANNOTATIONS+Copyright (c) 2005 Brian Goetz and Tim Peierls.+See http://www.jcip.net and the Creative Commons Attribution License+(http://creativecommons.org/licenses/by/2.5)+diff --git a/solr/lib/httpcore-NOTICE.txt b/solr/lib/httpcore-NOTICE.txtnew file mode 100644index 00000000000..3a98f4542f5--- /dev/null+++ b/solr/lib/httpcore-NOTICE.txt@@ -0,0 +1,8 @@+Apache HttpComponents Client+Copyright 1999-2011 The Apache Software Foundation++This product includes software developed by+The Apache Software Foundation (http://www.apache.org/).++This project contains annotations derived from JCIP-ANNOTATIONS+Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net\ No newline at end of filediff --git a/solr/lib/httpmime-4.1.3.jar b/solr/lib/httpmime-4.1.3.jarnew file mode 100644index 00000000000..8dbfcaa3a47--- /dev/null+++ b/solr/lib/httpmime-4.1.3.jar@@ -0,0 +1,2 @@+AnyObjectId[ff2014f339462497cdb2c4bdb62d2755c19cd033] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/solr/lib/httpmime-LICENSE-ASL.txt b/solr/lib/httpmime-LICENSE-ASL.txtnew file mode 100644index 00000000000..2c41ec88f61--- /dev/null+++ b/solr/lib/httpmime-LICENSE-ASL.txt@@ -0,0 +1,182 @@+ 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++This project contains annotations derived from JCIP-ANNOTATIONS+Copyright (c) 2005 Brian Goetz and Tim Peierls.+See http://www.jcip.net and the Creative Commons Attribution License+(http://creativecommons.org/licenses/by/2.5)+diff --git a/solr/lib/httpmime-NOTICE.txt b/solr/lib/httpmime-NOTICE.txtnew file mode 100644index 00000000000..3a98f4542f5--- /dev/null+++ b/solr/lib/httpmime-NOTICE.txt@@ -0,0 +1,8 @@+Apache HttpComponents Client+Copyright 1999-2011 The Apache Software Foundation++This product includes software developed by+The Apache Software Foundation (http://www.apache.org/).++This project contains annotations derived from JCIP-ANNOTATIONS+Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net\ No newline at end of filediff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.javaindex 5e2c117a556..f50c25140e5 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java@@ -28,8 +28,8 @@ import java.util.Random;import java.util.Set;import java.util.concurrent.TimeoutException;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;@@ -55,14 +55,14 @@ public class CloudSolrServer extends SolrServer {private volatile String defaultCollection;private LBHttpSolrServer lbServer;Random rand = new Random();- private MultiThreadedHttpConnectionManager connManager;+ private ThreadSafeClientConnManager connManager;/*** @param zkHost The address of the zookeeper quorum containing the cloud state*/public CloudSolrServer(String zkHost) throws MalformedURLException {- connManager = new MultiThreadedHttpConnectionManager();+ connManager = new ThreadSafeClientConnManager();this.zkHost = zkHost;- this.lbServer = new LBHttpSolrServer(new HttpClient(connManager));+ this.lbServer = new LBHttpSolrServer(new DefaultHttpClient(connManager));}/**diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CommonsHttpSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CommonsHttpSolrServer.javadeleted file mode 100644index a5ea9ad6fdb..00000000000--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CommonsHttpSolrServer.java+++ /dev/null@@ -1,703 +0,0 @@-/**- * 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.InputStream;-import java.io.OutputStream;-import java.net.MalformedURLException;-import java.net.URL;-import java.util.*;-import java.util.zip.GZIPInputStream;-import java.util.zip.InflaterInputStream;--import org.apache.commons.httpclient.*;-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.RequestEntity;-import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;-import org.apache.commons.httpclient.methods.multipart.FilePart;-import org.apache.commons.httpclient.methods.multipart.Part;-import org.apache.commons.httpclient.methods.multipart.PartSource;-import org.apache.commons.httpclient.methods.multipart.StringPart;-import org.apache.commons.httpclient.params.HttpMethodParams;-import org.apache.solr.client.solrj.ResponseParser;-import org.apache.solr.client.solrj.SolrRequest;-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.request.RequestWriter;-import org.apache.solr.client.solrj.request.UpdateRequest;-import org.apache.solr.client.solrj.util.ClientUtils;-import org.apache.solr.common.SolrException;-import org.apache.solr.common.SolrInputDocument;-import org.apache.solr.common.params.CommonParams;-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;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * The {@link CommonsHttpSolrServer} uses the Apache Commons HTTP Client to connect to solr.- * <pre class="prettyprint" >SolrServer server = new CommonsHttpSolrServer( url );</pre>- *- *- * @since solr 1.3- */-public class CommonsHttpSolrServer extends SolrServer-{- private static final long serialVersionUID = 1L;-- /**- * User-Agent String as identified by the HTTP request by the {@link- * org.apache.commons.httpclient.HttpClient HttpClient} to the Solr- * server from the client.- */- public static final String AGENT = "Solr["+CommonsHttpSolrServer.class.getName()+"] 1.0";-- private static Logger log = LoggerFactory.getLogger(CommonsHttpSolrServer.class);-- /**- * The URL of the Solr server.- */- protected String _baseURL;-- /**- * Default value: null / empty. <p/>- * Parameters that are added to every request regardless. This may be a place to add- * something like an authentication token.- */- protected ModifiableSolrParams _invariantParams;-- /**- * Default response parser is BinaryResponseParser <p/>- * This parser represents the default Response Parser chosen to- * parse the response if the parser were not specified as part of- * the request.- * @see org.apache.solr.client.solrj.impl.BinaryResponseParser- */- protected ResponseParser _parser;-- /**- * The RequestWriter used to write all requests to Solr- * @see org.apache.solr.client.solrj.request.RequestWriter- */- protected RequestWriter requestWriter = new RequestWriter();-- private final HttpClient _httpClient;-- /**- * This defaults to false under the- * assumption that if you are following a redirect to get to a Solr- * installation, something is misconfigured somewhere.- */- private boolean _followRedirects = false;-- /**- * If compression is enabled, both gzip and deflate compression will- * be accepted in the HTTP response.- */- private boolean _allowCompression = false;-- /**- * Maximum number of retries to attempt in the event of transient- * errors. Default: 0 (no) retries. No more than 1 recommended.- */- private int _maxRetries = 0;-- /**- * Default value: <b> false </b>- * <p>- * If set to false, add the query parameters as URL-encoded parameters to the- * POST request in a single part. If set to true, create a new part of a- * multi-part request for each parameter.- *- * The reason for adding all parameters as parts of a multi-part request is- * that this allows us to specify the charset -- standards for single-part- * requests specify that non-ASCII characters should be URL-encoded, but don't- * specify the charset of the characters to be URL-encoded (cf.- * http://www.w3.org/TR/html401/interact/forms.html#form-content-type).- * Therefore you have to rely on your servlet container doing the right thing- * with single-part requests.- */- private boolean useMultiPartPost;-- private boolean shutdownHttpClient = false;-- /**- * @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));- }-- /**- * Talk to the Solr server via the given HttpClient. The connection manager- * for the client should be a MultiThreadedHttpConnectionManager if this- * client is being reused across SolrServer instances, or of multiple threads- * will use this SolrServer.- */- public CommonsHttpSolrServer(String solrServerUrl, HttpClient httpClient) throws MalformedURLException {- this(new URL(solrServerUrl), httpClient, new BinaryResponseParser(), false);- }-- public CommonsHttpSolrServer(String solrServerUrl, HttpClient httpClient, boolean useMultiPartPost) throws MalformedURLException {- this(new URL(solrServerUrl), httpClient, new BinaryResponseParser(), useMultiPartPost);- }-- public CommonsHttpSolrServer(String solrServerUrl, HttpClient httpClient, ResponseParser parser) throws MalformedURLException {- this(new URL(solrServerUrl), httpClient, parser, false);- }-- /**- * @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, null, new BinaryResponseParser(), false);- }-- public CommonsHttpSolrServer(URL baseURL, HttpClient client) {- this(baseURL, client, new BinaryResponseParser(), false);- }-- /**- *- * @see #useMultiPartPost- */- public CommonsHttpSolrServer(URL baseURL, HttpClient client, boolean useMultiPartPost) {- this(baseURL, client, new BinaryResponseParser(), useMultiPartPost);- }-- /**- * @see #useMultiPartPost- * @see #_parser- */- public CommonsHttpSolrServer(URL baseURL, HttpClient client, ResponseParser parser, boolean useMultiPartPost) {- _baseURL = baseURL.toExternalForm();- if( _baseURL.endsWith( "/" ) ) {- _baseURL = _baseURL.substring( 0, _baseURL.length()-1 );- }- if( _baseURL.indexOf( '?' ) >=0 ) {- throw new RuntimeException( "Invalid base url for solrj. The base URL must not contain parameters: "+_baseURL );- }-- if (client == null) {- shutdownHttpClient = true;- _httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()) ;-- // prevent retries (note: this didn't work when set on mgr.. needed to be set on client)- DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);- _httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);-- // set some better defaults if we created a new connection manager and client-- // increase the default connections- this.setDefaultMaxConnectionsPerHost( 32 ); // 2- this.setMaxTotalConnections( 128 ); // 20- } else {- _httpClient = client;- }-- _parser = parser;-- this.useMultiPartPost = useMultiPartPost;- }--- //------------------------------------------------------------------------- //-------------------------------------------------------------------------- /**- * Process the request. If {@link org.apache.solr.client.solrj.SolrRequest#getResponseParser()} is null, then use- * {@link #getParser()}- * @param request The {@link org.apache.solr.client.solrj.SolrRequest} to process- * @return The {@link org.apache.solr.common.util.NamedList} result- * @throws SolrServerException- * @throws IOException- *- * @see #request(org.apache.solr.client.solrj.SolrRequest, org.apache.solr.client.solrj.ResponseParser)- */- @Override- public NamedList<Object> request( final SolrRequest request ) throws SolrServerException, IOException- {- ResponseParser responseParser = request.getResponseParser();- if (responseParser == null) {- responseParser = _parser;- }- return request(request, responseParser);- }--- public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException {- HttpMethod method = null;- InputStream is = null;- SolrParams params = request.getParams();- Collection<ContentStream> streams = requestWriter.getContentStreams(request);- String path = requestWriter.getPath(request);- if( path == null || !path.startsWith( "/" ) ) {- path = "/select";- }-- ResponseParser parser = request.getResponseParser();- if( parser == null ) {- parser = _parser;- }-- // The parser 'wt=' and 'version=' params are used instead of the original params- ModifiableSolrParams wparams = new ModifiableSolrParams(params);- wparams.set( CommonParams.WT, parser.getWriterType() );- wparams.set( CommonParams.VERSION, parser.getVersion());- if (_invariantParams != null) {- wparams.add( _invariantParams );- }- params = wparams;-- int tries = _maxRetries + 1;- try {- while( tries-- > 0 ) {- // Note: since we aren't doing intermittent time keeping- // ourselves, the potential non-timeout latency could be as- // much as tries-times (plus scheduling effects) the given- // timeAllowed.- 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) {- PostMethod post = new PostMethod(url);- post.getParams().setContentCharset("UTF-8");- if (!this.useMultiPartPost && !isMultipart) {- post.addRequestHeader("Content-Type",- "application/x-www-form-urlencoded; charset=UTF-8");- }-- List<Part> parts = new LinkedList<Part>();- Iterator<String> iter = params.getParameterNamesIterator();- while (iter.hasNext()) {- String p = iter.next();- String[] vals = params.getParams(p);- if (vals != null) {- for (String v : vals) {- if (this.useMultiPartPost || isMultipart) {- parts.add(new StringPart(p, v, "UTF-8"));- } else {- post.addParameter(p, v);- }- }- }- }-- if (isMultipart) {- int i = 0;- for (ContentStream content : streams) {- final ContentStream c = content;-- String charSet = null;- PartSource source = new PartSource() {- @Override- public long getLength() {- return c.getSize();- }-- public String getFileName() {- return c.getName();- }-- @Override- public InputStream createInputStream() throws IOException {- return c.getStream();- }- };-- parts.add(new FilePart(c.getName(), source,- c.getContentType(), charSet));- }- }- if (parts.size() > 0) {- post.setRequestEntity(new MultipartRequestEntity(parts- .toArray(new Part[parts.size()]), post.getParams()));- }-- 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- final ContentStream[] contentStream = new ContentStream[1];- for (ContentStream content : streams) {- contentStream[0] = content;- break;- }- if (contentStream[0] instanceof RequestWriter.LazyContentStream) {- post.setRequestEntity(new RequestEntity() {- public long getContentLength() {- return -1;- }-- public String getContentType() {- return contentStream[0].getContentType();- }-- public boolean isRepeatable() {- return false;- }-- public void writeRequest(OutputStream outputStream) throws IOException {- ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);- }- }- );-- } else {- is = contentStream[0].getStream();- post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType()));- }- method = post;- }- }- else {- throw new SolrServerException("Unsupported method: "+request.getMethod() );- }- }- catch( NoHttpResponseException r ) {- // This is generally safe to retry on- method.releaseConnection();- method = null;- if(is != null) {- is.close();- }- // If out of tries then just rethrow (as normal error).- if( ( tries < 1 ) ) {- throw r;- }- //log.warn( "Caught: " + r + ". Retrying..." );- }- }- }- catch( IOException ex ) {- throw new SolrServerException("error reading streams", ex );- }-- method.setFollowRedirects( _followRedirects );- method.addRequestHeader( "User-Agent", AGENT );- if( _allowCompression ) {- method.setRequestHeader( new Header( "Accept-Encoding", "gzip,deflate" ) );- }-- try {- // Execute the method.- //System.out.println( "EXECUTE:"+method.getURI() );- int statusCode = _httpClient.executeMethod(method);-- // Read the contents- String charset = "UTF-8";- if( method instanceof HttpMethodBase ) {- charset = ((HttpMethodBase)method).getResponseCharSet();- }- InputStream respBody = method.getResponseBodyAsStream();- // Jakarta Commons HTTPClient doesn't handle any- // compression natively. Handle gzip or deflate- // here if applicable.- if( _allowCompression ) {- Header contentEncodingHeader = method.getResponseHeader( "Content-Encoding" );- if( contentEncodingHeader != null ) {- String contentEncoding = contentEncodingHeader.getValue();- if( contentEncoding.contains( "gzip" ) ) {- //log.debug( "wrapping response in GZIPInputStream" );- respBody = new GZIPInputStream( respBody );- }- else if( contentEncoding.contains( "deflate" ) ) {- //log.debug( "wrapping response in InflaterInputStream" );- respBody = new InflaterInputStream(respBody);- }- }- else {- Header contentTypeHeader = method.getResponseHeader( "Content-Type" );- if( contentTypeHeader != null ) {- String contentType = contentTypeHeader.getValue();- if( contentType != null ) {- if( contentType.startsWith( "application/x-gzip-compressed" ) ) {- //log.debug( "wrapping response in GZIPInputStream" );- respBody = new GZIPInputStream( respBody );- }- else if ( contentType.startsWith("application/x-deflate") ) {- //log.debug( "wrapping response in InflaterInputStream" );- respBody = new InflaterInputStream(respBody);- }- }- }- }- }-- NamedList<Object> rsp = processor.processResponse(respBody, charset);- if (statusCode != HttpStatus.SC_OK) {- String reason = null;- try {- NamedList err = (NamedList)rsp.get("error");- if(err!=null) {- reason = (String)err.get("msg");- // TODO? get the trace?- }- }- catch(Exception ex) {}- if(reason == null) {- 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() );- reason = java.net.URLDecoder.decode(msg.toString(), "UTF-8");- }- throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), reason );- }- return rsp;- }- catch (HttpException e) {- throw new SolrServerException(getBaseURL(), e);- }- catch (IOException e) {- throw new SolrServerException(getBaseURL(), e);- }- finally {- method.releaseConnection();- if(is != null) {- is.close();- }- }- }-- //-------------------------------------------------------------------- //--------------------------------------------------------------------- /**- * Retrieve the default list of parameters are added to every request regardless.- *- * @see #_invariantParams- */- public ModifiableSolrParams getInvariantParams()- {- return _invariantParams;- }-- public String getBaseURL() {- return _baseURL;- }-- public void setBaseURL(String baseURL) {- this._baseURL = baseURL;- }-- public ResponseParser getParser() {- return _parser;- }-- /**- * Note: This setter method is <b>not thread-safe</b>.- * @param processor Default Response Parser chosen to parse the response if the parser were not specified as part of the request.- * @see org.apache.solr.client.solrj.SolrRequest#getResponseParser()- */- public void setParser(ResponseParser processor) {- _parser = processor;- }-- public HttpClient getHttpClient() {- return _httpClient;- }-- private HttpConnectionManager getConnectionManager() {- return _httpClient.getHttpConnectionManager();- }-- /** set connectionTimeout on the underlying HttpConnectionManager- * @param timeout Timeout in milliseconds- **/- public void setConnectionTimeout(int timeout) {- getConnectionManager().getParams().setConnectionTimeout(timeout);- }-- /** set connectionManagerTimeout on the HttpClient.- * @param timeout Timeout in milliseconds- * @deprecated Use {@link #setConnectionManagerTimeout(long)} **/- @Deprecated- public void setConnectionManagerTimeout(int timeout) {- _httpClient.getParams().setConnectionManagerTimeout(timeout);- }-- /**- * Sets soTimeout (read timeout) on the underlying- * HttpConnectionManager. This is desirable for queries, but- * probably not for indexing.- *- * @param timeout Timeout in milliseconds- */- public void setConnectionManagerTimeout(long timeout) {- _httpClient.getParams().setConnectionManagerTimeout(timeout);- }--- /**- * Sets soTimeout (read timeout) on the underlying- * HttpConnectionManager. This is desirable for queries, but- * probably not for indexing.- * @param timeout Timeout in milliseconds- **/- public void setSoTimeout(int timeout) {- getConnectionManager().getParams().setSoTimeout(timeout);- }-- /** set maxConnectionsPerHost on the underlying HttpConnectionManager */- public void setDefaultMaxConnectionsPerHost(int connections) {- getConnectionManager().getParams().setDefaultMaxConnectionsPerHost(connections);- }-- /** set maxTotalConnection on the underlying HttpConnectionManager */- public void setMaxTotalConnections(int connections) {- getConnectionManager().getParams().setMaxTotalConnections(connections);- }-- /**- * set followRedirects.- * @see #_followRedirects- */- public void setFollowRedirects( boolean followRedirects ) {- _followRedirects = followRedirects;- }-- /**- * set allowCompression.- * @see #_allowCompression- */- public void setAllowCompression( boolean allowCompression ) {- _allowCompression = allowCompression;- }-- /**- * set maximum number of retries to attempt in the event of- * transient errors.- * @param maxRetries No more than 1 recommended- * @see #_maxRetries- */- public void setMaxRetries( int maxRetries ) {- if (maxRetries > 1) {- log.warn("CommonsHttpSolrServer: maximum Retries " + maxRetries + " > 1. Maximum recommended retries is 1.");- }- _maxRetries = maxRetries;- }-- public void setRequestWriter(RequestWriter requestWriter) {- this.requestWriter = requestWriter;- }-- /**- * Adds the documents supplied by the given iterator.- * @param docIterator the iterator which returns SolrInputDocument instances- * @return the response from the SolrServer- */- public UpdateResponse add(Iterator<SolrInputDocument> docIterator)- throws SolrServerException, IOException {- return add(docIterator, -1);- }-- /**- * Adds the documents supplied by the given iterator, specifying max time before they become committed- * @param docIterator the iterator which returns SolrInputDocument instances- * @param commitWithinMs the time in milliseconds before a commit automatically is triggered- * @return the response from the SolrServer- */- public UpdateResponse add(Iterator<SolrInputDocument> docIterator, int commitWithinMs)- throws SolrServerException, IOException {- UpdateRequest req = new UpdateRequest();- req.setDocIterator(docIterator);- req.setCommitWithin(commitWithinMs);- return req.process(this);- }-- /**- * Adds the beans supplied by the given iterator- * @param beanIterator the iterator which returns Beans- * @return the response from the SolrServer- */- public UpdateResponse addBeans(final Iterator<?> beanIterator)- throws SolrServerException, IOException {- return addBeans(beanIterator, -1);- }-- /**- * Adds the beans supplied by the given iterator, specifying max time before they become committed- * @param commitWithinMs the time in milliseconds before a commit automatically is triggered- * @param beanIterator the iterator which returns Beans- * @return the response from the SolrServer- */- public UpdateResponse addBeans(final Iterator<?> beanIterator, int commitWithinMs)- throws SolrServerException, IOException {- UpdateRequest req = new UpdateRequest();- req.setDocIterator(new Iterator<SolrInputDocument>() {-- public boolean hasNext() {- return beanIterator.hasNext();- }-- public SolrInputDocument next() {- Object o = beanIterator.next();- if (o == null) return null;- return getBinder().toSolrInputDocument(o);- }-- public void remove() {- beanIterator.remove();- }- });- req.setCommitWithin(commitWithinMs);- return req.process(this);- }-- public void shutdown() {- if (shutdownHttpClient && _httpClient != null- && _httpClient.getHttpConnectionManager() instanceof MultiThreadedHttpConnectionManager) {- ((MultiThreadedHttpConnectionManager) _httpClient- .getHttpConnectionManager()).shutdown();- }- }-- @Override- public String toString() {- return this.getClass().getSimpleName() + "{url=" + _baseURL + "}";- }-}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrServer.javanew file mode 100644index 00000000000..e2acc2dc585--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrServer.java@@ -0,0 +1,371 @@+/**+ * 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.OutputStream;+import java.net.MalformedURLException;+import java.util.LinkedList;+import java.util.Queue;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.locks.Lock;+import java.util.concurrent.locks.ReentrantLock;++import org.apache.http.HttpResponse;+import org.apache.http.HttpStatus;+import org.apache.http.client.HttpClient;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.entity.ContentProducer;+import org.apache.http.entity.EntityTemplate;+import org.apache.solr.client.solrj.ResponseParser;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.RequestWriter;+import org.apache.solr.client.solrj.request.UpdateRequest;+import org.apache.solr.client.solrj.util.ClientUtils;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.params.UpdateParams;+import org.apache.solr.common.util.NamedList;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * ConcurrentUpdateSolrServer buffers all added documents and writes+ * them into open HTTP connections. This class is thread safe.+ *+ * Although any SolrServer request can be made with this implementation, it is+ * only recommended to use ConcurrentUpdateSolrServer with /update+ * requests. The class {@link HttpSolrServer} is better suited for the+ * query interface.+ */+public class ConcurrentUpdateSolrServer extends SolrServer {+ private static final long serialVersionUID = 1L;+ static final Logger log = LoggerFactory+ .getLogger(ConcurrentUpdateSolrServer.class);+ private HttpSolrServer server;+ final BlockingQueue<UpdateRequest> queue;+ final ExecutorService scheduler = Executors.newCachedThreadPool();+ final String updateUrl = "/update";+ final Queue<Runner> runners;+ volatile CountDownLatch lock = null; // used to block everything+ final int threadCount;++ /**+ * Uses an internal ThreadSafeClientConnManager to manage http+ * connections.+ *+ * @param solrServerUrl+ * The Solr server URL+ * @param queueSize+ * The buffer size before the documents are sent to the server+ * @param threadCount+ * The number of background threads used to empty the queue+ * @throws MalformedURLException+ */+ public ConcurrentUpdateSolrServer(String solrServerUrl, int queueSize,+ int threadCount) throws MalformedURLException {+ this(solrServerUrl, null, queueSize, threadCount);+ }++ /**+ * Uses the supplied HttpClient to send documents to the Solr server, the+ * HttpClient should be instantiated using a+ * ThreadSafeClientConnManager.+ */+ public ConcurrentUpdateSolrServer(String solrServerUrl,+ HttpClient client, int queueSize, int threadCount)+ throws MalformedURLException {+ this.server = new HttpSolrServer(solrServerUrl, client);+ this.server.setFollowRedirects(false);+ queue = new LinkedBlockingQueue<UpdateRequest>(queueSize);+ this.threadCount = threadCount;+ runners = new LinkedList<Runner>();+ }++ /**+ * Opens a connection and sends everything...+ */+ class Runner implements Runnable {+ final Lock runnerLock = new ReentrantLock();++ public void run() {+ runnerLock.lock();++ // info is ok since this should only happen once for each thread+ log.info("starting runner: {}", this);+ HttpPost method = null;+ HttpResponse response = null;+ try {+ while (!queue.isEmpty()) {+ try {+ final UpdateRequest updateRequest = queue.poll(250,+ TimeUnit.MILLISECONDS);+ if (updateRequest == null)+ break;++ EntityTemplate template = new EntityTemplate(new ContentProducer() {++ public void writeTo(OutputStream out) throws IOException {+ try {+ if (ClientUtils.TEXT_XML.equals(server.requestWriter+ .getUpdateContentType())) {+ out.write("<stream>".getBytes("UTF-8")); // can be anything+ }+ UpdateRequest req = updateRequest;+ while (req != null) {+ server.requestWriter.write(req, out);+ if (ClientUtils.TEXT_XML.equals(server.requestWriter+ .getUpdateContentType())) {+ // check for commit or optimize+ SolrParams params = req.getParams();+ if (params != null) {+ String fmt = null;+ if (params.getBool(UpdateParams.OPTIMIZE, false)) {+ fmt = "<optimize waitSearcher=\"%s\" waitFlush=\"%s\" />";+ } else if (params.getBool(UpdateParams.COMMIT, false)) {+ fmt = "<commit waitSearcher=\"%s\" waitFlush=\"%s\" />";+ }+ if (fmt != null) {+ byte[] content = String.format(+ fmt,+ params.getBool(UpdateParams.WAIT_SEARCHER, false)+ + "").getBytes("UTF-8");+ out.write(content);+ }+ }+ }+ out.flush();+ req = queue.poll(250, TimeUnit.MILLISECONDS);+ }+ if (ClientUtils.TEXT_XML.equals(server.requestWriter+ .getUpdateContentType())) {+ out.write("</stream>".getBytes("UTF-8"));+ }++ } catch (InterruptedException e) {+ e.printStackTrace();+ }+ }+ });++ String path = ClientUtils.TEXT_XML.equals(server.requestWriter+ .getUpdateContentType()) ? "/update" : "/update/javabin";++ method = new HttpPost(server.getBaseURL() + path);+ method.setEntity(template);+ method.addHeader("User-Agent", HttpSolrServer.AGENT);+ response = server.getHttpClient().execute(method);+ int statusCode = response.getStatusLine().getStatusCode();+ log.info("Status for: "+ + updateRequest.getDocuments().get(0).getFieldValue("id")+ + " is " + statusCode);+ if (statusCode != HttpStatus.SC_OK) {+ StringBuilder msg = new StringBuilder();+ msg.append(response.getStatusLine().getReasonPhrase());+ msg.append("\n\n");+ msg.append("\n\n");+ msg.append("request: ").append(method.getURI());+ handleError(new Exception(msg.toString()));+ }+ } finally {+ try {+ if (response != null) {+ response.getEntity().getContent().close();+ }+ } catch (Exception ex) {+ }+ }+ }+ } catch (Throwable e) {+ handleError(e);+ } finally {++ // remove it from the list of running things unless we are the last+ // runner and the queue is full...+ // in which case, the next queue.put() would block and there would be no+ // runners to handle it.+ // This case has been further handled by using offer instead of put, and+ // using a retry loop+ // to avoid blocking forever (see request()).+ synchronized (runners) {+ if (runners.size() == 1 && queue.remainingCapacity() == 0) {+ // keep this runner alive+ scheduler.execute(this);+ } else {+ runners.remove(this);+ }+ }++ log.info("finished: {}", this);+ runnerLock.unlock();+ }+ }+ }++ public NamedList<Object> request(final SolrRequest request)+ throws SolrServerException, IOException {+ if (!(request instanceof UpdateRequest)) {+ return server.request(request);+ }+ UpdateRequest req = (UpdateRequest) request;++ // this happens for commit...+ if (req.getDocuments() == null || req.getDocuments().isEmpty()) {+ blockUntilFinished();+ return server.request(request);+ }++ SolrParams params = req.getParams();+ if (params != null) {+ // check if it is waiting for the searcher+ if (params.getBool(UpdateParams.WAIT_SEARCHER, false)) {+ log.info("blocking for commit/optimize");+ blockUntilFinished(); // empty the queue+ return server.request(request);+ }+ }++ try {+ CountDownLatch tmpLock = lock;+ if (tmpLock != null) {+ tmpLock.await();+ }++ boolean success = queue.offer(req);++ for (;;) {+ synchronized (runners) {+ if (runners.isEmpty() || (queue.remainingCapacity() < queue.size() // queue+ // is+ // half+ // full+ // and+ // we+ // can+ // add+ // more+ // runners+ && runners.size() < threadCount)) {+ // We need more runners, so start a new one.+ Runner r = new Runner();+ runners.add(r);+ scheduler.execute(r);+ } else {+ // break out of the retry loop if we added the element to the queue+ // successfully, *and*+ // while we are still holding the runners lock to prevent race+ // conditions.+ // race conditions.+ if (success)+ break;+ }+ }++ // Retry to add to the queue w/o the runners lock held (else we risk+ // temporary deadlock)+ // This retry could also fail because+ // 1) existing runners were not able to take off any new elements in the+ // queue+ // 2) the queue was filled back up since our last try+ // If we succeed, the queue may have been completely emptied, and all+ // runners stopped.+ // In all cases, we should loop back to the top to see if we need to+ // start more runners.+ //+ if (!success) {+ success = queue.offer(req, 100, TimeUnit.MILLISECONDS);+ }++ }++ } catch (InterruptedException e) {+ log.error("interrupted", e);+ throw new IOException(e.getLocalizedMessage());+ }++ // RETURN A DUMMY result+ NamedList<Object> dummy = new NamedList<Object>();+ dummy.add("NOTE", "the request is processed in a background stream");+ return dummy;+ }++ public synchronized void blockUntilFinished() {+ lock = new CountDownLatch(1);+ try {+ // Wait until no runners are running+ for (;;) {+ Runner runner;+ synchronized (runners) {+ runner = runners.peek();+ }+ if (runner == null)+ break;+ runner.runnerLock.lock();+ runner.runnerLock.unlock();+ }+ } finally {+ lock.countDown();+ lock = null;+ }+ }++ public void handleError(Throwable ex) {+ log.error("error", ex);+ }++ public void shutdown() {+ server.shutdown();+ scheduler.shutdown();+ try {+ if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {+ scheduler.shutdownNow();+ if (!scheduler.awaitTermination(60, TimeUnit.SECONDS))+ log.error("ExecutorService did not terminate");+ }+ } catch (InterruptedException ie) {+ scheduler.shutdownNow();+ Thread.currentThread().interrupt();+ }+ }++ public void shutdownNow() {+ server.shutdown();+ scheduler.shutdownNow(); // Cancel currently executing tasks+ try {+ if (!scheduler.awaitTermination(30, TimeUnit.SECONDS))+ log.error("ExecutorService did not terminate");+ } catch (InterruptedException ie) {+ scheduler.shutdownNow();+ Thread.currentThread().interrupt();+ }+ }++ public void setParser(ResponseParser responseParser) {+ server.setParser(responseParser);+ }++ public void setRequestWriter(RequestWriter requestWriter) {+ server.setRequestWriter(requestWriter);+ }+}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.javanew file mode 100644index 00000000000..febe1e08e19--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/HttpSolrServer.java@@ -0,0 +1,630 @@+/**+ * 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.InputStream;+import java.net.ConnectException;+import java.net.SocketTimeoutException;+import java.util.Collection;+import java.util.Iterator;+import java.util.zip.GZIPInputStream;+import java.util.zip.InflaterInputStream;++import org.apache.http.Header;+import org.apache.http.HeaderElement;+import org.apache.http.HttpEntity;+import org.apache.http.HttpException;+import org.apache.http.HttpRequest;+import org.apache.http.HttpRequestInterceptor;+import org.apache.http.HttpResponse;+import org.apache.http.HttpResponseInterceptor;+import org.apache.http.HttpStatus;+import org.apache.http.client.HttpClient;+import org.apache.http.client.methods.HttpGet;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.client.methods.HttpRequestBase;+import org.apache.http.client.params.ClientPNames;+import org.apache.http.client.params.ClientParamBean;+import org.apache.http.conn.scheme.PlainSocketFactory;+import org.apache.http.conn.scheme.Scheme;+import org.apache.http.conn.scheme.SchemeRegistry;+import org.apache.http.conn.ssl.SSLSocketFactory;+import org.apache.http.entity.HttpEntityWrapper;+import org.apache.http.entity.mime.FormBodyPart;+import org.apache.http.entity.mime.HttpMultipartMode;+import org.apache.http.entity.mime.MultipartEntity;+import org.apache.http.entity.mime.content.InputStreamBody;+import org.apache.http.entity.mime.content.StringBody;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.http.params.HttpConnectionParams;+import org.apache.http.protocol.HttpContext;+import org.apache.http.util.EntityUtils;+import org.apache.solr.client.solrj.ResponseParser;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.SolrServer;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.RequestWriter;+import org.apache.solr.client.solrj.request.UpdateRequest;+import org.apache.solr.client.solrj.response.UpdateResponse;+import org.apache.solr.client.solrj.util.ClientUtils;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.CommonParams;+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;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HttpSolrServer extends SolrServer {+ private static final String UTF_8 = "UTF-8";+ private static final String DEFAULT_PATH = "/select";+ private static final long serialVersionUID = -946812319974801896L;+ /**+ * User-Agent String.+ */+ public static final String AGENT = "Solr[" + HttpSolrServer.class.getName()+ + "] 1.0";++ private static Logger log = LoggerFactory.getLogger(HttpSolrServer.class);++ /**+ * The URL of the Solr server.+ */+ protected String baseUrl;++ /**+ * Default value: null / empty.+ * <p/>+ * Parameters that are added to every request regardless. This may be a place+ * to add something like an authentication token.+ */+ protected ModifiableSolrParams invariantParams;++ /**+ * Default response parser is BinaryResponseParser+ * <p/>+ * This parser represents the default Response Parser chosen to parse the+ * response if the parser were not specified as part of the request.+ *+ * @see org.apache.solr.client.solrj.impl.BinaryResponseParser+ */+ protected ResponseParser parser;++ /**+ * The RequestWriter used to write all requests to Solr+ *+ * @see org.apache.solr.client.solrj.request.RequestWriter+ */+ protected RequestWriter requestWriter = new RequestWriter();++ private final HttpClient httpClient;++ /**+ * This defaults to false under the assumption that if you are following a+ * redirect to get to a Solr installation, something is misconfigured+ * somewhere.+ */+ private boolean followRedirects = false;++ /**+ * Maximum number of retries to attempt in the event of transient errors.+ * Default: 0 (no) retries. No more than 1 recommended.+ */+ private int maxRetries = 0;++ private ThreadSafeClientConnManager ccm;++ /**+ * @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 HttpSolrServer(String baseURL) {+ this(baseURL, null, new BinaryResponseParser());+ }++ public HttpSolrServer(String baseURL, HttpClient client) {+ this(baseURL, client, new BinaryResponseParser());+ }++ public HttpSolrServer(String baseURL, HttpClient client, ResponseParser parser) {+ this.baseUrl = baseURL;+ if (baseUrl.endsWith("/")) {+ baseUrl = baseUrl.substring(0, baseUrl.length() - 1);+ }+ if (baseUrl.indexOf('?') >= 0) {+ throw new RuntimeException(+ "Invalid base url for solrj. The base URL must not contain parameters: "+ + baseUrl);+ }++ if (client != null) {+ httpClient = client;+ } else {+ httpClient = createClient();+ }++ this.parser = parser;+ }++ private DefaultHttpClient createClient() {+ SchemeRegistry schemeRegistry = new SchemeRegistry();+ schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory+ .getSocketFactory()));+ schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory+ .getSocketFactory()));++ ccm = new ThreadSafeClientConnManager(schemeRegistry);+ // Increase default max connection per route to 32+ ccm.setDefaultMaxPerRoute(32);+ // Increase max total connection to 128+ ccm.setMaxTotal(128);+ DefaultHttpClient httpClient = new DefaultHttpClient(ccm);+ httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,+ followRedirects);+ return httpClient;+ }++ /**+ * Process the request. If+ * {@link org.apache.solr.client.solrj.SolrRequest#getResponseParser()} is+ * null, then use {@link #getParser()}+ *+ * @param request+ * The {@link org.apache.solr.client.solrj.SolrRequest} to process+ * @return The {@link org.apache.solr.common.util.NamedList} result+ * @throws SolrServerException+ * @throws IOException+ *+ * @see #request(org.apache.solr.client.solrj.SolrRequest,+ * org.apache.solr.client.solrj.ResponseParser)+ */+ @Override+ public NamedList<Object> request(final SolrRequest request)+ throws SolrServerException, IOException {+ ResponseParser responseParser = request.getResponseParser();+ if (responseParser == null) {+ responseParser = parser;+ }+ return request(request, responseParser);+ }++ public NamedList<Object> request(final SolrRequest request,+ final ResponseParser processor) throws SolrServerException {+ HttpRequestBase method = null;+ SolrParams params = request.getParams();+ String path = requestWriter.getPath(request);+ if (path == null || !path.startsWith("/")) {+ path = DEFAULT_PATH;+ }++ ResponseParser parser = request.getResponseParser();+ if (parser == null) {+ parser = this.parser;+ }++ // The parser 'wt=' and 'version=' params are used instead of the original+ // params+ ModifiableSolrParams wparams = new ModifiableSolrParams(params);+ wparams.set(CommonParams.WT, parser.getWriterType());+ wparams.set(CommonParams.VERSION, parser.getVersion());+ if (invariantParams != null) {+ wparams.add(invariantParams);+ }+ params = wparams;++ int tries = maxRetries + 1;+ try {+ while (tries-- > 0) { // XXX this retry thing seems noop to me+ Collection<ContentStream> streams = requestWriter+ .getContentStreams(request);+ // Note: since we aren't doing intermittent time keeping+ // ourselves, the potential non-timeout latency could be as+ // much as tries-times (plus scheduling effects) the given+ // timeAllowed.+ try {+ if (SolrRequest.METHOD.GET == request.getMethod()) {+ if (streams != null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,+ "GET can't send streams!");+ }+ method = new HttpGet(baseUrl + path+ + ClientUtils.toQueryString(params, false));+ } else if (SolrRequest.METHOD.POST == request.getMethod()) {+ String url = baseUrl + path;++ MultipartEntity entity = new MultipartEntity(+ HttpMultipartMode.BROWSER_COMPATIBLE);++ final HttpPost post = new HttpPost(url);++ final Iterator<String> iter = params.getParameterNamesIterator();+ if (iter.hasNext()) {++ while (iter.hasNext()) {+ final String name = iter.next();+ final String[] vals = params.getParams(name);+ if (vals != null) {+ for (String value : vals) {+ entity.addPart(name, new StringBody(value));+ }+ }+ }+ }+ addParts(streams, entity);+ post.setEntity(entity);+ method = post;+ } else {+ throw new SolrServerException("Unsupported method: "+ + request.getMethod());+ }+ } catch (RuntimeException r) {+ // If out of tries then just rethrow (as normal error).+ if ((tries < 1)) {+ throw r;+ }+ // log.warn( "Caught: " + r + ". Retrying..." );+ }+ }+ } catch (IOException ex) {+ throw new SolrServerException("error reading streams", ex);+ }++ // TODO: move to a interceptor?+ method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,+ followRedirects);+ method.addHeader("User-Agent", AGENT);+ method.setHeader("Content-Charset", UTF_8);+ method.setHeader("Accept-Charset", UTF_8);++ InputStream respBody = null;++ try {+ // Execute the method.+ final HttpResponse response = httpClient.execute(method);+ int httpStatus = response.getStatusLine().getStatusCode();++ // Read the contents+ String charset = EntityUtils.getContentCharSet(response.getEntity());+ respBody = response.getEntity().getContent();++ // handle some http level checks before trying to parse the response+ switch (httpStatus) {+ case HttpStatus.SC_OK:+ case HttpStatus.SC_BAD_REQUEST:+ break;+ case HttpStatus.SC_MOVED_PERMANENTLY:+ case HttpStatus.SC_MOVED_TEMPORARILY:+ if (!followRedirects) {+ throw new SolrServerException("Server at " + getBaseURL()+ + " sent back a redirect (" + httpStatus + ").");+ }+ break;+ case HttpStatus.SC_NOT_FOUND:+ throw new SolrServerException("Server at " + getBaseURL()+ + " was not found (404).");+ default:+ throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL()+ + " returned non ok status:" + httpStatus + ", message:"+ + response.getStatusLine().getReasonPhrase());++ }+ NamedList<Object> rsp = processor.processResponse(respBody, charset);+ if (httpStatus != HttpStatus.SC_OK) {+ String reason = null;+ try {+ NamedList err = (NamedList) rsp.get("error");+ if (err != null) {+ reason = (String) err.get("msg");+ // TODO? get the trace?+ }+ } catch (Exception ex) {}+ if (reason == null) {+ StringBuilder msg = new StringBuilder();+ msg.append(response.getStatusLine().getReasonPhrase());+ msg.append("\n\n");+ msg.append("request: " + method.getURI());+ reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);+ }+ throw new SolrException(+ SolrException.ErrorCode.getErrorCode(httpStatus), reason);+ }+ return rsp;+ } catch (ConnectException e) {+ throw new SolrServerException("Server refused connection at: "+ + getBaseURL(), e);+ } catch (SocketTimeoutException e) {+ throw new SolrServerException(+ "Timeout occured while waiting response from server at: "+ + getBaseURL(), e);+ } catch (IOException e) {+ throw new SolrServerException(+ "IOException occured when talking to server at: " + getBaseURL(), e);+ } finally {+ if (respBody != null) {+ try {+ respBody.close();+ } catch (Throwable t) {} // ignore+ }+ }+ }++ private void addParts(Collection<ContentStream> streams,+ MultipartEntity entity) throws IOException {+ if (streams != null) {+ for (ContentStream content : streams) {+ entity.addPart(new FormBodyPart(CommonParams.STREAM_BODY,+ new InputStreamBody(content.getStream(), "")));+ }+ }+ }++ // -------------------------------------------------------------------+ // -------------------------------------------------------------------++ /**+ * Retrieve the default list of parameters are added to every request+ * regardless.+ *+ * @see #invariantParams+ */+ public ModifiableSolrParams getInvariantParams() {+ return invariantParams;+ }++ public String getBaseURL() {+ return baseUrl;+ }++ public void setBaseURL(String baseURL) {+ this.baseUrl = baseURL;+ }++ public ResponseParser getParser() {+ return parser;+ }++ /**+ * Note: This setter method is <b>not thread-safe</b>.+ *+ * @param processor+ * Default Response Parser chosen to parse the response if the parser+ * were not specified as part of the request.+ * @see org.apache.solr.client.solrj.SolrRequest#getResponseParser()+ */+ public void setParser(ResponseParser processor) {+ parser = processor;+ }++ public HttpClient getHttpClient() {+ return httpClient;+ }++ /**+ * HttpConnectionParams.setConnectionTimeout+ *+ * @param timeout+ * Timeout in milliseconds+ **/+ public void setConnectionTimeout(int timeout) {+ HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), timeout);+ }++ /**+ * Sets HttpConnectionParams.setSoTimeout (read timeout). This is desirable+ * for queries, but probably not for indexing.+ *+ * @param timeout+ * Timeout in milliseconds+ **/+ public void setSoTimeout(int timeout) {+ HttpConnectionParams.setSoTimeout(httpClient.getParams(), timeout);+ }++ /**+ * HttpClientParams.setRedirecting+ *+ * @see #followRedirects+ */+ public void setFollowRedirects(boolean followRedirects) {+ this.followRedirects = followRedirects;+ new ClientParamBean(httpClient.getParams())+ .setHandleRedirects(followRedirects);+ }++ private static class UseCompressionRequestInterceptor implements+ HttpRequestInterceptor {++ @Override+ public void process(HttpRequest request, HttpContext context)+ throws HttpException, IOException {+ if (!request.containsHeader("Accept-Encoding")) {+ request.addHeader("Accept-Encoding", "gzip, deflate");+ }+ }+ }++ private static class UseCompressionResponseInterceptor implements+ HttpResponseInterceptor {++ public void process(final HttpResponse response, final HttpContext context)+ throws HttpException, IOException {++ HttpEntity entity = response.getEntity();+ Header ceheader = entity.getContentEncoding();+ if (ceheader != null) {+ HeaderElement[] codecs = ceheader.getElements();+ for (int i = 0; i < codecs.length; i++) {+ if (codecs[i].getName().equalsIgnoreCase("gzip")) {+ response+ .setEntity(new GzipDecompressingEntity(response.getEntity()));+ return;+ }+ if (codecs[i].getName().equalsIgnoreCase("deflate")) {+ response.setEntity(new DeflateDecompressingEntity(response+ .getEntity()));+ return;+ }+ }+ }+ }+ }++ private static class GzipDecompressingEntity extends HttpEntityWrapper {+ public GzipDecompressingEntity(final HttpEntity entity) {+ super(entity);+ }++ public InputStream getContent() throws IOException, IllegalStateException {+ return new GZIPInputStream(wrappedEntity.getContent());+ }++ public long getContentLength() {+ return -1;+ }+ }++ private static class DeflateDecompressingEntity extends+ GzipDecompressingEntity {+ public DeflateDecompressingEntity(final HttpEntity entity) {+ super(entity);+ }++ public InputStream getContent() throws IOException, IllegalStateException {+ return new InflaterInputStream(wrappedEntity.getContent());+ }+ }++ /**+ * Allow server->client communication to be compressed. Currently gzip and+ * deflate are supported. If the server supports compression the response will+ * be compressed.+ */+ public void setAllowCompression(boolean allowCompression) {+ if (httpClient instanceof DefaultHttpClient) {+ final DefaultHttpClient client = (DefaultHttpClient) httpClient;+ client+ .removeRequestInterceptorByClass(UseCompressionRequestInterceptor.class);+ client+ .removeResponseInterceptorByClass(UseCompressionResponseInterceptor.class);+ if (allowCompression) {+ client.addRequestInterceptor(new UseCompressionRequestInterceptor());+ client.addResponseInterceptor(new UseCompressionResponseInterceptor());+ }+ } else {+ throw new UnsupportedOperationException(+ "HttpClient instance was not of type DefaultHttpClient");+ }+ }++ /**+ * Set maximum number of retries to attempt in the event of transient errors.+ *+ * @param maxRetries+ * No more than 1 recommended+ * @see #maxRetries+ */+ public void setMaxRetries(int maxRetries) {+ if (maxRetries > 1) {+ log.warn("CommonsHttpSolrServer: maximum Retries " + maxRetries+ + " > 1. Maximum recommended retries is 1.");+ }+ this.maxRetries = maxRetries;+ }++ public void setRequestWriter(RequestWriter requestWriter) {+ this.requestWriter = requestWriter;+ }++ /**+ * Adds the documents supplied by the given iterator.+ *+ * @param docIterator+ * the iterator which returns SolrInputDocument instances+ *+ * @return the response from the SolrServer+ */+ public UpdateResponse add(Iterator<SolrInputDocument> docIterator)+ throws SolrServerException, IOException {+ UpdateRequest req = new UpdateRequest();+ req.setDocIterator(docIterator);+ return req.process(this);+ }++ /**+ * Adds the beans supplied by the given iterator.+ *+ * @param beanIterator+ * the iterator which returns Beans+ *+ * @return the response from the SolrServer+ */+ public UpdateResponse addBeans(final Iterator<?> beanIterator)+ throws SolrServerException, IOException {+ UpdateRequest req = new UpdateRequest();+ req.setDocIterator(new Iterator<SolrInputDocument>() {++ public boolean hasNext() {+ return beanIterator.hasNext();+ }++ public SolrInputDocument next() {+ Object o = beanIterator.next();+ if (o == null) return null;+ return getBinder().toSolrInputDocument(o);+ }++ public void remove() {+ beanIterator.remove();+ }+ });+ return req.process(this);+ }++ public void shutdown() {+ if (httpClient != null) {+ httpClient.getConnectionManager().shutdown();+ }+ }++ public void setDefaultMaxConnectionsPerHost(int max) {+ if (ccm != null) {+ ccm.setDefaultMaxPerRoute(max);+ } else {+ throw new UnsupportedOperationException(+ "Client was created outside of HttpSolrServer");+ }+ }++ /**+ * Set the maximum number of connections that can be open at any given time.+ */+ public void setMaxTotalConnections(int max) {+ if (ccm != null) {+ ccm.setMaxTotal(max);+ } else {+ throw new UnsupportedOperationException(+ "Client was created outside of HttpSolrServer");+ }+ }+}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrServer.javaindex 32a86096a23..6692c01b5b3 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrServer.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrServer.java@@ -16,10 +16,11 @@*/package org.apache.solr.client.solrj.impl;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;-import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;-import org.apache.commons.httpclient.params.HttpMethodParams;+import org.apache.http.client.HttpClient;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;+import org.apache.http.params.CoreConnectionPNames;import org.apache.solr.client.solrj.*;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.util.NamedList;@@ -91,7 +92,7 @@ public class LBHttpSolrServer extends SolrServer {}private static class ServerWrapper {- final CommonsHttpSolrServer solrServer;+ final HttpSolrServer solrServer;long lastUsed; // last time used for a real requestlong lastChecked; // last time checked for liveness@@ -103,7 +104,7 @@ public class LBHttpSolrServer extends SolrServer {int failedPings = 0;- public ServerWrapper(CommonsHttpSolrServer solrServer) {+ public ServerWrapper(HttpSolrServer solrServer) {this.solrServer = solrServer;}@@ -175,12 +176,16 @@ public class LBHttpSolrServer extends SolrServer {}public LBHttpSolrServer(String... solrServerUrls) throws MalformedURLException {- this(new HttpClient(new MultiThreadedHttpConnectionManager()), solrServerUrls);-- DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);- httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);+ this(getDefaultClient(), solrServerUrls);}+ private static HttpClient getDefaultClient(){+ DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());;+ DefaultHttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(0, false);+ client.setHttpRequestRetryHandler(retryhandler);+ return client;+ }+/** The provided httpClient should use a multi-threaded connection manager */public LBHttpSolrServer(HttpClient httpClient, String... solrServerUrl)throws MalformedURLException {@@ -204,8 +209,8 @@ public class LBHttpSolrServer extends SolrServer {return server;}- protected CommonsHttpSolrServer makeServer(String server) throws MalformedURLException {- return new CommonsHttpSolrServer(server, httpClient, binaryParser);+ protected HttpSolrServer makeServer(String server) throws MalformedURLException {+ return new HttpSolrServer(server, httpClient, binaryParser);}@@ -245,7 +250,7 @@ public class LBHttpSolrServer extends SolrServer {continue;}rsp.server = serverStr;- CommonsHttpSolrServer server = makeServer(serverStr);+ HttpSolrServer server = makeServer(serverStr);try {rsp.rsp = server.request(req.getRequest());@@ -322,7 +327,7 @@ public class LBHttpSolrServer extends SolrServer {}- private Exception addZombie(CommonsHttpSolrServer server,+ private Exception addZombie(HttpSolrServer server,Exception e) {ServerWrapper wrapper;@@ -361,7 +366,7 @@ public class LBHttpSolrServer extends SolrServer {}public void addSolrServer(String server) throws MalformedURLException {- CommonsHttpSolrServer solrServer = makeServer(server);+ HttpSolrServer solrServer = makeServer(server);addToAlive(new ServerWrapper(solrServer));}@@ -383,14 +388,7 @@ public class LBHttpSolrServer extends SolrServer {}public void setConnectionTimeout(int timeout) {- httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);- }-- /**- * set connectionManagerTimeout on the HttpClient.*- */- public void setConnectionManagerTimeout(int timeout) {- httpClient.getParams().setConnectionManagerTimeout(timeout);+ httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);}/**@@ -398,7 +396,7 @@ public class LBHttpSolrServer extends SolrServer {* not for indexing.*/public void setSoTimeout(int timeout) {- httpClient.getParams().setSoTimeout(timeout);+ httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);}public void shutdown() {diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/StreamingUpdateSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/StreamingUpdateSolrServer.javadeleted file mode 100644index a04738c0262..00000000000--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/StreamingUpdateSolrServer.java+++ /dev/null@@ -1,335 +0,0 @@-/**- * 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.OutputStream;-import java.net.MalformedURLException;-import java.util.LinkedList;-import java.util.Queue;-import java.util.concurrent.BlockingQueue;-import java.util.concurrent.CountDownLatch;-import java.util.concurrent.ExecutorService;-import java.util.concurrent.Executors;-import java.util.concurrent.LinkedBlockingQueue;-import java.util.concurrent.TimeUnit;-import java.util.concurrent.locks.Lock;-import java.util.concurrent.locks.ReentrantLock;--import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.HttpStatus;-import org.apache.commons.httpclient.methods.PostMethod;-import org.apache.commons.httpclient.methods.RequestEntity;-import org.apache.solr.client.solrj.SolrRequest;-import org.apache.solr.client.solrj.SolrServerException;-import org.apache.solr.client.solrj.request.UpdateRequest;-import org.apache.solr.client.solrj.util.ClientUtils;-import org.apache.solr.common.params.SolrParams;-import org.apache.solr.common.params.UpdateParams;-import org.apache.solr.common.util.NamedList;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * {@link StreamingUpdateSolrServer} buffers all added documents and writes them- * into open HTTP connections. This class is thread safe.- *- * Although any SolrServer request can be made with this implementation,- * it is only recommended to use {@link StreamingUpdateSolrServer} with- * /update requests. The base class {&link CommonsHttpSolrServer} is- * better suited for the query interface.- *- * @since solr 1.4- */-public class StreamingUpdateSolrServer extends CommonsHttpSolrServer-{- static final Logger log = LoggerFactory.getLogger( StreamingUpdateSolrServer.class );-- final BlockingQueue<UpdateRequest> queue;- final ExecutorService scheduler = Executors.newCachedThreadPool();- final String updateUrl = "/update";- final Queue<Runner> runners;- volatile CountDownLatch lock = null; // used to block everything- final int threadCount;-- /**- * Uses an internal MultiThreadedHttpConnectionManager to manage http connections- *- * @param solrServerUrl The Solr server URL- * @param queueSize The buffer size before the documents are sent to the server- * @param threadCount The number of background threads used to empty the queue- * @throws MalformedURLException- */- public StreamingUpdateSolrServer(String solrServerUrl, int queueSize, int threadCount) throws MalformedURLException {- this(solrServerUrl, null, queueSize, threadCount);- }-- /**- * Uses the supplied HttpClient to send documents to the Solr server, the HttpClient should be instantiated using a- * MultiThreadedHttpConnectionManager.- */- public StreamingUpdateSolrServer(String solrServerUrl, HttpClient client, int queueSize, int threadCount) throws MalformedURLException {- super(solrServerUrl, client);- queue = new LinkedBlockingQueue<UpdateRequest>(queueSize);- this.threadCount = threadCount;- runners = new LinkedList<Runner>();- }-- /**- * Opens a connection and sends everything...- */- class Runner implements Runnable {- final Lock runnerLock = new ReentrantLock();-- public void run() {- runnerLock.lock();-- // info is ok since this should only happen once for each thread- log.info( "starting runner: {}" , this );- PostMethod method = null;- try {- while (!queue.isEmpty()) {- try {- final UpdateRequest updateRequest = queue.poll(250, TimeUnit.MILLISECONDS);- if (updateRequest == null) break;- RequestEntity request = new RequestEntity() {- // we don't know the length- public long getContentLength() { return -1; }- public String getContentType() { return requestWriter.getUpdateContentType(); }- public boolean isRepeatable() { return false; }-- public void writeRequest(OutputStream out) throws IOException {- try {- if (ClientUtils.TEXT_XML.equals(requestWriter.getUpdateContentType())) {- out.write("<stream>".getBytes("UTF-8")); // can be anything- }- UpdateRequest req = updateRequest;- while (req != null) {- requestWriter.write(req, out);- if (ClientUtils.TEXT_XML.equals(requestWriter.getUpdateContentType())) {- // check for commit or optimize- SolrParams params = req.getParams();- if (params != null) {- String fmt = null;- if (params.getBool(UpdateParams.OPTIMIZE, false)) {- fmt = "<optimize waitSearcher=\"%s\" waitFlush=\"%s\" />";- } else if (params.getBool(UpdateParams.COMMIT, false)) {- fmt = "<commit waitSearcher=\"%s\" waitFlush=\"%s\" />";- }- if (fmt != null) {- byte[] content = String.format(fmt,- params.getBool(UpdateParams.WAIT_SEARCHER, false) + "").getBytes("UTF-8");- out.write(content);- }- }- }- out.flush();- req = queue.poll(250, TimeUnit.MILLISECONDS);- }- if (ClientUtils.TEXT_XML.equals(requestWriter.getUpdateContentType())) {- out.write("</stream>".getBytes("UTF-8"));- }- out.flush();- } catch (InterruptedException e) {- e.printStackTrace();- }- }- };-- String path = ClientUtils.TEXT_XML.equals(requestWriter.getUpdateContentType()) ? "/update" : "/update/javabin";-- method = new PostMethod(_baseURL+path );- method.setRequestEntity( request );- method.setFollowRedirects( false );- method.addRequestHeader( "User-Agent", AGENT );-- int statusCode = getHttpClient().executeMethod(method);- log.info("Status for: " + updateRequest.getDocuments().get(0).getFieldValue("id") + " is " + statusCode);- 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: ").append(method.getURI());- handleError( new Exception( msg.toString() ) );- }- } finally {- try {- // make sure to release the connection- if(method != null)- method.releaseConnection();- }- catch( Exception ex ){}- }- }- }- catch (Throwable e) {- handleError( e );- }- finally {-- // remove it from the list of running things unless we are the last runner and the queue is full...- // in which case, the next queue.put() would block and there would be no runners to handle it.- // This case has been further handled by using offer instead of put, and using a retry loop- // to avoid blocking forever (see request()).- synchronized (runners) {- if (runners.size() == 1 && queue.remainingCapacity() == 0) {- // keep this runner alive- scheduler.execute(this);- } else {- runners.remove( this );- }- }-- log.info( "finished: {}" , this );- runnerLock.unlock();- }- }- }-- @Override- public NamedList<Object> request( final SolrRequest request ) throws SolrServerException, IOException- {- if( !(request instanceof UpdateRequest) ) {- return super.request( request );- }- UpdateRequest req = (UpdateRequest)request;-- // this happens for commit...- if( req.getDocuments()==null || req.getDocuments().isEmpty() ) {- blockUntilFinished();- return super.request( request );- }-- SolrParams params = req.getParams();- if( params != null ) {- // check if it is waiting for the searcher- if( params.getBool( UpdateParams.WAIT_SEARCHER, false ) ) {- log.info( "blocking for commit/optimize" );- blockUntilFinished(); // empty the queue- return super.request( request );- }- }-- try {- CountDownLatch tmpLock = lock;- if( tmpLock != null ) {- tmpLock.await();- }-- boolean success = queue.offer(req);-- for(;;) {- synchronized( runners ) {- if( runners.isEmpty()- || (queue.remainingCapacity() < queue.size() // queue is half full and we can add more runners- && runners.size() < threadCount) )- {- // We need more runners, so start a new one.- Runner r = new Runner();- runners.add( r );- scheduler.execute( r );- } else {- // break out of the retry loop if we added the element to the queue successfully, *and*- // while we are still holding the runners lock to prevent race conditions.- // race conditions.- if (success) break;- }- }-- // Retry to add to the queue w/o the runners lock held (else we risk temporary deadlock)- // This retry could also fail because- // 1) existing runners were not able to take off any new elements in the queue- // 2) the queue was filled back up since our last try- // If we succeed, the queue may have been completely emptied, and all runners stopped.- // In all cases, we should loop back to the top to see if we need to start more runners.- //- if (!success) {- success = queue.offer(req, 100, TimeUnit.MILLISECONDS);- }-- }--- }- catch (InterruptedException e) {- log.error( "interrupted", e );- throw new IOException( e.getLocalizedMessage() );- }-- // RETURN A DUMMY result- NamedList<Object> dummy = new NamedList<Object>();- dummy.add( "NOTE", "the request is processed in a background stream" );- return dummy;- }-- public synchronized void blockUntilFinished()- {- lock = new CountDownLatch(1);- try {- // Wait until no runners are running- for(;;) {- Runner runner;- synchronized(runners) {- runner = runners.peek();- }- if (runner == null) break;- runner.runnerLock.lock();- runner.runnerLock.unlock();- }- } finally {- lock.countDown();- lock=null;- }- }-- public void handleError( Throwable ex )- {- log.error( "error", ex );- }-- @Override- public void shutdown() {- super.shutdown();- scheduler.shutdown();- try {- if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {- scheduler.shutdownNow();- if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) log- .error("ExecutorService did not terminate");- }- } catch (InterruptedException ie) {- scheduler.shutdownNow();- Thread.currentThread().interrupt();- }- }--- public void shutdownNow() {- super.shutdown();- scheduler.shutdownNow(); // Cancel currently executing tasks- try {- if (!scheduler.awaitTermination(30, TimeUnit.SECONDS)) log- .error("ExecutorService did not terminate");- } catch (InterruptedException ie) {- scheduler.shutdownNow();- Thread.currentThread().interrupt();- }- }-}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.java b/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.javaindex 4724964b904..88a634198ef 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/util/ClientUtils.java@@ -33,8 +33,6 @@ import java.util.TimeZone;import java.util.Map.Entry;import java.nio.ByteBuffer;-import org.apache.commons.httpclient.util.DateParseException;-import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.SolrInputField;@@ -159,7 +157,7 @@ public class ClientUtils* @deprecated Use {@link org.apache.solr.common.util.DateUtil#parseDate(String)}*/@Deprecated- public static Date parseDate( String d ) throws ParseException, DateParseException+ public static Date parseDate( String d ) throws ParseException{return DateUtil.parseDate(d);}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/BasicHttpSolrServerTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/BasicHttpSolrServerTest.javanew file mode 100644index 00000000000..feb6993d892--- /dev/null+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/BasicHttpSolrServerTest.java@@ -0,0 +1,249 @@+/**+ * 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.net.MalformedURLException;+import java.net.Socket;+import java.util.Enumeration;+import java.util.HashMap;++import javax.servlet.ServletException;+import javax.servlet.http.HttpServlet;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;++import org.apache.http.Header;+import org.apache.http.HttpEntity;+import org.apache.http.HttpResponse;+import org.apache.http.client.methods.HttpGet;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.solr.SolrJettyTestBase;+import org.apache.solr.client.solrj.SolrRequest.METHOD;+import org.apache.solr.client.solrj.impl.HttpSolrServer;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.util.ExternalPaths;+import org.junit.BeforeClass;+import org.junit.Test;++public class BasicHttpSolrServerTest extends SolrJettyTestBase {++ public static class RedirectServlet extends HttpServlet {+ @Override+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)+ throws ServletException, IOException {+ resp.sendRedirect("/solr/select?" + req.getQueryString());+ }+ }++ public static class SlowServlet extends HttpServlet {+ @Override+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)+ throws ServletException, IOException {+ try {+ Thread.sleep(5000);+ } catch (InterruptedException e) {}+ }+ }++ public static class DebugServlet extends HttpServlet {++ public static String lastMethod = null;+ public static HashMap<String,String> headers = null;++ @Override+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)+ throws ServletException, IOException {+ lastMethod = "get";+ setHeaders(req);+ }++ private void setHeaders(HttpServletRequest req) {+ Enumeration<String> headerNames = req.getHeaderNames();+ headers = new HashMap<String,String>();+ while (headerNames.hasMoreElements()) {+ final String name = headerNames.nextElement();+ headers.put(name, req.getHeader(name));+ }+ }++ @Override+ protected void doPost(HttpServletRequest req, HttpServletResponse resp)+ throws ServletException, IOException {+ lastMethod = "post";+ setHeaders(req);+ }+ }++ @BeforeClass+ public static void beforeTest() throws Exception {+ createJetty(ExternalPaths.EXAMPLE_HOME, null, null);+ jetty.getDispatchFilter().getServletHandler()+ .addServletWithMapping(RedirectServlet.class, "/redirect/*");+ jetty.getDispatchFilter().getServletHandler()+ .addServletWithMapping(SlowServlet.class, "/slow/*");+ jetty.getDispatchFilter().getServletHandler()+ .addServletWithMapping(DebugServlet.class, "/debug/*");+ }++ @Test+ public void testConnectionRefused() throws MalformedURLException {+ int unusedPort = findUnusedPort(); // XXX even if fwe found an unused port+ // it might not be unused anymore+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:" + unusedPort+ + "/solr");+ SolrQuery q = new SolrQuery("*:*");+ try {+ QueryResponse response = server.query(q);+ fail("Should have thrown an exception.");+ } catch (SolrServerException e) {+ assertTrue(e.getMessage().contains("refused"));+ }+ }++ @Test+ public void testTimeout() throws Exception {+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:"+ + jetty.getLocalPort() + "/solr/slow/foo");+ SolrQuery q = new SolrQuery("*:*");+ server.setSoTimeout(2000);+ try {+ QueryResponse response = server.query(q, METHOD.GET);+ fail("No exception thrown.");+ } catch (SolrServerException e) {+ assertTrue(e.getMessage().contains("Timeout"));+ }+ }++ @Test+ public void testMethods() throws Exception {+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:"+ + jetty.getLocalPort() + "/solr/debug/foo");+ SolrQuery q = new SolrQuery("*:*");+ try {+ QueryResponse response = server.query(q, METHOD.GET);+ } catch (Throwable t) {}+ assertEquals("get", DebugServlet.lastMethod);++ try {+ QueryResponse response = server.query(q, METHOD.POST);+ } catch (Throwable t) {}+ assertEquals("post", DebugServlet.lastMethod);+ }++ @Test+ public void testAgent() throws Exception {+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:"+ + jetty.getLocalPort() + "/solr/debug/foo");+ SolrQuery q = new SolrQuery("*:*");+ try {+ server.query(q, METHOD.GET);+ } catch (Throwable t) {}+ assertEquals("Solr[" + org.apache.solr.client.solrj.impl.HttpSolrServer.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));+ try {+ server.query(q, METHOD.POST);+ } catch (Throwable t) {}+ assertEquals("Solr[" + org.apache.solr.client.solrj.impl.HttpSolrServer.class.getName() + "] 1.0", DebugServlet.headers.get("User-Agent"));+ }++ @Test+ public void testRedirect() throws Exception {+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:"+ + jetty.getLocalPort() + "/solr/redirect/foo");+ SolrQuery q = new SolrQuery("*:*");+ // default = false+ try {+ QueryResponse response = server.query(q);+ fail("Should have thrown an exception.");+ } catch (SolrServerException e) {+ assertTrue(e.getMessage().contains("redirect"));+ }+ server.setFollowRedirects(true);+ try {+ QueryResponse response = server.query(q);+ } catch (Throwable t) {+ fail("Exception was thrown:" + t);+ }+ }++ @Test+ public void testCompression() throws Exception {+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:"+ + jetty.getLocalPort() + "/solr/debug/foo");+ SolrQuery q = new SolrQuery("*:*");++ // verify request header gets set+ try {+ server.query(q);+ } catch (Throwable t) {}+ assertNull(DebugServlet.headers.get("Accept-Encoding"));+ server.setAllowCompression(true);+ try {+ server.query(q);+ } catch (Throwable t) {}+ assertNotNull(DebugServlet.headers.get("Accept-Encoding"));+ server.setAllowCompression(false);+ try {+ server.query(q);+ } catch (Throwable t) {}+ assertNull(DebugServlet.headers.get("Accept-Encoding"));++ // verify server compresses output+ HttpGet get = new HttpGet("http://127.0.0.1:" + jetty.getLocalPort()+ + "/solr/select?q=foo&wt=xml");+ get.setHeader("Accept-Encoding", "gzip");+ DefaultHttpClient client = new DefaultHttpClient();+ HttpEntity entity = null;+ try {+ HttpResponse response = client.execute(get);+ entity = response.getEntity();+ Header ceheader = entity.getContentEncoding();+ assertEquals("gzip", ceheader.getValue());++ } finally {+ if(entity!=null) {+ entity.getContent().close();+ }+ client.getConnectionManager().shutdown();+ }++ // verify compressed response can be handled+ server = new HttpSolrServer("http://127.0.0.1:" + jetty.getLocalPort()+ + "/solr");+ server.setAllowCompression(true);+ q = new SolrQuery("foo");+ QueryResponse response = server.query(q);+ assertEquals(0, response.getStatus());+ }++ private int findUnusedPort() {+ for (int port = 0; port < 65535; port++) {+ Socket s = new Socket();+ try {+ s.bind(null);+ int availablePort = s.getLocalPort();+ s.close();+ return availablePort;+ } catch (IOException e) {+ e.printStackTrace();+ }+ }+ throw new RuntimeException("Could not find unused TCP port.");+ }++}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleBinaryTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleBinaryTest.javaindex 6baa3775570..0f1849e19e3 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleBinaryTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleBinaryTest.java@@ -21,7 +21,7 @@ import org.apache.solr.client.solrj.SolrExampleTests;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.impl.BinaryRequestWriter;import org.apache.solr.client.solrj.impl.BinaryResponseParser;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.util.ExternalPaths;import org.junit.BeforeClass;@@ -42,7 +42,7 @@ public class SolrExampleBinaryTest extends SolrExampleTests {try {// setup the server...String url = "http://localhost:"+port+context;- CommonsHttpSolrServer s = new CommonsHttpSolrServer( url );+ HttpSolrServer s = new HttpSolrServer( url );s.setConnectionTimeout(100); // 1/10th secs.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.javaindex b2be7ddae29..48a5bc65508 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java@@ -29,12 +29,11 @@ import junit.framework.Assert;import org.apache.lucene.util._TestUtil;import org.apache.solr.SolrJettyTestBase;import org.apache.solr.client.solrj.impl.BinaryResponseParser;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.impl.XMLResponseParser;import org.apache.solr.client.solrj.request.DirectXmlRequest;import org.apache.solr.client.solrj.request.LukeRequest;import org.apache.solr.client.solrj.request.QueryRequest;-import org.apache.solr.client.solrj.request.SolrPing;import org.apache.solr.client.solrj.response.FieldStatsInfo;import org.apache.solr.client.solrj.request.UpdateRequest;import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;@@ -288,19 +287,19 @@ abstract public class SolrExampleTests extends SolrJettyTestBase// save the old parser, so we can set it back.ResponseParser oldParser = null;- if (server instanceof CommonsHttpSolrServer) {- CommonsHttpSolrServer cserver = (CommonsHttpSolrServer) server;+ if (server instanceof HttpSolrServer) {+ HttpSolrServer cserver = (HttpSolrServer) server;oldParser = cserver.getParser();}try {for (int iteration = 0; iteration < numIterations; iteration++) {// choose format- if (server instanceof CommonsHttpSolrServer) {+ if (server instanceof HttpSolrServer) {if (random.nextBoolean()) {- ((CommonsHttpSolrServer) server).setParser(new BinaryResponseParser());+ ((HttpSolrServer) server).setParser(new BinaryResponseParser());} else {- ((CommonsHttpSolrServer) server).setParser(new XMLResponseParser());+ ((HttpSolrServer) server).setParser(new XMLResponseParser());}}@@ -336,7 +335,7 @@ abstract public class SolrExampleTests extends SolrJettyTestBase} finally {if (oldParser != null) {// set the old parser back- ((CommonsHttpSolrServer)server).setParser(oldParser);+ ((HttpSolrServer)server).setParser(oldParser);}}}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExceptionTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExceptionTest.javaindex 674700eb5d8..23310df6ea2 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExceptionTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExceptionTest.java@@ -17,11 +17,10 @@package org.apache.solr.client.solrj;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.lucene.util.LuceneTestCase;--import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;/***@@ -38,9 +37,9 @@ public class SolrExceptionTest extends LuceneTestCase {try {// switched to a local address to avoid going out on the net, ns lookup issues, etc.// set a 1ms timeout to let the connection fail faster.- HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());- httpClient.getParams().setParameter("http.connection.timeout", new Integer(1));- SolrServer client = new CommonsHttpSolrServer("http://[ff01::114]:11235/solr/", httpClient);+ DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());+ httpClient.getParams().setIntParameter("http.connection.timeout", 1);+ SolrServer client = new HttpSolrServer("http://[ff01::114]:11235/solr/", httpClient);SolrQuery query = new SolrQuery("test123");client.query(query);} catch (SolrServerException sse) {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/TestBatchUpdate.java b/solr/solrj/src/test/org/apache/solr/client/solrj/TestBatchUpdate.javaindex 4ebb24819eb..a2618ed4bed 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/TestBatchUpdate.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/TestBatchUpdate.java@@ -19,7 +19,7 @@ package org.apache.solr.client.solrj;import org.apache.solr.SolrJettyTestBase;import org.apache.solr.client.solrj.beans.Field;import org.apache.solr.client.solrj.impl.BinaryRequestWriter;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.RequestWriter;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrInputDocument;@@ -48,7 +48,7 @@ public class TestBatchUpdate extends SolrJettyTestBase {@Testpublic void testWithXml() throws Exception {- CommonsHttpSolrServer commonsHttpSolrServer = (CommonsHttpSolrServer) getSolrServer();+ HttpSolrServer commonsHttpSolrServer = (HttpSolrServer) getSolrServer();commonsHttpSolrServer.setRequestWriter(new RequestWriter());commonsHttpSolrServer.deleteByQuery( "*:*" ); // delete everything!doIt(commonsHttpSolrServer);@@ -56,7 +56,7 @@ public class TestBatchUpdate extends SolrJettyTestBase {@Testpublic void testWithBinary()throws Exception{- CommonsHttpSolrServer commonsHttpSolrServer = (CommonsHttpSolrServer) getSolrServer();+ HttpSolrServer commonsHttpSolrServer = (HttpSolrServer) getSolrServer();commonsHttpSolrServer.setRequestWriter(new BinaryRequestWriter());commonsHttpSolrServer.deleteByQuery( "*:*" ); // delete everything!doIt(commonsHttpSolrServer);@@ -64,7 +64,7 @@ public class TestBatchUpdate extends SolrJettyTestBase {@Testpublic void testWithBinaryBean()throws Exception{- CommonsHttpSolrServer commonsHttpSolrServer = (CommonsHttpSolrServer) getSolrServer();+ HttpSolrServer commonsHttpSolrServer = (HttpSolrServer) getSolrServer();commonsHttpSolrServer.setRequestWriter(new BinaryRequestWriter());commonsHttpSolrServer.deleteByQuery( "*:*" ); // delete everything!final int[] counter = new int[1];@@ -100,7 +100,7 @@ public class TestBatchUpdate extends SolrJettyTestBase {String cat;}- private void doIt(CommonsHttpSolrServer commonsHttpSolrServer) throws SolrServerException, IOException {+ private void doIt(HttpSolrServer commonsHttpSolrServer) throws SolrServerException, IOException {final int[] counter = new int[1];counter[0] = 0;commonsHttpSolrServer.add(new Iterator<SolrInputDocument>() {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrServer.java b/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrServer.javaindex 4bf4da17cbc..bb8ba7fe151 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrServer.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrServer.java@@ -18,13 +18,13 @@package org.apache.solr.client.solrj;import junit.framework.Assert;-import org.apache.commons.httpclient.HttpClient;-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;import org.apache.commons.io.FileUtils;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.lucene.util.LuceneTestCase;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.impl.LBHttpSolrServer;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.client.solrj.response.UpdateResponse;@@ -48,7 +48,7 @@ import java.util.Set;*/public class TestLBHttpSolrServer extends LuceneTestCase {SolrInstance[] solr = new SolrInstance[3];- HttpClient httpClient;+ DefaultHttpClient httpClient;// TODO: fix this test to not require FSDirectorystatic String savedFactory;@@ -69,7 +69,7 @@ public class TestLBHttpSolrServer extends LuceneTestCase {@Overridepublic void setUp() throws Exception {super.setUp();- httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());+ httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());httpClient.getParams().setParameter("http.connection.timeout", new Integer(1000));for (int i = 0; i < solr.length; i++) {@@ -88,7 +88,7 @@ public class TestLBHttpSolrServer extends LuceneTestCase {doc.addField("name", solrInstance.name);docs.add(doc);}- CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(solrInstance.getUrl(), httpClient);+ HttpSolrServer solrServer = new HttpSolrServer(solrInstance.getUrl(), httpClient);UpdateResponse resp = solrServer.add(docs);assertEquals(0, resp.getStatus());resp = solrServer.commit();@@ -178,7 +178,7 @@ public class TestLBHttpSolrServer extends LuceneTestCase {for (int i = 0; i < solr.length; i++) {s[i] = solr[i].getUrl();}- HttpClient myHttpClient = new HttpClient(new MultiThreadedHttpConnectionManager());+ DefaultHttpClient myHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());myHttpClient.getParams().setParameter("http.connection.timeout", new Integer(250));myHttpClient.getParams().setParameter("http.socket.timeout", new Integer(250));diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/MultiCoreExampleJettyTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/MultiCoreExampleJettyTest.javaindex c998d1e7482..0eb30cd0a23 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/MultiCoreExampleJettyTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/MultiCoreExampleJettyTest.java@@ -20,16 +20,14 @@ package org.apache.solr.client.solrj.embedded;import org.apache.solr.client.solrj.MultiCoreExampleTestBase;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.client.solrj.request.UpdateRequest;import org.apache.solr.client.solrj.request.UpdateRequest.ACTION;-import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.ShardParams;-import org.apache.solr.search.SolrIndexSearcher.QueryResult;import org.junit.Test;/**@@ -96,7 +94,7 @@ public class MultiCoreExampleJettyTest extends MultiCoreExampleTestBase {try {// setup the server...String url = "http://localhost:"+port+context+"/"+name;- CommonsHttpSolrServer s = new CommonsHttpSolrServer( url );+ HttpSolrServer s = new HttpSolrServer( url );s.setConnectionTimeout(100); // 1/10th secs.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleJettyTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleJettyTest.javaindex 41bbaeb29e2..c790b3ead6d 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleJettyTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleJettyTest.java@@ -18,7 +18,7 @@package org.apache.solr.client.solrj.embedded;import org.apache.solr.client.solrj.SolrExampleTests;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.util.ExternalPaths;import org.junit.Assert;import org.junit.BeforeClass;@@ -43,7 +43,7 @@ public class SolrExampleJettyTest extends SolrExampleTests {try {// setup the server...String url = "http://localhost/?core=xxx";- CommonsHttpSolrServer s = new CommonsHttpSolrServer( url );+ HttpSolrServer s = new HttpSolrServer( url );Assert.fail( "CommonsHttpSolrServer should not allow a path with a parameter: "+s.getBaseURL() );}catch( Exception ex ) {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingBinaryTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingBinaryTest.javaindex 1864423639b..fa9ee7498fe 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingBinaryTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingBinaryTest.java@@ -21,8 +21,7 @@ import org.apache.solr.client.solrj.SolrExampleTests;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.impl.BinaryRequestWriter;import org.apache.solr.client.solrj.impl.BinaryResponseParser;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;-import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;+import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;import org.apache.solr.util.ExternalPaths;import org.junit.BeforeClass;@@ -39,15 +38,12 @@ public class SolrExampleStreamingBinaryTest extends SolrExampleTests {// setup the server...String url = "http://localhost:"+port+context;// smaller queue size hits locks more often- CommonsHttpSolrServer s = new StreamingUpdateSolrServer( url, 2, 5 ) {+ ConcurrentUpdateSolrServer s = new ConcurrentUpdateSolrServer( url, 2, 5 ) {@Overridepublic void handleError(Throwable ex) {ex.printStackTrace();}};- s.setConnectionTimeout(100); // 1/10th sec- s.setDefaultMaxConnectionsPerHost(100);- s.setMaxTotalConnections(100);s.setParser(new BinaryResponseParser());s.setRequestWriter(new BinaryRequestWriter());return s;diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingTest.javaindex 511db090a5d..50fd02cc842 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/SolrExampleStreamingTest.java@@ -19,8 +19,7 @@ package org.apache.solr.client.solrj.embedded;import org.apache.solr.client.solrj.SolrExampleTests;import org.apache.solr.client.solrj.SolrServer;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;-import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;+import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;import org.apache.solr.util.ExternalPaths;import org.junit.BeforeClass;@@ -42,15 +41,13 @@ public class SolrExampleStreamingTest extends SolrExampleTests {try {// setup the server...String url = "http://localhost:"+port+context; // smaller queue size hits locks more often- CommonsHttpSolrServer s = new StreamingUpdateSolrServer( url, 2, 5 ) {- @Override+ ConcurrentUpdateSolrServer s = new ConcurrentUpdateSolrServer( url, 2, 5 ) {++ @Overridepublic void handleError(Throwable ex) {// do something... TODO?}};- s.setConnectionTimeout(100); // 1/10th sec- s.setDefaultMaxConnectionsPerHost(100);- s.setMaxTotalConnections(100);return s;}catch( Exception ex ) {diff --git a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.javaindex 55b50680357..0542eb074f7 100644--- a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java+++ b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java@@ -36,7 +36,7 @@ import junit.framework.TestCase;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.client.solrj.request.UpdateRequest;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.client.solrj.response.UpdateResponse;@@ -230,9 +230,9 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {protected void destroyServers() throws Exception {controlJetty.stop();- ((CommonsHttpSolrServer) controlClient).shutdown();+ ((HttpSolrServer) controlClient).shutdown();for (JettySolrRunner jetty : jettys) jetty.stop();- for (SolrServer client : clients) ((CommonsHttpSolrServer) client).shutdown();+ for (SolrServer client : clients) ((HttpSolrServer) client).shutdown();clients.clear();jettys.clear();}@@ -259,7 +259,7 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {try {// setup the server...String url = "http://localhost:" + port + context;- CommonsHttpSolrServer s = new CommonsHttpSolrServer(url);+ HttpSolrServer s = new HttpSolrServer(url);s.setConnectionTimeout(100); // 1/10th secs.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);diff --git a/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.java b/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.javaindex 1cebb5077ee..58586dc4b3f 100755--- a/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.java@@ -20,7 +20,7 @@ package org.apache.solr;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;import org.apache.solr.client.solrj.embedded.JettySolrRunner;-import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;+import org.apache.solr.client.solrj.impl.HttpSolrServer;import org.apache.solr.util.ExternalPaths;import org.junit.AfterClass;@@ -34,7 +34,7 @@ abstract public class SolrJettyTestBase extends SolrTestCaseJ4public static JettySolrRunner jetty;public static int port;- public static SolrServer server;+ public static SolrServer server = null;public static String context;public static JettySolrRunner createJetty(String solrHome, String configFile, String context) throws Exception {@@ -87,7 +87,7 @@ abstract public class SolrJettyTestBase extends SolrTestCaseJ4try {// setup the server...String url = "http://localhost:"+port+context;- CommonsHttpSolrServer s = new CommonsHttpSolrServer( url );+ HttpSolrServer s = new HttpSolrServer( url );s.setConnectionTimeout(100); // 1/10th secs.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);