001package org.kuali.incubator; 002 003import org.apache.log4j.Logger; 004import org.apache.solr.client.solrj.SolrQuery; 005import org.apache.solr.client.solrj.SolrServer; 006import org.apache.solr.client.solrj.SolrServerException; 007import org.apache.solr.client.solrj.impl.HttpSolrServer; 008import org.apache.solr.client.solrj.response.QueryResponse; 009import org.apache.solr.client.solrj.response.UpdateResponse; 010import org.apache.solr.common.SolrDocument; 011import org.apache.solr.common.SolrDocumentList; 012import org.apache.solr.common.SolrInputDocument; 013import org.kuali.ole.docstore.common.exception.DocstoreIndexException; 014import org.kuali.rice.core.api.config.property.ConfigContext; 015 016import java.util.*; 017 018/** 019 * Created by IntelliJ IDEA. 020 * User: pvsubrah 021 * Date: 10/21/11 022 * Time: 10:57 AM 023 * To change this template use File | Settings | File Templates. 024 */ 025public class SolrRequestReponseHandler { 026 027 private static final Logger LOG = Logger.getLogger(SolrRequestReponseHandler.class); 028 029 private HttpSolrServer server; 030 031 public List retriveResults(String queryString) { 032 ArrayList<HashMap<String, Object>> hitsOnPage = new ArrayList<HashMap<String, Object>>(); 033 034 server = getHttpSolrServer(); 035 036 SolrQuery query = new SolrQuery(); 037 query.setQuery(queryString); 038 query.setIncludeScore(true); 039 040 try { 041 QueryResponse qr = server.query(query); 042 043 SolrDocumentList sdl = qr.getResults(); 044 045 046 for (SolrDocument d : sdl) { 047 HashMap<String, Object> values = new HashMap<String, Object>(); 048 049 for (Iterator<Map.Entry<String, Object>> i = d.iterator(); i.hasNext(); ) { 050 Map.Entry<String, Object> e2 = i.next(); 051 052 values.put(e2.getKey(), e2.getValue()); 053 } 054 055 hitsOnPage.add(values); 056 } 057 } catch (SolrServerException e) { 058 e.printStackTrace(); 059 } 060 return hitsOnPage; 061 } 062 063 private HttpSolrServer getHttpSolrServer() { 064 if (null == server) { 065 try { 066 String serverUrl = getSolrUrl(); 067 server = new HttpSolrServer(serverUrl); 068 } catch (Exception e) { 069 e.printStackTrace(); 070 } 071 } 072 return server; 073 } 074 075 public String getSolrUrl() { 076 return ConfigContext.getCurrentContextConfig().getProperty("discovery.url"); 077 } 078 079 public UpdateResponse updateSolr(List<SolrInputDocument> solrInputDocument){ 080 UpdateResponse updateResponse = null; 081 try { 082 UpdateResponse response = getHttpSolrServer().add(solrInputDocument); 083 updateResponse = server.commit(); 084 } catch (Exception e) { 085 e.printStackTrace(); 086 LOG.error("Error while updating document to solr."); 087 } 088 return updateResponse; 089 } 090}