Skip to content

Instantly share code, notes, and snippets.

@iamnoah
Created May 22, 2011 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamnoah/985125 to your computer and use it in GitHub Desktop.
Save iamnoah/985125 to your computer and use it in GitHub Desktop.
Simple DSL for creating GAE Entities
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
/**
* Example (groovy syntax, but works just as well in Java):
* <pre>
EntityBuilder.build("Library").
key(key). // can create your own Key instance
child("Owner").
p("books",[123,456]).
p('name','Joe Blow').
finish().
child("Book").
key(456).
finish().
child("Book").
key(123).
p('title','Eating Animals')
child("Chapter").
p('name','How to serve man').
finish().
child("Chapter").
p('name','How to serve pig').
finish()
</pre>
*
* @author noah
*
*/
public class EntityBuilder {
public class SubEntityBuilder {
public KeyBuilder child(String kind) {
return new EntityBuilder(kind, EntityBuilder.this).key();
}
public SubEntityBuilder finish() {
return EntityBuilder.this.finish();
}
}
public class KeyBuilder {
public EntityBuilder key(Key key) {
entity = new Entity(key);
return EntityBuilder.this;
}
public EntityBuilder key(long key) {
entity = parent == null ?
new Entity(kind, key) :
new Entity(kind, key, parent.entity.getKey());
return EntityBuilder.this;
}
public EntityBuilder name(String name) {
entity = parent == null ?
new Entity(kind, name) :
new Entity(kind, name, parent.entity.getKey());
return EntityBuilder.this;
}
public EntityBuilder p(String name, Object value) {
defaultKey();
return EntityBuilder.this.p(name, value);
}
private void defaultKey() {
entity = parent == null ?
new Entity(EntityBuilder.this.kind) :
new Entity(kind, parent.entity.getKey());
}
public KeyBuilder child(String kind) {
defaultKey();
return new EntityBuilder(kind, EntityBuilder.this).key();
}
}
private String kind;
private EntityBuilder(String kind,EntityBuilder parent) {
super();
this.datastore = DatastoreServiceFactory.getDatastoreService();
this.parent = parent;
this.kind = kind;
}
public static KeyBuilder build(String kind) {
return new EntityBuilder(kind,null).key();
}
private KeyBuilder key() {
return new KeyBuilder();
}
private Entity entity;
private final EntityBuilder parent;
private final DatastoreService datastore;
public EntityBuilder p(String name, Object value) {
entity.setProperty(name, value);
return this;
}
public KeyBuilder child(String kind) {
finish();
return new SubEntityBuilder().child(kind);
}
public SubEntityBuilder finish() {
datastore.put(entity);
return parent == null ? null :
parent.new SubEntityBuilder();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment