Java Code Examples for com.fasterxml.jackson.core.JsonLocation

The following examples show how to use com.fasterxml.jackson.core.JsonLocation. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openrtb   Source File: OpenRtbJsonExtComplexReader.java    License: Apache License 2.0 6 votes vote down vote up
@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());
    }
  }
}
 
Example 2
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;
}
 
Example 3
Source Project: titus-control-plane   Source File: TitusExceptionMapper.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 4
Source Project: emodb   Source File: PartitionAwareServiceFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source Project: herd   Source File: TagHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 6
@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);
    }
}
 
Example 7
Source Project: Bats   Source File: BaseJsonProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  JsonLocation location = parser.getCurrentLocation();
  return getClass().getSimpleName() + "[Line=" + location.getLineNr()
      + ", Column=" + (location.getColumnNr() + 1)
      + ", Field=" + getCurrentField()
      + "]";
}
 
Example 8
Source Project: Bats   Source File: BaseJsonProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 9
Source Project: dropbox-sdk-java   Source File: DbxOAuthError.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 10
Source Project: dropbox-sdk-java   Source File: DbxAccountInfo.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 11
@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;
}
 
Example 12
Source Project: dropbox-sdk-java   Source File: DbxLongpollDeltaResult.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 13
@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;
}
 
Example 14
Source Project: sailfish-core   Source File: JSONMatrixParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CustomValue getNullValue(DeserializationContext ctxt){
    JsonLocation currentLocation = ctxt.getParser().getCurrentLocation();
    int lineNr = currentLocation.getLineNr();
    int column = currentLocation.getColumnNr();
    return new NullValue(lineNr, column);
}
 
Example 15
Source Project: dropbox-sdk-java   Source File: DbxClientV1.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 16
Source Project: dropbox-sdk-java   Source File: DbxEntry.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 17
/**
 * @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);
}
 
Example 18
Source Project: lams   Source File: InvalidFormatException.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example 19
/**
 * @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;
}
 
Example 20
Source Project: immutables   Source File: JsonParserReader.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 21
/**
 * @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);
}
 
Example 22
/**
 * @deprecated Since 2.7
 */
@Deprecated
public IgnoredPropertyException(String msg, JsonLocation loc,
        Class<?> referringClass, String propName,
        Collection<Object> propertyIds)
{
    super(msg, loc, referringClass, propName, propertyIds);
}
 
Example 23
Source Project: dropbox-sdk-java   Source File: JsonReader.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 24
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;
}
 
Example 25
Source Project: bitshares_wallet   Source File: BitlibJsonModule.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 26
Source Project: business   Source File: DataManagerImpl.java    License: Mozilla Public License 2.0 5 votes vote down vote up
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());
}
 
Example 27
Source Project: dropbox-sdk-java   Source File: JsonReader.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 28
Source Project: dropbox-sdk-java   Source File: JsonReader.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 29
Source Project: caravan   Source File: CustomProtobufParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
}
 
Example 30
Source Project: dropbox-sdk-java   Source File: DbxClientV1.java    License: MIT License 5 votes vote down vote up
@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);
}