下面列出了怎么用com.fasterxml.jackson.core.JsonLocation的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings("unchecked")
private void readRepeated(EB msg, JsonParser par) throws IOException {
par.nextToken();
JsonToken tokLast = par.getCurrentToken();
JsonLocation locLast = par.getCurrentLocation();
for (startArray(par); endArray(par); par.nextToken()) {
boolean objRead = false;
XB ext = (XB) key.getMessageDefaultInstance().toBuilder();
for (startObject(par); endObject(par); par.nextToken()) {
read(ext, par);
JsonToken tokNew = par.getCurrentToken();
JsonLocation locNew = par.getCurrentLocation();
if (tokNew != tokLast || !locNew.equals(locLast)) {
objRead = true;
}
tokLast = tokNew;
locLast = locNew;
}
if (objRead) {
msg.addExtension(key, ext.build());
}
}
}
private ValueInstantiator _findStdValueInstantiator(DeserializationConfig config,
BeanDescription beanDesc)
throws JsonMappingException
{
Class<?> raw = beanDesc.getBeanClass();
if (raw == JsonLocation.class) {
return new JsonLocationInstantiator();
}
// [databind#1868]: empty List/Set/Map
if (Collection.class.isAssignableFrom(raw)) {
if (Collections.EMPTY_SET.getClass() == raw) {
return new ConstantValueInstantiator(Collections.EMPTY_SET);
}
if (Collections.EMPTY_LIST.getClass() == raw) {
return new ConstantValueInstantiator(Collections.EMPTY_LIST);
}
} else if (Map.class.isAssignableFrom(raw)) {
if (Collections.EMPTY_MAP.getClass() == raw) {
return new ConstantValueInstantiator(Collections.EMPTY_MAP);
}
}
return null;
}
private Response fromJsonProcessingException(JsonProcessingException e) {
StringBuilder msgBuilder = new StringBuilder();
if (e.getOriginalMessage() != null) {
msgBuilder.append(e.getOriginalMessage());
} else {
msgBuilder.append("JSON processing error");
}
JsonLocation location = e.getLocation();
if (location != null) {
msgBuilder.append(" location: [line: ").append(location.getLineNr())
.append(", column: ").append(location.getColumnNr()).append(']');
}
ErrorResponse errorResponse = ErrorResponse.newError(HttpServletResponse.SC_BAD_REQUEST, msgBuilder.toString())
.clientRequest(httpServletRequest)
.serverContext()
.exceptionContext(e)
.build();
return Response.status(Status.BAD_REQUEST).entity(errorResponse).build();
}
@Test
public void testDelegateDeclaredExceptionPropagation() throws Exception {
doThrow(new JsonParseException("Simulated declared exception", JsonLocation.NA)).when(_delegate).doIt();
TestInterface service = _serviceFactory.create(_remoteEndPoint);
try {
service.doIt();
fail("JsonParseException not thrown");
} catch (JsonParseException e) {
assertEquals(e.getOriginalMessage(), "Simulated declared exception");
}
assertEquals(_metricRegistry.getMeters().get("bv.emodb.web.partition-forwarding.TestInterface.errors").getCount(), 0);
verify(_delegateServiceFactory).create(_remoteEndPoint);
verify(_delegate).doIt();
}
@Test
public void testSafeObjectMapperWriteValueAsStringJsonParseException()
{
// Create a tag entity.
final TagEntity tagEntity = tagDaoTestHelper.createTagEntity(TAG_TYPE, TAG_CODE, TAG_DISPLAY_NAME, TAG_DESCRIPTION);
// Mock the external calls.
when(jsonHelper.objectToJson(any()))
.thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2))));
// Call the method being tested.
String result = tagHelper.safeObjectMapperWriteValueAsString(tagEntity);
// Verify the external calls.
verify(jsonHelper).objectToJson(any());
verifyNoMoreInteractions(alternateKeyHelper, jsonHelper);
// Validate the returned object.
assertEquals("", result);
}
@Override
public AbstractNode deserialize(JsonParser p, DeserializationContext context)
throws IOException, JsonProcessingException {
JsonLocation startLocation = p.getTokenLocation();
if (p.getCurrentToken() == JsonToken.FIELD_NAME) {
p.nextToken();
}
switch (p.getCurrentToken()) {
case START_OBJECT:
return deserializeObjectNode(p, context, startLocation);
case START_ARRAY:
return deserializeArrayNode(p, context, startLocation);
default:
return deserializeValueNode(p, context, startLocation);
}
}
@Override
public String toString() {
JsonLocation location = parser.getCurrentLocation();
return getClass().getSimpleName() + "[Line=" + location.getLineNr()
+ ", Column=" + (location.getColumnNr() + 1)
+ ", Field=" + getCurrentField()
+ "]";
}
@Override
public UserException.Builder getExceptionWithContext(UserException.Builder builder, String message) {
builder.message(message);
JsonLocation location = parser.getCurrentLocation();
builder.addContext("Line", location.getLineNr())
.addContext("Column", location.getColumnNr() + 1);
String fieldName = getCurrentField();
if (fieldName != null) {
builder.addContext("Field", fieldName);
}
return builder;
}
@Override
public final DbxOAuthError read(JsonParser parser)
throws IOException, JsonReadException
{
JsonLocation top = JsonReader.expectObjectStart(parser);
String error = null;
String errorDescription = null;
while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
String fieldName = parser.getCurrentName();
parser.nextToken();
try {
if (fieldName.equals("error")) {
error = StringReader.readField(parser, fieldName, error);
}
else if (fieldName.equals("error_description")) {
errorDescription = StringReader.readField(parser, fieldName, errorDescription);
}
else {
// Unknown field. Skip over it.
JsonReader.skipValue(parser);
}
}
catch (JsonReadException ex) {
throw ex.addFieldContext(fieldName);
}
}
JsonReader.expectObjectEnd(parser);
if (error == null) {
throw new JsonReadException("missing field \"error\"", top);
}
return new DbxOAuthError(error, errorDescription);
}
public final Quota read(JsonParser parser)
throws IOException, JsonReadException
{
JsonLocation top = JsonReader.expectObjectStart(parser);
long quota = -1;
long normal = -1;
long shared = -1;
while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
String fieldName = parser.getCurrentName();
parser.nextToken();
int fi = FM.get(fieldName);
try {
switch (fi) {
case -1: JsonReader.skipValue(parser); break;
case FM_quota: quota = JsonReader.readUnsignedLongField(parser, fieldName, quota); break;
case FM_normal: normal = JsonReader.readUnsignedLongField(parser, fieldName, normal); break;
case FM_shared: shared = JsonReader.readUnsignedLongField(parser, fieldName, shared); break;
default:
throw new AssertionError("bad index: " + fi + ", field = \"" + fieldName + "\"");
}
}
catch (JsonReadException ex) {
throw ex.addFieldContext(fieldName);
}
}
JsonReader.expectObjectEnd(parser);
if (quota < 0) throw new JsonReadException("missing field \"quota\"", top);
if (normal < 0) throw new JsonReadException("missing field \"normal\"", top);
if (shared < 0) throw new JsonReadException("missing field \"shared\"", top);
return new Quota(quota, normal, shared);
}
@Override
public Sha256Hash deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
Sha256Hash hash = Sha256Hash.fromString(node.asText());
if (hash == null) {
throw new JsonParseException("Failed to convert string '" + node.asText() + "' into a Sha256 hash",
JsonLocation.NA);
}
return hash;
}
@Override
public DbxLongpollDeltaResult read(JsonParser parser) throws IOException, JsonReadException
{
JsonLocation top = JsonReader.expectObjectStart(parser);
Boolean changes = null;
long backoff = -1;
while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
String fieldName = parser.getCurrentName();
parser.nextToken();
try {
if (fieldName.equals("changes")) {
changes = JsonReader.BooleanReader.readField(parser, fieldName, changes);
} else if (fieldName.equals("backoff")) {
backoff = JsonReader.readUnsignedLongField(parser, fieldName, backoff);
} else {
JsonReader.skipValue(parser);
}
} catch (JsonReadException ex) {
throw ex.addFieldContext(fieldName);
}
}
JsonReader.expectObjectEnd(parser);
if (changes == null) throw new JsonReadException("missing field \"changes\"", top);
return new DbxLongpollDeltaResult(changes, backoff);
}
@Override
public Sha256Hash deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
Sha256Hash hash = Sha256Hash.fromString(node.asText());
if (hash == null) {
throw new JsonParseException("Failed to convert string '" + node.asText() + "' into a Sha256 hash",
JsonLocation.NA);
}
return hash;
}
@Override
public CustomValue getNullValue(DeserializationContext ctxt){
JsonLocation currentLocation = ctxt.getParser().getCurrentLocation();
int lineNr = currentLocation.getLineNr();
int column = currentLocation.getColumnNr();
return new NullValue(lineNr, column);
}
@Override
public String read(JsonParser parser) throws IOException, JsonReadException {
JsonLocation top = JsonReader.expectObjectStart(parser);
String cursorId = null;
while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
String fieldName = parser.getCurrentName();
parser.nextToken();
try {
if (fieldName.equals("cursor")) {
cursorId = JsonReader.StringReader.readField(parser, fieldName, cursorId);
} else {
JsonReader.skipValue(parser);
}
} catch (JsonReadException ex) {
throw ex.addFieldContext(fieldName);
}
}
JsonReader.expectObjectEnd(parser);
if (cursorId == null) throw new JsonReadException("missing field \"cursor\"", top);
return cursorId;
}
public final DbxEntry.Folder read(JsonParser parser)
throws IOException, JsonReadException
{
JsonLocation top = parser.getCurrentLocation();
DbxEntry e = DbxEntry.read(parser, null).entry;
if (!(e instanceof DbxEntry.Folder)) {
throw new JsonReadException("Expecting a file entry, got a folder entry", top);
}
return (DbxEntry.Folder) e;
}
/**
* @deprecated Since 2.7
*/
@Deprecated // since 2.7
public UnrecognizedPropertyException(String msg, JsonLocation loc,
Class<?> referringClass, String propName,
Collection<Object> propertyIds)
{
super(msg, loc, referringClass, propName, propertyIds);
}
/**
* @deprecated Since 2.7 Use variant that takes {@link JsonParser}
*/
@Deprecated // since 2.7
public InvalidFormatException(String msg, JsonLocation loc,
Object value, Class<?> targetType)
{
super(null, msg, loc);
_value = value;
_targetType = targetType;
}
/**
* @since 2.7
*/
protected PropertyBindingException(JsonParser p, String msg, JsonLocation loc,
Class<?> referringClass, String propName,
Collection<Object> propertyIds)
{
super(p, msg, loc);
_referringClass = referringClass;
_propertyName = propName;
_propertyIds = propertyIds;
}
private String getLocationString() {
JsonLocation l = parser.getCurrentLocation();
List<String> parts = new ArrayList<>(4);
parts.add("line: " + l.getLineNr());
parts.add("column: " + l.getColumnNr());
if (l.getByteOffset() >= 0) {
parts.add("byte offset: " + l.getByteOffset());
}
return parts.toString();
}
/**
* @since 2.7
*/
public IgnoredPropertyException(JsonParser p, String msg, JsonLocation loc,
Class<?> referringClass, String propName,
Collection<Object> propertyIds)
{
super(p, msg, loc, referringClass, propName, propertyIds);
}
/**
* @deprecated Since 2.7
*/
@Deprecated
public IgnoredPropertyException(String msg, JsonLocation loc,
Class<?> referringClass, String propName,
Collection<Object> propertyIds)
{
super(msg, loc, referringClass, propName, propertyIds);
}
public static JsonLocation expectObjectStart(JsonParser parser)
throws IOException, JsonReadException
{
if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
throw new JsonReadException("expecting the start of an object (\"{\")", parser.getTokenLocation());
}
JsonLocation loc = parser.getTokenLocation();
nextToken(parser);
return loc;
}
public static JsonNode build(final JsonProcessingException e,
final boolean crlf)
{
final JsonLocation location = e.getLocation();
final ObjectNode ret = JsonNodeFactory.instance.objectNode();
/*
* Unfortunately, for some reason, Jackson botches the column number in
* its JsonPosition -- I cannot figure out why exactly. However, it does
* have a correct offset into the buffer.
*
* The problem is that if the input has CR/LF line terminators, its
* offset will be "off" by the number of lines minus 1 with regards to
* what JavaScript sees as positions in text areas. Make the necessary
* adjustments so that the caret jumps at the correct position in this
* case.
*/
final int lineNr = location.getLineNr();
int offset = (int) location.getCharOffset();
if (crlf)
offset = offset - lineNr + 1;
ret.put(LINE, lineNr);
ret.put(OFFSET, offset);
// Finally, put the message
ret.put(MESSAGE, e.getOriginalMessage());
return ret;
}
@Override
public Address deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
Address address = Address.fromString(node.asText());
if (address == null) {
throw new JsonParseException("Failed to convert string '" + node.asText() + "' into an address",
JsonLocation.NA);
}
return address;
}
private void throwParsingError(JsonLocation jsonLocation, String message) {
throw BusinessException.createNew(DataErrorCode.FAILED_TO_PARSE_DATA_STREAM)
.put("parsingError", message)
.put("line", jsonLocation.getLineNr())
.put("col", jsonLocation.getColumnNr())
.put("offset", jsonLocation.getCharOffset());
}
public static JsonLocation expectArrayEnd(JsonParser parser)
throws IOException, JsonReadException
{
if (parser.getCurrentToken() != JsonToken.END_ARRAY) {
throw new JsonReadException("expecting the end of an array (\"[\")", parser.getTokenLocation());
}
JsonLocation loc = parser.getTokenLocation();
nextToken(parser);
return loc;
}
public static JsonLocation expectArrayStart(JsonParser parser)
throws IOException, JsonReadException
{
if (parser.getCurrentToken() != JsonToken.START_ARRAY) {
throw new JsonReadException("expecting the start of an array (\"[\")", parser.getTokenLocation());
}
JsonLocation loc = parser.getTokenLocation();
nextToken(parser);
return loc;
}
/**
* Overridden since we do not really have character-based locations,
* but we do have byte offset to specify.
*/
@Override
public JsonLocation getCurrentLocation()
{
final long offset = _currInputProcessed + _inputPtr;
return new JsonLocation(_ioContext.getSourceReference(),
offset, // bytes
-1, -1, (int) offset); // char offset, line, column
}
@Override
public CopyRef read(JsonParser parser)
throws IOException, JsonReadException
{
JsonLocation top = JsonReader.expectObjectStart(parser);
String id = null;
Date expires = null;
while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
String fieldName = parser.getCurrentName();
parser.nextToken();
try {
if (fieldName.equals("copy_ref")) {
id = JsonReader.StringReader.readField(parser, fieldName, id);
}
else if (fieldName.equals("expires")) {
expires = JsonDateReader.Dropbox.readField(parser, fieldName, expires);
}
else {
JsonReader.skipValue(parser);
}
}
catch (JsonReadException ex) {
throw ex.addFieldContext(fieldName);
}
}
JsonReader.expectObjectEnd(parser);
if (id == null) throw new JsonReadException("missing field \"copy_ref\"", top);
if (expires == null) throw new JsonReadException("missing field \"expires\"", top);
return new CopyRef(id, expires);
}