From 88f144ec3375b9a4f84af4f3c1d8c17577c1f518 Mon Sep 17 00:00:00 2001 From: rbygrave Date: Sat, 9 May 2015 01:11:44 +1200 Subject: [PATCH] No effective change - change newline char --- .../server/text/csv/TCsvReader.java | 710 +++++++++--------- .../server/text/json/DJsonContext.java | 612 +++++++-------- .../server/text/json/PathStack.java | 52 +- 3 files changed, 687 insertions(+), 687 deletions(-) diff --git a/src/main/java/com/avaje/ebeaninternal/server/text/csv/TCsvReader.java b/src/main/java/com/avaje/ebeaninternal/server/text/csv/TCsvReader.java index 362683993..a72d61310 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/text/csv/TCsvReader.java +++ b/src/main/java/com/avaje/ebeaninternal/server/text/csv/TCsvReader.java @@ -1,355 +1,355 @@ -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 implements CsvReader { - - private static final TimeStringParser TIME_PARSER = new TimeStringParser(); - - private final EbeanServer server; - - private final BeanDescriptor descriptor; - - private final List columnList = new ArrayList(); - - 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 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 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); - 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) { - - ElPropertyValue elProp = descriptor.getElGetValue(propertyName); - if (parser == null) { - parser = elProp.getStringParser(); - } - CsvColumn column = new CsvColumn(elProp, parser); - columnList.add(column); - } - - public void process(Reader reader) throws Exception { - DefaultCsvCallback callback = new DefaultCsvCallback(persistBatchSize, logInfoFrequency); - process(reader, callback); - } - - public void process(Reader reader, CsvCallback 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(); - addProperty(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, EntityBean 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; - - /** - * Constructor for the IGNORE column. - */ - private CsvColumn() { - this.elProp = null; - this.parser = null; - this.ignore = true; - } - - /** - * Construct with a property and parser. - */ - public CsvColumn(ElPropertyValue elProp, StringParser parser) { - this.elProp = elProp; - this.parser = parser; - this.ignore = false; - } - - /** - * Convert the string to the appropriate value and set it to the bean. - */ - public void convertAndSet(String strValue, EntityBean bean) { - - if (!ignore) { - Object value = parser.parse(strValue); - elProp.elSetValue(bean, value, true); - } - } - } - - /** - * 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); - } - } - - } -} +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 implements CsvReader { + + private static final TimeStringParser TIME_PARSER = new TimeStringParser(); + + private final EbeanServer server; + + private final BeanDescriptor descriptor; + + private final List columnList = new ArrayList(); + + 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 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 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); + 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) { + + ElPropertyValue elProp = descriptor.getElGetValue(propertyName); + if (parser == null) { + parser = elProp.getStringParser(); + } + CsvColumn column = new CsvColumn(elProp, parser); + columnList.add(column); + } + + public void process(Reader reader) throws Exception { + DefaultCsvCallback callback = new DefaultCsvCallback(persistBatchSize, logInfoFrequency); + process(reader, callback); + } + + public void process(Reader reader, CsvCallback 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(); + addProperty(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, EntityBean 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; + + /** + * Constructor for the IGNORE column. + */ + private CsvColumn() { + this.elProp = null; + this.parser = null; + this.ignore = true; + } + + /** + * Construct with a property and parser. + */ + public CsvColumn(ElPropertyValue elProp, StringParser parser) { + this.elProp = elProp; + this.parser = parser; + this.ignore = false; + } + + /** + * Convert the string to the appropriate value and set it to the bean. + */ + public void convertAndSet(String strValue, EntityBean bean) { + + if (!ignore) { + Object value = parser.parse(strValue); + elProp.elSetValue(bean, value, true); + } + } + } + + /** + * 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); + } + } + + } +} diff --git a/src/main/java/com/avaje/ebeaninternal/server/text/json/DJsonContext.java b/src/main/java/com/avaje/ebeaninternal/server/text/json/DJsonContext.java index 0f47b1202..a3f0ed7a0 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/text/json/DJsonContext.java +++ b/src/main/java/com/avaje/ebeaninternal/server/text/json/DJsonContext.java @@ -1,306 +1,306 @@ -package com.avaje.ebeaninternal.server.text.json; - -import com.avaje.ebean.bean.EntityBean; -import com.avaje.ebean.text.json.EJson; -import com.avaje.ebean.text.PathProperties; -import com.avaje.ebean.text.json.JsonContext; -import com.avaje.ebean.text.json.JsonIOException; -import com.avaje.ebean.text.json.JsonWriteOptions; -import com.avaje.ebeaninternal.api.SpiEbeanServer; -import com.avaje.ebeaninternal.server.deploy.BeanDescriptor; -import com.avaje.ebeaninternal.util.ParamTypeHelper; -import com.avaje.ebeaninternal.util.ParamTypeHelper.ManyType; -import com.avaje.ebeaninternal.util.ParamTypeHelper.TypeInfo; -import com.fasterxml.jackson.core.*; - -import java.io.*; -import java.lang.reflect.Type; -import java.util.*; -import java.util.Map.Entry; - -/** - * Default implementation of JsonContext. - */ -public class DJsonContext implements JsonContext { - - private final SpiEbeanServer server; - - private final JsonFactory jsonFactory; - - public DJsonContext(SpiEbeanServer server, JsonFactory jsonFactory) { - this.server = server; - this.jsonFactory = (jsonFactory != null) ? jsonFactory : new JsonFactory(); - } - - public boolean isSupportedType(Type genericType) { - return server.isSupportedType(genericType); - } - - public JsonGenerator createGenerator(Writer writer) throws JsonIOException { - try { - return jsonFactory.createGenerator(writer); - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - public JsonParser createParser(Reader reader) throws JsonIOException { - try { - return jsonFactory.createParser(reader); - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - public T toBean(Class cls, String json) throws JsonIOException { - return toBean(cls, new StringReader(json)); - } - - public T toBean(Class cls, Reader jsonReader) throws JsonIOException { - return toBean(cls, createParser(jsonReader)); - } - - public T toBean(Class cls, JsonParser parser) throws JsonIOException { - - try { - BeanDescriptor d = getDescriptor(cls); - return d.jsonRead(parser, null); - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - public List toList(Class cls, String json) throws JsonIOException { - return toList(cls, new StringReader(json)); - } - - - public List toList(Class cls, Reader jsonReader) throws JsonIOException { - return toList(cls, createParser(jsonReader)); - } - - public List toList(Class cls, JsonParser src) throws JsonIOException { - - try { - BeanDescriptor d = getDescriptor(cls); - - List list = new ArrayList(); - - JsonToken event = src.nextToken(); - if (event != JsonToken.START_ARRAY) { - throw new JsonParseException("Expecting start_array event but got " + event, src.getCurrentLocation()); - } - - do { - T bean = d.jsonRead(src, null); - if (bean == null) { - break; - } else { - list.add(bean); - } - } while (true); - - return list; - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - public Object toObject(Type genericType, String json) throws JsonIOException { - - return toObject(genericType, createParser(new StringReader(json))); - } - - public Object toObject(Type genericType, Reader json) throws JsonIOException { - - return toObject(genericType, createParser(json)); - } - - public Object toObject(Type genericType, JsonParser jsonParser) throws JsonIOException { - - TypeInfo info = ParamTypeHelper.getTypeInfo(genericType); - ManyType manyType = info.getManyType(); - switch (manyType) { - case NONE: - return toBean(info.getBeanType(), jsonParser); - - case LIST: - return toList(info.getBeanType(), jsonParser); - - default: - throw new JsonIOException("Type " + manyType + " not supported"); - } - } - - @Override - public void toJson(Object value, JsonGenerator generator) throws JsonIOException { - // generator passed in so don't close it - toJsonNoClose(value, generator, null); - } - - @Override - public void toJson(Object value, JsonGenerator generator, PathProperties pathProperties) throws JsonIOException { - // generator passed in so don't close it - toJsonNoClose(value, generator, JsonWriteOptions.pathProperties(pathProperties)); - } - - @Override - public void toJson(Object o, JsonGenerator generator, JsonWriteOptions options) throws JsonIOException { - // generator passed in so don't close it - toJsonNoClose(o, generator, options); - } - - @Override - public void toJson(Object o, Writer writer) throws JsonIOException { - // close generator - toJsonWithClose(o, createGenerator(writer), null); - } - - @Override - public String toJson(Object value, PathProperties pathProperties) throws JsonIOException { - return toJson(value, JsonWriteOptions.pathProperties(pathProperties)); - } - - @Override - public void toJson(Object o, Writer writer, PathProperties pathProperties) throws JsonIOException { - // close generator - toJsonWithClose(o, createGenerator(writer), JsonWriteOptions.pathProperties(pathProperties)); - } - - @Override - public void toJson(Object o, Writer writer, JsonWriteOptions options) throws JsonIOException { - // close generator - toJsonWithClose(o, createGenerator(writer), options); - } - - /** - * Write to the JsonGenerator and close when complete. - */ - private void toJsonWithClose(Object o, JsonGenerator generator, JsonWriteOptions options) throws JsonIOException { - try { - toJsonInternal(o, generator, options); - generator.close(); - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - /** - * Write to the JsonGenerator and without closing it (as it was created externally). - */ - private void toJsonNoClose(Object o, JsonGenerator generator, JsonWriteOptions options) throws JsonIOException { - try { - toJsonInternal(o, generator, options); - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - @Override - public String toJson(Object o) throws JsonIOException { - return toJsonString(o, null); - } - - @Override - public String toJson(Object o, JsonWriteOptions options) throws JsonIOException { - return toJsonString(o, options); - } - - private String toJsonString(Object value, JsonWriteOptions options) throws JsonIOException { - try { - StringWriter writer = new StringWriter(500); - JsonGenerator gen = createGenerator(writer); - toJsonInternal(value, gen, options); - gen.close(); - return writer.toString(); - } catch (IOException e) { - throw new JsonIOException(e); - } - } - - @SuppressWarnings("unchecked") - private void toJsonInternal(Object value, JsonGenerator gen, JsonWriteOptions options) throws IOException { - - if (value == null) { - gen.writeNull(); - } else if (value instanceof Number) { - gen.writeNumber(((Number) value).doubleValue()); - } else if (value instanceof Boolean) { - gen.writeBoolean((Boolean) value); - } else if (value instanceof String) { - gen.writeString((String) value); - - // } else if (o instanceof JsonElement) { - - } else if (value instanceof Map) { - toJsonFromMap((Map) value, gen, options); - - } else if (value instanceof Collection) { - toJsonFromCollection((Collection) value, null, gen, options); - - } else if (value instanceof EntityBean) { - BeanDescriptor d = getDescriptor(value.getClass()); - WriteJson writeJson = createWriteJson(gen, options); - d.jsonWrite(writeJson, (EntityBean) value, null); - } - } - - private WriteJson createWriteJson(JsonGenerator gen, JsonWriteOptions options) { - PathProperties pathProps = (options == null) ? null : options.getPathProperties(); - return new WriteJson(server, gen, pathProps); - } - - private void toJsonFromCollection(Collection collection, String key, JsonGenerator gen, JsonWriteOptions options) throws IOException { - - if (key != null) { - gen.writeFieldName(key); - } - gen.writeStartArray(); - - WriteJson writeJson = createWriteJson(gen, options); - - for (T bean : collection) { - BeanDescriptor d = getDescriptor(bean.getClass()); - d.jsonWrite(writeJson, (EntityBean) bean, null); - } - gen.writeEndArray(); - } - - private void toJsonFromMap(Map map, JsonGenerator gen, JsonWriteOptions options) throws IOException { - - Set> entrySet = map.entrySet(); - Iterator> it = entrySet.iterator(); - - WriteJson writeJson = createWriteJson(gen, options); - gen.writeStartObject(); - - while (it.hasNext()) { - Entry entry = it.next(); - String key = entry.getKey().toString(); - Object value = entry.getValue(); - if (value == null) { - gen.writeNullField(key); - } else { - if (value instanceof Collection) { - toJsonFromCollection((Collection) value, key, gen, options); - - } else if (value instanceof EntityBean) { - BeanDescriptor d = getDescriptor(value.getClass()); - d.jsonWrite(writeJson, (EntityBean) value, key); - - } else { - EJson.write(entry, gen); - } - } - } - gen.writeEndObject(); - } - - private BeanDescriptor getDescriptor(Class cls) { - BeanDescriptor d = server.getBeanDescriptor(cls); - if (d == null) { - throw new RuntimeException("No BeanDescriptor found for " + cls); - } - return d; - } -} +package com.avaje.ebeaninternal.server.text.json; + +import com.avaje.ebean.bean.EntityBean; +import com.avaje.ebean.text.json.EJson; +import com.avaje.ebean.text.PathProperties; +import com.avaje.ebean.text.json.JsonContext; +import com.avaje.ebean.text.json.JsonIOException; +import com.avaje.ebean.text.json.JsonWriteOptions; +import com.avaje.ebeaninternal.api.SpiEbeanServer; +import com.avaje.ebeaninternal.server.deploy.BeanDescriptor; +import com.avaje.ebeaninternal.util.ParamTypeHelper; +import com.avaje.ebeaninternal.util.ParamTypeHelper.ManyType; +import com.avaje.ebeaninternal.util.ParamTypeHelper.TypeInfo; +import com.fasterxml.jackson.core.*; + +import java.io.*; +import java.lang.reflect.Type; +import java.util.*; +import java.util.Map.Entry; + +/** + * Default implementation of JsonContext. + */ +public class DJsonContext implements JsonContext { + + private final SpiEbeanServer server; + + private final JsonFactory jsonFactory; + + public DJsonContext(SpiEbeanServer server, JsonFactory jsonFactory) { + this.server = server; + this.jsonFactory = (jsonFactory != null) ? jsonFactory : new JsonFactory(); + } + + public boolean isSupportedType(Type genericType) { + return server.isSupportedType(genericType); + } + + public JsonGenerator createGenerator(Writer writer) throws JsonIOException { + try { + return jsonFactory.createGenerator(writer); + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + public JsonParser createParser(Reader reader) throws JsonIOException { + try { + return jsonFactory.createParser(reader); + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + public T toBean(Class cls, String json) throws JsonIOException { + return toBean(cls, new StringReader(json)); + } + + public T toBean(Class cls, Reader jsonReader) throws JsonIOException { + return toBean(cls, createParser(jsonReader)); + } + + public T toBean(Class cls, JsonParser parser) throws JsonIOException { + + try { + BeanDescriptor d = getDescriptor(cls); + return d.jsonRead(parser, null); + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + public List toList(Class cls, String json) throws JsonIOException { + return toList(cls, new StringReader(json)); + } + + + public List toList(Class cls, Reader jsonReader) throws JsonIOException { + return toList(cls, createParser(jsonReader)); + } + + public List toList(Class cls, JsonParser src) throws JsonIOException { + + try { + BeanDescriptor d = getDescriptor(cls); + + List list = new ArrayList(); + + JsonToken event = src.nextToken(); + if (event != JsonToken.START_ARRAY) { + throw new JsonParseException("Expecting start_array event but got " + event, src.getCurrentLocation()); + } + + do { + T bean = d.jsonRead(src, null); + if (bean == null) { + break; + } else { + list.add(bean); + } + } while (true); + + return list; + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + public Object toObject(Type genericType, String json) throws JsonIOException { + + return toObject(genericType, createParser(new StringReader(json))); + } + + public Object toObject(Type genericType, Reader json) throws JsonIOException { + + return toObject(genericType, createParser(json)); + } + + public Object toObject(Type genericType, JsonParser jsonParser) throws JsonIOException { + + TypeInfo info = ParamTypeHelper.getTypeInfo(genericType); + ManyType manyType = info.getManyType(); + switch (manyType) { + case NONE: + return toBean(info.getBeanType(), jsonParser); + + case LIST: + return toList(info.getBeanType(), jsonParser); + + default: + throw new JsonIOException("Type " + manyType + " not supported"); + } + } + + @Override + public void toJson(Object value, JsonGenerator generator) throws JsonIOException { + // generator passed in so don't close it + toJsonNoClose(value, generator, null); + } + + @Override + public void toJson(Object value, JsonGenerator generator, PathProperties pathProperties) throws JsonIOException { + // generator passed in so don't close it + toJsonNoClose(value, generator, JsonWriteOptions.pathProperties(pathProperties)); + } + + @Override + public void toJson(Object o, JsonGenerator generator, JsonWriteOptions options) throws JsonIOException { + // generator passed in so don't close it + toJsonNoClose(o, generator, options); + } + + @Override + public void toJson(Object o, Writer writer) throws JsonIOException { + // close generator + toJsonWithClose(o, createGenerator(writer), null); + } + + @Override + public String toJson(Object value, PathProperties pathProperties) throws JsonIOException { + return toJson(value, JsonWriteOptions.pathProperties(pathProperties)); + } + + @Override + public void toJson(Object o, Writer writer, PathProperties pathProperties) throws JsonIOException { + // close generator + toJsonWithClose(o, createGenerator(writer), JsonWriteOptions.pathProperties(pathProperties)); + } + + @Override + public void toJson(Object o, Writer writer, JsonWriteOptions options) throws JsonIOException { + // close generator + toJsonWithClose(o, createGenerator(writer), options); + } + + /** + * Write to the JsonGenerator and close when complete. + */ + private void toJsonWithClose(Object o, JsonGenerator generator, JsonWriteOptions options) throws JsonIOException { + try { + toJsonInternal(o, generator, options); + generator.close(); + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + /** + * Write to the JsonGenerator and without closing it (as it was created externally). + */ + private void toJsonNoClose(Object o, JsonGenerator generator, JsonWriteOptions options) throws JsonIOException { + try { + toJsonInternal(o, generator, options); + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + @Override + public String toJson(Object o) throws JsonIOException { + return toJsonString(o, null); + } + + @Override + public String toJson(Object o, JsonWriteOptions options) throws JsonIOException { + return toJsonString(o, options); + } + + private String toJsonString(Object value, JsonWriteOptions options) throws JsonIOException { + try { + StringWriter writer = new StringWriter(500); + JsonGenerator gen = createGenerator(writer); + toJsonInternal(value, gen, options); + gen.close(); + return writer.toString(); + } catch (IOException e) { + throw new JsonIOException(e); + } + } + + @SuppressWarnings("unchecked") + private void toJsonInternal(Object value, JsonGenerator gen, JsonWriteOptions options) throws IOException { + + if (value == null) { + gen.writeNull(); + } else if (value instanceof Number) { + gen.writeNumber(((Number) value).doubleValue()); + } else if (value instanceof Boolean) { + gen.writeBoolean((Boolean) value); + } else if (value instanceof String) { + gen.writeString((String) value); + + // } else if (o instanceof JsonElement) { + + } else if (value instanceof Map) { + toJsonFromMap((Map) value, gen, options); + + } else if (value instanceof Collection) { + toJsonFromCollection((Collection) value, null, gen, options); + + } else if (value instanceof EntityBean) { + BeanDescriptor d = getDescriptor(value.getClass()); + WriteJson writeJson = createWriteJson(gen, options); + d.jsonWrite(writeJson, (EntityBean) value, null); + } + } + + private WriteJson createWriteJson(JsonGenerator gen, JsonWriteOptions options) { + PathProperties pathProps = (options == null) ? null : options.getPathProperties(); + return new WriteJson(server, gen, pathProps); + } + + private void toJsonFromCollection(Collection collection, String key, JsonGenerator gen, JsonWriteOptions options) throws IOException { + + if (key != null) { + gen.writeFieldName(key); + } + gen.writeStartArray(); + + WriteJson writeJson = createWriteJson(gen, options); + + for (T bean : collection) { + BeanDescriptor d = getDescriptor(bean.getClass()); + d.jsonWrite(writeJson, (EntityBean) bean, null); + } + gen.writeEndArray(); + } + + private void toJsonFromMap(Map map, JsonGenerator gen, JsonWriteOptions options) throws IOException { + + Set> entrySet = map.entrySet(); + Iterator> it = entrySet.iterator(); + + WriteJson writeJson = createWriteJson(gen, options); + gen.writeStartObject(); + + while (it.hasNext()) { + Entry entry = it.next(); + String key = entry.getKey().toString(); + Object value = entry.getValue(); + if (value == null) { + gen.writeNullField(key); + } else { + if (value instanceof Collection) { + toJsonFromCollection((Collection) value, key, gen, options); + + } else if (value instanceof EntityBean) { + BeanDescriptor d = getDescriptor(value.getClass()); + d.jsonWrite(writeJson, (EntityBean) value, key); + + } else { + EJson.write(entry, gen); + } + } + } + gen.writeEndObject(); + } + + private BeanDescriptor getDescriptor(Class cls) { + BeanDescriptor d = server.getBeanDescriptor(cls); + if (d == null) { + throw new RuntimeException("No BeanDescriptor found for " + cls); + } + return d; + } +} diff --git a/src/main/java/com/avaje/ebeaninternal/server/text/json/PathStack.java b/src/main/java/com/avaje/ebeaninternal/server/text/json/PathStack.java index b62bd1d97..9d17f0541 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/text/json/PathStack.java +++ b/src/main/java/com/avaje/ebeaninternal/server/text/json/PathStack.java @@ -1,26 +1,26 @@ -package com.avaje.ebeaninternal.server.text.json; - -import com.avaje.ebeaninternal.server.util.ArrayStack; - -public class PathStack extends ArrayStack { - - 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); - } - -} +package com.avaje.ebeaninternal.server.text.json; + +import com.avaje.ebeaninternal.server.util.ArrayStack; + +public class PathStack extends ArrayStack { + + 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); + } + +}