格式化代码 修复nameWithoutQuotes方法未生效的问题...

Signed-off-by: 502647092 <jtb1@163.com>
master
502647092 2016-01-12 17:06:47 +08:00
parent 628868dadc
commit 25375227f6
38 changed files with 2692 additions and 2023 deletions

View File

@ -6,6 +6,51 @@ import java.io.IOException;
public abstract interface JsonWriter extends Closeable, Flushable {
/**
* An array with no elements requires no separators or newlines before it is
* closed.
*/
static final int EMPTY_ARRAY = 1;
/**
* A array with at least one value requires a comma and newline before the
* next element.
*/
static final int NONEMPTY_ARRAY = 2;
/**
* An object with no name/value pairs requires no separators or newlines
* before it is closed.
*/
static final int EMPTY_OBJECT = 3;
/**
* An object whose most recent element is a key. The next element must be a
* value.
*/
static final int DANGLING_NAME = 4;
/**
* An object with at least one name/value pair requires a comma and newline
* before the next element.
*/
static final int NONEMPTY_OBJECT = 5;
/**
* No object or array has been started.
*/
static final int EMPTY_DOCUMENT = 6;
/**
* A document with at an array or object.
*/
static final int NONEMPTY_DOCUMENT = 7;
/**
* A document that's been closed and cannot be accessed.
*/
static final int CLOSED = 8;
public JsonWriter beginArray() throws IOException;
public JsonWriter beginObject() throws IOException;
@ -50,6 +95,5 @@ public abstract interface JsonWriter extends Closeable, Flushable {
public JsonWriter value(String value) throws IOException;
void string(String value) throws IOException;
void stringExtend(String value) throws IOException;
}

View File

@ -4,6 +4,7 @@
package cn.citycraft.GsonAgent.api.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Gson(7)
@ -13,6 +14,29 @@ import java.lang.reflect.Constructor;
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class Utils {
public static final String[] REPLACEMENT_CHARS;
public static final String[] HTML_SAFE_REPLACEMENT_CHARS;
static {
REPLACEMENT_CHARS = new String[128];
for (int i = 0; i <= 0x1f; i++) {
REPLACEMENT_CHARS[i] = String.format("\\u%04x", i);
}
REPLACEMENT_CHARS['"'] = "\\\"";
REPLACEMENT_CHARS['\\'] = "\\\\";
REPLACEMENT_CHARS['\t'] = "\\t";
REPLACEMENT_CHARS['\b'] = "\\b";
REPLACEMENT_CHARS['\n'] = "\\n";
REPLACEMENT_CHARS['\r'] = "\\r";
REPLACEMENT_CHARS['\f'] = "\\f";
HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone();
HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c";
HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e";
HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026";
HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d";
HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027";
}
public static <T> T deepCopyObject(final T obj) {
try {
return (T) obj.getClass().getDeclaredMethod("deepCopy").invoke(obj);
@ -21,6 +45,51 @@ public class Utils {
}
}
public static Field getDeclareField(final Class clzz, final String fieldName) throws Exception {
final Field field = clzz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
}
public static Object invokeField(final Object object, final Field field) {
try {
return field.get(object);
} catch (final Exception e) {
}
return null;
}
public static int[] invokeIntArrayField(final Object object, final Field field) {
try {
return (int[]) invokeField(object, field);
} catch (final Exception e) {
}
return null;
}
public static int invokeIntField(final Object object, final Field field) {
try {
return ((Number) invokeField(object, field)).intValue();
} catch (final Exception e) {
}
return 0;
}
public static String invokeStringField(final Object object, final Field field) {
try {
return (String) invokeField(object, field);
} catch (final Exception e) {
}
return null;
}
public static void modifyField(final Object object, final Field field, final Object value) {
try {
field.set(object, value);
} catch (final Exception e) {
}
}
public static <T> T newInstance(final Class<T> clzz) {
try {
final Constructor<T> constructor = clzz.getDeclaredConstructor();

View File

@ -4,138 +4,225 @@ import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import cn.citycraft.GsonAgent.api.utils.Utils;
import net.minecraft.util.com.google.gson.stream.JsonWriter;
public class JsonWriterHandle implements cn.citycraft.GsonAgent.api.stream.JsonWriter {
private static String[] REPLACEMENT_CHARS;
private static String[] HTML_SAFE_REPLACEMENT_CHARS;
public class JsonWriterHandle extends JsonWriter implements cn.citycraft.GsonAgent.api.stream.JsonWriter {
/*
* From RFC 4627, "All Unicode characters may be placed within the
* quotation marks except for the characters that must be escaped:
* quotation mark, reverse solidus, and the control characters
* (U+0000 through U+001F)."
*
* We also escape '\u2028' and '\u2029', which JavaScript interprets as
* newline characters. This prevents eval() from failing with a syntax
* error. http://code.google.com/p/google-gson/issues/detail?id=341
*/
private static Field stackField, stackSizeField, indentField, separatorField;
static {
final Class<JsonWriter> clzz = JsonWriter.class;
try {
Field field = JsonWriter.class.getDeclaredField("REPLACEMENT_CHARS");
field.setAccessible(true);
REPLACEMENT_CHARS = (String[]) field.get(null);
field = JsonWriter.class.getDeclaredField("HTML_SAFE_REPLACEMENT_CHARS");
field.setAccessible(true);
HTML_SAFE_REPLACEMENT_CHARS = (String[]) field.get(null);
stackField = Utils.getDeclareField(clzz, "stack");
stackSizeField = Utils.getDeclareField(clzz, "stackSize");
indentField = Utils.getDeclareField(clzz, "indent");
separatorField = Utils.getDeclareField(clzz, "separator");
} catch (final Exception e) {
e.printStackTrace();
}
}
private final JsonWriter handle;
private Writer out;
/**
* The output data, containing at most one top-level array or object.
*/
private final Writer out;
private String deferredName;
private boolean withoutQuotes = false;
/**
* Creates a new instance that writes a JSON-encoded stream to {@code out}.
* For best performance, ensure {@link Writer} is buffered; wrapping in
* {@link java.io.BufferedWriter BufferedWriter} if necessary.
*
* @param out
*/
public JsonWriterHandle(final Writer out) {
this(new JsonWriter(out));
super(out);
this.out = out;
}
protected JsonWriterHandle(final JsonWriter handle) {
this.handle = handle;
}
/**
* Begins encoding a new array. Each call to this method must be paired with
* a call to {@link #endArray}.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle beginArray() throws IOException {
getHandle().beginArray();
return this;
writeDeferredName();
return open(EMPTY_ARRAY, "[");
}
/**
* Begins encoding a new object. Each call to this method must be paired
* with a call to {@link #endObject}.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle beginObject() throws IOException {
getHandle().beginObject();
return this;
writeDeferredName();
return open(EMPTY_OBJECT, "{");
}
/**
* Flushes and closes this writer and the underlying {@link Writer}.
*
* @throws IOException
* if the JSON document is incomplete.
*/
@Override
public void close() throws IOException {
getHandle().close();
out.close();
final int size = this.getStackSize();
if (size > 1 || size == 1 && this.getStack()[size - 1] != NONEMPTY_DOCUMENT) {
throw new IOException("Incomplete document");
}
this.setStackSize(0);
}
/**
* Ends encoding the current array.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle endArray() throws IOException {
getHandle().endArray();
return this;
return close(EMPTY_ARRAY, NONEMPTY_ARRAY, "]");
}
/**
* Ends encoding the current object.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle endObject() throws IOException {
getHandle().endObject();
return close(EMPTY_OBJECT, NONEMPTY_OBJECT, "}");
}
/**
* Ensures all buffered data is written to the underlying {@link Writer} and
* flushes that writer.
*
* @throws java.io.IOException
*/
@Override
public void flush() throws IOException {
if (this.getStackSize() == 0) {
throw new IllegalStateException("JsonWriterHandle is closed.");
}
out.flush();
}
public JsonWriterHandle getHandle() {
return this;
}
@Override
public void flush() throws IOException {
getHandle().flush();
public String getIndent() {
return Utils.invokeStringField(this, indentField);
}
public JsonWriter getHandle() {
return handle;
public String getSeparator() {
return Utils.invokeStringField(this, separatorField);
}
@Override
public boolean getSerializeNulls() {
return getHandle().getSerializeNulls();
public int[] getStack() {
return Utils.invokeIntArrayField(this, stackField);
}
@Override
public boolean isHtmlSafe() {
return getHandle().isHtmlSafe();
}
@Override
public boolean isLenient() {
return getHandle().isLenient();
public int getStackSize() {
return Utils.invokeIntField(this, stackSizeField);
}
/**
* Encodes the property name.
*
* @param name
* the name of the forthcoming value. May not be null.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle name(final String name) throws IOException {
getHandle().name(name);
if (name == null) {
throw new NullPointerException("name == null");
}
if (deferredName != null) {
throw new IllegalStateException();
}
if (this.getStackSize() == 0) {
throw new IllegalStateException("JsonWriterHandle is closed.");
}
deferredName = name;
withoutQuotes = false;
return this;
}
@Override
public JsonWriterHandle nameWithoutQuotes(final String name) throws IOException {
getHandle().name(name);
this.name(name);
withoutQuotes = true;
return this;
}
/**
* Encodes {@code null}.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle nullValue() throws IOException {
getHandle().nullValue();
if (deferredName != null) {
if (this.getSerializeNulls()) {
writeDeferredName();
} else {
deferredName = null;
return this; // skip the name and the value
}
}
beforeValue(false);
out.write("null");
return this;
}
@Override
public void setHtmlSafe(final boolean htmlSafe) {
getHandle().setHtmlSafe(htmlSafe);
public void setSeparator(final String separator) {
Utils.modifyField(this, separatorField, separator);
}
public void setStack(final int index, final int value) {
final int[] newStack = this.getStack();
newStack[index] = value;
this.setStack(newStack);
}
public void setStack(final int[] stack) {
Utils.modifyField(this, stackField, stack);
}
public void setStackSize(final int stackSize) {
Utils.modifyField(this, stackSizeField, stackSize);
}
@Override
public void setIndent(final String indent) {
getHandle().setIndent(indent);
}
@Override
public void setLenient(final boolean lenient) {
getHandle().setLenient(lenient);
}
@Override
public void setSerializeNulls(final boolean serializeNulls) {
getHandle().setSerializeNulls(serializeNulls);
}
@Override
public void string(final String value) throws IOException {
final String[] replacements = getHandle().isHtmlSafe() ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
public void stringExtend(final String value) throws IOException {
final String[] replacements = this.isHtmlSafe() ? Utils.HTML_SAFE_REPLACEMENT_CHARS : Utils.REPLACEMENT_CHARS;
if (!this.withoutQuotes) {
this.out.write("\"");
}
@ -144,30 +231,26 @@ public class JsonWriterHandle implements cn.citycraft.GsonAgent.api.stream.JsonW
for (int i = 0; i < length; i++) {
final char c = value.charAt(i);
String replacement;
if (c < '€') {
if (c < 128) {
replacement = replacements[c];
if (replacement == null) {
continue;
}
} else {
if (c == '') {
} else if (c == '\u2028') {
replacement = "\\u2028";
} else if (c == '\u2029') {
replacement = "\\u2029";
} else {
if (c != '') {
continue;
}
replacement = "\\u2029";
}
}
if (last < i) {
this.out.write(value, last, i - last);
out.write(value, last, i - last);
}
this.out.write(replacement);
out.write(replacement);
last = i + 1;
}
if (last < length) {
this.out.write(value, last, length - last);
out.write(value, last, length - last);
}
if (!this.withoutQuotes) {
this.out.write("\"");
@ -175,34 +258,229 @@ public class JsonWriterHandle implements cn.citycraft.GsonAgent.api.stream.JsonW
withoutQuotes = false;
}
/**
* Encodes {@code value}.
*
* @param value
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final boolean value) throws IOException {
getHandle().value(value);
writeDeferredName();
beforeValue(false);
out.write(value ? "true" : "false");
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* a finite value. May not be {@link Double#isNaN() NaNs} or
* {@link Double#isInfinite() infinities}.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final double value) throws IOException {
getHandle().value(value);
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
writeDeferredName();
beforeValue(false);
out.append(Double.toString(value));
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final long value) throws IOException {
getHandle().value(value);
writeDeferredName();
beforeValue(false);
out.write(Long.toString(value));
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* a finite value. May not be {@link Double#isNaN() NaNs} or
* {@link Double#isInfinite() infinities}.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final Number value) throws IOException {
getHandle().value(value);
if (value == null) {
return nullValue();
}
writeDeferredName();
final String string = value.toString();
if (!this.isLenient() && (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue(false);
out.append(string);
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* the literal string value, or null to encode a null literal.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final String value) throws IOException {
getHandle().value(value);
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue(false);
stringExtend(value);
return this;
}
/**
* Inserts any necessary separators and whitespace before a name. Also
* adjusts the stack to expect the name's value.
*/
private void beforeName() throws IOException {
final int context = peek();
if (context == NONEMPTY_OBJECT) { // first in object
out.write(',');
} else if (context != EMPTY_OBJECT) { // not in an object!
throw new IllegalStateException("Nesting problem.");
}
newline();
replaceTop(DANGLING_NAME);
}
/**
* Inserts any necessary separators and whitespace before a literal value,
* inline array, or inline object. Also adjusts the stack to expect either a
* closing bracket or another element.
*
* @param root
* true if the value is a new array or object, the two values
* permitted as top-level elements.
*/
@SuppressWarnings("fallthrough")
private void beforeValue(final boolean root) throws IOException {
switch (peek()) {
case NONEMPTY_DOCUMENT:
if (!this.isLenient()) {
throw new IllegalStateException("JSON must have only one top-level value.");
}
// fall-through
case EMPTY_DOCUMENT: // first in document
if (!this.isLenient() && !root) {
throw new IllegalStateException("JSON must start with an array or an object.");
}
replaceTop(NONEMPTY_DOCUMENT);
break;
case EMPTY_ARRAY: // first in array
replaceTop(NONEMPTY_ARRAY);
newline();
break;
case NONEMPTY_ARRAY: // another in array
out.append(',');
newline();
break;
case DANGLING_NAME: // value for name
out.append(this.getSeparator());
replaceTop(NONEMPTY_OBJECT);
break;
default:
throw new IllegalStateException("Nesting problem.");
}
}
/**
* Closes the current scope by appending any necessary whitespace and the
* given bracket.
*/
private JsonWriterHandle close(final int empty, final int nonempty, final String closeBracket) throws IOException {
final int context = peek();
if (context != nonempty && context != empty) {
throw new IllegalStateException("Nesting problem.");
}
if (deferredName != null) {
throw new IllegalStateException("Dangling name: " + deferredName);
}
this.setStackSize(this.getStackSize() - 1);
if (context == nonempty) {
newline();
}
out.write(closeBracket);
return this;
}
private void newline() throws IOException {
if (this.getIndent() == null) {
return;
}
out.write("\n");
for (int i = 1, size = this.getStackSize(); i < size; i++) {
out.write(this.getIndent());
}
}
/**
* Enters a new scope by appending any necessary whitespace and the given
* bracket.
*/
private JsonWriterHandle open(final int empty, final String openBracket) throws IOException {
beforeValue(true);
push(empty);
out.write(openBracket);
return this;
}
/**
* Returns the value on the top of the stack.
*/
private int peek() {
if (this.getStackSize() == 0) {
throw new IllegalStateException("JsonWriterHandle is closed.");
}
return this.getStack()[this.getStackSize() - 1];
}
private void push(final int newTop) {
int[] stacks = this.getStack();
if (this.getStackSize() == stacks.length) {
final int[] newStack = new int[stacks.length * 2];
System.arraycopy(stacks, 0, newStack, 0, stacks.length);
stacks = newStack;
this.setStack(stacks);
}
this.setStack(this.getStackSize(), newTop);
this.setStackSize(this.getStackSize() + 1);
}
/**
* Replace the value on the top of the stack with the given value.
*/
private void replaceTop(final int topOfStack) {
this.getStack()[this.getStackSize() - 1] = topOfStack;
}
private void writeDeferredName() throws IOException {
if (deferredName != null) {
beforeName();
stringExtend(deferredName);
deferredName = null;
}
}
}

View File

@ -6,136 +6,223 @@ import java.lang.reflect.Field;
import com.google.gson.stream.JsonWriter;
public class JsonWriterHandle implements cn.citycraft.GsonAgent.api.stream.JsonWriter {
import cn.citycraft.GsonAgent.api.utils.Utils;
private static String[] REPLACEMENT_CHARS;
private static String[] HTML_SAFE_REPLACEMENT_CHARS;
public class JsonWriterHandle extends JsonWriter implements cn.citycraft.GsonAgent.api.stream.JsonWriter {
/*
* From RFC 4627, "All Unicode characters may be placed within the
* quotation marks except for the characters that must be escaped:
* quotation mark, reverse solidus, and the control characters
* (U+0000 through U+001F)."
*
* We also escape '\u2028' and '\u2029', which JavaScript interprets as
* newline characters. This prevents eval() from failing with a syntax
* error. http://code.google.com/p/google-gson/issues/detail?id=341
*/
private static Field stackField, stackSizeField, indentField, separatorField;
static {
final Class<JsonWriter> clzz = JsonWriter.class;
try {
Field field = JsonWriter.class.getDeclaredField("REPLACEMENT_CHARS");
field.setAccessible(true);
REPLACEMENT_CHARS = (String[]) field.get(null);
field = JsonWriter.class.getDeclaredField("HTML_SAFE_REPLACEMENT_CHARS");
field.setAccessible(true);
HTML_SAFE_REPLACEMENT_CHARS = (String[]) field.get(null);
stackField = Utils.getDeclareField(clzz, "stack");
stackSizeField = Utils.getDeclareField(clzz, "stackSize");
indentField = Utils.getDeclareField(clzz, "indent");
separatorField = Utils.getDeclareField(clzz, "separator");
} catch (final Exception e) {
e.printStackTrace();
}
}
private final JsonWriter handle;
private Writer out;
/**
* The output data, containing at most one top-level array or object.
*/
private final Writer out;
private String deferredName;
private boolean withoutQuotes = false;
/**
* Creates a new instance that writes a JSON-encoded stream to {@code out}.
* For best performance, ensure {@link Writer} is buffered; wrapping in
* {@link java.io.BufferedWriter BufferedWriter} if necessary.
*
* @param out
*/
public JsonWriterHandle(final Writer out) {
this(new JsonWriter(out));
super(out);
this.out = out;
}
protected JsonWriterHandle(final JsonWriter handle) {
this.handle = handle;
}
/**
* Begins encoding a new array. Each call to this method must be paired with
* a call to {@link #endArray}.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle beginArray() throws IOException {
getHandle().beginArray();
return this;
writeDeferredName();
return open(EMPTY_ARRAY, "[");
}
/**
* Begins encoding a new object. Each call to this method must be paired
* with a call to {@link #endObject}.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle beginObject() throws IOException {
getHandle().beginObject();
return this;
writeDeferredName();
return open(EMPTY_OBJECT, "{");
}
/**
* Flushes and closes this writer and the underlying {@link Writer}.
*
* @throws IOException
* if the JSON document is incomplete.
*/
@Override
public void close() throws IOException {
getHandle().close();
out.close();
final int size = this.getStackSize();
if (size > 1 || size == 1 && this.getStack()[size - 1] != NONEMPTY_DOCUMENT) {
throw new IOException("Incomplete document");
}
this.setStackSize(0);
}
/**
* Ends encoding the current array.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle endArray() throws IOException {
getHandle().endArray();
return this;
return close(EMPTY_ARRAY, NONEMPTY_ARRAY, "]");
}
/**
* Ends encoding the current object.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle endObject() throws IOException {
getHandle().endObject();
return close(EMPTY_OBJECT, NONEMPTY_OBJECT, "}");
}
/**
* Ensures all buffered data is written to the underlying {@link Writer} and
* flushes that writer.
*
* @throws java.io.IOException
*/
@Override
public void flush() throws IOException {
if (this.getStackSize() == 0) {
throw new IllegalStateException("JsonWriterHandle is closed.");
}
out.flush();
}
public JsonWriterHandle getHandle() {
return this;
}
@Override
public void flush() throws IOException {
getHandle().flush();
public String getIndent() {
return Utils.invokeStringField(this, indentField);
}
public JsonWriter getHandle() {
return handle;
public String getSeparator() {
return Utils.invokeStringField(this, separatorField);
}
@Override
public boolean getSerializeNulls() {
return getHandle().getSerializeNulls();
public int[] getStack() {
return Utils.invokeIntArrayField(this, stackField);
}
@Override
public boolean isHtmlSafe() {
return getHandle().isHtmlSafe();
}
@Override
public boolean isLenient() {
return getHandle().isLenient();
public int getStackSize() {
return Utils.invokeIntField(this, stackSizeField);
}
/**
* Encodes the property name.
*
* @param name
* the name of the forthcoming value. May not be null.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle name(final String name) throws IOException {
getHandle().name(name);
if (name == null) {
throw new NullPointerException("name == null");
}
if (deferredName != null) {
throw new IllegalStateException();
}
if (this.getStackSize() == 0) {
throw new IllegalStateException("JsonWriterHandle is closed.");
}
deferredName = name;
withoutQuotes = false;
return this;
}
@Override
public JsonWriterHandle nameWithoutQuotes(final String name) throws IOException {
getHandle().name(name);
this.name(name);
withoutQuotes = true;
return this;
}
/**
* Encodes {@code null}.
*
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle nullValue() throws IOException {
getHandle().nullValue();
if (deferredName != null) {
if (this.getSerializeNulls()) {
writeDeferredName();
} else {
deferredName = null;
return this; // skip the name and the value
}
}
beforeValue(false);
out.write("null");
return this;
}
@Override
public void setHtmlSafe(final boolean htmlSafe) {
getHandle().setHtmlSafe(htmlSafe);
public void setSeparator(final String separator) {
Utils.modifyField(this, separatorField, separator);
}
@Override
public void setIndent(final String indent) {
getHandle().setIndent(indent);
public void setStack(final int index, final int value) {
final int[] newStack = this.getStack();
newStack[index] = value;
this.setStack(newStack);
}
@Override
public void setLenient(final boolean lenient) {
getHandle().setLenient(lenient);
public void setStack(final int[] stack) {
Utils.modifyField(this, stackField, stack);
}
@Override
public void setSerializeNulls(final boolean serializeNulls) {
getHandle().setSerializeNulls(serializeNulls);
public void setStackSize(final int stackSize) {
Utils.modifyField(this, stackSizeField, stackSize);
}
@Override
public void string(final String value) throws IOException {
final String[] replacements = getHandle().isHtmlSafe() ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
public void stringExtend(final String value) throws IOException {
final String[] replacements = this.isHtmlSafe() ? Utils.HTML_SAFE_REPLACEMENT_CHARS : Utils.REPLACEMENT_CHARS;
if (!this.withoutQuotes) {
this.out.write("\"");
}
@ -144,30 +231,26 @@ public class JsonWriterHandle implements cn.citycraft.GsonAgent.api.stream.JsonW
for (int i = 0; i < length; i++) {
final char c = value.charAt(i);
String replacement;
if (c < '€') {
if (c < 128) {
replacement = replacements[c];
if (replacement == null) {
continue;
}
} else {
if (c == '') {
} else if (c == '\u2028') {
replacement = "\\u2028";
} else if (c == '\u2029') {
replacement = "\\u2029";
} else {
if (c != '') {
continue;
}
replacement = "\\u2029";
}
}
if (last < i) {
this.out.write(value, last, i - last);
out.write(value, last, i - last);
}
this.out.write(replacement);
out.write(replacement);
last = i + 1;
}
if (last < length) {
this.out.write(value, last, length - last);
out.write(value, last, length - last);
}
if (!this.withoutQuotes) {
this.out.write("\"");
@ -175,34 +258,229 @@ public class JsonWriterHandle implements cn.citycraft.GsonAgent.api.stream.JsonW
withoutQuotes = false;
}
/**
* Encodes {@code value}.
*
* @param value
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final boolean value) throws IOException {
getHandle().value(value);
writeDeferredName();
beforeValue(false);
out.write(value ? "true" : "false");
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* a finite value. May not be {@link Double#isNaN() NaNs} or
* {@link Double#isInfinite() infinities}.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final double value) throws IOException {
getHandle().value(value);
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
writeDeferredName();
beforeValue(false);
out.append(Double.toString(value));
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final long value) throws IOException {
getHandle().value(value);
writeDeferredName();
beforeValue(false);
out.write(Long.toString(value));
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* a finite value. May not be {@link Double#isNaN() NaNs} or
* {@link Double#isInfinite() infinities}.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final Number value) throws IOException {
getHandle().value(value);
if (value == null) {
return nullValue();
}
writeDeferredName();
final String string = value.toString();
if (!this.isLenient() && (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue(false);
out.append(string);
return this;
}
/**
* Encodes {@code value}.
*
* @param value
* the literal string value, or null to encode a null literal.
* @return this writer.
* @throws java.io.IOException
*/
@Override
public JsonWriterHandle value(final String value) throws IOException {
getHandle().value(value);
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue(false);
stringExtend(value);
return this;
}
/**
* Inserts any necessary separators and whitespace before a name. Also
* adjusts the stack to expect the name's value.
*/
private void beforeName() throws IOException {
final int context = peek();
if (context == NONEMPTY_OBJECT) { // first in object
out.write(',');
} else if (context != EMPTY_OBJECT) { // not in an object!
throw new IllegalStateException("Nesting problem.");
}
newline();
replaceTop(DANGLING_NAME);
}
/**
* Inserts any necessary separators and whitespace before a literal value,
* inline array, or inline object. Also adjusts the stack to expect either a
* closing bracket or another element.
*
* @param root
* true if the value is a new array or object, the two values
* permitted as top-level elements.
*/
@SuppressWarnings("fallthrough")
private void beforeValue(final boolean root) throws IOException {
switch (peek()) {
case NONEMPTY_DOCUMENT:
if (!this.isLenient()) {
throw new IllegalStateException("JSON must have only one top-level value.");
}
// fall-through
case EMPTY_DOCUMENT: // first in document
if (!this.isLenient() && !root) {
throw new IllegalStateException("JSON must start with an array or an object.");
}
replaceTop(NONEMPTY_DOCUMENT);
break;
case EMPTY_ARRAY: // first in array
replaceTop(NONEMPTY_ARRAY);
newline();
break;
case NONEMPTY_ARRAY: // another in array
out.append(',');
newline();
break;
case DANGLING_NAME: // value for name
out.append(this.getSeparator());
replaceTop(NONEMPTY_OBJECT);
break;
default:
throw new IllegalStateException("Nesting problem.");
}
}
/**
* Closes the current scope by appending any necessary whitespace and the
* given bracket.
*/
private JsonWriterHandle close(final int empty, final int nonempty, final String closeBracket) throws IOException {
final int context = peek();
if (context != nonempty && context != empty) {
throw new IllegalStateException("Nesting problem.");
}
if (deferredName != null) {
throw new IllegalStateException("Dangling name: " + deferredName);
}
this.setStackSize(this.getStackSize() - 1);
if (context == nonempty) {
newline();
}
out.write(closeBracket);
return this;
}
private void newline() throws IOException {
if (this.getIndent() == null) {
return;
}
out.write("\n");
for (int i = 1, size = this.getStackSize(); i < size; i++) {
out.write(this.getIndent());
}
}
/**
* Enters a new scope by appending any necessary whitespace and the given
* bracket.
*/
private JsonWriterHandle open(final int empty, final String openBracket) throws IOException {
beforeValue(true);
push(empty);
out.write(openBracket);
return this;
}
/**
* Returns the value on the top of the stack.
*/
private int peek() {
if (this.getStackSize() == 0) {
throw new IllegalStateException("JsonWriterHandle is closed.");
}
return this.getStack()[this.getStackSize() - 1];
}
private void push(final int newTop) {
int[] stacks = this.getStack();
if (this.getStackSize() == stacks.length) {
final int[] newStack = new int[stacks.length * 2];
System.arraycopy(stacks, 0, newStack, 0, stacks.length);
stacks = newStack;
this.setStack(stacks);
}
this.setStack(this.getStackSize(), newTop);
this.setStackSize(this.getStackSize() + 1);
}
/**
* Replace the value on the top of the stack with the given value.
*/
private void replaceTop(final int topOfStack) {
this.getStack()[this.getStackSize() - 1] = topOfStack;
}
private void writeDeferredName() throws IOException {
if (deferredName != null) {
beforeName();
stringExtend(deferredName);
deferredName = null;
}
}
}