package com.onpositive.gae.baseviewer.impl;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Blob;
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.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;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.Text;
import com.onpositive.auth.SessionManager;
import com.onpositive.gae.baseviewer.taskqueuehandlers.AbstractHandler;
import com.onpositive.gae.baseviewer.taskqueuehandlers.StatisticHandler;
public class Request {
public static final int ADD = 1;
public static final int REMOVE = 2;
public static final int UPDATE = 3;
public static final int VIEW = 4;
public static final int GET_ENTITY = 5;
public static final int BULK_GET_ENTITY = 6;
public static final int ADD_BLOB = 7;
public static final int STORE_BLOB = 8;
public static final int REMOVE_BLOB = 9;
public static final int VIEW_BLOB = 10;
public static final int REMOVE_ALL = 11;
public static final int REMOVE_PROP = 12;
public static final int RENAME_PROP = 13;
public static final int INIT = 14;
public static final int CHECK_STATUS = 15;
public static final int COPY_ENT = 16;
public static final int INDEXATION = 17;
public static final int SET_PROP_VALUE = 18;
public static final int SET_PROP_VALUE_BY_DEF = 19;
private static byte[] bytes = new byte[0];
public static final String BLOB_KIND = "blobstore_entity";
protected ArrayList<RequestPart> parts = new ArrayList<RequestPart>();
private DataOutputStream stream;
private String key;
private boolean local;
private static HttpServletResponse resp;
private static String namespace;
public abstract static class RequestPart {
public RequestPart(DataInputStream str) {
}
public abstract void run(Request r) throws IOException;
}
public static abstract class QueueRequestPart extends RequestPart {
protected Map<String, String> parameters = new HashMap();
protected String kind;
protected String jobId;
public QueueRequestPart(DataInputStream str) {
super(str);
try {
kind = str.readUTF();
jobId = StatisticHandler.initStatistic(kind, namespace,
getType());
parameters.put(AbstractHandler.KIND_PARAM_NAME, kind);
parameters.put(AbstractHandler.NAMESPACE_PARAM_NAME, namespace);
parameters.put(AbstractHandler.JOB_ID_PARAM_NAME, jobId);
parameters.put(AbstractHandler.TYPE_PARAM_NAME, INIT + "");
parameters.put(AbstractHandler.INIT_TYPE_PARAM_NAME, getType()
+ "");
} catch (IOException e) {
e.printStackTrace();
}
}
protected abstract int getType();
protected abstract void initParametersMap();
@Override
public void run(Request r) throws IOException {
try {
//System.out.println("RUN START");
initParametersMap();
addTaskToQueue(parameters);
//System.out.println("TASK ADDED");
r.stream.writeInt(0);
r.stream.writeUTF(jobId);
//System.out.println("ID Written");
} catch (Throwable e) {
r.stream.writeInt(1);
r.stream.writeUTF(e.getMessage());
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
printWriter.close();
r.stream.writeUTF(stringWriter.toString());
//System.out.println("EXCEPTION Caught");
}
}
}
public static void addTaskToQueue(Map<String, String> params) {
TaskQueeAccess.addTaskToQueue(params);
}
public static class CopyEntityRequestPart extends QueueRequestPart {
private String key;
private int count;
public CopyEntityRequestPart(DataInputStream str) {
super(str);
try {
count = str.readInt();
key = str.readUTF();
Key kkk = KeyFactory.stringToKey(key);
Key modded = cloneCorrectKey(kkk);
key = KeyFactory.keyToString(modded);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected int getType() {
return COPY_ENT;
}
@Override
protected void initParametersMap() {
parameters.put(AbstractHandler.PROP_FIRST_PARAM_NAME, key);
parameters.put(AbstractHandler.PROP_SECOND_PARAM_NAME, count + "");
parameters.put(AbstractHandler.PRE_CALCULATED_TOTAL_PARAM_NAME,
count + "");
}
}
public static class CheckStatusRequestPart extends RequestPart {
private String id;
public CheckStatusRequestPart(DataInputStream str) {
super(str);
try {
id = str.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(Request r) throws IOException {
Entity e = StatisticHandler.getStatistic(id, namespace);
EntityAccess.writeEntityToStream(e, r.stream);
}
}
public static class RemoveAllRequestPart extends QueueRequestPart {
public RemoveAllRequestPart(DataInputStream str) {
super(str);
}
@Override
protected int getType() {
return REMOVE_ALL;
}
@Override
protected void initParametersMap() {
}
}
public static class ChangeIndexationRequestPart extends QueueRequestPart {
private String property;
private boolean makeUnindexed;
public ChangeIndexationRequestPart(DataInputStream str) {
super(str);
try {
property = str.readUTF();
makeUnindexed = str.readBoolean();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected int getType() {
return INDEXATION;
}
@Override
protected void initParametersMap() {
parameters.put(AbstractHandler.PROP_FIRST_PARAM_NAME, property);
parameters.put(AbstractHandler.PROP_SECOND_PARAM_NAME,
makeUnindexed + "");
}
}
public static class SetPropValueRequestPart extends QueueRequestPart {
private String property;
private boolean setDefault;
private Entity object;
public SetPropValueRequestPart(DataInputStream str) {
super(str);
try {
property = str.readUTF();
setDefault = str.readBoolean();
object = EntityAccess.read(str);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected int getType() {
return SET_PROP_VALUE;
}
@Override
protected void initParametersMap() {
StatisticHandler.setTmpStoredObjec(jobId, property,
object.getProperty(property), namespace);
parameters.put(AbstractHandler.PROP_FIRST_PARAM_NAME, property);
parameters.put(AbstractHandler.PROP_SECOND_PARAM_NAME, setDefault
+ "");
}
}
public static class RenamePropRequestPart extends QueueRequestPart {
private String oldProp;
private String newProp;
public RenamePropRequestPart(DataInputStream str) {
super(str);
try {
oldProp = str.readUTF();
newProp = str.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected int getType() {
return RENAME_PROP;
}
@Override
protected void initParametersMap() {
parameters.put(AbstractHandler.PROP_FIRST_PARAM_NAME, oldProp);
parameters.put(AbstractHandler.PROP_SECOND_PARAM_NAME, newProp);
}
}
public static class RemovePropRequestPart extends QueueRequestPart {
private String prop;
public RemovePropRequestPart(DataInputStream str) {
super(str);
try {
prop = str.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected int getType() {
return REMOVE_PROP;
}
@Override
protected void initParametersMap() {
parameters.put(AbstractHandler.PROP_FIRST_PARAM_NAME, prop);
}
}
public static abstract class BlobRequestPart extends RequestPart {
public static final String BLOBKEY_PROP = "blobKey";
public static final String FILENAME_PROP = "fileName";
public static final String SIZEF_PROP = "size";
public static final String DATE_PROP = "created_at";
public static final String CONTENT_PROP = "content_type";
public BlobRequestPart(DataInputStream str) {
super(str);
}
}
public static class StoreBlobPart extends BlobRequestPart {
Entity readed;
public StoreBlobPart(DataInputStream str) {
super(str);
try {
//System.out.println("STORE (init): ");
readed = EntityAccess.read(str);
} catch (IOException e) {
//System.out.println("STORE (init): exception");
e.printStackTrace();
}
}
public void run(Request r) throws IOException {
BlobstoreService bss = BlobstoreServiceFactory
.getBlobstoreService();
BlobKey key = (BlobKey) readed.getProperty(BLOBKEY_PROP);
//System.out.println("STORE (key): " + key);
if (resp != null) {
// System.out.println("STORE (key): resp != null");
bss.serve(key, resp);
}
}
}
public static class AddBlobPart extends BlobRequestPart {
private String readed;
public AddBlobPart(DataInputStream str) {
super(str);
try {
//System.out.println("ADD BLOB request part created");
BufferedReader br = new BufferedReader(new InputStreamReader(
str));
readed = br.readLine();
//System.out.println("ADD BLOB init string created");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(Request r) throws IOException {
BlobstoreService bss = BlobstoreServiceFactory
.getBlobstoreService();
//System.out.println("URL Transform begin");
String modified = bss.createUploadUrl(readed);
//System.out.println("URL Transform end");
r.stream.writeInt(modified.length());
//System.out.println("!");
r.stream.write(modified.getBytes());
//System.out.println("!!");
//System.out.println("All written");
}
}
public static class ViewBlobPart extends BlobRequestPart {
int limit;
public ViewBlobPart(DataInputStream str) {
super(str);
try {
limit = str.readInt();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(Request r) throws IOException {
BlobInfoFactory bif = new BlobInfoFactory(
DatastoreServiceFactory.getDatastoreService());
Iterator<BlobInfo> i = bif.queryBlobInfos();
List<BlobInfo> res = new ArrayList();
// System.out.println("VIEW BLOB BEGIN");
while (i.hasNext()) {
BlobInfo bi = i.next();
res.add(bi);
// System.out.println("RES " + bi.getBlobKey().getKeyString());
}
long l0 = System.currentTimeMillis();
try {
if (limit > 0) {
for (BlobInfo b : res) {
BlobKey bk = b.getBlobKey();
String filename = b.getFilename();
Entity ne = new Entity(BLOB_KIND);
ne.setProperty(FILENAME_PROP, filename);
ne.setProperty(BLOBKEY_PROP, bk);
ne.setProperty(SIZEF_PROP, b.getSize());
ne.setProperty(DATE_PROP, b.getCreation());
ne.setProperty(CONTENT_PROP, b.getContentType());
r.stream.writeInt(1);
EntityAccess.writeEntityToStream(ne, r.stream);
long l2 = System.currentTimeMillis();
if ((l2 - l0) > 15000) {
r.stream.flush();
}
if ((l2 - l0) > 25000) {
r.stream.writeInt(3);
r.stream.writeLong(l2 - l0);
}
}
}
} catch (Throwable e) {
r.stream.writeInt(2);
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
r.stream.writeUTF(e.getMessage());
r.stream.writeUTF(out.toString());
long l1 = System.currentTimeMillis();
r.stream.writeLong(l1 - l0);
} finally {
r.stream.writeInt(0);
long l1 = System.currentTimeMillis();
r.stream.writeLong(l1 - l0);
// System.out.println("VIEW BLOB END");
}
}
}
public static class RemoveBlobPart extends BlobRequestPart {
private Entity readed;
public RemoveBlobPart(DataInputStream str) {
super(str);
try {
//System.out.println("READ ENTITY");
readed = EntityAccess.read(str);
} catch (IOException e) {
//System.out.println("EXC!!!");
e.printStackTrace();
}
}
public void run(Request r) throws IOException {
//System.out.println("RUN REMOVING!!!");
BlobKey key = (BlobKey) readed.getProperty(BLOBKEY_PROP);
//System.out.println("Key to Removing " + key);
BlobstoreService bss = BlobstoreServiceFactory
.getBlobstoreService();
bss.delete(key);
}
}
public static class AddPart extends RequestPart {
private Entity read;
public AddPart(DataInputStream str) throws IOException {
super(str);
//System.out.println("1_READ!!! ADD");
Entity readed = EntityAccess.read(str);
Key oldK = readed.getKey();
Key newK = null;
if (!oldK.isComplete()) {
Key pKey = readed.getParent();
if (pKey != null) {
Key modded = cloneCorrectKey(pKey);
read = new Entity(readed.getKind(), modded);
} else {
read = new Entity(readed.getKind());
}
read.setPropertiesFrom(readed);
} else {
//System.out.println("ADD PART CLONE KEY old: "
// + KeyFactory.keyToString(oldK));
newK = cloneCorrectKey(oldK);
//System.out.println("ADD PART CLONE KEY new: "
// + KeyFactory.keyToString(newK));
read = new Entity(newK);
read.setPropertiesFrom(readed);
}
}
public void run(Request r) {
if (read.hasProperty("$$OLD_KEY_SET")) {
Key c = (Key) read.getProperty("$$OLD_KEY"
+ Entity.KEY_RESERVED_PROPERTY);
read.removeProperty("$$OLD_KEY_SET");
read.removeProperty("$$OLD_KEY" + Entity.KEY_RESERVED_PROPERTY);
if (c != null) {
DatastoreServiceFactory.getDatastoreService().put(read);
DatastoreServiceFactory.getDatastoreService().delete(c);
}
} else {
DatastoreServiceFactory.getDatastoreService().put(read);
}
}
}
public static class RemovePart extends RequestPart {
private Entity read;
public RemovePart(DataInputStream str) throws IOException {
super(str);
read = EntityAccess.read(str);
}
public void run(Request r) {
String nsp = NamespaceManager.get();
//System.out.println("NSP " + nsp);
Key modded = cloneCorrectKey(read.getKey());
DatastoreServiceFactory.getDatastoreService().delete(modded);
}
}
public static class UpdatePart extends RequestPart {
private Entity read;
public UpdatePart(DataInputStream str) throws IOException {
super(str);
read = EntityAccess.read(str);
}
public void run(Request r) {
Key oldK = read.getKey();
// System.out.println("UPDATE PART CLONE KEY new: "
// +KeyFactory.keyToString(oldK));
Key mod = cloneCorrectKey(oldK);
// System.out.println("UPDATE PART CLONE KEY new: "
// +KeyFactory.keyToString(mod));
Entity newE = new Entity(mod);
if (read.hasProperty("$$OLD_KEY_SET")) {
//System.out.println("OLD KEY SET!!!");
Key c = (Key) read.getProperty("$$OLD_KEY"
+ Entity.KEY_RESERVED_PROPERTY);
read.removeProperty("$$OLD_KEY_SET");
read.removeProperty("$$OLD_KEY" + Entity.KEY_RESERVED_PROPERTY);
newE.setPropertiesFrom(read);
if (c != null) {
DatastoreServiceFactory.getDatastoreService().put(newE);
DatastoreServiceFactory.getDatastoreService().delete(c);
}
} else {
// System.out.println("JUST STOREs!!!");
newE.setPropertiesFrom(read);
DatastoreServiceFactory.getDatastoreService().put(newE);
}
}
}
public static Key cloneCorrectKey(Key oldK) {
Key parent = oldK.getParent();
if (parent != null) {
parent = cloneCorrectKey(parent);
}
if (oldK.isComplete()) {
long id = oldK.getId();
try {
if (id == 0) {
Key tmp = KeyFactory.createKey(parent, oldK.getKind(),
oldK.getName());
return tmp;
} else {
Key tmp = KeyFactory.createKey(parent, oldK.getKind(),
oldK.getId());
return tmp;
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public static class BulkGetEntry extends RequestPart {
private Entity read;
public BulkGetEntry(DataInputStream str) throws IOException {
super(str);
str.readInt();
read = EntityAccess.read(str);
}
public void run(Request r) throws IOException {
Iterable<Key> property = (Collection<Key>) read.getProperty("key");
Map<Key, Entity> entity = DatastoreServiceFactory
.getDatastoreService().get(property);
r.stream.writeInt(entity.size());
for (Entity e : entity.values()) {
EntityAccess.writeEntityToStream(e, r.stream);
}
}
}
public static class GetEntry extends RequestPart {
private Entity read;
public GetEntry(DataInputStream str) throws IOException {
super(str);
read = EntityAccess.read(str);
}
public void run(Request r) throws IOException {
try {
Entity entity = DatastoreServiceFactory.getDatastoreService()
.get(read.getKey());
r.stream.writeInt(1);
EntityAccess.writeEntityToStream(entity, r.stream);
} catch (EntityNotFoundException e) {
r.stream.writeInt(2);
}
}
}
public static class ViewPart extends RequestPart {
private String kind;
private Entity filters;
private String orderBy;
private boolean ascending;
private boolean keysonly;
private boolean count;
private Key key;
private int limit;
private boolean isForStoring;
public ViewPart(DataInputStream str) throws IOException {
super(str);
//System.out.println("CREATION START");
kind = str.readUTF();
orderBy = str.readUTF();
ascending = str.readBoolean();
filters = EntityAccess.read(str);
limit = str.readInt();
String readUTF = str.readUTF();
if (readUTF.length() > 0) {
key = KeyFactory.stringToKey(readUTF);
}
keysonly = str.readBoolean();
count = str.readBoolean();
isForStoring = str.readBoolean();
//System.out.println("CREATION STOP");
}
public void run(Request r) throws IOException {
try {
// System.out.println("RUN_START");
// System.out.println("ISFORSTORING = " + isForStoring);
Query query = new Query(kind);
if (filters != null) {
for (String s : filters.getProperties().keySet()) {
if (s.startsWith("$ONPOSITIVE_FILTER_OPERATOR")) {
continue;
}
if (!s.equals(Entity.KEY_RESERVED_PROPERTY)) {
Object property = filters.getProperty(s);
Object property2 = filters
.getProperty("$ONPOSITIVE_FILTER_OPERATOR_"
+ s);
if (s.equals("ONPOSITIVE_FILTER_FOR_PRIMARY_KEY")) {
s = Entity.KEY_RESERVED_PROPERTY;
if (property instanceof Key) {
property = cloneCorrectKey((Key) property);
}
}
// System.out.println("PROP: " + s + " OPER: "
// + property2 + " VAL: " + property);
if (s.equals("ONPOSITIVE_FILTER_FOR_PARENT_KEY")) {
Key k = (Key) property;
query.setAncestor(k);
} else {
if (property2 != null) {
Long i = (Long) property2;
if (i == 0) {
query.addFilter(s,
FilterOperator.EQUAL, property);
}
if (i == 1) {
query.addFilter(s,
FilterOperator.GREATER_THAN,
property);
}
if (i == 2) {
query.addFilter(
s,
FilterOperator.GREATER_THAN_OR_EQUAL,
property);
}
if (i == 3) {
query.addFilter(s,
FilterOperator.LESS_THAN,
property);
}
if (i == 4) {
query.addFilter(
s,
FilterOperator.LESS_THAN_OR_EQUAL,
property);
}
} else {
query.addFilter(s, FilterOperator.EQUAL,
property);
}
}
}
}
}
if (orderBy != null && orderBy.length() > 0) {
query.addSort(orderBy, ascending ? SortDirection.ASCENDING
: SortDirection.DESCENDING);
}
long l0 = System.currentTimeMillis();
PreparedQuery prepare = null;
FetchOptions options = null;
if (limit != -1) {
options = FetchOptions.Builder.withLimit(limit)
.prefetchSize(limit);
}
if (keysonly) {
query.setKeysOnly();
}
prepare = DatastoreServiceFactory.getDatastoreService()
.prepare(query);
// System.out.println("EXTRACT Ents!!!!! count = "
// + prepare.countEntities() + " isforStoring ="
// + isForStoring);
Iterator<Entity> results = (options == null ? prepare
.asIterable() : prepare.asIterable(options)).iterator();
int countEntities = prepare.countEntities();
if (prepare.countEntities() < limit && orderBy != null
&& orderBy.length() > 0
&& !orderBy.equals(Entity.KEY_RESERVED_PROPERTY)) {
Query qq = new Query(kind);
if (query.getAncestor() != null) {
qq.setAncestor(query.getAncestor());
}
List<FilterPredicate> fp = query.getFilterPredicates();
for (FilterPredicate fpred : fp) {
qq.addFilter(fpred.getPropertyName(),
fpred.getOperator(), fpred.getValue());
}
Iterator<Entity> iter1 = results;
FetchOptions newNo = null;
if (limit > 0) {
newNo = FetchOptions.Builder.withLimit(limit);
}
prepare = DatastoreServiceFactory.getDatastoreService()
.prepare(qq);
Iterator<Entity> iter2 = (newNo == null ? prepare
.asIterable() : prepare.asIterable(newNo))
.iterator();
ArrayList<Entity> ress = new ArrayList<Entity>();
while (iter1.hasNext()) {
ress.add(iter1.next());
}
while (iter2.hasNext()) {
Entity tmp = iter2.next();
if (!ress.contains(tmp)) {
ress.add(tmp);
}
}
countEntities = ress.size();
results = ress.iterator();
}
if (count) {
r.stream.writeInt(6);
r.stream.writeInt(countEntities);
}
// Iterator<Entity> it = (options == null ? prepare.asIterable()
// : prepare.asIterable(options)).iterator();
try {
int maxSize = 1000;
try {
// System.out.println("EXTRACT Ents!!!!! Loop Start");
while (results.hasNext()) {
Entity next = results.next();
// System.out
// .println("EXTRACT Ents!!!!! CLEANUP_START");
cleanup(next, isForStoring);
// System.out.println("EXTRACT Ents!!!!! CLEANUP_END");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
maxSize);
DataOutputStream stream2 = new DataOutputStream(
byteArrayOutputStream);
EntityAccess.writeEntityToStream(next, stream2);
stream2.close();
byte[] byteArray = byteArrayOutputStream
.toByteArray();
if (r.stream.size() + byteArray.length > 10 * 1000 * 1000) {
r.stream.writeInt(2);
r.stream.writeUTF("Max response size exceeded");
r.stream.writeUTF("");
long l1 = System.currentTimeMillis();
r.stream.writeLong(l1 - l0);
break;
}
r.stream.writeInt(1);
r.stream.write(byteArray);
long l2 = System.currentTimeMillis();
if ((l2 - l0) > 15000) {
r.stream.flush();
}
if ((l2 - l0) > 25000) {
r.stream.writeInt(3);
r.stream.writeLong(l2 - l0);
}
}
} catch (Throwable e) {
// System.out.println("EXCEPTION THROWABLE 1 " + e);
r.stream.writeInt(2);
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
r.stream.writeUTF(e.getMessage());
r.stream.writeUTF(out.toString());
long l1 = System.currentTimeMillis();
r.stream.writeLong(l1 - l0);
}
} finally {
r.stream.writeInt(0);
long l1 = System.currentTimeMillis();
r.stream.writeLong(l1 - l0);
}
} catch (Throwable e) {
// System.out.println("EXCEPTION THROWABLE 2 " + e);
r.stream.writeInt(5);
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
if (e.getMessage() != null && e.getMessage().length() != 0) {
r.stream.writeUTF(e.getMessage());
} else {
r.stream.writeUTF("no message");
}
r.stream.writeUTF(out.toString());
}
}
}
public Request(DataInputStream stream,
ServletOutputStream servletOutputStream, HttpServletRequest req,
HttpServletResponse resp) throws IOException {
this.stream = new DataOutputStream(servletOutputStream);
key = stream.readUTF();
local = SessionManager.isLocal(req);
this.resp = resp;
int count = stream.readInt();
namespace = stream.readUTF();
//namespace = "";
NamespaceManager.set(namespace);
for (int a = 0; a < count; a++) {
int readInt = stream.readInt();
if (readInt != CHECK_STATUS) {
// System.out.println("CODE <" + readInt + "> NAMESPACE <"
// + namespace + "> key <" + key + "> local <" + local
// + "> count <" + count);
}
/* System.out.println("CODE: " + readInt); */
switch (readInt) {
case ADD:
parts.add(new AddPart(stream));
break;
case REMOVE:
parts.add(new RemovePart(stream));
break;
case UPDATE:
parts.add(new UpdatePart(stream));
break;
case VIEW:
/*System.out.println("VIEW");*/
parts.add(new ViewPart(stream));
break;
case GET_ENTITY:
parts.add(new GetEntry(stream));
break;
case BULK_GET_ENTITY:
parts.add(new BulkGetEntry(stream));
break;
case VIEW_BLOB:
parts.add(new ViewBlobPart(stream));
break;
case ADD_BLOB:
parts.add(new AddBlobPart(stream));
break;
case REMOVE_BLOB:
parts.add(new RemoveBlobPart(stream));
break;
case STORE_BLOB:
parts.add(new StoreBlobPart(stream));
break;
case REMOVE_ALL:
parts.add(new RemoveAllRequestPart(stream));
break;
case RENAME_PROP:
parts.add(new RenamePropRequestPart(stream));
break;
case REMOVE_PROP:
parts.add(new RemovePropRequestPart(stream));
break;
case CHECK_STATUS:
parts.add(new CheckStatusRequestPart(stream));
break;
case COPY_ENT:
parts.add(new CopyEntityRequestPart(stream));
break;
case INDEXATION:
parts.add(new ChangeIndexationRequestPart(stream));
break;
case SET_PROP_VALUE:
case SET_PROP_VALUE_BY_DEF:
parts.add(new SetPropValueRequestPart(stream));
default:
/*System.out.println("DEF");*/
break;
}
}
}
public static void cleanup(Entity next, boolean isForStoring) {
Map<String, Object> properties = next.getProperties();
HashSet<String> shortened = new HashSet<String>();
HashMap<String, Object> toPatch = null;
for (String e : properties.keySet()) {
if (e.equals(Entity.KEY_RESERVED_PROPERTY)) {
continue;
}
Object value = properties.get(e);
// System.out.println("EEEE1 = " + e + " BEFORECHECK = " + value);
Object afterCheck = check(value, shortened, isForStoring);
// System.out.println("EEEE1 = " + e + " AFTERCHECK = " +
// afterCheck);
if (value != null && !afterCheck.equals(value)) {
// System.out.println("EEEE1 = " + e + " ISFORSTORING = "
// + isForStoring);
if (toPatch == null) {
toPatch = new HashMap<String, Object>();
}
toPatch.put(e, afterCheck);
}
}
StringBuilder bld = new StringBuilder();
if (toPatch != null) {
for (String s : toPatch.keySet()) {
// System.out.println("EEEE2 = " + s + " ISFORSTORING = "
// + isForStoring);
Object property = next.getProperty(s);
if (property instanceof Blob) {
bld.append(s);
bld.append('=');
bld.append(property.toString());
bld.append(',');
}
next.setProperty(s, toPatch.get(s));
}
if (bld.length() > 0) {
bld = bld.deleteCharAt(bld.length() - 1);
}
// System.out.println("EEEE3 = ONPOSITIVE_MAGIC_SHORTENED_PROPERTIES"
// + bld.toString() + " ISFORSTORING = " + isForStoring);
next.setProperty("ONPOSITIVE_MAGIC_SHORTENED_PROPERTIES",
bld.toString());
}
}
private static Object check(Object value, HashSet<String> shortened,
boolean isForStoring) {
if (value instanceof Collection<?>) {
ArrayList<Object> m = new ArrayList<Object>();
boolean hasChanged = false;
for (Object o : (Collection<?>) value) {
Object check = check(o, shortened, isForStoring);
if (check != o) {
hasChanged = true;
}
m.add(check);
}
if (hasChanged) {
return m;
}
return value;
}
if (value instanceof Text) {
Text t = (Text) value;
String value2 = t.getValue();
if (value2.length() > 1000 && !isForStoring) {
return new Text(value2.substring(0, 100) + "...");
}
}
if (value instanceof Blob) {
if (!isForStoring) {
return new Blob(bytes);
}
}
return value;
}
public boolean run() throws IOException {
// System.out.println("RUN!!!");
if (!local) {
boolean acceptableKey = SessionManager.isAcceptableKey(key);
if (!acceptableKey) {
stream.writeInt(500);
return true;
}
}
stream.writeInt(200);
// System.out.println("RUN Parts");
boolean flg = true;
for (RequestPart p : parts) {
if (p instanceof BlobRequestPart) {
flg = false;
}
p.run(this);
}
return flg;
}
}