package com.xt.hb.data.util;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.SolrParams;

import com.xt.hb.data.system.GlobalData;
import com.yuanxd.tools.utils.string.StringUtils;

/**
 * solr客户端共通
 * 
 * @author 袁晓冬
 *
 */
public abstract class SolrClientUtils {
	/**
	 * 根据参数查询
	 * 
	 * @param param
	 * @return
	 */
	public static SolrDocumentList query(SolrParams param) {
		if (null == param) {
			return null;
		}
		HttpSolrClient client = getHttpSolrClient();
		try {
			QueryResponse response = client.query(param);
			SolrDocumentList list = response.getResults();
			return list;
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
			}
		}
		return null;

	}

	/**
	 * 默认查询
	 * 
	 * @param param
	 * @return
	 */
	public static SolrDocumentList query(String param) {
		if (StringUtils.isEmpty(param)) {
			return null;
		}
		HttpSolrClient client = getHttpSolrClient();
		try {
			SolrQuery query = new SolrQuery();
			query.set("q", param);
			query.setRows(1000);
			query.setStart(0);
			QueryResponse response = client.query(GlobalData.SOLR_GIS_CORE, query);
			SolrDocumentList list = response.getResults();
			return list;
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
			}
		}
		return null;
	}

	/**
	 * 获取系统默认solr服务器地址
	 * 
	 * @return
	 */
	public static HttpSolrClient getHttpSolrClient() {
		HttpSolrClient client = new HttpSolrClient(GlobalData.SOLR_URL);
		client.setSoTimeout(3000); // socket read timeout
		client.setConnectionTimeout(1000);
		client.setDefaultMaxConnectionsPerHost(1000);
		client.setMaxTotalConnections(10);
		client.setFollowRedirects(false); // defaults to false
		client.setAllowCompression(true);
		return client;
	}

	/**
	 * 根据指定的url获取solr服务
	 * 
	 * @return
	 */
	public static HttpSolrClient getHttpSolrClient(String url) {
		HttpSolrClient client = new HttpSolrClient(url);
		client.setSoTimeout(3000); // socket read timeout
		client.setConnectionTimeout(1000);
		client.setDefaultMaxConnectionsPerHost(1000);
		client.setMaxTotalConnections(10);
		client.setFollowRedirects(false); // defaults to false
		client.setAllowCompression(true);
		return client;
	}
}
