1 package org.kuali.incubator;
2
3 import org.apache.log4j.Logger;
4 import org.apache.solr.client.solrj.SolrQuery;
5 import org.apache.solr.client.solrj.SolrServer;
6 import org.apache.solr.client.solrj.SolrServerException;
7 import org.apache.solr.client.solrj.impl.HttpSolrServer;
8 import org.apache.solr.client.solrj.response.QueryResponse;
9 import org.apache.solr.client.solrj.response.UpdateResponse;
10 import org.apache.solr.common.SolrDocument;
11 import org.apache.solr.common.SolrDocumentList;
12 import org.apache.solr.common.SolrInputDocument;
13 import org.kuali.ole.docstore.common.exception.DocstoreIndexException;
14 import org.kuali.rice.core.api.config.property.ConfigContext;
15
16 import java.util.*;
17
18
19
20
21
22
23
24
25 public class SolrRequestReponseHandler {
26
27 private static final Logger LOG = Logger.getLogger(SolrRequestReponseHandler.class);
28
29 private HttpSolrServer server;
30
31 public List retriveResults(String queryString) {
32 ArrayList<HashMap<String, Object>> hitsOnPage = new ArrayList<HashMap<String, Object>>();
33
34 server = getHttpSolrServer();
35
36 SolrQuery query = new SolrQuery();
37 query.setQuery(queryString);
38 query.setIncludeScore(true);
39
40 try {
41 QueryResponse qr = server.query(query);
42
43 SolrDocumentList sdl = qr.getResults();
44
45
46 for (SolrDocument d : sdl) {
47 HashMap<String, Object> values = new HashMap<String, Object>();
48
49 for (Iterator<Map.Entry<String, Object>> i = d.iterator(); i.hasNext(); ) {
50 Map.Entry<String, Object> e2 = i.next();
51
52 values.put(e2.getKey(), e2.getValue());
53 }
54
55 hitsOnPage.add(values);
56 }
57 } catch (SolrServerException e) {
58 e.printStackTrace();
59 }
60 return hitsOnPage;
61 }
62
63 private HttpSolrServer getHttpSolrServer() {
64 if (null == server) {
65 try {
66 String serverUrl = getSolrUrl();
67 server = new HttpSolrServer(serverUrl);
68 } catch (Exception e) {
69 e.printStackTrace();
70 }
71 }
72 return server;
73 }
74
75 public String getSolrUrl() {
76 return ConfigContext.getCurrentContextConfig().getProperty("discovery.url");
77 }
78
79 public UpdateResponse updateSolr(List<SolrInputDocument> solrInputDocument){
80 UpdateResponse updateResponse = null;
81 try {
82 UpdateResponse response = getHttpSolrServer().add(solrInputDocument);
83 updateResponse = server.commit();
84 } catch (Exception e) {
85 e.printStackTrace();
86 LOG.error("Error while updating document to solr.");
87 }
88 return updateResponse;
89 }
90 }