Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/json/custom-codecs.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,12 @@ representation, such as `MoneyCodec` above, does not reserve graph memory. Compl
perform their own application validation; Fory JSON does not wrap a complete custom representation
with the target type's `JsonValidator` methods.

A codec can reject a malformed value by throwing any unchecked exception. When `fromJson` reads the
value, Fory JSON reports that exception as a `ForyJsonException` that keeps it as the cause and
names the JSON position, so callers can handle every read failure through `ForyException`. A
`ForyException` thrown by the codec and any `Error` propagate unchanged. Exceptions thrown while
writing, or inside an operation passed to `ForyJson.readUtf8`, keep their own type.

Registering a custom codec for a `JsonSubTypes` base replaces that base's subtype annotation.
Registering one for a listed subtype is supported by the two wrapper inclusions but not by inline
property inclusion.
Expand Down
66 changes: 60 additions & 6 deletions java/fory-json/src/main/java/org/apache/fory/json/ForyJson.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.fory.exception.ForyException;
import org.apache.fory.json.reader.JsonReader;
import org.apache.fory.json.reader.Latin1JsonReader;
import org.apache.fory.json.reader.Utf16JsonReader;
Expand Down Expand Up @@ -999,7 +1000,14 @@ private Object readJavaStringValue(String json, TypeRef<?> type, JsonState state

private Object readLatin1Value(Latin1JsonReader reader, Class<?> type, JsonState state) {
JsonTypeInfo typeInfo = state.declaredRootTypeInfo(type);
Object value = typeInfo.latin1Reader().readLatin1(reader);
Object value;
try {
value = typeInfo.latin1Reader().readLatin1(reader);
} catch (ForyException e) {
throw e;
} catch (RuntimeException e) {
throw readFailure(reader, e);
}
reader.finish();
return value;
}
Expand All @@ -1010,14 +1018,28 @@ private Object readLatin1Value(Latin1JsonReader reader, TypeRef<?> type, JsonSta
reader.finish();
return null;
}
Object value = typeInfo.latin1Reader().readLatin1(reader);
Object value;
try {
value = typeInfo.latin1Reader().readLatin1(reader);
} catch (ForyException e) {
throw e;
} catch (RuntimeException e) {
throw readFailure(reader, e);
}
reader.finish();
return value;
}

private Object readUtf16Value(Utf16JsonReader reader, Class<?> type, JsonState state) {
JsonTypeInfo typeInfo = state.declaredRootTypeInfo(type);
Object value = typeInfo.utf16Reader().readUtf16(reader);
Object value;
try {
value = typeInfo.utf16Reader().readUtf16(reader);
} catch (ForyException e) {
throw e;
} catch (RuntimeException e) {
throw readFailure(reader, e);
}
reader.finish();
return value;
}
Expand All @@ -1028,14 +1050,28 @@ private Object readUtf16Value(Utf16JsonReader reader, TypeRef<?> type, JsonState
reader.finish();
return null;
}
Object value = typeInfo.utf16Reader().readUtf16(reader);
Object value;
try {
value = typeInfo.utf16Reader().readUtf16(reader);
} catch (ForyException e) {
throw e;
} catch (RuntimeException e) {
throw readFailure(reader, e);
}
reader.finish();
return value;
}

private Object readUtf8Value(Utf8JsonReader reader, Class<?> type, JsonState state) {
JsonTypeInfo typeInfo = state.declaredRootTypeInfo(type);
Object value = typeInfo.utf8Reader().readUtf8(reader);
Object value;
try {
value = typeInfo.utf8Reader().readUtf8(reader);
} catch (ForyException e) {
throw e;
} catch (RuntimeException e) {
throw readFailure(reader, e);
}
reader.finish();
return value;
}
Expand All @@ -1046,11 +1082,29 @@ private Object readUtf8Value(Utf8JsonReader reader, TypeRef<?> type, JsonState s
reader.finish();
return null;
}
Object value = typeInfo.utf8Reader().readUtf8(reader);
Object value;
try {
value = typeInfo.utf8Reader().readUtf8(reader);
} catch (ForyException e) {
throw e;
} catch (RuntimeException e) {
throw readFailure(reader, e);
}
reader.finish();
return value;
}

/**
* Reports an unchecked failure of the root value read, such as one thrown by a custom codec, as a
* {@link ForyJsonException} that keeps the failure as its cause. Fory exceptions and errors are
* not routed here. Wrapping once per root read keeps codec, property, and generated read paths
* free of per-value exception handling.
*/
private static ForyJsonException readFailure(JsonReader reader, RuntimeException cause) {
return new ForyJsonException(
"Cannot read JSON value at JSON position " + reader.position() + ": " + cause, cause);
}

