Apache Solr open-source search software
set svn:eol-style native
Yonik Seeley5f8d60640fa0
diff --git a/src/java/org/apache/solr/analysis/SolrAnalyzer.java b/src/java/org/apache/solr/analysis/SolrAnalyzer.javaindex 730ee2b769e..4d4774f813b 100644--- a/src/java/org/apache/solr/analysis/SolrAnalyzer.java+++ b/src/java/org/apache/solr/analysis/SolrAnalyzer.java@@ -1,19 +1,19 @@-package org.apache.solr.analysis;--import org.apache.lucene.analysis.Analyzer;--/**- * @author yonik- * @version $Id$- */-public abstract class SolrAnalyzer extends Analyzer {- int posIncGap=0;-- public void setPositionIncrementGap(int gap) {- posIncGap=gap;- }-- public int getPositionIncrementGap(String fieldName) {- return posIncGap;- }-}+package org.apache.solr.analysis;++import org.apache.lucene.analysis.Analyzer;++/**+ * @author yonik+ * @version $Id$+ */+public abstract class SolrAnalyzer extends Analyzer {+ int posIncGap=0;++ public void setPositionIncrementGap(int gap) {+ posIncGap=gap;+ }++ public int getPositionIncrementGap(String fieldName) {+ return posIncGap;+ }+}diff --git a/src/java/org/apache/solr/request/JSONResponseWriter.java b/src/java/org/apache/solr/request/JSONResponseWriter.javaindex 309c63f1fd7..4405da58226 100644--- a/src/java/org/apache/solr/request/JSONResponseWriter.java+++ b/src/java/org/apache/solr/request/JSONResponseWriter.java@@ -1,703 +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('\'');- }+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.javaindex 75657646f93..b6ee2ce7100 100644--- a/src/java/org/apache/solr/request/PythonResponseWriter.java+++ b/src/java/org/apache/solr/request/PythonResponseWriter.java@@ -1,17 +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;- }-}+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.javaindex 0e480a466c7..e62762fb2e5 100644--- a/src/java/org/apache/solr/request/RubyResponseWriter.java+++ b/src/java/org/apache/solr/request/RubyResponseWriter.java@@ -1,17 +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;- }-}+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.javaindex d970efcb9e2..b32e5461388 100644--- a/src/java/org/apache/solr/request/TextResponseWriter.java+++ b/src/java/org/apache/solr/request/TextResponseWriter.java@@ -1,194 +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;-}+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/search/PrefixFilter.java b/src/java/org/apache/solr/search/PrefixFilter.javaindex 1f5aba86fcf..3b5cfa33d4a 100644--- a/src/java/org/apache/solr/search/PrefixFilter.java+++ b/src/java/org/apache/solr/search/PrefixFilter.java@@ -1,79 +1,79 @@-package org.apache.solr.search;--import org.apache.lucene.search.Filter;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.TermEnum;-import org.apache.lucene.index.TermDocs;--import java.util.BitSet;-import java.io.IOException;--/**- * @author yonik- * @version $Id$- */-public class PrefixFilter extends Filter {- protected final Term prefix;-- PrefixFilter(Term prefix) {- this.prefix = prefix;- }-- Term getPrefix() { return prefix; }-- public BitSet bits(IndexReader reader) throws IOException {- final BitSet bitSet = new BitSet(reader.maxDoc());- new PrefixGenerator(prefix) {- public void handleDoc(int doc) {- bitSet.set(doc);- }- }.generate(reader);- return bitSet;- }-}--// keep this protected until I decide if it's a good way-// to separate id generation from collection (or should-// I just reuse hitcollector???)-interface IdGenerator {- public void generate(IndexReader reader) throws IOException;- public void handleDoc(int doc);-}---abstract class PrefixGenerator implements IdGenerator {- protected final Term prefix;-- PrefixGenerator(Term prefix) {- this.prefix = prefix;- }-- public void generate(IndexReader reader) throws IOException {- TermEnum enumerator = reader.terms(prefix);- TermDocs termDocs = reader.termDocs();-- try {-- String prefixText = prefix.text();- String prefixField = prefix.field();- do {- Term term = enumerator.term();- if (term != null &&- term.text().startsWith(prefixText) &&- term.field() == prefixField)- {- termDocs.seek(term);- while (termDocs.next()) {- handleDoc(termDocs.doc());- }- } else {- break;- }- } while (enumerator.next());- } finally {- termDocs.close();- enumerator.close();- }- }-}+package org.apache.solr.search;++import org.apache.lucene.search.Filter;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.TermEnum;+import org.apache.lucene.index.TermDocs;++import java.util.BitSet;+import java.io.IOException;++/**+ * @author yonik+ * @version $Id$+ */+public class PrefixFilter extends Filter {+ protected final Term prefix;++ PrefixFilter(Term prefix) {+ this.prefix = prefix;+ }++ Term getPrefix() { return prefix; }++ public BitSet bits(IndexReader reader) throws IOException {+ final BitSet bitSet = new BitSet(reader.maxDoc());+ new PrefixGenerator(prefix) {+ public void handleDoc(int doc) {+ bitSet.set(doc);+ }+ }.generate(reader);+ return bitSet;+ }+}++// keep this protected until I decide if it's a good way+// to separate id generation from collection (or should+// I just reuse hitcollector???)+interface IdGenerator {+ public void generate(IndexReader reader) throws IOException;+ public void handleDoc(int doc);+}+++abstract class PrefixGenerator implements IdGenerator {+ protected final Term prefix;++ PrefixGenerator(Term prefix) {+ this.prefix = prefix;+ }++ public void generate(IndexReader reader) throws IOException {+ TermEnum enumerator = reader.terms(prefix);+ TermDocs termDocs = reader.termDocs();++ try {++ String prefixText = prefix.text();+ String prefixField = prefix.field();+ do {+ Term term = enumerator.term();+ if (term != null &&+ term.text().startsWith(prefixText) &&+ term.field() == prefixField)+ {+ termDocs.seek(term);+ while (termDocs.next()) {+ handleDoc(termDocs.doc());+ }+ } else {+ break;+ }+ } while (enumerator.next());+ } finally {+ termDocs.close();+ enumerator.close();+ }+ }+}diff --git a/src/webapp/src/org/apache/solr/servlet/SolrServletRequest.java b/src/webapp/src/org/apache/solr/servlet/SolrServletRequest.javaindex caf9257ef30..7dc4f470bc8 100644--- a/src/webapp/src/org/apache/solr/servlet/SolrServletRequest.java+++ b/src/webapp/src/org/apache/solr/servlet/SolrServletRequest.java@@ -1,61 +1,61 @@-package org.apache.solr.servlet;--import org.apache.solr.request.SolrQueryRequestBase;-import org.apache.solr.core.SolrCore;-import org.apache.solr.util.StrUtils;--import javax.servlet.http.HttpServletRequest;-import java.util.Map;-import java.util.Set;--/**- * @author yonik- * @version $Id$- */-class SolrServletRequest extends SolrQueryRequestBase {-- final HttpServletRequest req;-- public SolrServletRequest(SolrCore core, HttpServletRequest req) {- super(core);- this.req = req;- }-- public String getParam(String name) {- return req.getParameter(name);- }-- public String[] getParams(String name) {- return req.getParameterValues(name);- }--- public String getParamString() {- StringBuilder sb = new StringBuilder(128);- try {- boolean first=true;-- for (Map.Entry<String,String[]> entry : (Set<Map.Entry<String,String[]>>)req.getParameterMap().entrySet()) {- String key = entry.getKey();- String[] valarr = entry.getValue();-- for (String val : valarr) {- if (!first) sb.append('&');- first=false;- sb.append(key);- sb.append('=');- StrUtils.partialURLEncodeVal(sb, val==null ? "" : val);- }- }- }- catch (Exception e) {- // should never happen... we only needed this because- // partialURLEncodeVal can throw an IOException, but it- // never will when adding to a StringBuilder.- throw new RuntimeException(e);- }-- return sb.toString();- }--}+package org.apache.solr.servlet;++import org.apache.solr.request.SolrQueryRequestBase;+import org.apache.solr.core.SolrCore;+import org.apache.solr.util.StrUtils;++import javax.servlet.http.HttpServletRequest;+import java.util.Map;+import java.util.Set;++/**+ * @author yonik+ * @version $Id$+ */+class SolrServletRequest extends SolrQueryRequestBase {++ final HttpServletRequest req;++ public SolrServletRequest(SolrCore core, HttpServletRequest req) {+ super(core);+ this.req = req;+ }++ public String getParam(String name) {+ return req.getParameter(name);+ }++ public String[] getParams(String name) {+ return req.getParameterValues(name);+ }+++ public String getParamString() {+ StringBuilder sb = new StringBuilder(128);+ try {+ boolean first=true;++ for (Map.Entry<String,String[]> entry : (Set<Map.Entry<String,String[]>>)req.getParameterMap().entrySet()) {+ String key = entry.getKey();+ String[] valarr = entry.getValue();++ for (String val : valarr) {+ if (!first) sb.append('&');+ first=false;+ sb.append(key);+ sb.append('=');+ StrUtils.partialURLEncodeVal(sb, val==null ? "" : val);+ }+ }+ }+ catch (Exception e) {+ // should never happen... we only needed this because+ // partialURLEncodeVal can throw an IOException, but it+ // never will when adding to a StringBuilder.+ throw new RuntimeException(e);+ }++ return sb.toString();+ }++}diff --git a/src/webapp/src/org/apache/solr/servlet/SolrUpdateServlet.java b/src/webapp/src/org/apache/solr/servlet/SolrUpdateServlet.javaindex af1795eeca8..c590448ca8b 100644--- a/src/webapp/src/org/apache/solr/servlet/SolrUpdateServlet.java+++ b/src/webapp/src/org/apache/solr/servlet/SolrUpdateServlet.java@@ -1,54 +1,54 @@-package org.apache.solr.servlet;/**- * Copyright 2006 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.solr.core.SolrCore;-import org.apache.solr.core.SolrException;-import org.apache.solr.request.XMLResponseWriter;-import org.apache.solr.request.SolrQueryResponse;--import javax.servlet.http.HttpServlet;-import javax.servlet.http.HttpServletRequest;-import javax.servlet.http.HttpServletResponse;-import javax.servlet.ServletException;-import java.util.logging.Logger;-import java.io.IOException;-import java.io.BufferedReader;-import java.io.PrintWriter;--/**- * @author yonik- * @version $Id$- */-public class SolrUpdateServlet extends HttpServlet {- final Logger log = Logger.getLogger(SolrUpdateServlet.class.getName());- private SolrCore core;- private static String CONTENT_TYPE="text/xml;charset=UTF-8";-- XMLResponseWriter xmlResponseWriter;-- public void init() throws ServletException- {- core = SolrCore.getSolrCore();- log.info("SolrUpdateServlet.init() done");- }-- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {- BufferedReader requestReader = request.getReader();- response.setContentType(CONTENT_TYPE);- PrintWriter responseWriter = response.getWriter();- core.update(requestReader, responseWriter);- }-}+package org.apache.solr.servlet;/**+ * Copyright 2006 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrException;+import org.apache.solr.request.XMLResponseWriter;+import org.apache.solr.request.SolrQueryResponse;++import javax.servlet.http.HttpServlet;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;+import javax.servlet.ServletException;+import java.util.logging.Logger;+import java.io.IOException;+import java.io.BufferedReader;+import java.io.PrintWriter;++/**+ * @author yonik+ * @version $Id$+ */+public class SolrUpdateServlet extends HttpServlet {+ final Logger log = Logger.getLogger(SolrUpdateServlet.class.getName());+ private SolrCore core;+ private static String CONTENT_TYPE="text/xml;charset=UTF-8";++ XMLResponseWriter xmlResponseWriter;++ public void init() throws ServletException+ {+ core = SolrCore.getSolrCore();+ log.info("SolrUpdateServlet.init() done");+ }++ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {+ BufferedReader requestReader = request.getReader();+ response.setContentType(CONTENT_TYPE);+ PrintWriter responseWriter = response.getWriter();+ core.update(requestReader, responseWriter);+ }+}