Skip to content

Instantly share code, notes, and snippets.

@takai
Created June 24, 2009 01:03
Show Gist options
  • Save takai/134940 to your computer and use it in GitHub Desktop.
Save takai/134940 to your computer and use it in GitHub Desktop.
package net.recompile.gae.counter;
import java.util.Iterator;
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.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
public class CounterStore {
private static final String COUNTER_KIND = "Counter";
private static final String COUNTER_VALUE = "value";
private static final DatastoreService DATASTORE_SERVICE = DatastoreServiceFactory.getDatastoreService();
private Key counterKey;
public CounterStore() {
setCounterKey();
}
public Long getAndIncrement() {
Transaction tx = DATASTORE_SERVICE.beginTransaction();
try {
Long count = getByKey(tx);
put(tx, count + 1);
tx.commit();
return count;
} catch (RuntimeException e) {
tx.rollback();
throw e;
}
}
private Long getByKey(Transaction tx) {
try {
Entity entity = DATASTORE_SERVICE.get(tx, counterKey);
return (Long) entity.getProperty(COUNTER_VALUE);
} catch (EntityNotFoundException e) {
throw new RuntimeException(e);
}
}
private Key put(Transaction tx, Long value) {
try {
Entity entity = DATASTORE_SERVICE.get(counterKey);
entity.setProperty(COUNTER_VALUE, value);
return DATASTORE_SERVICE.put(tx, entity);
} catch (EntityNotFoundException e) {
throw new RuntimeException(e);
}
}
private Entity querySingleEntity() {
Query query = new Query(COUNTER_KIND);
PreparedQuery prepared = DATASTORE_SERVICE.prepare(query);
Iterable<Entity> entries = prepared.asIterable();
Iterator<Entity> iter = entries.iterator();
if (iter.hasNext()) {
return iter.next();
} else {
return null;
}
}
private void setCounterKey() {
Entity entry = querySingleEntity();
if (entry != null) {
counterKey = entry.getKey();
} else {
Entity entity = new Entity(COUNTER_KIND);
entity.setProperty(COUNTER_VALUE, Long.valueOf(0));
counterKey = DATASTORE_SERVICE.put(entity);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment