[JAVA-33] convenience methods for constructing DBObject trees Created: 04/Sep/09 Updated: 02/Oct/09 Resolved: 12/Sep/09 |
|
| Status: | Closed |
| Project: | Java Driver |
| Component/s: | None |
| Affects Version/s: | None |
| Fix Version/s: | 0.10 |
| Type: | New Feature | Priority: | Major - P3 |
| Reporter: | Jason Sachs | Assignee: | Eliot Horowitz (Inactive) |
| Resolution: | Done | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Description |
|
Take some time to think about good ways to offer convenience methods for constructing DBObject trees. Obviously, literal JSON strings is one way, but it doesn't allow the use of program variables. I offer this as an example: static public class DBObjBuilder public DBObjBuilder() { this.objStack = new LinkedList<DBObject>(); }public DBObjBuilder push(DBObject obj) { this.objStack.addLast(obj); return this; }public DBObjBuilder push() { return push(new BasicDBObject()); }public DBObjBuilder pop(String key) { DBObject last = objStack.removeLast(); top().put(key, last); return this; } public DBObjBuilder pop(String... keys) DBObject _top = top(); for (int i = 0; i < n; ++i) { _top.put(keys[i], objs[i]); } return this; } public DBObjBuilder wrap(String key) { DBObject last = objStack.removeLast(); DBObject o = new BasicDBObject(); o.put(key, last); return push(o); } public DBObjBuilder wrap(String... keys) { int n = keys.length; DBObject[] objs = new DBObject[n]; for (int i = n; --i >= 0; ) { objs[i] = objStack.removeLast(); } DBObject o = new BasicDBObject(); return push(o); public DBObjBuilder setList(String key, Object... values) top().put(key, l); } This is somewhat like an RPN calculator for constructing DBObjects. DBObjBuilder msetBuilder = new DBObjBuilder(); This creates the equivalent to JSON object {"$set": {"metadata": {"foo": 1, "bar": "cleveland", "baz", [3, "Wombat", 44]}}} (running commentary: push() creates a new object on the stack; set() and setList() set a bunch of fields; wrap() pops the top object and sets a value of a new object that gets pushed on the top of the stack; get() returns the top object on the stack) |
| Comments |
| Comment by Eliot Horowitz (Inactive) [ 12/Sep/09 ] |
|
@Test(groups = {"basic"}) DBObject x = b.get(); , 'z' : { 'b' : 3 }}" ); assert( x.equals( y ) ); |
| Comment by Jason Sachs [ 04/Sep/09 ] |
|
(I did see BasicDBObjectBuilder, but it doesn't really add much functionality) |