initial add of EbeanORM server based on v2.8.1

This commit is contained in:
rbygrave committed 2012-09-14 00:40:39 +12:00
1 parent 2b74d0f9d9
commit 96ce4c0ddf
1188 files changed
+135034

No files matched your search

@@ -0,0 +1,326 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.avaje.ebean.text.TextException;
import com.avaje.ebean.text.json.JsonContext;
import com.avaje.ebean.text.json.JsonElement;
import com.avaje.ebean.text.json.JsonReadOptions;
import com.avaje.ebean.text.json.JsonValueAdapter;
import com.avaje.ebean.text.json.JsonWriteOptions;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.type.EscapeJson;
import com.avaje.ebeaninternal.util.ParamTypeHelper;
import com.avaje.ebeaninternal.util.ParamTypeHelper.ManyType;
import com.avaje.ebeaninternal.util.ParamTypeHelper.TypeInfo;
/**
* Default implementation of JsonContext.
*
* @author rbygrave
*/
public class DJsonContext implements JsonContext {
private final SpiEbeanServer server;
private final JsonValueAdapter dfltValueAdapter;
private final boolean dfltPretty;
public DJsonContext(SpiEbeanServer server, JsonValueAdapter dfltValueAdapter, boolean dfltPretty){
this.server = server;
this.dfltValueAdapter = dfltValueAdapter;
this.dfltPretty = dfltPretty;
}
public boolean isSupportedType(Type genericType) {
return server.isSupportedType(genericType);
}
private ReadJsonSource createReader(Reader jsonReader) {
return new ReadJsonSourceReader(jsonReader, 256, 512);
}
public <T> T toBean(Class<T> cls, String json){
return toBean(cls, new ReadJsonSourceString(json), null);
}
public <T> T toBean(Class<T> cls, Reader jsonReader) {
return toBean(cls, createReader(jsonReader), null);
}
public <T> T toBean(Class<T> cls, String json, JsonReadOptions options){
return toBean(cls, new ReadJsonSourceString(json), options);
}
public <T> T toBean(Class<T> cls, Reader jsonReader, JsonReadOptions options) {
return toBean(cls, createReader(jsonReader), options);
}
private <T> T toBean(Class<T> cls, ReadJsonSource src, JsonReadOptions options){
BeanDescriptor<T> d = getDecriptor(cls);
ReadJsonContext ctx = new ReadJsonContext(src, dfltValueAdapter, options);
return d.jsonReadBean(ctx, null);
}
public <T> List<T> toList(Class<T> cls, String json){
return toList(cls, new ReadJsonSourceString(json), null);
}
public <T> List<T> toList(Class<T> cls, String json, JsonReadOptions options){
return toList(cls, new ReadJsonSourceString(json), options);
}
public <T> List<T> toList(Class<T> cls, Reader jsonReader){
return toList(cls, createReader(jsonReader), null);
}
public <T> List<T> toList(Class<T> cls, Reader jsonReader, JsonReadOptions options){
return toList(cls, createReader(jsonReader), options);
}
private <T> List<T> toList(Class<T> cls, ReadJsonSource src, JsonReadOptions options){
try {
BeanDescriptor<T> d = getDecriptor(cls);
List<T> list = new ArrayList<T>();
ReadJsonContext ctx = new ReadJsonContext(src, dfltValueAdapter, options);
ctx.readArrayBegin();
do {
T bean = d.jsonReadBean(ctx, null);
if (bean != null){
list.add(bean);
}
if (!ctx.readArrayNext()){
break;
}
} while(true);
return list;
} catch (RuntimeException e){
throw new TextException("Error parsing "+src, e);
}
}
public Object toObject(Type genericType, String json, JsonReadOptions options) {
TypeInfo info = ParamTypeHelper.getTypeInfo(genericType);
Class<?> beanType = info.getBeanType();
if (JsonElement.class.isAssignableFrom(beanType)){
return InternalJsonParser.parse(json);
}
ManyType manyType = info.getManyType();
switch (manyType) {
case NONE:
return toBean(info.getBeanType(), json, options);
case LIST:
return toList(info.getBeanType(), json, options);
default:
String msg = "ManyType "+manyType+" not supported yet";
throw new TextException(msg);
}
}
public Object toObject(Type genericType, Reader json, JsonReadOptions options) {
TypeInfo info = ParamTypeHelper.getTypeInfo(genericType);
Class<?> beanType = info.getBeanType();
if (JsonElement.class.isAssignableFrom(beanType)){
return InternalJsonParser.parse(json);
}
ManyType manyType = info.getManyType();
switch (manyType) {
case NONE:
return toBean(info.getBeanType(), json, options);
case LIST:
return toList(info.getBeanType(), json, options);
default:
String msg = "ManyType "+manyType+" not supported yet";
throw new TextException(msg);
}
}
public void toJsonWriter(Object o, Writer writer) {
toJsonWriter(o, writer, dfltPretty, null, null);
}
public void toJsonWriter(Object o, Writer writer, boolean pretty) {
toJsonWriter(o, writer, pretty, null, null);
}
public void toJsonWriter(Object o, Writer writer, boolean pretty, JsonWriteOptions options){
toJsonWriter(o, writer, pretty, null, null);
}
public void toJsonWriter(Object o, Writer writer, boolean pretty, JsonWriteOptions options, String callback) {
toJsonInternal(o, new WriteJsonBufferWriter(writer), pretty, options, callback);
}
public String toJsonString(Object o){
return toJsonString(o, dfltPretty, null);
}
public String toJsonString(Object o, boolean pretty){
return toJsonString(o, pretty, null);
}
public String toJsonString(Object o, boolean pretty, JsonWriteOptions options){
return toJsonString(o, pretty, options, null);
}
public String toJsonString(Object o, boolean pretty, JsonWriteOptions options, String callback){
WriteJsonBufferString b = new WriteJsonBufferString();
toJsonInternal(o, b, pretty, options, callback);
return b.getBufferOutput();
}
@SuppressWarnings("unchecked")
private void toJsonInternal(Object o, WriteJsonBuffer buffer, boolean pretty, JsonWriteOptions options, String requestCallback){
if (o == null){
buffer.append("null");
} else if (o instanceof Number) {
buffer.append(o.toString());
} else if (o instanceof Boolean) {
buffer.append(o.toString());
} else if (o instanceof String) {
EscapeJson.escapeQuote(o.toString(), buffer);
} else if (o instanceof JsonElement) {
} else if (o instanceof Map<?,?>){
toJsonFromMap((Map<Object,Object>)o, buffer, pretty, options, requestCallback);
} else if (o instanceof Collection<?>){
toJsonFromCollection((Collection<?>)o, buffer, pretty, options, requestCallback);
} else {
BeanDescriptor<?> d = getDecriptor(o.getClass());
WriteJsonContext ctx = new WriteJsonContext(buffer, pretty, dfltValueAdapter, options, requestCallback);
d.jsonWrite(ctx, o);
ctx.end();
}
}
private <T> void toJsonFromCollection(Collection<T> c, WriteJsonBuffer buffer, boolean pretty,
JsonWriteOptions options, String requestCallback){
Iterator<T> it = c.iterator();
if (!it.hasNext()){
buffer.append("[]");
return;
}
WriteJsonContext ctx = new WriteJsonContext(buffer, pretty, dfltValueAdapter, options, requestCallback);
Object o = it.next();
BeanDescriptor<?> d = getDecriptor(o.getClass());
ctx.appendArrayBegin();
d.jsonWrite(ctx, o);
while (it.hasNext()) {
ctx.appendComma();
T t = it.next();
d.jsonWrite(ctx, t);
}
ctx.appendArrayEnd();
ctx.end();
}
private void toJsonFromMap(Map<Object,Object> map, WriteJsonBuffer buffer, boolean pretty,
JsonWriteOptions options, String requestCallback){
if (map.isEmpty()){
buffer.append("{}");
return;
}
WriteJsonContext ctx = new WriteJsonContext(buffer, pretty, dfltValueAdapter, options, requestCallback);
Set<Entry<Object,Object>> entrySet = map.entrySet();
Iterator<Entry<Object, Object>> it = entrySet.iterator();
Entry<Object, Object> entry = it.next();
ctx.appendObjectBegin();
toJsonMapKey(buffer, false, entry.getKey());
toJsonMapValue(buffer, pretty, options, requestCallback, entry.getValue());
while (it.hasNext()) {
entry = it.next();
ctx.appendComma();
toJsonMapKey(buffer, pretty, entry.getKey());
toJsonMapValue(buffer, pretty, options, requestCallback, entry.getValue());
}
ctx.appendObjectEnd();
ctx.end();
}
private void toJsonMapKey(WriteJsonBuffer buffer, boolean pretty, Object key) {
if (pretty){
buffer.append("\n");
}
buffer.append("\"");
buffer.append(key.toString());
buffer.append("\":");
}
private void toJsonMapValue(WriteJsonBuffer buffer, boolean pretty, JsonWriteOptions options, String requestCallback,
Object value) {
if (value == null){
buffer.append("null");
} else {
toJsonInternal(value, buffer, pretty, options, requestCallback);
}
}
private <T> BeanDescriptor<T> getDecriptor(Class<T> cls) {
BeanDescriptor<T> d = server.getBeanDescriptor(cls);
if (d == null){
String msg = "No BeanDescriptor found for "+cls;
throw new RuntimeException(msg);
}
return d;
}
}
@@ -0,0 +1,70 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import com.avaje.ebean.text.json.JsonValueAdapter;
public class DefaultJsonValueAdapter implements JsonValueAdapter {
private final SimpleDateFormat dateTimeProto;
public DefaultJsonValueAdapter(String dateTimeFormat){
this.dateTimeProto = new SimpleDateFormat(dateTimeFormat);
this.dateTimeProto.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public DefaultJsonValueAdapter(){
this("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
}
private SimpleDateFormat dtFormat() {
return (SimpleDateFormat)dateTimeProto.clone();
}
public String jsonFromDate(Date date) {
return "\""+date.toString()+"\"";
}
public String jsonFromTimestamp(Timestamp date) {
return "\""+dtFormat().format(date)+"\"";
}
public Date jsonToDate(String jsonDate) {
return Date.valueOf(jsonDate);
}
public Timestamp jsonToTimestamp(String jsonDateTime) {
try {
java.util.Date d = dtFormat().parse(jsonDateTime);
return new Timestamp(d.getTime());
} catch (Exception e) {
String m = "Error parsing Datetime["+jsonDateTime+"]";
throw new RuntimeException(m, e);
}
}
}
@@ -0,0 +1,23 @@
package com.avaje.ebeaninternal.server.text.json;
import java.io.Reader;
import com.avaje.ebean.text.json.JsonElement;
public class InternalJsonParser {
public static JsonElement parse(String s) {
ReadJsonSourceString src = new ReadJsonSourceString(s);
ReadBasicJsonContext b = new ReadBasicJsonContext(src);
return ReadJsonRawReader.readJsonElement(b);
}
public static JsonElement parse(Reader s) {
ReadJsonSourceReader src = new ReadJsonSourceReader(s, 512, 256);
ReadBasicJsonContext b = new ReadBasicJsonContext(src);
return ReadJsonRawReader.readJsonElement(b);
}
}
@@ -0,0 +1,45 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import com.avaje.ebeaninternal.server.util.ArrayStack;
public class PathStack extends ArrayStack<String> {
public String peekFullPath(String key){
String prefix = peekWithNull();
if (prefix != null){
return prefix+"."+key;
} else {
return key;
}
}
public void pushPathKey(String key) {
String prefix = peekWithNull();
if (prefix != null){
key = prefix+"."+key;
}
push(key);
}
}
@@ -0,0 +1,269 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import com.avaje.ebean.text.TextException;
public class ReadBasicJsonContext implements ReadJsonInterface {
private final ReadJsonSource src;
private char tokenStart;
private String tokenKey;
public ReadBasicJsonContext(ReadJsonSource src) {
this.src = src;
}
public char getToken() {
return tokenStart;
}
public String getTokenKey() {
return tokenKey;
}
public boolean isTokenKey() {
return '\"' == tokenStart;
}
public boolean isTokenObjectEnd() {
return '}' == tokenStart;
}
public boolean readObjectBegin() {
readNextToken();
if ('{' == tokenStart){
return true;
} else if ('n' == tokenStart) {
return false;
} else if (']' == tokenStart) {
// an empty array
return false;
}
throw new RuntimeException("Expected object begin at "+src.getErrorHelp());
}
public boolean readKeyNext() {
readNextToken();
if ('\"' == tokenStart){
return true;
} else if ('}' == tokenStart) {
return false;
}
throw new RuntimeException("Expected '\"' or '}' at "+src.getErrorHelp());
}
public boolean readValueNext() {
readNextToken();
if (',' == tokenStart){
return true;
} else if ('}' == tokenStart) {
return false;
}
throw new RuntimeException("Expected ',' or '}' at "+src.getErrorHelp()+" but got "+tokenStart);
}
public boolean readArrayBegin() {
readNextToken();
if ('[' == tokenStart){
return true;
} else if ('n' == tokenStart) {
return false;
}
throw new RuntimeException("Expected array begin at "+src.getErrorHelp());
}
public boolean readArrayNext() {
readNextToken();
if (',' == tokenStart){
return true;
}
if (']' == tokenStart){
return false;
}
throw new RuntimeException("Expected ',' or ']' at "+src.getErrorHelp());
}
public void readNextToken() {
ignoreWhiteSpace();
tokenStart = src.nextChar("EOF finding next token");
switch (tokenStart) {
case '"':
internalReadKey();
break;
case '{': break;
case '}': break;
case '[': break; // not expected
case ']': break; // not expected
case ',': break; // not expected
case ':': break; // not expected
case 'n':
internalReadNull();
break; // not expected
default:
throw new RuntimeException("Unexpected tokenStart["+tokenStart+"] "+src.getErrorHelp());
}
}
public String readQuotedValue() {
boolean escape = false;
StringBuilder sb = new StringBuilder();
do {
char ch = src.nextChar("EOF reading quoted value");
if (escape) {
// in escape mode so just append the character
escape = false;
switch (ch) {
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'f':
sb.append('\f');
break;
case 'b':
sb.append('\b');
break;
case '"':
sb.append('"');
break;
default:
sb.append('\\');
sb.append(ch);
break;
}
} else {
switch (ch) {
case '\\':
// put into 'escape' mode for next character
escape = true;
break;
case '"':
return sb.toString();
default:
sb.append(ch);
}
}
} while (true);
}
public String readUnquotedValue(char c) {
String v = readUnquotedValueRaw(c);
if ("null".equals(v)){
return null;
} else {
return v;
}
}
private String readUnquotedValueRaw(char c) {
StringBuilder sb = new StringBuilder();
sb.append(c);
do {
tokenStart = src.nextChar("EOF reading unquoted value");
switch (tokenStart) {
case ',':
src.back();
return sb.toString();
case '}':
src.back();
return sb.toString();
case ' ':
return sb.toString();
case '\t':
return sb.toString();
case '\r':
return sb.toString();
case '\n':
return sb.toString();
default:
sb.append(tokenStart);
}
} while (true);
}
private void internalReadNull() {
StringBuilder sb = new StringBuilder(4);
sb.append(tokenStart);
for (int i = 0; i < 3; i++) {
char c = src.nextChar("EOF reading null ");
sb.append(c);
}
if (!"null".equals(sb.toString())){
throw new TextException("Expected 'null' but got "+sb.toString()+" "+src.getErrorHelp());
}
}
private void internalReadKey() {
StringBuilder sb = new StringBuilder();
do {
char c = src.nextChar("EOF reading key");
if ('\"' == c){
tokenKey = sb.toString();
break;
} else {
sb.append(c);
}
} while (true);
ignoreWhiteSpace();
char c = src.nextChar("EOF reading ':'");
if (':' != c){
throw new TextException("Expected to find colon after key at "+(src.pos()-1)+" but found ["+c+"]"+src.getErrorHelp());
}
}
public void ignoreWhiteSpace() {
src.ignoreWhiteSpace();
}
public char nextChar() {
tokenStart = src.nextChar("EOF getting nextChar for raw json");
return tokenStart;
}
}
@@ -0,0 +1,201 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.text.json.JsonElement;
import com.avaje.ebean.text.json.JsonReadBeanVisitor;
import com.avaje.ebean.text.json.JsonReadOptions;
import com.avaje.ebean.text.json.JsonValueAdapter;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.util.ArrayStack;
public class ReadJsonContext extends ReadBasicJsonContext {
private final Map<String, JsonReadBeanVisitor<?>> visitorMap;
private final JsonValueAdapter valueAdapter;
private final PathStack pathStack;
private final ArrayStack<ReadBeanState> beanState;
private ReadBeanState currentState;
public ReadJsonContext(ReadJsonSource src, JsonValueAdapter dfltValueAdapter, JsonReadOptions options) {
super(src);
this.beanState = new ArrayStack<ReadBeanState>();
if (options == null){
this.valueAdapter = dfltValueAdapter;
this.visitorMap = null;
this.pathStack = null;
} else {
this.valueAdapter = getValueAdapter(dfltValueAdapter, options.getValueAdapter());
this.visitorMap = options.getVisitorMap();
this.pathStack = (visitorMap == null || visitorMap.isEmpty()) ? null : new PathStack();
}
}
private JsonValueAdapter getValueAdapter(JsonValueAdapter dfltValueAdapter, JsonValueAdapter valueAdapter) {
return valueAdapter == null ? dfltValueAdapter : valueAdapter;
}
public JsonValueAdapter getValueAdapter() {
return valueAdapter;
}
public String readScalarValue() {
ignoreWhiteSpace();
char prevChar = nextChar();//"EOF reading scalarValue?");
if ('"' == prevChar){
return readQuotedValue();
} else {
return readUnquotedValue(prevChar);
}
}
public void pushBean(Object bean, String path, BeanDescriptor<?> beanDescriptor){
currentState = new ReadBeanState(bean, beanDescriptor);
beanState.push(currentState);
if (pathStack != null){
pathStack.pushPathKey(path);
}
}
public ReadBeanState popBeanState() {
if (pathStack != null){
String path = pathStack.peekWithNull();
JsonReadBeanVisitor<?> beanVisitor = visitorMap.get(path);
if (beanVisitor != null){
currentState.visit(beanVisitor);
}
pathStack.pop();
}
// return the current ReadBeanState as we can't call setLoadedState()
// yet. We might bind master/detail beans together via mappedBy property
// so wait until after that before calling ReadBeanStatesetLoadedState();
ReadBeanState s = currentState;
beanState.pop();
currentState = beanState.peekWithNull();
return s;
}
public void setProperty(String propertyName){
currentState.setLoaded(propertyName);
}
/**
* Got a key that doesn't map to a known property so read the json value
* which could be json primitive, object or array.
* <p>
* Provide these values to a JsonReadBeanVisitor if registered.
* </p>
*/
public JsonElement readUnmappedJson(String key) {
JsonElement rawJsonValue = ReadJsonRawReader.readJsonElement(this);
if (visitorMap != null){
currentState.addUnmappedJson(key, rawJsonValue);
}
return rawJsonValue;
}
public static class ReadBeanState implements PropertyChangeListener {
private final Object bean;
private final BeanDescriptor<?> beanDescriptor;
private final EntityBeanIntercept ebi;
private final Set<String> loadedProps;
private Map<String,JsonElement> unmapped;
private ReadBeanState(Object bean, BeanDescriptor<?> beanDescriptor) {
this.bean = bean;
this.beanDescriptor = beanDescriptor;
if (bean instanceof EntityBean){
this.ebi = ((EntityBean)bean)._ebean_getIntercept();
this.loadedProps = new HashSet<String>();
} else {
this.ebi = null;
this.loadedProps = null;
}
}
public String toString(){
return bean.getClass().getSimpleName()+" loaded:"+loadedProps;
}
/**
* Add a loaded/set property to the set of loadedProps.
*/
public void setLoaded(String propertyName){
if (ebi != null){
loadedProps.add(propertyName);
}
}
private void addUnmappedJson(String key, JsonElement value){
if (unmapped == null){
unmapped = new LinkedHashMap<String, JsonElement>();
}
unmapped.put(key, value);
}
@SuppressWarnings("unchecked")
private <T> void visit(JsonReadBeanVisitor<T> beanVisitor) {
// listen for property change events so that
// we can update the loadedProps if necessary
if (ebi != null){
ebi.addPropertyChangeListener(this);
}
beanVisitor.visit((T)bean, unmapped);
if (ebi != null){
ebi.removePropertyChangeListener(this);
}
}
public void setLoadedState(){
if (ebi != null){
// takes into account reference beans
beanDescriptor.setLoadedProps(ebi, loadedProps);
}
}
public void propertyChange(PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
loadedProps.add(propName);
}
public Object getBean() {
return bean;
}
}
}
@@ -0,0 +1,22 @@
package com.avaje.ebeaninternal.server.text.json;
public interface ReadJsonInterface {
public void ignoreWhiteSpace();
public char nextChar();
public String getTokenKey();
public boolean readKeyNext();
public boolean readValueNext();
public boolean readArrayNext();
public String readQuotedValue();
public String readUnquotedValue(char c);
}
@@ -0,0 +1,126 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import com.avaje.ebean.text.json.JsonElementArray;
import com.avaje.ebean.text.json.JsonElementBoolean;
import com.avaje.ebean.text.json.JsonElementNull;
import com.avaje.ebean.text.json.JsonElementNumber;
import com.avaje.ebean.text.json.JsonElementObject;
import com.avaje.ebean.text.json.JsonElementString;
import com.avaje.ebean.text.json.JsonElement;
public class ReadJsonRawReader {
public static JsonElement readJsonElement(ReadJsonInterface ctx) {
return new ReadJsonRawReader(ctx).readJsonElement();
}
private final ReadJsonInterface ctx;
private ReadJsonRawReader(ReadJsonInterface ctx){
this.ctx = ctx;
}
private JsonElement readJsonElement() {
return readValue();
}
private JsonElement readValue() {
ctx.ignoreWhiteSpace();
char c = ctx.nextChar();
switch (c) {
case '{':
return readObject();
case '[':
return readArray();
case '"':
return readString();
default:
return readUnquoted(c);
}
}
private JsonElement readArray() {
JsonElementArray a = new JsonElementArray();
do {
JsonElement value = readValue();
a.add(value);
if (!ctx.readArrayNext()){
break;
}
} while(true);
return a;
}
private JsonElement readObject() {
JsonElementObject o = new JsonElementObject();
do {
if (!ctx.readKeyNext()){
break;
} else {
// we read a property key ...
String key = ctx.getTokenKey();
JsonElement value = readValue();
o.put(key, value);
if (!ctx.readValueNext()){
break;
}
}
} while(true);
return o;
}
private JsonElement readString() {
String s = ctx.readQuotedValue();
return new JsonElementString(s);
}
private JsonElement readUnquoted(char c) {
String s = ctx.readUnquotedValue(c);
if ("null".equals(s)){
return JsonElementNull.NULL;
} else if ("true".equals(s)){
return JsonElementBoolean.TRUE;
} else if ("false".equals(s)) {
return JsonElementBoolean.FALSE;
}
return new JsonElementNumber(s);
}
}
@@ -0,0 +1,34 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
public interface ReadJsonSource {
public char nextChar(String eofMsg);
public void ignoreWhiteSpace();
public void back();
public int pos();
public String getErrorHelp();
}
@@ -0,0 +1,102 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import com.avaje.ebean.text.TextException;
public class ReadJsonSourceReader implements ReadJsonSource {
private final Reader reader;
private char[] localBuffer;
private int totalPos;
private int localPos;
private int localPosEnd;
public ReadJsonSourceReader(Reader reader, int localBufferSize, int bufferSize) {
this.reader = new BufferedReader(reader,bufferSize);
this.localBuffer = new char[localBufferSize];
}
public String toString() {
return String.valueOf(localBuffer);
}
public String getErrorHelp() {
int prev = localPos - 30;
if (prev < 0){
prev = 0;
}
String c = new String(localBuffer, prev, (localPos-prev));
return "pos:"+pos()+" preceding:"+c;
}
public int pos() {
return totalPos+localPos;
}
public void ignoreWhiteSpace() {
do {
char c = nextChar("EOF ignoring whitespace");
if (!Character.isWhitespace(c)){
--localPos;
break;
}
} while(true);
}
public void back() {
localPos--;
}
public char nextChar(String eofMsg) {
if (localPos >= localPosEnd){
if (!loadLocalBuffer()) {
throw new TextException(eofMsg+" at pos:"+(totalPos+localPos));
}
}
return localBuffer[localPos++];
}
private boolean loadLocalBuffer() {
try {
localPosEnd = reader.read(localBuffer);
if (localPosEnd > 0){
totalPos += localPos;
localPos = 0;
return true;
} else {
this.localBuffer = null;
return false;
}
} catch (IOException e){
throw new TextException(e);
}
}
}
@@ -0,0 +1,73 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import com.avaje.ebean.text.TextException;
public class ReadJsonSourceString implements ReadJsonSource {
private final String source;
private final int sourceLength;
private int pos;
public ReadJsonSourceString(String source){
this.source = source;
this.sourceLength = source.length();
}
public String getErrorHelp() {
int prev = pos - 50;
if (prev < 0){
prev = 0;
}
String c = source.substring(prev, pos);
return "pos:"+pos+" precedingcontent:"+c;
}
public String toString() {
return source;
}
public int pos() {
return pos;
}
public void back() {
pos--;
}
public char nextChar(String eofMsg) {
if (pos >= sourceLength){
throw new TextException(eofMsg+" at pos:"+pos);
}
return source.charAt(pos++);
}
public void ignoreWhiteSpace() {
do {
char c = source.charAt(pos);
if (Character.isWhitespace(c)){
++pos;
} else {
break;
}
} while(true);
}
}
@@ -0,0 +1,27 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
public interface WriteJsonBuffer extends Appendable {
public WriteJsonBuffer append(String content);
}
@@ -0,0 +1,59 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.io.IOException;
public class WriteJsonBufferString implements WriteJsonBuffer {
private final StringBuilder buffer;
public WriteJsonBufferString(){
this.buffer = new StringBuilder(256);
}
public WriteJsonBufferString append(CharSequence csq) throws IOException {
buffer.append(csq);
return this;
}
public WriteJsonBufferString append(CharSequence csq, int start, int end) throws IOException {
buffer.append(csq, start, end);
return this;
}
public WriteJsonBufferString append(char c) throws IOException {
buffer.append(c);
return this;
}
public WriteJsonBufferString append(String content){
buffer.append(content);
return this;
}
public String getBufferOutput() {
return buffer.toString();
}
public String toString() {
return buffer.toString();
}
}
@@ -0,0 +1,64 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.io.IOException;
import java.io.Writer;
import com.avaje.ebean.text.TextException;
public class WriteJsonBufferWriter implements WriteJsonBuffer {
private final Writer buffer;
public WriteJsonBufferWriter(Writer buffer){
this.buffer = buffer;
}
public WriteJsonBufferWriter append(String content){
try {
buffer.write(content);
return this;
} catch (IOException e) {
throw new TextException(e);
}
}
public WriteJsonBufferWriter append(CharSequence csq) throws IOException {
return append(csq, 0, csq.length());
}
public WriteJsonBufferWriter append(CharSequence csq, int start, int end) throws IOException {
for (int i = start; i < end; i++) {
buffer.append(csq.charAt(i));
}
return this;
}
public WriteJsonBufferWriter append(char c) throws IOException {
try {
buffer.write(c);
return this;
} catch (IOException e) {
throw new TextException(e);
}
}
}
@@ -0,0 +1,395 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.text.json;
import java.util.Map;
import java.util.Set;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.text.PathProperties;
import com.avaje.ebean.text.json.JsonValueAdapter;
import com.avaje.ebean.text.json.JsonWriteBeanVisitor;
import com.avaje.ebean.text.json.JsonWriteOptions;
import com.avaje.ebean.text.json.JsonWriter;
import com.avaje.ebeaninternal.server.type.EscapeJson;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.server.util.ArrayStack;
public class WriteJsonContext implements JsonWriter {
private final WriteJsonBuffer buffer;
private final boolean pretty;
private final JsonValueAdapter valueAdapter;
private final ArrayStack<Object> parentBeans = new ArrayStack<Object>();
private final PathProperties pathProperties;
private final Map<String, JsonWriteBeanVisitor<?>> visitorMap;
private final String callback;
private final PathStack pathStack;
private WriteBeanState beanState;
private int depthOffset;
boolean assocOne;
public WriteJsonContext(WriteJsonBuffer buffer, boolean pretty, JsonValueAdapter dfltValueAdapter,
JsonWriteOptions options, String requestCallback){
this.buffer = buffer;
this.pretty = pretty;
this.pathStack = new PathStack();
this.callback = getCallback(requestCallback, options);
if (options == null){
this.valueAdapter = dfltValueAdapter;
this.visitorMap = null;
this.pathProperties = null;
} else {
this.valueAdapter = getValueAdapter(dfltValueAdapter, options.getValueAdapter());
this.visitorMap = emptyToNull(options.getVisitorMap());
this.pathProperties = emptyToNull(options.getPathProperties());
}
if (callback != null){
buffer.append(requestCallback).append("(");
}
}
public void appendRawValue(String key, String rawJsonValue) {
appendKeyWithComma(key, true);
buffer.append(rawJsonValue);
}
public void appendQuoteEscapeValue(String key, String valueToEscape) {
appendKeyWithComma(key, true);
EscapeJson.escapeQuote(valueToEscape, buffer);
}
public void end() {
if (callback != null){
buffer.append(")");
}
}
private <MK,MV> Map<MK,MV> emptyToNull(Map<MK,MV> m){
if ( m == null || m.isEmpty()) {
return null;
} else {
return m;
}
}
private PathProperties emptyToNull(PathProperties m){
if ( m == null || m.isEmpty()) {
return null;
} else {
return m;
}
}
private String getCallback(String requestCallback, JsonWriteOptions options) {
if (requestCallback != null){
return requestCallback;
}
if (options != null){
return options.getCallback();
}
return null;
}
private JsonValueAdapter getValueAdapter(JsonValueAdapter dfltValueAdapter, JsonValueAdapter valueAdapter) {
return valueAdapter == null ? dfltValueAdapter : valueAdapter;
}
/**
* Return the set of properties to write to JSON. If null is returned then
* the default will output the properties loaded for this bean.
*/
public Set<String> getIncludeProperties() {
if (pathProperties != null){
String path = pathStack.peekWithNull();
return pathProperties.get(path);
}
return null;
}
public JsonWriteBeanVisitor<?> getBeanVisitor() {
if (visitorMap != null){
String path = pathStack.peekWithNull();
return visitorMap.get(path);
}
return null;
}
public String getJson() {
return buffer.toString();
}
private void appendIndent(){
buffer.append("\n");
int depth = depthOffset + parentBeans.size();
for (int i = 0; i < depth; i++) {
buffer.append(" ");
}
}
public void appendObjectBegin(){
if (pretty && !assocOne){
appendIndent();
}
buffer.append("{");
}
public void appendObjectEnd(){
buffer.append("}");
}
public void appendArrayBegin(){
if (pretty){
appendIndent();
}
buffer.append("[");
depthOffset++;
}
public void appendArrayEnd(){
depthOffset--;
if (pretty){
appendIndent();
}
buffer.append("]");
}
public void appendComma(){
buffer.append(",");
}
public void addDepthOffset(int offset){
depthOffset += offset;
}
public void beginAssocOneIsNull(String key) {
depthOffset++;
internalAppendKeyBegin(key);
appendNull();
depthOffset--;
}
public void beginAssocOne(String key) {
pathStack.pushPathKey(key);
internalAppendKeyBegin(key);
assocOne = true;
}
public void endAssocOne() {
pathStack.pop();
assocOne = false;
}
public Boolean includeMany(String key) {
if (pathProperties != null){
String fullPath = pathStack.peekFullPath(key);
return pathProperties.hasPath(fullPath);
}
return null;
}
public void beginAssocMany(String key) {
pathStack.pushPathKey(key);
depthOffset--;
internalAppendKeyBegin(key);
depthOffset++;
buffer.append("[");
}
public void endAssocMany(){
pathStack.pop();
if (pretty){
depthOffset--;
appendIndent();
depthOffset++;
}
buffer.append("]");
}
private void internalAppendKeyBegin(String key) {
if (!beanState.isFirstKey()){
buffer.append(",");
}
if (pretty){
appendIndent();
}
appendKeyWithComma(key, false);
}
public <T> void appendNameValue(String key, ScalarType<T> scalarType, T value) {
appendKeyWithComma(key, true);
scalarType.jsonWrite(buffer, value, getValueAdapter());
}
public void appendDiscriminator(String key, String discValue) {
appendKeyWithComma(key, true);
buffer.append("\"");
buffer.append(discValue);
buffer.append("\"");
}
private void appendKeyWithComma(String key, boolean withComma) {
if (withComma){
if (!beanState.isFirstKey()){
buffer.append(",");
}
}
buffer.append("\"");
if(key == null) {
buffer.append("null");
} else {
buffer.append(key);
}
buffer.append("\":");
}
public void appendNull(String key) {
appendKeyWithComma(key, true);
buffer.append("null");
}
public void appendNull() {
buffer.append("null");
}
public JsonValueAdapter getValueAdapter() {
return valueAdapter;
}
public String toString() {
return buffer.toString();
}
public void popParentBean(){
parentBeans.pop();
}
public void pushParentBean(Object parentBean){
parentBeans.push(parentBean);
}
public void popParentBeanMany(){
parentBeans.pop();
depthOffset--;
}
public void pushParentBeanMany(Object parentBean){
parentBeans.push(parentBean);
depthOffset++;
}
public boolean isParentBean(Object bean){
if (parentBeans.isEmpty()){
return false;
} else {
return parentBeans.contains(bean);
}
}
public WriteBeanState pushBeanState(Object bean) {
WriteBeanState newState = new WriteBeanState(bean);
WriteBeanState prevState = beanState;
beanState = newState;
return prevState;
}
public void pushPreviousState(WriteBeanState previousState) {
this.beanState = previousState;
}
public boolean isReferenceBean() {
return beanState.isReferenceBean();
}
public boolean includedProp(String name) {
return beanState.includedProp(name);
}
public Set<String> getLoadedProps() {
return beanState.getLoadedProps();
}
public static class WriteBeanState {
private final EntityBeanIntercept ebi;
private final Set<String> loadedProps;
private final boolean referenceBean;
private boolean firstKeyOut;
public WriteBeanState(Object bean) {
if (bean instanceof EntityBean){
this.ebi = ((EntityBean)bean)._ebean_getIntercept();
this.loadedProps = ebi.getLoadedProps();
this.referenceBean = ebi.isReference();
} else {
this.ebi = null;
this.loadedProps = null;
this.referenceBean = false;
}
}
public Set<String> getLoadedProps() {
return loadedProps;
}
public boolean includedProp(String name) {
if (loadedProps == null || loadedProps.contains(name)){
return true;
} else {
return false;
}
}
public boolean isReferenceBean() {
return referenceBean;
}
public boolean isFirstKey() {
if (!firstKeyOut){
firstKeyOut = true;
return true;
} else {
return false;
}
}
}
}