package com.onpositive.gae.baseviewer.taskqueuehandlers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.google.appengine.api.datastore.DatastoreFailureException;
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.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
public abstract class SpecialTaskHandler extends AbstractHandler {
// private String lastKey;
public SpecialTaskHandler(int id) {
super(id);
// TODO Auto-generated constructor stub
}
protected int handleRequest(HttpServletRequest req1) {
interpreteParameters();
DatastoreService dss = DatastoreServiceFactory.getDatastoreService();
Query q = new Query(kind);
FetchOptions fo = insertParametersToQueue(q);
PreparedQuery pq = dss.prepare(q);
boolean finish = false;
if (pq.countEntities() > 0) {
boolean thrown = false;
Entity lst = null;
int readed = -1;
try {
List<Entity> arr = pq.asList(fo);
if (arr.size() > 0) {
lst = arr.get(arr.size() - 1);
} else {
finish = true;
}
ArrayList<Entity> forUpdate = new ArrayList();
for (Entity e : arr) {
boolean handled = handleEntity(e);
if (handled) {
forUpdate.add(e);
}
}
commit(dss, forUpdate);
readed = arr.size();
} catch (DatastoreFailureException e) {
thrown = true;
} catch (Throwable e) {
thrown = true;
}
// if (!finish) {
if (!thrown) {
StatisticHandler.increaseParameter(StatisticHandler.STAT_COUNT,
idJob, namespace, readed);
Key lstKey = lst.getKey();
keyString = KeyFactory.keyToString(lstKey);
}
// } else {
// return AbstractHandler.FINISH;
// }
if (thrown) {
return AbstractHandler.WITH_ERRORS;
}
} else {
finish = true;
}
if (finish) {
return AbstractHandler.FINISH;
}
return AbstractHandler.NO_ERRORS;
}
protected abstract boolean handleEntity(Entity e);
protected abstract void interpreteParameters();
protected void writeQueueParameters(Map<String, String> params) {
super.writeQueueParameters(params);
if (keyString != null && keyString.length() > 0) {
params.put(LAST_KEY_PARAM_NAME, keyString);
}
}
protected void commit(DatastoreService dss, Collection<Entity> objects) {
if (objects.size() != 0) {
dss.put(objects);
}
}
}