Apache Solr open-source search software
JSON, Python, Ruby response writers: SOLR-31
Yonik Seeley02aafbc34daa
diff --git a/example/solr/conf/solrconfig.xml b/example/solr/conf/solrconfig.xmlindex 9558660757d..4573cc83cb3 100755--- a/example/solr/conf/solrconfig.xml+++ b/example/solr/conf/solrconfig.xml@@ -228,6 +228,10 @@<queryResponseWriter name="custom" class="com.example.MyResponseWriter"/>-->+ <queryResponseWriter name="json" class="org.apache.solr.request.JSONResponseWriter"/>+ <queryResponseWriter name="python" class="org.apache.solr.request.PythonResponseWriter"/>+ <queryResponseWriter name="ruby" class="org.apache.solr.request.RubyResponseWriter"/>+<!-- config for the admin interface --><admin>diff --git a/src/java/org/apache/solr/request/JSONResponseWriter.java b/src/java/org/apache/solr/request/JSONResponseWriter.javanew file mode 100644index 00000000000..309c63f1fd7--- /dev/null+++ b/src/java/org/apache/solr/request/JSONResponseWriter.java@@ -0,0 +1,703 @@+package org.apache.solr.request;++import org.apache.lucene.document.Document;+import org.apache.lucene.document.Fieldable;+import org.apache.solr.schema.SchemaField;+import org.apache.solr.schema.TextField;+import org.apache.solr.search.DocIterator;+import org.apache.solr.search.DocList;+import org.apache.solr.util.NamedList;++import java.io.IOException;+import java.io.Writer;+import java.util.*;++/**+ * @author yonik+ * @version $Id$+ */++public class JSONResponseWriter implements QueryResponseWriter {+ static String CONTENT_TYPE_JSON_UTF8="text/x-json;charset=UTF-8";+++ public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {+ JSONWriter w = new JSONWriter(writer, req, rsp);+ w.writeResponse();+ }++ public String getContentType(SolrQueryRequest request, SolrQueryResponse response) {+ // using the text/plain allows this to be viewed in the browser easily+ return CONTENT_TYPE_TEXT_UTF8;+ }+}+++class JSONWriter extends TextResponseWriter {++ // cache the calendar instance in case we are writing many dates...+ private Calendar cal;++ private String namedListStyle;++ private static final String JSON_NL_STYLE="json.nl";+ private static final String JSON_NL_MAP="map";+ private static final String JSON_NL_ARROFARR="arrarr";+ private static final String JSON_NL_ARROFMAP="arrmap";+++ public JSONWriter(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) {+ super(writer, req, rsp);+ namedListStyle = req.getParam(JSON_NL_STYLE);+ namedListStyle = namedListStyle==null ? JSON_NL_MAP : namedListStyle.intern();+ }++ public void writeResponse() throws IOException {+ int qtime=(int)(rsp.getEndTime() - req.getStartTime());+ NamedList nl = new NamedList();+ HashMap header = new HashMap(1);+ header.put("qtime",qtime);+ nl.add("header", header);+ nl.addAll(rsp.getValues());+ // give the main response a name it it doesn't have one+ if (nl.size()>1 && nl.getVal(1) instanceof DocList && nl.getName(1)==null) {+ nl.setName(1,"response");+ }+ writeNamedList(null, nl);+ }++ protected void writeKey(String fname, boolean needsEscaping) throws IOException {+ writeStr(null, fname, needsEscaping);+ writer.write(':');+ }++ // Represents a NamedList directly as a JSON Object (essentially a Map)+ // more natural but potentially problematic since order is not maintained and keys+ // can't be repeated.+ protected void writeNamedListAsMap(String name, NamedList val) throws IOException {+ int sz = val.size();+ writer.write('{');+ incLevel();++ // In JSON objects (maps) we can't have null keys or duplicates...+ // map null to "" and append a qualifier to duplicates.+ //+ // a=123,a=456 will be mapped to {a=1,a__1=456}+ // Disad: this is ambiguous since a real key could be called a__1+ //+ // Another possible mapping could aggregate multiple keys to an array:+ // a=123,a=456 maps to a=[123,456]+ // Disad: this is ambiguous with a real single value that happens to be an array+ //+ // Both of these mappings have ambiguities.+ HashMap<String,Integer> repeats = new HashMap<String,Integer>(4);++ boolean first=true;+ for (int i=0; i<sz; i++) {+ String key = val.getName(i);+ if (key==null) key="";++ if (first) {+ first=false;+ repeats.put(key,0);+ } else {+ writer.write(',');++ Integer repeatCount = repeats.get(key);+ if (repeatCount==null) {+ repeats.put(key,0);+ } else {+ String newKey = key;+ int newCount = repeatCount;+ do { // avoid generated key clashing with a real key+ newKey = key + ' ' + (++newCount);+ repeatCount = repeats.get(newKey);+ } while (repeatCount != null);++ repeats.put(key,newCount);+ key = newKey;+ }+ }++ indent();+ writeKey(key, true);+ writeVal(key,val.getVal(i));+ }++ decLevel();+ writer.write('}');+ }++ // Represents a NamedList directly as an array of JSON objects...+ // NamedList("a"=1,"b"=2,null=3) => [{"a":1},{"b":2},3]+ protected void writeNamedListAsArrMap(String name, NamedList val) throws IOException {+ int sz = val.size();+ indent();+ writer.write('[');+ incLevel();++ boolean first=true;+ for (int i=0; i<sz; i++) {+ String key = val.getName(i);++ if (first) {+ first=false;+ } else {+ writer.write(',');+ }++ indent();++ if (key==null) {+ writeVal(null,val.getVal(i));+ } else {+ writer.write('{');+ writeKey(key, true);+ writeVal(key,val.getVal(i));+ writer.write('}');+ }++ }++ decLevel();+ writer.write(']');+ }++ // Represents a NamedList directly as an array of JSON objects...+ // NamedList("a"=1,"b"=2,null=3) => [["a",1],["b",2],[null,3]]+ protected void writeNamedListAsArrArr(String name, NamedList val) throws IOException {+ int sz = val.size();+ indent();+ writer.write('[');+ incLevel();++ boolean first=true;+ for (int i=0; i<sz; i++) {+ String key = val.getName(i);++ if (first) {+ first=false;+ } else {+ writer.write(',');+ }++ indent();++ /*** if key is null, just write value???+ if (key==null) {+ writeVal(null,val.getVal(i));+ } else {+ ***/++ writer.write('[');+ incLevel();+ writeStr(null,key,true);+ writer.write(',');+ writeVal(key,val.getVal(i));+ decLevel();+ writer.write(']');+++ }++ decLevel();+ writer.write(']');+ }+++ public void writeNamedList(String name, NamedList val) throws IOException {+ if (namedListStyle==JSON_NL_ARROFMAP) {+ writeNamedListAsArrMap(name,val);+ } else if (namedListStyle==JSON_NL_ARROFARR) {+ writeNamedListAsArrArr(name,val);+ } else {+ writeNamedListAsMap(name,val);+ }+ }+++ private static class MultiValueField {+ final SchemaField sfield;+ final ArrayList<Fieldable> fields;+ MultiValueField(SchemaField sfield, Fieldable firstVal) {+ this.sfield = sfield;+ this.fields = new ArrayList<Fieldable>(4);+ this.fields.add(firstVal);+ }+ }++ public void writeDoc(String name, Collection<Fieldable> fields, Set<String> returnFields, Map pseudoFields) throws IOException {+ writer.write('{');+ incLevel();++ HashMap<String, MultiValueField> multi = new HashMap<String, MultiValueField>();++ boolean first=true;++ for (Fieldable ff : fields) {+ String fname = ff.name();+ if (returnFields!=null && !returnFields.contains(fname)) {+ continue;+ }++ // if the field is multivalued, it may have other values further on... so+ // build up a list for each multi-valued field.+ SchemaField sf = schema.getField(fname);+ if (sf.multiValued()) {+ MultiValueField mf = multi.get(fname);+ if (mf==null) {+ mf = new MultiValueField(sf, ff);+ multi.put(fname, mf);+ } else {+ mf.fields.add(ff);+ }+ } else {+ // not multi-valued, so write it immediately.+ if (first) {+ first=false;+ } else {+ writer.write(',');+ }+ indent();+ writeKey(fname,true);+ sf.write(this, fname, ff);+ }+ }++ for(MultiValueField mvf : multi.values()) {+ if (first) {+ first=false;+ } else {+ writer.write(',');+ }++ indent();+ writeKey(mvf.sfield.getName(), true);++ boolean indentArrElems=false;+ if (doIndent) {+ // heuristic... TextField is probably the only field type likely to be long enough+ // to warrant indenting individual values.+ indentArrElems = (mvf.sfield.getType() instanceof TextField);+ }++ writer.write('[');+ boolean firstArrElem=true;+ incLevel();++ for (Fieldable ff : mvf.fields) {+ if (firstArrElem) {+ firstArrElem=false;+ } else {+ writer.write(',');+ }+ if (indentArrElems) indent();+ mvf.sfield.write(this, null, ff);+ }+ writer.write(']');+ decLevel();+ }++ if (pseudoFields !=null && pseudoFields.size()>0) {+ writeMap(null,pseudoFields,true,first);+ }++ decLevel();+ writer.write('}');+ }++ // reusable map to store the "score" pseudo-field.+ // if a Doc can ever contain another doc, this optimization would have to go.+ private final HashMap scoreMap = new HashMap(1);++ public void writeDoc(String name, Document doc, Set<String> returnFields, float score, boolean includeScore) throws IOException {+ Map other = null;+ if (includeScore) {+ other = scoreMap;+ scoreMap.put("score",score);+ }+ writeDoc(name, (List<Fieldable>)(doc.getFields()), returnFields, other);+ }++ public void writeDocList(String name, DocList ids, Set<String> fields, Map otherFields) throws IOException {+ boolean includeScore=false;+ if (fields!=null) {+ includeScore = fields.contains("score");+ if (fields.size()==0 || (fields.size()==1 && includeScore) || fields.contains("*")) {+ fields=null; // null means return all stored fields+ }+ }++ int sz=ids.size();++ writer.write('{');+ incLevel();+ writeKey("numFound",false);+ writeInt(null,ids.matches());+ writer.write(',');+ writeKey("start",false);+ writeInt(null,ids.offset());++ if (includeScore) {+ writer.write(',');+ writeKey("maxScore",false);+ writeFloat(null,ids.maxScore());+ }+ writer.write(',');+ // indent();+ writeKey("docs",false);+ writer.write('[');++ incLevel();+ boolean first=true;++ DocIterator iterator = ids.iterator();+ for (int i=0; i<sz; i++) {+ int id = iterator.nextDoc();+ Document doc = searcher.doc(id);++ if (first) {+ first=false;+ } else {+ writer.write(',');+ }+ indent();+ writeDoc(null, doc, fields, (includeScore ? iterator.score() : 0.0f), includeScore);+ }+ decLevel();+ writer.write(']');++ if (otherFields !=null) {+ writeMap(null, otherFields, true, false);+ }++ decLevel();+ indent();+ writer.write('}');+ }+++++ public void writeStr(String name, String val, boolean needsEscaping) throws IOException {+ writer.write('"');+ // it might be more efficient to use a stringbuilder or write substrings+ // if writing chars to the stream is slow.+ if (needsEscaping) {+ for (int i=0; i<val.length(); i++) {+ char ch = val.charAt(i);+ switch(ch) {+ case '"':+ case '\\':+ writer.write('\\');+ writer.write(ch);+ break;+ /*** the following are not required to be escaped+ case '\r':+ case '\n':+ case '\t':+ case '\b':+ case '\f':+ case '/':+ ***/+ default: writer.write(ch);+ }+ }+ } else {+ writer.write(val);+ }+ writer.write('"');+ }+++ public void writeMap(String name, Map val, boolean excludeOuter, boolean isFirstVal) throws IOException {+ if (!excludeOuter) {+ writer.write('{');+ incLevel();+ isFirstVal=true;+ }++ for (Map.Entry entry : (Set<Map.Entry>)val.entrySet()) {+ Object e = entry.getKey();+ String k = e==null ? null : e.toString();+ Object v = entry.getValue();++ if (isFirstVal) {+ isFirstVal=false;+ } else {+ writer.write(',');+ }++ indent();+ writeKey(k,true);+ writeVal(k,v);+ }++ if (!excludeOuter) {+ decLevel();+ writer.write('}');+ }+ }+++ public void writeArray(String name, Object[] val) throws IOException {+ writeArray(name, Arrays.asList(val));+ }++ public void writeArray(String name, Collection val) throws IOException {+ writer.write('[');+ int sz = val.size();+ incLevel();+ boolean first=true;+ for (Object o : val) {+ if (first) {+ first=false;+ } else {+ writer.write(',');+ }+ if (sz>0) indent();+ writeVal(null, o);+ }+ decLevel();+ writer.write(']');+ }++ //+ // Primitive types+ //+ public void writeNull(String name) throws IOException {+ writeStr(name,"null",false);+ }++ public void writeInt(String name, String val) throws IOException {+ writer.write(val);+ }++ public void writeLong(String name, String val) throws IOException {+ writer.write(val);+ }++ public void writeBool(String name, String val) throws IOException {+ writer.write(val);+ }++ public void writeFloat(String name, String val) throws IOException {+ writer.write(val);+ }++ public void writeDouble(String name, String val) throws IOException {+ writer.write(val);+ }++ // TODO: refactor this out to a DateUtils class or something...+ public void writeDate(String name, Date val) throws IOException {+ // using a stringBuilder for numbers can be nice since+ // a temporary string isn't used (it's added directly to the+ // builder's buffer.++ StringBuilder sb = new StringBuilder();+ if (cal==null) cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));+ cal.setTime(val);++ int i = cal.get(Calendar.YEAR);+ sb.append(i);+ sb.append('-');+ i = cal.get(Calendar.MONTH) + 1; // 0 based, so add 1+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append('-');+ i=cal.get(Calendar.DAY_OF_MONTH);+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append('T');+ i=cal.get(Calendar.HOUR_OF_DAY); // 24 hour time format+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append(':');+ i=cal.get(Calendar.MINUTE);+ if (i<10) sb.append('0');+ sb.append(i);+ sb.append(':');+ i=cal.get(Calendar.SECOND);+ if (i<10) sb.append('0');+ sb.append(i);+ i=cal.get(Calendar.MILLISECOND);+ if (i != 0) {+ sb.append('.');+ if (i<100) sb.append('0');+ if (i<10) sb.append('0');+ sb.append(i);++ // handle canonical format specifying fractional+ // seconds shall not end in '0'. Given the slowness of+ // integer div/mod, simply checking the last character+ // is probably the fastest way to check.+ int lastIdx = sb.length()-1;+ if (sb.charAt(lastIdx)=='0') {+ lastIdx--;+ if (sb.charAt(lastIdx)=='0') {+ lastIdx--;+ }+ sb.setLength(lastIdx+1);+ }++ }+ sb.append('Z');+ writeDate(name, sb.toString());+ }++ public void writeDate(String name, String val) throws IOException {+ writeStr(name, val, false);+ }++ protected static void unicodeEscape(Appendable sb, int ch) throws IOException {+ String str = Integer.toHexString(ch & 0xffff);+ switch (str.length()) {+ case 1: sb.append("\\u000"); break;+ case 2: sb.append("\\u00"); break;+ case 3: sb.append("\\u0"); break;+ default: sb.append("\\u"); break;+ }+ sb.append(str);+ }++}++class PythonWriter extends JSONWriter {+ public PythonWriter(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) {+ super(writer, req, rsp);+ }++ @Override+ public void writeNull(String name) throws IOException {+ writer.write("None");+ }++ @Override+ public void writeBool(String name, boolean val) throws IOException {+ writer.write(val ? "True" : "False");+ }++ @Override+ public void writeBool(String name, String val) throws IOException {+ writeBool(name,val.charAt(0)=='t');+ }++ /* optionally use a unicode python string if necessary */+ @Override+ public void writeStr(String name, String val, boolean needsEscaping) throws IOException {+ if (!needsEscaping) {+ writer.write('\'');+ writer.write(val);+ writer.write('\'');+ return;+ }++ // use python unicode strings...+ // python doesn't tolerate newlines in strings in it's eval(), so we must escape them.++ StringBuilder sb = new StringBuilder(val.length());+ boolean needUnicode=false;++ for (int i=0; i<val.length(); i++) {+ char ch = val.charAt(i);+ switch(ch) {+ case '\'':+ case '\\': sb.append('\\'); sb.append(ch); break;+ case '\r': sb.append("\\r"); break;+ case '\n': sb.append("\\n"); break;+ default:+ // we don't strictly have to escape these chars, but it will probably increase+ // portability to stick to visible ascii+ if (ch<' ' || ch>127) {+ unicodeEscape(sb, ch);+ needUnicode=true;+ } else {+ sb.append(ch);+ }+ }+ }++ writer.write( needUnicode ? "u'" : "'");+ writer.append(sb);+ writer.write('\'');+ }++ /*+ old version that always used unicode+ public void writeStr(String name, String val, boolean needsEscaping) throws IOException {+ // use python unicode strings...+ // python doesn't tolerate newlines in strings in it's eval(), so we must escape them.+ writer.write("u'");+ // it might be more efficient to use a stringbuilder or write substrings+ // if writing chars to the stream is slow.+ if (needsEscaping) {+ for (int i=0; i<val.length(); i++) {+ char ch = val.charAt(i);+ switch(ch) {+ case '\'':+ case '\\': writer.write('\\'); writer.write(ch); break;+ case '\r': writer.write("\\r"); break;+ case '\n': writer.write("\\n"); break;+ default:+ // we don't strictly have to escape these chars, but it will probably increase+ // portability to stick to visible ascii+ if (ch<' ' || ch>127) {+ unicodeChar(ch);+ } else {+ writer.write(ch);+ }+ }+ }+ } else {+ writer.write(val);+ }+ writer.write('\'');+ }+ */++}+++class RubyWriter extends JSONWriter {+ public RubyWriter(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) {+ super(writer, req, rsp);+ }++ @Override+ public void writeNull(String name) throws IOException {+ writer.write("nil");+ }++ @Override+ protected void writeKey(String fname, boolean needsEscaping) throws IOException {+ writeStr(null, fname, needsEscaping);+ writer.write("=>");+ }++ @Override+ public void writeStr(String name, String val, boolean needsEscaping) throws IOException {+ // Ruby doesn't do unicode escapes... so let the servlet container write raw UTF-8+ // bytes into the string.+ //+ // Use single quoted strings for safety since no evaluation is done within them.+ // Also, there are very few escapes recognized in a singe quoted string, so+ // only escape the backspace and single quote.+ writer.write('\'');+ // it might be more efficient to use a stringbuilder or write substrings+ // if writing chars to the stream is slow.+ if (needsEscaping) {+ for (int i=0; i<val.length(); i++) {+ char ch = val.charAt(i);+ switch(ch) {+ case '\'':+ case '\\': writer.write('\\'); writer.write(ch); break;+ default: writer.write(ch); break;+ }+ }+ } else {+ writer.write(val);+ }+ writer.write('\'');+ }+}\ No newline at end of filediff --git a/src/java/org/apache/solr/request/PythonResponseWriter.java b/src/java/org/apache/solr/request/PythonResponseWriter.javanew file mode 100644index 00000000000..75657646f93--- /dev/null+++ b/src/java/org/apache/solr/request/PythonResponseWriter.java@@ -0,0 +1,17 @@+package org.apache.solr.request;++import java.io.Writer;+import java.io.IOException;++public class PythonResponseWriter implements QueryResponseWriter {+ static String CONTENT_TYPE_PYTHON_ASCII="text/x-python;charset=US-ASCII";++ public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {+ PythonWriter w = new PythonWriter(writer, req, rsp);+ w.writeResponse();+ }++ public String getContentType(SolrQueryRequest request, SolrQueryResponse response) {+ return CONTENT_TYPE_TEXT_ASCII;+ }+}diff --git a/src/java/org/apache/solr/request/RubyResponseWriter.java b/src/java/org/apache/solr/request/RubyResponseWriter.javanew file mode 100644index 00000000000..0e480a466c7--- /dev/null+++ b/src/java/org/apache/solr/request/RubyResponseWriter.java@@ -0,0 +1,17 @@+package org.apache.solr.request;++import java.io.Writer;+import java.io.IOException;++public class RubyResponseWriter implements QueryResponseWriter {+ static String CONTENT_TYPE_RUBY_UTF8="text/x-ruby;charset=UTF-8";++ public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {+ RubyWriter w = new RubyWriter(writer, req, rsp);+ w.writeResponse();+ }++ public String getContentType(SolrQueryRequest request, SolrQueryResponse response) {+ return CONTENT_TYPE_TEXT_UTF8;+ }+}diff --git a/src/java/org/apache/solr/request/TextResponseWriter.java b/src/java/org/apache/solr/request/TextResponseWriter.javanew file mode 100644index 00000000000..d970efcb9e2--- /dev/null+++ b/src/java/org/apache/solr/request/TextResponseWriter.java@@ -0,0 +1,194 @@+package org.apache.solr.request;++import org.apache.lucene.document.Document;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.search.DocList;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.util.NamedList;++import java.io.IOException;+import java.io.Writer;+import java.util.Collection;+import java.util.Date;+import java.util.Map;+import java.util.Set;++/** Base class for text-oriented response writers.+ *+ * @author yonik+ * @version $Id$+ */+public abstract class TextResponseWriter {+ protected final Writer writer;+ protected final IndexSchema schema;+ protected final SolrIndexSearcher searcher;+ protected final SolrQueryRequest req;+ protected final SolrQueryResponse rsp;++ // the default set of fields to return for each document+ protected Set<String> returnFields;++ protected int level;+ protected boolean doIndent;+++ public TextResponseWriter(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) {+ this.writer = writer;+ this.schema = req.getSchema();+ this.searcher = req.getSearcher();+ this.req = req;+ this.rsp = rsp;+ String indent = req.getParam("indent");+ if (indent != null && !"".equals(indent) && !"off".equals(indent)) {+ doIndent=true;+ }+ returnFields = rsp.getReturnFields();+ }++ /** returns the Writer that the response is being written to */+ public Writer getWriter() { return writer; }++ // use a combination of tabs and spaces to minimize the size of an indented response.+ private static final String[] indentArr = new String[] {+ "\n",+ "\n ",+ "\n ",+ "\n\t",+ "\n\t ",+ "\n\t ", // could skip this one (the only 3 char seq)+ "\n\t\t",+ "\n\t\t "};++ public void indent() throws IOException {+ if (doIndent) indent(level);+ }++ public void indent(int lev) throws IOException {+ int arrsz = indentArr.length-1;+ // power-of-two intent array (gratuitous optimization :-)+ String istr = indentArr[lev & (indentArr.length-1)];+ writer.write(istr);+ }++ //+ // Functions to manipulate the current logical nesting level.+ // Any indentation will be partially based on level.+ //+ public void setLevel(int level) { this.level = level; }+ public int level() { return level; }+ public int incLevel() { return ++level; }+ public int decLevel() { return --level; }+ public void setIndent(boolean doIndent) {+ this.doIndent = doIndent;+ }+++ public abstract void writeNamedList(String name, NamedList val) throws IOException;++ public void writeVal(String name, Object val) throws IOException {++ // if there get to be enough types, perhaps hashing on the type+ // to get a handler might be faster (but types must be exact to do that...)++ // go in order of most common to least common+ if (val==null) {+ writeNull(name);+ } else if (val instanceof String) {+ writeStr(name, val.toString(), true);+ // micro-optimization... using toString() avoids a cast first+ } else if (val instanceof Integer) {+ writeInt(name, val.toString());+ } else if (val instanceof Boolean) {+ writeBool(name, val.toString());+ } else if (val instanceof Long) {+ writeLong(name, val.toString());+ } else if (val instanceof Date) {+ writeDate(name,(Date)val);+ } else if (val instanceof Float) {+ // we pass the float instead of using toString() because+ // it may need special formatting. same for double.+ writeFloat(name, ((Float)val).floatValue());+ } else if (val instanceof Double) {+ writeDouble(name, ((Double)val).doubleValue());+ } else if (val instanceof Document) {+ writeDoc(name, (Document)val, returnFields, 0.0f, false);+ } else if (val instanceof DocList) {+ // requires access to IndexReader+ writeDocList(name, (DocList)val, returnFields,null);+ // }+ // else if (val instanceof DocSet) {+ // how do we know what fields to read?+ // todo: have a DocList/DocSet wrapper that+ // restricts the fields to write...?+ } else if (val instanceof Map) {+ writeMap(name, (Map)val, false, true);+ } else if (val instanceof NamedList) {+ writeNamedList(name, (NamedList)val);+ } else if (val instanceof Collection) {+ writeArray(name,(Collection)val);+ } else if (val instanceof Object[]) {+ writeArray(name,(Object[])val);+ } else {+ // default... for debugging only+ writeStr(name, val.getClass().getName() + ':' + val.toString(), true);+ }+ }++ // names are passed when writing primitives like writeInt to allow many different+ // types of formats, including those where the name may come after the value (like+ // some XML formats).++ public abstract void writeDoc(String name, Document doc, Set<String> returnFields, float score, boolean includeScore) throws IOException;++ public abstract void writeDocList(String name, DocList ids, Set<String> fields, Map otherFields) throws IOException;++ public abstract void writeStr(String name, String val, boolean needsEscaping) throws IOException;++ public abstract void writeMap(String name, Map val, boolean excludeOuter, boolean isFirstVal) throws IOException;++ public abstract void writeArray(String name, Object[] val) throws IOException;++ public abstract void writeArray(String name, Collection val) throws IOException;++ public abstract void writeNull(String name) throws IOException;++ /** if this form of the method is called, val is the Java string form of an int */+ public abstract void writeInt(String name, String val) throws IOException;++ public void writeInt(String name, int val) throws IOException {+ writeInt(name,Integer.toString(val));+ }++ /** if this form of the method is called, val is the Java string form of a long */+ public abstract void writeLong(String name, String val) throws IOException;++ public void writeLong(String name, long val) throws IOException {+ writeLong(name,Long.toString(val));+ }++ /** if this form of the method is called, val is the Java string form of a boolean */+ public abstract void writeBool(String name, String val) throws IOException;++ public void writeBool(String name, boolean val) throws IOException {+ writeBool(name,Boolean.toString(val));+ }++ /** if this form of the method is called, val is the Java string form of a float */+ public abstract void writeFloat(String name, String val) throws IOException;++ public void writeFloat(String name, float val) throws IOException {+ writeFloat(name,Float.toString(val));+ }++ /** if this form of the method is called, val is the Java string form of a double */+ public abstract void writeDouble(String name, String val) throws IOException;++ public void writeDouble(String name, double val) throws IOException {+ writeDouble(name,Double.toString(val));+ }++ public abstract void writeDate(String name, Date val) throws IOException;++ /** if this form of the method is called, val is the Solr ISO8601 based date format */+ public abstract void writeDate(String name, String val) throws IOException;+}diff --git a/src/java/org/apache/solr/schema/BCDIntField.java b/src/java/org/apache/solr/schema/BCDIntField.javaindex b7a8bc6e515..6b035cafc7e 100644--- a/src/java/org/apache/solr/schema/BCDIntField.java+++ b/src/java/org/apache/solr/schema/BCDIntField.java@@ -19,8 +19,10 @@ package org.apache.solr.schema;import org.apache.lucene.search.SortField;import org.apache.solr.search.function.ValueSource;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.util.BCDUtils;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -55,6 +57,10 @@ public class BCDIntField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeInt(name,toExternal(f));}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeInt(name,toExternal(f));+ }}diff --git a/src/java/org/apache/solr/schema/BoolField.java b/src/java/org/apache/solr/schema/BoolField.javaindex 10629d39db3..c96cadcd3b5 100644--- a/src/java/org/apache/solr/schema/BoolField.java+++ b/src/java/org/apache/solr/schema/BoolField.java@@ -24,7 +24,9 @@ import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.Tokenizer;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import org.apache.solr.analysis.SolrAnalyzer;import java.util.Map;@@ -95,4 +97,8 @@ public class BoolField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeBool(name, f.stringValue().charAt(0) =='T');}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeBool(name, f.stringValue().charAt(0) =='T');+ }}diff --git a/src/java/org/apache/solr/schema/DateField.java b/src/java/org/apache/solr/schema/DateField.javaindex 23cea13df06..5444b8d927e 100644--- a/src/java/org/apache/solr/schema/DateField.java+++ b/src/java/org/apache/solr/schema/DateField.java@@ -18,7 +18,9 @@ package org.apache.solr.schema;import org.apache.solr.core.SolrException;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.search.SortField;import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.OrdFieldSource;@@ -100,4 +102,8 @@ public class DateField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeDate(name, toExternal(f));}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeDate(name, toExternal(f));+ }}diff --git a/src/java/org/apache/solr/schema/DoubleField.java b/src/java/org/apache/solr/schema/DoubleField.javaindex f6af4381afd..dd5f3ef5870 100644--- a/src/java/org/apache/solr/schema/DoubleField.java+++ b/src/java/org/apache/solr/schema/DoubleField.java@@ -20,7 +20,9 @@ import org.apache.lucene.search.SortField;import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.FloatFieldSource;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -47,4 +49,8 @@ public class DoubleField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeDouble(name, f.stringValue());}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeDouble(name, f.stringValue());+ }}diff --git a/src/java/org/apache/solr/schema/FieldType.java b/src/java/org/apache/solr/schema/FieldType.javaindex 1c1f703ab87..106c15de870 100644--- a/src/java/org/apache/solr/schema/FieldType.java+++ b/src/java/org/apache/solr/schema/FieldType.java@@ -17,6 +17,7 @@package org.apache.solr.schema;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.Tokenizer;@@ -26,6 +27,7 @@ import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.OrdFieldSource;import org.apache.solr.search.Sorting;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import org.apache.solr.analysis.SolrAnalyzer;import org.apache.solr.core.SolrException;@@ -208,7 +210,7 @@ public abstract class FieldType extends FieldProperties {* value* @see #toInternal*/- public String toExternal(Field f) {+ public String toExternal(Fieldable f) {// currently used in writing XML of the search result (but perhaps// a more efficient toXML(Field f, Writer w) should be used// in the future.@@ -221,12 +223,12 @@ public abstract class FieldType extends FieldProperties {}/** :TODO: document this method */- public String storedToReadable(Field f) {+ public String storedToReadable(Fieldable f) {return toExternal(f);}/** :TODO: document this method */- public String storedToIndexed(Field f) {+ public String storedToIndexed(Fieldable f) {// right now, the transformation of single valued fields like SortableInt// is done when the Field is created, not at analysis time... this means// that the indexed form is the same as the stored field form.@@ -344,6 +346,11 @@ public abstract class FieldType extends FieldProperties {*/public abstract void write(XMLWriter xmlWriter, String name, Field f) throws IOException;+ /**+ * calls back to TextResponseWriter to write the field value+ */+ public abstract void write(TextResponseWriter writer, String name, Fieldable f) throws IOException;+/*** Returns the SortField instance that should be used to sort fieldsdiff --git a/src/java/org/apache/solr/schema/FloatField.java b/src/java/org/apache/solr/schema/FloatField.javaindex 75de65a3920..3bfafb556e2 100644--- a/src/java/org/apache/solr/schema/FloatField.java+++ b/src/java/org/apache/solr/schema/FloatField.java@@ -20,7 +20,9 @@ import org.apache.lucene.search.SortField;import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.FloatFieldSource;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -41,8 +43,11 @@ public class FloatField extends FieldType {return new FloatFieldSource(field.name);}-public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeFloat(name, f.stringValue());}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeFloat(name, f.stringValue());+ }}diff --git a/src/java/org/apache/solr/schema/IntField.java b/src/java/org/apache/solr/schema/IntField.javaindex 1b1d2761979..67c47edf4ef 100644--- a/src/java/org/apache/solr/schema/IntField.java+++ b/src/java/org/apache/solr/schema/IntField.java@@ -20,7 +20,9 @@ import org.apache.lucene.search.SortField;import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.IntFieldSource;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -44,4 +46,8 @@ public class IntField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeInt(name, f.stringValue());}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeInt(name, f.stringValue());+ }}diff --git a/src/java/org/apache/solr/schema/LongField.java b/src/java/org/apache/solr/schema/LongField.javaindex 1b4a331d193..b1648d40449 100644--- a/src/java/org/apache/solr/schema/LongField.java+++ b/src/java/org/apache/solr/schema/LongField.java@@ -20,7 +20,9 @@ import org.apache.lucene.search.SortField;import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.IntFieldSource;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -49,4 +51,8 @@ public class LongField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeLong(name, f.stringValue());}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeLong(name, f.stringValue());+ }}diff --git a/src/java/org/apache/solr/schema/SchemaField.java b/src/java/org/apache/solr/schema/SchemaField.javaindex 89a34576257..db6306a7088 100644--- a/src/java/org/apache/solr/schema/SchemaField.java+++ b/src/java/org/apache/solr/schema/SchemaField.java@@ -17,8 +17,10 @@package org.apache.solr.schema;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.search.SortField;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -95,6 +97,11 @@ public final class SchemaField extends FieldProperties {type.write(writer,name,val);}+ public void write(TextResponseWriter writer, String name, Fieldable val) throws IOException {+ // name is passed in because it may be null if name should not be used.+ type.write(writer,name,val);+ }+public SortField getSortField(boolean top) {return type.getSortField(this, top);}diff --git a/src/java/org/apache/solr/schema/SortableDoubleField.java b/src/java/org/apache/solr/schema/SortableDoubleField.javaindex d7f61fa6371..f082f568c57 100644--- a/src/java/org/apache/solr/schema/SortableDoubleField.java+++ b/src/java/org/apache/solr/schema/SortableDoubleField.java@@ -22,9 +22,11 @@ import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.FieldCacheSource;import org.apache.solr.search.function.DocValues;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.solr.util.NumberUtils;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -60,6 +62,11 @@ public class SortableDoubleField extends FieldType {String sval = f.stringValue();xmlWriter.writeDouble(name, NumberUtils.SortableStr2double(sval));}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ String sval = f.stringValue();+ writer.writeDouble(name, NumberUtils.SortableStr2double(sval));+ }}diff --git a/src/java/org/apache/solr/schema/SortableFloatField.java b/src/java/org/apache/solr/schema/SortableFloatField.javaindex 068dbdb1e92..d0f813166f8 100644--- a/src/java/org/apache/solr/schema/SortableFloatField.java+++ b/src/java/org/apache/solr/schema/SortableFloatField.java@@ -22,9 +22,11 @@ import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.FieldCacheSource;import org.apache.solr.search.function.DocValues;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.solr.util.NumberUtils;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -60,6 +62,11 @@ public class SortableFloatField extends FieldType {String sval = f.stringValue();xmlWriter.writeFloat(name, NumberUtils.SortableStr2float(sval));}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ String sval = f.stringValue();+ writer.writeFloat(name, NumberUtils.SortableStr2float(sval));+ }}diff --git a/src/java/org/apache/solr/schema/SortableIntField.java b/src/java/org/apache/solr/schema/SortableIntField.javaindex a9fbb4e936c..4e6f2a4a828 100644--- a/src/java/org/apache/solr/schema/SortableIntField.java+++ b/src/java/org/apache/solr/schema/SortableIntField.java@@ -22,9 +22,11 @@ import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.FieldCacheSource;import org.apache.solr.search.function.DocValues;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.solr.util.NumberUtils;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -65,6 +67,11 @@ public class SortableIntField extends FieldType {// in the future (saves the construction of one String)xmlWriter.writeInt(name, NumberUtils.SortableStr2int(sval,0,sval.length()));}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ String sval = f.stringValue();+ writer.writeInt(name, NumberUtils.SortableStr2int(sval,0,sval.length()));+ }}diff --git a/src/java/org/apache/solr/schema/SortableLongField.java b/src/java/org/apache/solr/schema/SortableLongField.javaindex 4fce602d537..7a3a7d28048 100644--- a/src/java/org/apache/solr/schema/SortableLongField.java+++ b/src/java/org/apache/solr/schema/SortableLongField.java@@ -22,9 +22,11 @@ import org.apache.solr.search.function.ValueSource;import org.apache.solr.search.function.FieldCacheSource;import org.apache.solr.search.function.DocValues;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.lucene.index.IndexReader;import org.apache.solr.util.NumberUtils;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -60,6 +62,11 @@ public class SortableLongField extends FieldType {String sval = f.stringValue();xmlWriter.writeLong(name, NumberUtils.SortableStr2long(sval,0,sval.length()));}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ String sval = f.stringValue();+ writer.writeLong(name, NumberUtils.SortableStr2long(sval,0,sval.length()));+ }}diff --git a/src/java/org/apache/solr/schema/StrField.java b/src/java/org/apache/solr/schema/StrField.javaindex 9a6ec36b8de..ba30a4fecbe 100644--- a/src/java/org/apache/solr/schema/StrField.java+++ b/src/java/org/apache/solr/schema/StrField.java@@ -18,7 +18,9 @@ package org.apache.solr.schema;import org.apache.lucene.search.SortField;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -26,7 +28,6 @@ import java.io.IOException;* @author yonik* @version $Id$*/-//TODO: allow specification of max string size?public class StrField extends FieldType {protected void init(IndexSchema schema, Map<String,String> args) {}@@ -38,4 +39,8 @@ public class StrField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeStr(name, f.stringValue());}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeStr(name, f.stringValue(), true);+ }}diff --git a/src/java/org/apache/solr/schema/TextField.java b/src/java/org/apache/solr/schema/TextField.javaindex 54975f75050..74f3d626000 100644--- a/src/java/org/apache/solr/schema/TextField.java+++ b/src/java/org/apache/solr/schema/TextField.java@@ -18,7 +18,9 @@ package org.apache.solr.schema;import org.apache.lucene.search.SortField;import org.apache.lucene.document.Field;+import org.apache.lucene.document.Fieldable;import org.apache.solr.request.XMLWriter;+import org.apache.solr.request.TextResponseWriter;import java.util.Map;import java.io.IOException;@@ -40,4 +42,8 @@ public class TextField extends FieldType {public void write(XMLWriter xmlWriter, String name, Field f) throws IOException {xmlWriter.writeStr(name, f.stringValue());}++ public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {+ writer.writeStr(name, f.stringValue(), true);+ }}diff --git a/src/java/org/apache/solr/util/NamedList.java b/src/java/org/apache/solr/util/NamedList.javaindex a1eb37531c8..a06fb9ac73d 100644--- a/src/java/org/apache/solr/util/NamedList.java+++ b/src/java/org/apache/solr/util/NamedList.java@@ -184,7 +184,13 @@ public class NamedList implements Cloneable, Serializable {Map.Entry entry = (Map.Entry)iter.next();add(entry.getKey().toString(), entry.getValue());}- return false;+ return args.size()>0;+ }++ /** Appends the elements of the given NamedList to this one. */+ public boolean addAll(NamedList nl) {+ nvPairs.addAll(nl.nvPairs);+ return nl.size()>0;}/**