让Ajax框架Buffalo支持JSON协议而非仅仅自定义的XML协议[JS前端及单元测试完成]
Buffalo默认实现了一套很棒的自定义XML协议(具体请参考拙作《Ajax框架Buffalo深度研究》)。
然而在崇尚“标准”的当下,很多人对这种“非标准”的自定义的协议并不感冒,哪怕它再好。
在这种情况下,本人也是本着对Buffalo的继续研究、提升自我的态度,尝试基于org.json的“正宗”JSON参考实现RI,让Buffalo完全支持JSON标准协议。
本来打算自己默默研究,等完全成型之后再发布出来,然而自《Ajax框架Buffalo深度研究》发布后,在社区所凝聚的人气之旺,让我有些震惊(或者说惊喜),继而灵机一动:何不利用社区的强大平台,在线开展此项工作呢?
不能保证每天甚至每周都有让人惊喜的进展,仅希望通过这种方式,鞭策自己的同时,也获得更多社区高手的批评斧正,快速提升,少走弯路。
接下来的工作,欢迎各位踊跃拍砖,谢谢!
2010-02-08,状态简述:
1)前端js已经编写完成:充分结合XML协议和JSON协议,完成了代码的重构
2)单元测试已经完成,并提供了完整的参考XML协议的js单一测试用例(同样基于script.aculo.us 的unittest.js)
3)升级prototype.js到最新的1.6.1(其实buffalo对prototype.js依赖不大)
接下来的工作:
1、完成前后端集成测试,并完善demo
2、适时开展RC
2010-01-25,状态简述:
1)后端代码重构完成,并已纳入buffalo SVN, 建立了新的branch,位于branches/json/;
2)接下来工作的重点是:a.着手编写前台js; c.并结合demo完成集成测试。
……
public static BuffaloProtocal getInstance(String p){ BuffaloProtocal instance = (BuffaloProtocal) instanceMap.get(p); if (instance == null) { instance = new BuffaloProtocal(); instance.protocol = p; instanceMap.put(p, instance); } return instance; }
}
};
}
为了发布上面的这个回复,我老老实实的提交-》不行(都是缺胳膊少腿的)-》编辑了足足5遍!!
Robbin TX啊,这么牛气哄哄(回帖还需要考试)的网站,可不能被这个破编辑器给砸了呀
老实说,也不是没在JSON的表达样式上思考过,我在写测试用例时就推翻了不下两个版本
我现在初步的考虑是:先完成一个解析JSON的版本的解析器,通过不同call请求对不同协议的需求,无缝的实现XML和JSON的输入-》解析-》服务寻址-》调用-》解析-》输出的同样过程。
也就是说,我要求自己写的JSON实现,在相同的测试用例下要一摸一样,同时都能通过
所以在这个角度上说,可能不能发挥JSON的“精炼”的特点,当然这可能更多的针对输入,输出上应该对JSON会更友好些。
但无论如何,对用户都是友好的,透明的
这么写实现上没有问题,但感觉丢掉了JSON自带的类型支持。例如,对float, int, string, boolean等原生数据类型的支持,JSON是可以自描述的,而不用写上string:"abc", double: 1.0之类。
例如service.divide(1.0, 2.0), 我期待用JSON写起来应该是这样子的:
{buffalo-call: 'divide', parameters: }
例如Map的例子:
{buffalo-call: 'somemethod', parameters: }
这样写需要对json更加智能的处理。
你的实现仍然是没有问题的;只是这样写出来的协议对于xml没有本质的区别,对于客户端调用而言也没有太多的改善之处。
import java.io.IOException; import java.io.InputStream;
import org.json.JSONArray; import org.json.JSONException;
import net.buffalo.protocal.ProtocolException; import net.buffalo.protocal.io.StreamException; import net.buffalo.protocal.io.StreamReader;
/**
The same as FastInputStreamReader
@see FastInputStreamReader.java */ public class JsonStandardInputStreamReader extends JsonStandardStreamReader implements StreamReader {
private final InputStream in;
public JsonStandardInputStreamReader(InputStream in) { this.in = in; int ch; try { ch = readSingleChar(); for (; ch > -1; ch = readSingleChar()) { sbuf.append((char)ch); } } catch (IOException e) { throw new StreamException(e); } try{ all = new JSONArray(sbuf.toString()); len = all.length(); }catch(JSONException e){ throw new ProtocolException("Invalid JSON String."); } moveDown(); }
public void close() { try { in.close(); } catch (IOException e) { throw new RuntimeException(e); } }
protected int readSingleChar() throws IOException { return in.read(); } }
import java.io.IOException; import java.io.Reader; import java.util.Stack;
import net.buffalo.protocal.ProtocalTag; import net.buffalo.protocal.ProtocolException; import net.buffalo.protocal.io.StreamException; import net.buffalo.protocal.io.StreamReader;
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
/**
The Implementation is not a general JSON StreamReader,
just for parsing buffalo-call only.
@author zhengxq
@see JsonStreamReader.java */ public class JsonStandardStreamReader implements StreamReader { private final Reader in; protected StringBuffer sbuf = new StringBuffer(); private final JSONArray all; private final int len;
protected Stack stack = new Stack(); protected int depth = 0;
protected Tag currentTag; private int pointer = 0;
protected Stack paramStack = new Stack(); private int paramDepth = 0; private JSONArray param; //temp for map or list private int innerPointer = 0; //for map or list param
protected JsonStandardStreamReader() { this.in = null; this.all = null; this.len = 0; }
public JsonStandardStreamReader(Reader in){ this.in = in; int ch; try { ch = readSingleChar(); for (; ch > -1; ch = readSingleChar()) { sbuf.append((char)ch); } } catch (IOException e) { throw new StreamException(e); } try{ all = new JSONArray(sbuf.toString()); len = all.length(); }catch(JSONException e){ throw new ProtocolException("Invalid JSON String."); } moveDown(); }
/* move to next, and parse a Tag */ public void moveDown() { JSONObject o = null; if(pointer==0){ // buffalo-call try{ o = all.getJSONObject(pointer); pointer++; if(o==null) throw new ProtocolException("The first tag should be 'buffalo-call'"); }catch(JSONException e){ throw new ProtocolException("Invalid JSON String."); }catch(ProtocolException e){ throw e; } }else if(pointer==1){ // method try{ o = all.getJSONObject(pointer); pointer++; if(o==null) throw new ProtocolException("The first tag should be 'method'"); }catch(JSONException e){ throw new ProtocolException("Invalid JSON String."); } }else{ // params try{ //test for map or list Tag test = (Tag) stack.get(depth - 1); if(test.tag.equalsIgnoreCase(ProtocalTag.TAG_MAP) || test.tag.equalsIgnoreCase(ProtocalTag.TAG_LIST)) { //it's map, then get the inner object if(param == null){ // reset it innerPointer = 0; //parse it param = (JSONArray)test.value; } if(innerPointer>=param.length()) { //try to restore try{ Param p = (Param) paramStack.pop(); param = p.array; innerPointer = p.pointer; }catch(Exception e){ throw new ProtocolException("JSONArray in the param is out of bound : len="+len+" but innerPointer="+innerPointer); } }
}
public void moveUp() { depth--; currentTag = (Tag) stack.pop();
}
/* get tag name from currentTag */ public String getNodeName() { return currentTag.tag; }
/* get tag value from currentTag */ public String getValue() { return String.valueOf(currentTag.value); }
/* test if there has more*/ public boolean hasMoreChildren() { //test for map or list Tag test = (Tag) stack.get(depth - 1); if(test.tag.equalsIgnoreCase(ProtocalTag.TAG_MAP) || test.tag.equalsIgnoreCase(ProtocalTag.TAG_LIST)){ //it's map, then get the inner object if(param == null){ //parse it param = (JSONArray)test.value; } if((innerPointer+1)<param.length()) return true; }else if(test.tag.equalsIgnoreCase(ProtocalTag.TAG_CALL) && pointer<all.length()) return true; return false; }
public void close() { try { in.close(); } catch (IOException e) { throw new StreamException(e); } }
protected int readSingleChar() throws IOException { return in.read(); }
// get value from a JSONObject, the key is a standard key private Tag parseTag(JSONObject o){ Tag t = new Tag(); for(int i=0; i < ProtocalTag.ALL_TYPED_TAGS.length; i++){ try{ t.tag = ProtocalTag.ALL_TYPED_TAGS*; t.value = o.get(t.tag); currentTag = t; return currentTag; }catch(JSONException e){} } return null; }
class Tag { protected String tag; protected Object value; public Tag(){} public Tag(String tag, Object value) { this.tag = tag; this.value = value; } }
class Param { protected JSONArray array; protected int pointer; public Param(JSONArray ja, int p) { this.array = ja; this.pointer = p; } } }
import java.io.StringReader;
import junit.framework.TestCase; import net.buffalo.protocal.io.StreamReader;
/** *
for json unit test
@author zhengxq
@see FastStreamReaderTest.java */ public class JsonStandardStreamReaderTest extends TestCase { private String simpleCall = ""; private String callWithMap = "}," + "{'string':test}" + "]"; private String hasMoreChildren = "}," + "]}]"; private String complexTest = "},"+ "{'map':}" + "]}," + "{'double':3.33}" + "]";
/* simpleCall */ public void testSimpleCall() throws Exception { StringReader reader = new StringReader(simpleCall); StreamReader streamReader = new JsonStandardStreamReader(reader); assertEquals("buffalo-call",streamReader.getNodeName()); streamReader.moveDown(); assertEquals("method",streamReader.getNodeName()); assertEquals("divide", streamReader.getValue()); streamReader.moveUp(); streamReader.moveDown(); assertEquals("double", streamReader.getNodeName()); assertEquals("1", streamReader.getValue()); streamReader.moveUp(); streamReader.moveDown(); assertEquals("double", streamReader.getNodeName()); assertEquals("2", streamReader.getValue()); }
/* callWithMap */ public void testShoudReadNested() throws Exception { StringReader reader = new StringReader(callWithMap); StreamReader streamReader = new JsonStandardStreamReader(reader); assertEquals("buffalo-call", streamReader.getNodeName()); streamReader.moveDown(); assertEquals("method", streamReader.getNodeName()); assertEquals("sum", streamReader.getValue()); streamReader.moveUp(); streamReader.moveDown(); assertEquals("int", streamReader.getNodeName()); assertEquals("1", streamReader.getValue());
}
/* hasMoreChildren */ public void testHasMoreChildren() throws Exception { StringReader reader = new StringReader(hasMoreChildren); StreamReader streamReader = new JsonStandardStreamReader(reader); assertTrue(streamReader.hasMoreChildren()); streamReader.moveDown(); //then {'method':'sum'} assertFalse(streamReader.hasMoreChildren()); streamReader.moveUp();
}
/**
more complex test.
//boolean、date、int、long、null、string、list、map、double
@author zhengxq */ public void testComplexTest() throws Exception { StringReader reader = new StringReader(complexTest); StreamReader streamReader = new JsonStandardStreamReader(reader); assertEquals("buffalo-call",streamReader.getNodeName()); assertTrue(streamReader.hasMoreChildren()); streamReader.moveDown(); //<method>fullTypeTest</method> assertEquals("method",streamReader.getNodeName()); assertEquals("fullTypeTest",streamReader.getValue()); assertFalse(streamReader.hasMoreChildren()); streamReader.moveUp();
streamReader.moveDown(); //<boolean>1</boolean> assertEquals("boolean",streamReader.getNodeName()); assertEquals("1",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<date>20100118T154212Z</date> assertEquals("date",streamReader.getNodeName()); assertEquals("20100118T154212Z",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<int>1</int> assertEquals("int",streamReader.getNodeName()); assertEquals("1",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<double>2.22</double> assertEquals("double",streamReader.getNodeName()); assertEquals("2.22",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>Hello world</string> assertEquals("string",streamReader.getNodeName()); assertEquals("Hello world",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<list>...</list> assertEquals("list",streamReader.getNodeName()); assertTrue(streamReader.hasMoreChildren());
streamReader.moveDown(); //<type></type> assertEquals("type",streamReader.getNodeName()); streamReader.moveUp();
streamReader.moveDown(); //<length>2</length> assertEquals("length",streamReader.getNodeName()); assertEquals("2",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<int>100</int> assertEquals("int",streamReader.getNodeName()); assertEquals("100",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>hi</string> assertEquals("string",streamReader.getNodeName()); assertEquals("hi",streamReader.getValue()); streamReader.moveUp();
streamReader.moveUp();//</list>
streamReader.moveDown(); //<map>...</map> assertEquals("map",streamReader.getNodeName()); assertTrue(streamReader.hasMoreChildren());
streamReader.moveDown(); //<type>java.util.HashMap</type> assertEquals("type",streamReader.getNodeName()); assertEquals("java.util.HashMap",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>key1</string> assertEquals("string",streamReader.getNodeName()); assertEquals("key1",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>value1</string> assertEquals("string",streamReader.getNodeName()); assertEquals("value1",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>key2</string> assertEquals("string",streamReader.getNodeName()); assertEquals("key2",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>value2</string> assertEquals("string",streamReader.getNodeName()); assertEquals("value2",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>java.util.ArrayList</string> assertEquals("string",streamReader.getNodeName()); assertEquals("java.util.ArrayList",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<list>...</list> assertEquals("list",streamReader.getNodeName()); assertTrue(streamReader.hasMoreChildren());
streamReader.moveDown(); //<type></type> assertEquals("type",streamReader.getNodeName()); streamReader.moveUp();
streamReader.moveDown(); //<length>3</length> assertEquals("length",streamReader.getNodeName()); assertEquals("3",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<int>1</int> assertEquals("int",streamReader.getNodeName()); assertEquals("1",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>good</string> assertEquals("string",streamReader.getNodeName()); assertEquals("good",streamReader.getValue()); streamReader.moveUp();
streamReader.moveDown(); //<string>baby</string> assertEquals("string",streamReader.getNodeName()); assertEquals("baby",streamReader.getValue()); streamReader.moveUp(); //assertEquals("list",streamReader.getNodeName());
streamReader.moveUp();//</list> assertEquals("map",streamReader.getNodeName()); streamReader.moveUp();//</map> assertEquals("buffalo-call",streamReader.getNodeName());
streamReader.moveDown(); //<double>3.33</double> assertEquals("double",streamReader.getNodeName()); assertEquals("3.33",streamReader.getValue()); streamReader.moveUp();
//assertEquals("buffalo-call",streamReader.getNodeName()); assertFalse(streamReader.hasMoreChildren()); } }
多年以后,一个贴子,引起我对Buffalo的回忆,感叹时光流逝,物是人非。。。
非常感谢楼上的推荐,昨天粗略看了下,你的beetle框架确实比较完整,值得学习,但个中的精华还没体会到,你可进一步开贴宣讲。
但我的目标不是简单的用AJAX框架,而是通过与原创作者沟通,结合自己的思考,学习和完善个人觉得比较精到的AJAX框架Buffalo
用不得改造那么累了,用我的beetle框架吧,其中基于web层ajax实现,通信协议用的就是json,可以实现java对象(包括列表等)与javascript对象透明转换,可以随意与当前流行的UI的js库整合。