private static boolean readOuterNull(JsonReader reader, TypeRef<?> type, JsonTypeInfo typeInfo) {
if (!typeInfo.nullable() && !typeInfo.rejectsNull()) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@
* Root runtime exception for JSON syntax, mapping, codec, generated-code, and resource-limit
* failures reported by Fory JSON.
*
* <p>User exceptions thrown by custom code may retain their own type; this exception identifies
* failures owned and contextualized by the JSON runtime itself.
* <p>An unchecked exception thrown by application code, such as a custom codec, while a {@code
* fromJson} root operation reads its value is reported as this exception with the original
* exception as its cause. A {@link ForyException} or an {@link Error} propagates unchanged. Write
* operations and the operations passed to {@link ForyJson#readUtf8} and {@link ForyJson#writeUtf8}
* may propagate application exceptions with their own type.
*/
public class ForyJsonException extends ForyException {
public ForyJsonException(String message) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
package org.apache.fory.json;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.fail;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -42,6 +45,7 @@
import org.apache.fory.json.annotation.JsonCreator;
import org.apache.fory.json.annotation.JsonIgnore;
import org.apache.fory.json.annotation.JsonProperty;
import org.apache.fory.json.codec.AbstractJsonValueCodec;
import org.apache.fory.json.codec.JsonValueCodec;
import org.apache.fory.json.codec.MapKeyCodec;
import org.apache.fory.json.reader.JsonReader;
Expand All @@ -52,6 +56,8 @@
import org.apache.fory.json.writer.StringJsonWriter;
import org.apache.fory.json.writer.Utf8JsonWriter;
import org.apache.fory.platform.JdkVersion;
import org.apache.fory.reflect.TypeRef;
import org.testng.Assert.ThrowingRunnable;
import org.testng.SkipException;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
Expand Down Expand Up @@ -80,6 +86,47 @@ public void representations() {
"utf8:x");
}

@Test
public void codecFailure() {
ForyJson json = newJson();
assertCodecFailure(json, Amount.class, "\"x\"");
assertCodecFailure(json, Amount.class, "\"é\"");
assertCodecFailure(json, Amount.class, "\"你\"");
assertCodecFailure(json, AmountHolder.class, "{\"amount\":\"x\"}");
assertCodecFailure(json, AmountHolder.class, "{\"amount\":\"你\"}");
assertGeneratedWhenSupported(json, AmountHolder.class);
assertSame(
expectThrows(
ForyJsonException.class,
() -> json.fromJson("{\"amount\":\"fory\"}", AmountHolder.class)),
AmountCodec.FORY_FAILURE);
assertSame(
expectThrows(
AmountCodecError.class,
() ->
json.fromJson(
"{\"amount\":\"error\"}".getBytes(StandardCharsets.UTF_8), AmountHolder.class)),
AmountCodec.ERROR);
assertEquals(json.fromJson("{\"amount\":\"12\"}", AmountHolder.class).amount.cents, 12L);
}

private static void assertCodecFailure(ForyJson json, Class<?> type, String text) {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
ThrowingRunnable[] reads = {
() -> json.fromJson(text, type),
() -> json.fromJson(text, TypeRef.of(type)),
() -> json.fromJson(bytes, type),
() -> json.fromJson(bytes, TypeRef.of(type)),
() -> json.fromJson(bytes, 0, bytes.length, type),
() -> json.fromJson(new ByteArrayInputStream(bytes), type)
};
for (ThrowingRunnable read : reads) {
ForyJsonException e = expectThrows(ForyJsonException.class, read);
assertTrue(e.getCause() instanceof NumberFormatException, String.valueOf(e.getCause()));
assertTrue(e.getMessage().contains("JSON position"), e.getMessage());
}
}

@Test
public void propertyDeclarations() {
ForyJson json = newJson();
Expand Down Expand Up @@ -1412,4 +1459,41 @@ public void put(@JsonCodec(AStringCodec.class) String key, String value) {}

@JsonCodec(elementCodec = AStringCodec.class)
public static class InvalidTypeDeclaration {}

@JsonCodec(AmountCodec.class)
public static final class Amount {
final long cents;

Amount(long cents) {
this.cents = cents;
}
}

public static class AmountHolder {
public Amount amount;
}

public static final class AmountCodecError extends Error {}

public static class AmountCodec extends AbstractJsonValueCodec<Amount> {
static final ForyJsonException FORY_FAILURE = new ForyJsonException("invalid amount");
static final AmountCodecError ERROR = new AmountCodecError();

@Override
public void write(JsonWriter writer, Amount value) {
writer.writeString(Long.toString(value.cents));
}

@Override
public Amount read(JsonReader reader) {
String text = reader.readString();
if (text.equals("fory")) {
throw FORY_FAILURE;
}
if (text.equals("error")) {
throw ERROR;
}
return new Amount(Long.parseLong(text));
}
}
}
Loading