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,249 @@
package com.avaje.ebeaninternal.server.text.csv;
// Original name: au.com.bytecode.opencsv.CSVReader
// rbygrave: Made some Java Generics tweaks to remove warnings
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* Glen Smith's CSV reader released under Apache License version 2.
*
* @author Glen Smith
*
*/
public class CsvUtilReader {
private BufferedReader br;
private boolean hasNext = true;
private char separator;
private char quotechar;
private int skipLines;
private boolean linesSkiped;
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/**
* The default line to start reading.
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Constructs CSVReader using a comma for the separator.
*
* @param reader
* the reader to an underlying CSV source.
*/
public CsvUtilReader(Reader reader) {
this(reader, DEFAULT_SEPARATOR);
}
/**
* Constructs CSVReader with supplied separator.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CsvUtilReader(Reader reader, char separator) {
this(reader, separator, DEFAULT_QUOTE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CsvUtilReader(Reader reader, char separator, char quotechar) {
this(reader, separator, quotechar, DEFAULT_SKIP_LINES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param line
* the line number to skip for start reading
*/
public CsvUtilReader(Reader reader, char separator, char quotechar, int line) {
this.br = new BufferedReader(reader);
this.separator = separator;
this.quotechar = quotechar;
this.skipLines = line;
}
/**
* Reads the entire file into a List with each element being a String[] of
* tokens.
*
* @return a List of String[], with each String[] representing a line of the
* file.
*
* @throws IOException
* if bad things happen during the read
*/
public List<String[]> readAll() throws IOException {
List<String[]> allElements = new ArrayList<String[]>();
while (hasNext) {
String[] nextLineAsTokens = readNext();
if (nextLineAsTokens != null)
allElements.add(nextLineAsTokens);
}
return allElements;
}
/**
* Reads the next line from the buffer and converts to a string array.
*
* @return a string array with each comma-separated element as a separate
* entry.
*
* @throws IOException
* if bad things happen during the read
*/
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}
/**
* Reads the next line from the file.
*
* @return the next line from the file without trailing newline
* @throws IOException
* if bad things happen during the read
*/
private String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
/**
* Parses an incoming String and returns an array of elements.
*
* @param nextLine
* the string to parse
* @return the comma-tokenized list of elements, or null if nextLine is null
* @throws IOException if bad things happen during the read
*/
private String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List<String> tokensOnThisLine = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
if (nextLine == null)
break;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == quotechar) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if( inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
sb.append(nextLine.charAt(i+1));
i++;
}else{
inQuotes = !inQuotes;
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if(i>2 //not on the begining of the line
&& nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence
&& nextLine.length()>(i+1) &&
nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence
){
sb.append(c);
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString().trim());
sb = new StringBuilder(); // start work on next token
} else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString().trim());
return tokensOnThisLine.toArray(new String[tokensOnThisLine.size()]);
}
/**
* Closes the underlying reader.
*
* @throws IOException if the close fails
*/
public void close() throws IOException{
br.close();
}
}
@@ -0,0 +1,388 @@
/**
* 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.csv;
import java.io.Reader;
import java.sql.Types;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.text.StringParser;
import com.avaje.ebean.text.TextException;
import com.avaje.ebean.text.TimeStringParser;
import com.avaje.ebean.text.csv.CsvCallback;
import com.avaje.ebean.text.csv.CsvReader;
import com.avaje.ebean.text.csv.DefaultCsvCallback;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
/**
*
* @author rbygrave
*/
public class TCsvReader<T> implements CsvReader<T> {
// private static final Logger logger =
// Logger.getLogger(TCsvReader.class.getName());
private static final TimeStringParser TIME_PARSER = new TimeStringParser();
private final EbeanServer server;
private final BeanDescriptor<T> descriptor;
private final List<CsvColumn> columnList = new ArrayList<CsvColumn>();
private final CsvColumn ignoreColumn = new CsvColumn();
private boolean treatEmptyStringAsNull = true;
private boolean hasHeader;
private int logInfoFrequency = 1000;
private String defaultTimeFormat = "HH:mm:ss";
private String defaultDateFormat = "yyyy-MM-dd";
private String defaultTimestampFormat = "yyyy-MM-dd hh:mm:ss.fffffffff";
private Locale defaultLocale = Locale.getDefault();
/**
* The batch size used for JDBC statement batching.
*/
protected int persistBatchSize = 30;
private boolean addPropertiesFromHeader;
// private String addHeaderDateTimeFormat;
// private Locale addHeaderLocale;
public TCsvReader(EbeanServer server, BeanDescriptor<T> descriptor) {
this.server = server;
this.descriptor = descriptor;
}
public void setDefaultLocale(Locale defaultLocale) {
this.defaultLocale = defaultLocale;
}
public void setDefaultTimeFormat(String defaultTimeFormat) {
this.defaultTimeFormat = defaultTimeFormat;
}
public void setDefaultDateFormat(String defaultDateFormat) {
this.defaultDateFormat = defaultDateFormat;
}
public void setDefaultTimestampFormat(String defaultTimestampFormat) {
this.defaultTimestampFormat = defaultTimestampFormat;
}
public void setPersistBatchSize(int persistBatchSize) {
this.persistBatchSize = persistBatchSize;
}
public void setIgnoreHeader() {
setHasHeader(true, false);
}
public void setAddPropertiesFromHeader() {
setHasHeader(true, true);
}
public void setHasHeader(boolean hasHeader, boolean addPropertiesFromHeader) {
this.hasHeader = hasHeader;
this.addPropertiesFromHeader = addPropertiesFromHeader;
}
public void setLogInfoFrequency(int logInfoFrequency) {
this.logInfoFrequency = logInfoFrequency;
}
public void addIgnore() {
columnList.add(ignoreColumn);
}
public void addProperty(String propertyName) {
addProperty(propertyName, null);
}
public void addReference(String propertyName) {
addProperty(propertyName, null, true);
}
public void addProperty(String propertyName, StringParser parser) {
addProperty(propertyName, parser, false);
}
public void addDateTime(String propertyName, String dateTimeFormat) {
addDateTime(propertyName, dateTimeFormat, Locale.getDefault());
}
public void addDateTime(String propertyName, String dateTimeFormat, Locale locale) {
ElPropertyValue elProp = descriptor.getElGetValue(propertyName);
if (!elProp.isDateTimeCapable()) {
throw new TextException("Property " + propertyName + " is not DateTime capable");
}
if (dateTimeFormat == null) {
dateTimeFormat = getDefaultDateTimeFormat(elProp.getJdbcType());
}
if (locale == null) {
locale = defaultLocale;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateTimeFormat, locale);
DateTimeParser parser = new DateTimeParser(sdf, dateTimeFormat, elProp);
CsvColumn column = new CsvColumn(elProp, parser, false);
columnList.add(column);
}
private String getDefaultDateTimeFormat(int jdbcType) {
switch (jdbcType) {
case Types.TIME:
return defaultTimeFormat;
case Types.DATE:
return defaultDateFormat;
case Types.TIMESTAMP:
return defaultTimestampFormat;
default:
throw new RuntimeException("Expected java.sql.Types TIME,DATE or TIMESTAMP but got [" + jdbcType + "]");
}
}
public void addProperty(String propertyName, StringParser parser, boolean reference) {
ElPropertyValue elProp = descriptor.getElGetValue(propertyName);
if (parser == null) {
parser = elProp.getStringParser();
}
CsvColumn column = new CsvColumn(elProp, parser, reference);
columnList.add(column);
}
public void process(Reader reader) throws Exception {
DefaultCsvCallback<T> callback = new DefaultCsvCallback<T>(persistBatchSize, logInfoFrequency);
process(reader, callback);
}
public void process(Reader reader, CsvCallback<T> callback) throws Exception {
if (reader == null) {
throw new NullPointerException("reader is null?");
}
if (callback == null) {
throw new NullPointerException("callback is null?");
}
CsvUtilReader utilReader = new CsvUtilReader(reader);
callback.begin(server);
int row = 0;
if (hasHeader) {
String[] line = utilReader.readNext();
if (addPropertiesFromHeader) {
addPropertiesFromHeader(line);
}
callback.readHeader(line);
}
try {
do {
++row;
String[] line = utilReader.readNext();
if (line == null) {
--row;
break;
}
if (callback.processLine(row, line)) {
// the line content is expected to be ok for processing
if (line.length != columnList.size()) {
// we have not got the expected number of columns
String msg = "Error at line " + row + ". Expected [" + columnList.size() + "] columns "
+ "but instead we have [" + line.length + "]. Line[" + Arrays.toString(line) + "]";
throw new TextException(msg);
}
T bean = buildBeanFromLineContent(row, line);
callback.processBean(row, line, bean);
}
} while (true);
callback.end(row);
} catch (Exception e) {
// notify that an error occured so that any
// transaction can be rolled back if required
callback.endWithError(row, e);
throw e;
}
}
private void addPropertiesFromHeader(String[] line) {
for (int i = 0; i < line.length; i++) {
ElPropertyValue elProp = descriptor.getElGetValue(line[i]);
if (elProp == null) {
throw new TextException("Property [" + line[i] + "] not found");
}
if (Types.TIME == elProp.getJdbcType()) {
addProperty(line[i], TIME_PARSER);
} else if (isDateTimeType(elProp.getJdbcType())) {
addDateTime(line[i], null, null);
} else if (elProp.isAssocProperty()) {
BeanPropertyAssocOne<?> assocOne = (BeanPropertyAssocOne<?>) elProp.getBeanProperty();
String idProp = assocOne.getBeanDescriptor().getIdBinder().getIdProperty();
addReference(line[i] + "." + idProp);
} else {
addProperty(line[i]);
}
}
}
private boolean isDateTimeType(int t) {
if (t == Types.TIMESTAMP || t == Types.DATE || t == Types.TIME) {
return true;
}
return false;
}
@SuppressWarnings("unchecked")
protected T buildBeanFromLineContent(int row, String[] line) {
try {
EntityBean entityBean = descriptor.createEntityBean();
T bean = (T) entityBean;
int columnPos = 0;
for (; columnPos < line.length; columnPos++) {
convertAndSetColumn(columnPos, line[columnPos], entityBean);
}
return bean;
} catch (RuntimeException e) {
String msg = "Error at line: " + row + " line[" + Arrays.toString(line) + "]";
throw new RuntimeException(msg, e);
}
}
protected void convertAndSetColumn(int columnPos, String strValue, Object bean) {
strValue = strValue.trim();
if (strValue.length() == 0 && treatEmptyStringAsNull) {
return;
}
CsvColumn c = columnList.get(columnPos);
c.convertAndSet(strValue, bean);
}
/**
* Processes a column in the csv content.
*/
public static class CsvColumn {
private final ElPropertyValue elProp;
private final StringParser parser;
private final boolean ignore;
private final boolean reference;
/**
* Constructor for the IGNORE column.
*/
private CsvColumn() {
this.elProp = null;
this.parser = null;
this.reference = false;
this.ignore = true;
}
/**
* Construct with a property and parser.
*/
public CsvColumn(ElPropertyValue elProp, StringParser parser, boolean reference) {
this.elProp = elProp;
this.parser = parser;
this.reference = reference;
this.ignore = false;
}
/**
* Convert the string to the appropriate value and set it to the bean.
*/
public void convertAndSet(String strValue, Object bean) {
if (!ignore) {
Object value = parser.parse(strValue);
elProp.elSetValue(bean, value, true, reference);
}
}
}
/**
* A StringParser for converting custom date/time/datetime strings into
* appropriate java types (Date, Calendar, SQL Date, Time, Timestamp, JODA
* etc).
*/
private static class DateTimeParser implements StringParser {
private final DateFormat dateFormat;
private final ElPropertyValue elProp;
private final String format;
DateTimeParser(DateFormat dateFormat, String format, ElPropertyValue elProp) {
this.dateFormat = dateFormat;
this.elProp = elProp;
this.format = format;
}
public Object parse(String value) {
try {
Date dt = dateFormat.parse(value);
return elProp.parseDateTime(dt.getTime());
} catch (ParseException e) {
throw new TextException("Error parsing [" + value + "] using format[" + format + "]", e);
}
}
}
}
@@ -0,0 +1,4 @@
/**
* CSV implementation.
*/
package com.avaje.ebeaninternal.server.text.csv;
@@ -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;
}
}
}
}