import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.apache.commons.lang.time.DateUtils;
public class SolrUtils {
private List<Node> docs = new ArrayList<Node>();
private Number numFound = 0;
private Document doc;
public List<Node> getDocs() {
return docs;
}
public Number getNumFound() {
return numFound;
}
@SuppressWarnings("unchecked")
public SolrUtils(String urlString) {
doc = documentFromURL(urlString);
if (doc != null ) {
docs = (List<Node>)doc.selectNodes("/response/result/doc");
numFound = doc.numberValueOf("/response/result/@numFound");
}
}
public Document documentFromURL(String urlString){
try {
SAXReader reader = new SAXReader();
URL url = new URL(urlString);
doc = reader.read(url);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String valueOf(Object obj, String name){
return valueOf(obj, "str", name);
}
public static Date dateValueOf(Object obj, String name){
String[] parsePatterns = new String[]{
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.S'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SS'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
};
try {
return DateUtils.parseDate(valueOf(obj, "date", name), parsePatterns);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String valueOf(Object obj, String type, String name){
String path = "./" + type + "[@name='" + name + "']";
if (obj instanceof Node) {
Node n = (Node)obj;
return n.valueOf(path);
}
return "";
}
public static Number numberValueOf(Object obj, String type, String name){
String path = "./" + type + "[@name='" + name + "']";
if (obj instanceof Node) {
Node n = (Node)obj;
return n.numberValueOf(path);
}
return null;
}
public static void main(String[] args) throws Exception {
String url = "http://localhost:8983/solr/db/select/?q=*%3A*&version=2.2&start=0&rows=10&indent=on";
SolrUtils su = new SolrUtils(url);
System.out.println(su.getNumFound());
System.out.println(su.getDocs().size());
for (Node doc : su.getDocs()) {
System.out.println(valueOf(doc, "id"));
System.out.println(valueOf(doc, "title"));
System.out.println(dateValueOf(doc, "pubtime"));
}
}
}
|