About This Blog

This blog contains some information about Java programming strongly connected to making web pages, and JEE applications.

5 February 2008 - 17:12Solr and HttpClient

I use quite a lot HttpClient from Jakarta Commons, so when I found post.jar and post.sh script in Solr examples directory, I decided to write my own piece of code to demonstrate indexing with this package. It's very simple piece of code, but anyway I publish it here, maybe soon I will need to use more of it functionality, because Solr seems to be very mature now.

package solr;
 
import java.io.*;
import org.apache.commons.httpclient.*;
 
public class SolrTest {
 
	private static final String SOLR_HOST = "localhost";
	private static final int SOLR_PORT = 8983;
	private static final String SOLR_PATH = "/solr/update/";
 
	static String examplesDir = "/home/ghost/apache-solr-1.2.0/example/exampledocs/";
 
	public static void main(String[] args) throws IOException {
		File dir = new File(examplesDir);
		File[] files = dir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.indexOf(".xml") != -1;
			}
		});
		for(File file : files) {
			FileReader fr =  new FileReader(file);
			BufferedReader reader = new BufferedReader(fr);
			String line;
			StringBuilder sb = new StringBuilder();
			while((line = reader.readLine()) != null) {
				sb.append(line);
			}
			reader.close();
			fr.close();
			sendXML(sb.toString());
		}
		sendXML("<commit />");
	}
 
	public static void sendXML(String xml) throws HttpException, IOException {
		HttpClientParams httpClientParams = new HttpClientParams();
		HttpClient client = new HttpClient(httpClientParams);
 
		HostConfiguration hostConfiguration = new HostConfiguration();
		hostConfiguration.setHost(SOLR_HOST, SOLR_PORT);
		client.setHostConfiguration(hostConfiguration );
 
		PostMethod postMethod = new PostMethod();
		postMethod.setPath(SOLR_PATH);
		postMethod.addRequestHeader("Content-type", "text/xml; charset=utf-8");
 
		RequestEntity entity = new StringRequestEntity(xml);
		postMethod.setRequestEntity(entity);
 
		client.executeMethod(postMethod);
 
		postMethod.releaseConnection();
	}
}
 

No Comments | Tags: Solr

Add a Comment

You must be logged in to post a comment.