Java Code Examples for com.fasterxml.jackson.core.JsonParser#getCurrentLocation()

The following examples show how to use com.fasterxml.jackson.core.JsonParser#getCurrentLocation() . 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 File: ArrowRecordBatchSerDe.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@Override
protected ArrowRecordBatch doDeserialize(JsonParser jparser, DeserializationContext ctxt)
        throws IOException
{
    if (jparser.nextToken() != JsonToken.VALUE_EMBEDDED_OBJECT) {
        throw new IllegalStateException("Expecting " + JsonToken.VALUE_STRING + " but found " + jparser.getCurrentLocation());
    }
    byte[] bytes = jparser.getBinaryValue();
    AtomicReference<ArrowRecordBatch> batch = new AtomicReference<>();
    try {
        return blockAllocator.registerBatch((BufferAllocator root) -> {
            batch.set((ArrowRecordBatch) MessageSerializer.deserializeMessageBatch(
                    new ReadChannel(Channels.newChannel(new ByteArrayInputStream(bytes))), root));
            return batch.get();
        });
    }
    catch (Exception ex) {
        if (batch.get() != null) {
            batch.get().close();
        }
        throw ex;
    }
}
 
Example 2
Source File: StdCallbackContext.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Object readCollection(Class<?> type, JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.isExpectedStartArrayToken()) {
        throw new JsonParseException(p, "Expected array for encoded object got " + p.currentToken());
    }
    try {
        Collection<Object> value = (Collection<Object>) type.getDeclaredConstructor().newInstance();
        p.nextToken(); // move to next token
        do {
            Object val = readObject(p, ctxt);
            value.add(val);
        } while (p.nextToken() != JsonToken.END_ARRAY);
        return value;
    } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
        throw new IOException("Can not create empty constructor collection class " + type + " @ "
            + p.getCurrentLocation(), e);
    }
}
 
Example 3
Source File: OpenRtbJsonExtComplexReader.java    From openrtb with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void readSingle(EB msg, JsonParser par, XB ext) throws IOException {
  if (isJsonObject) {
    startObject(par);
  }
  boolean extRead = false;
  JsonToken tokLast = par.getCurrentToken();
  JsonLocation locLast = par.getCurrentLocation();
  while (endObject(par) && (isJsonObject || filter(par))) {
    read(ext, par);
    if (par.getCurrentToken() != tokLast || !par.getCurrentLocation().equals(locLast)) {
      extRead = true;
      par.nextToken();
      tokLast = par.getCurrentToken();
      locLast = par.getCurrentLocation();
    } else {
      break;
    }
  }
  if (extRead) {
    msg.setExtension(key, ext.build());
  }
  if (isJsonObject) {
    par.nextToken();
  }
}
 
Example 4
Source File: IgnoredPropertyException.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Factory method used for constructing instances of this exception type.
 * 
 * @param p Underlying parser used for reading input being used for data-binding
 * @param fromObjectOrClass Reference to either instance of problematic type (
 *    if available), or if not, type itself
 * @param propertyName Name of unrecognized property
 * @param propertyIds (optional, null if not available) Set of properties that
 *    type would recognize, if completely known: null if set cannot be determined.
 */
public static IgnoredPropertyException from(JsonParser p,
        Object fromObjectOrClass, String propertyName,
        Collection<Object> propertyIds)
{
    Class<?> ref;
    if (fromObjectOrClass instanceof Class<?>) {
        ref = (Class<?>) fromObjectOrClass;
    } else { // also acts as null check:
        ref = fromObjectOrClass.getClass();
    }
    String msg = String.format("Ignored field \"%s\" (class %s) encountered; mapper configured not to allow this",
            propertyName, ref.getName());
    IgnoredPropertyException e = new IgnoredPropertyException(p, msg,
            p.getCurrentLocation(), ref, propertyName, propertyIds);
    // but let's also ensure path includes this last (missing) segment
    e.prependPath(fromObjectOrClass, propertyName);
    return e;
}
 
Example 5
Source File: JsonBufferedObject.java    From RedReader with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void buildBuffered(final JsonParser jp) throws IOException {

	JsonToken jt;

	while((jt = jp.nextToken()) != JsonToken.END_OBJECT) {

		if(jt != JsonToken.FIELD_NAME)
			throw new JsonParseException(jp, "Expecting field name, got " + jt.name(),
					jp.getCurrentLocation());

		final String fieldName = jp.getCurrentName();
		final JsonValue value = new JsonValue(jp);

		synchronized(this) {
			properties.put(fieldName, value);
			notifyAll();
		}

		value.buildInThisThread();
	}
}
 
Example 6
Source File: UnrecognizedPropertyException.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Factory method used for constructing instances of this exception type.
 * 
 * @param p Underlying parser used for reading input being used for data-binding
 * @param fromObjectOrClass Reference to either instance of problematic type (
 *    if available), or if not, type itself
 * @param propertyName Name of unrecognized property
 * @param propertyIds (optional, null if not available) Set of properties that
 *    type would recognize, if completely known: null if set cannot be determined.
 */
public static UnrecognizedPropertyException from(JsonParser p,
        Object fromObjectOrClass, String propertyName,
        Collection<Object> propertyIds)
{
    Class<?> ref;
    if (fromObjectOrClass instanceof Class<?>) {
        ref = (Class<?>) fromObjectOrClass;
    } else {
        ref = fromObjectOrClass.getClass();
    }
    String msg = String.format("Unrecognized field \"%s\" (class %s), not marked as ignorable",
            propertyName, ref.getName());
    UnrecognizedPropertyException e = new UnrecognizedPropertyException(p, msg,
            p.getCurrentLocation(), ref, propertyName, propertyIds);
    // but let's also ensure path includes this last (missing) segment
    e.prependPath(fromObjectOrClass, propertyName);
    return e;
}
 
Example 7
Source File: DbxEntry.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public final DbxEntry.File read(JsonParser parser)
    throws IOException, JsonReadException
{
    JsonLocation top = parser.getCurrentLocation();
    DbxEntry e = DbxEntry.read(parser, null).entry;
    if (!(e instanceof DbxEntry.File)) {
        throw new JsonReadException("Expecting a file entry, got a folder entry", top);
    }
    return (DbxEntry.File) e;
}
 
Example 8
Source File: DbxEntry.java    From dropbox-sdk-java with 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 9
Source File: CustomEntityDeserializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
    T result;
    try {
        result = clazz.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
        throw new IOException("Error deserializing JSON!", ex);
    }
    // need to make subclass of this class for every Entity subclass with custom field to get expected class!!!
    BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz));
    ObjectMapper mapper = (ObjectMapper) parser.getCodec();
    JsonNode obj = mapper.readTree(parser);
    List<BeanPropertyDefinition> properties = beanDescription.findProperties();
    Iterator<Map.Entry<String, JsonNode>> i = obj.fields();

    // First check if we know all properties that are present.
    if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        while (i.hasNext()) {
            Map.Entry<String, JsonNode> next = i.next();
            String fieldName = next.getKey();
            Optional<BeanPropertyDefinition> findFirst = properties.stream().filter(p -> p.getName().equals(fieldName)).findFirst();
            if (!findFirst.isPresent()) {
                throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName, parser.getCurrentLocation(), clazz, fieldName, null);
            }
        }
    }

    for (BeanPropertyDefinition classProperty : properties) {
        deserialiseProperty(obj, classProperty, properties, mapper, result);
    }
    return result;
}
 
Example 10
Source File: DbxEntry.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public final DbxEntry./*@Nullable*/File read(JsonParser parser)
    throws IOException, JsonReadException
{
    JsonLocation top = parser.getCurrentLocation();
    WithChildrenC<?> wc = DbxEntry._read(parser, null, true);
    if (wc == null) return null;
    DbxEntry e = wc.entry;
    if (!(e instanceof DbxEntry.File)) {
        throw new JsonReadException("Expecting a file entry, got a folder entry", top);
    }
    return (DbxEntry.File) e;
}
 
Example 11
Source File: JsonReader.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public T readFully(JsonParser parser)
    throws IOException, JsonReadException
{
    parser.nextToken();
    T value = this.read(parser);
    if (parser.getCurrentToken() != null) {
        throw new AssertionError("The JSON library should ensure there's no tokens after the main value: "
                                 + parser.getCurrentToken() + "@" + parser.getCurrentLocation());
    }
    validate(value);
    return value;
}
 
Example 12
Source File: JsonEntityParser.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public static Message parseMessage(IDictionaryManager dictionaryManager, JsonParser parser, Map<String, String> rootFields, boolean compact, boolean storeId) throws JsonParseException, IOException {
    try {
        parser.nextToken();

        String protocol = rootFields.get(JsonMessageConverter.JSON_MESSAGE_PROTOCOL);
        String dictionaryURI = rootFields.get(JsonMessageConverter.JSON_MESSAGE_DICTIONARY_URI);
        String dirty = ObjectUtils.defaultIfNull(rootFields.get(JsonMessageConverter.JSON_MESSAGE_DIRTY), "");

        JsonMLMessageDecoder decoder = new JsonMLMessageDecoder(dictionaryManager, dictionaryURI, protocol);
        boolean isDirty = !dirty.isEmpty() && Boolean.parseBoolean(dirty);

        Message message;
        if (storeId) {
            message = decoder.parse(parser, compact);
        } else {
            message = decoder.parse(parser,
                    protocol,
                    SailfishURI.parse(dictionaryURI),
                    rootFields.get(JsonMessageConverter.JSON_MESSAGE_NAMESPACE),
                    rootFields.get(JsonMessageConverter.JSON_MESSAGE_NAME),
                    compact, isDirty);
        }

        message.setDirty(isDirty);

        return message;

    } catch (RuntimeException | SailfishURIException e) {
        throw new JsonParseException("Incorrect data for parsing message", parser.getCurrentLocation(), e);
    }
}
 
Example 13
Source File: Rectangle2DDeserializer.java    From gtfs-validator with MIT License 5 votes vote down vote up
@Override
public Rectangle2D deserialize(JsonParser jp, DeserializationContext arg1)
        throws IOException, JsonProcessingException {

    IntermediateBoundingBox bbox = jp.readValueAs(IntermediateBoundingBox.class);

    if (bbox.north == null || bbox.south == null || bbox.east == null || bbox.west == null)
        throw new JsonParseException("Unable to deserialize bounding box; need north, south, east, and west.", jp.getCurrentLocation());

    Rectangle2D.Double ret = new Rectangle2D.Double(bbox.west, bbox.north, 0, 0);
    ret.add(bbox.east, bbox.south);
    return ret;
}
 
Example 14
Source File: JsonMessageDecoder.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
protected static void checkToken(JsonParser parser, JsonToken expected, JsonToken actual) throws JsonParseException, IOException {
    if (expected != actual) {
        throw new JsonParseException("Incorrect structure, expectd: " + expected + ", actual: " + actual, parser.getCurrentLocation());
    }
}
 
Example 15
Source File: Sequence.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public LogicalOperator deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
    JsonProcessingException {
  ObjectIdGenerator<Integer> idGenerator = new ObjectIdGenerators.IntSequenceGenerator();
  JsonLocation start = jp.getCurrentLocation();
  JsonToken t = jp.getCurrentToken();
  LogicalOperator parent = null;
  LogicalOperator first = null;
  LogicalOperator prev = null;
  Integer id = null;

  while (true) {
    String fieldName = jp.getText();
    t = jp.nextToken();
    switch (fieldName) { // switch on field names.
    case "@id":
      id = _parseIntPrimitive(jp, ctxt);
      break;
    case "input":
      JavaType tp = ctxt.constructType(LogicalOperator.class);
      JsonDeserializer<Object> d = ctxt.findRootValueDeserializer(tp);
      parent = (LogicalOperator) d.deserialize(jp, ctxt);
      break;

    case "do":
      if (!jp.isExpectedStartArrayToken()) {
        throwE(
            jp,
            "The do parameter of sequence should be an array of SimpleOperators.  Expected a JsonToken.START_ARRAY token but received a "
                + t.name() + "token.");
      }

      int pos = 0;
      while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
        // logger.debug("Reading sequence child {}.", pos);
        JsonLocation l = jp.getCurrentLocation(); // get current location
                                                  // first so we can
                                                  // correctly reference the
                                                  // start of the object in
                                                  // the case that the type
                                                  // is wrong.
        LogicalOperator o = jp.readValueAs(LogicalOperator.class);

        if (pos == 0) {
          if (!(o instanceof SingleInputOperator) && !(o instanceof SourceOperator)) {
            throwE(
                l,
                "The first operator in a sequence must be either a ZeroInput or SingleInput operator.  The provided first operator was not. It was of type "
                    + o.getClass().getName());
          }
          first = o;
        } else {
          if (!(o instanceof SingleInputOperator)) {
            throwE(l, "All operators after the first must be single input operators.  The operator at position "
                + pos + " was not. It was of type " + o.getClass().getName());
          }
          SingleInputOperator now = (SingleInputOperator) o;
          now.setInput(prev);
        }
        prev = o;

        pos++;
      }
      break;
    default:
      throwE(jp, "Unknown field name provided for Sequence: " + jp.getText());
    }

    t = jp.nextToken();
    if (t == JsonToken.END_OBJECT) {
      break;
    }
  }

  if (first == null) {
    throwE(start, "A sequence must include at least one operator.");
  }
  if ((parent == null && first instanceof SingleInputOperator)
      || (parent != null && first instanceof SourceOperator)) {
    throwE(start,
        "A sequence must either start with a ZeroInputOperator or have a provided input. It cannot have both or neither.");
  }

  if (parent != null && first instanceof SingleInputOperator) {
    ((SingleInputOperator) first).setInput(parent);
  }

  // set input reference.
  if (id != null) {

    ReadableObjectId rid = ctxt.findObjectId(id, idGenerator, null);
    rid.bindItem(prev);
    // logger.debug("Binding id {} to item {}.", rid.id, rid.item);

  }

  return first;
}
 
Example 16
Source File: JsonMessageDecoder.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public T parse(JsonParser parser, boolean compact) throws JsonParseException, IOException, SailfishURIException {
    try {
        checkToken(parser, JsonToken.START_OBJECT, parser.getCurrentToken());
        getValue(parser, JSON_MESSAGE_ID, JavaType.JAVA_LANG_LONG);
        getValue(parser, JSON_MESSAGE_TIMESTAMP, JavaType.JAVA_LANG_LONG);
        String name = getValue(parser, JSON_MESSAGE_NAME, JavaType.JAVA_LANG_STRING);
        String namespace = getValue(parser, JSON_MESSAGE_NAMESPACE, JavaType.JAVA_LANG_STRING);
        String dictionaryURIValue = JsonMessageDecoder.<String>getValue(parser, JSON_MESSAGE_DICTIONARY_URI, JavaType.JAVA_LANG_STRING);
        SailfishURI dictionaryURI = StringUtils.isNotEmpty(dictionaryURIValue)
                ? SailfishURI.parse(dictionaryURIValue)
                : null;
        String protocol = getValue(parser, JSON_MESSAGE_PROTOCOL, JavaType.JAVA_LANG_STRING);
        Map<String, String> optionalTokens = new HashMap();

        while(parser.getCurrentName() != JSON_MESSAGE) {
            JsonToken token = parser.getCurrentToken();
            optionalTokens.put(parser.getCurrentName(), parser.getValueAsString());
            parser.nextToken();
        }

        checkFieldName(parser, parser.getCurrentToken(), JSON_MESSAGE);
        parser.nextToken();
        boolean dirty = BooleanUtils.toBoolean(optionalTokens.get(JSON_MESSAGE_DIRTY));
        boolean admin = BooleanUtils.toBoolean(optionalTokens.get(JSON_MESSAGE_ADMIN));
        T message = parse(parser, protocol, dictionaryURI, namespace, name, compact, dirty);
        if (message instanceof IMessage) {
            ((IMessage)message).getMetaData().setRejectReason(optionalTokens.get(JSON_MESSAGE_RR));
            ((IMessage)message).getMetaData().setDirty(dirty);
            ((IMessage)message).getMetaData().setAdmin(admin);
        }

//        IMessage message = messageFactory.createMessage(name, namespace);
//        MsgMetaData metaData = new MsgMetaData(namespace, name, new Date(timestamp));
//        metaData.setProtocol(protocol);
        //TODO: set new MsgMetaData
        
        return message;
    } catch (RuntimeException e) {
        throw new JsonParseException(e.getMessage(), parser.getCurrentLocation(), e); 
    }
}
 
Example 17
Source File: AbstractOpenRtbJsonReader.java    From openrtb with Apache License 2.0 4 votes vote down vote up
/**
 * Read any extensions that may exist in a message.
 *
 * @param msg Builder of a message that may contain extensions
 * @param par The JSON parser, positioned at the "ext" field
 * @param <EB> Type of message builder being constructed
 * @throws IOException any parsing error
 */
protected final <EB extends ExtendableBuilder<?, EB>>
void readExtensions(EB msg, JsonParser par) throws IOException {
  @SuppressWarnings("unchecked")
  Set<OpenRtbJsonExtReader<EB>> extReaders = factory.getReaders((Class<EB>) msg.getClass());
  if (extReaders.isEmpty()) {
    par.skipChildren();
    return;
  }

  startObject(par);
  JsonToken tokLast = par.getCurrentToken();
  JsonLocation locLast = par.getCurrentLocation();

  while (true) {
    boolean extRead = false;
    for (OpenRtbJsonExtReader<EB> extReader : extReaders) {
      if (extReader.filter(par)) {
        extReader.read(msg, par);
        JsonToken tokNew = par.getCurrentToken();
        JsonLocation locNew = par.getCurrentLocation();
        boolean advanced = tokNew != tokLast || !locNew.equals(locLast);
        extRead |= advanced;

        if (!endObject(par)) {
          return;
        } else if (advanced && par.getCurrentToken() != JsonToken.FIELD_NAME) {
          tokLast = par.nextToken();
          locLast = par.getCurrentLocation();
        } else {
          tokLast = tokNew;
          locLast = locNew;
        }
      }
    }

    if (!endObject(par)) {
      // Can't rely on this exit condition inside the for loop because no readers may filter.
      return;
    }

    if (!extRead) {
      // No field was consumed by any reader, so we need to skip the field to make progress.
      if (logger.isDebugEnabled()) {
        logger.debug("Extension field not consumed by any reader, skipping: {} @{}:{}",
            par.getCurrentName(), locLast.getLineNr(), locLast.getCharOffset());
      }
      par.nextToken();
      par.skipChildren();
      tokLast = par.nextToken();
      locLast = par.getCurrentLocation();
    }
    // Else loop, try all readers again
  }
}
 
Example 18
Source File: DbxHost.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
@Override
public DbxHost read(JsonParser parser) throws IOException, JsonReadException {
    JsonToken t = parser.getCurrentToken();
    if (t == JsonToken.VALUE_STRING) {
        String s = parser.getText();
        JsonReader.nextToken(parser);
        return DbxHost.fromBaseHost(s);
    } else if (t == JsonToken.START_OBJECT) {
        JsonLocation top = parser.getTokenLocation();
        nextToken(parser);

        String api = null;
        String content = null;
        String web = null;
        String notify = null;

        while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            String fieldName = parser.getCurrentName();
            parser.nextToken();

            try {
                if (fieldName.equals("api")) {
                    api = JsonReader.StringReader.readField(parser, fieldName, api);
                }
                else if (fieldName.equals("content")) {
                    content = JsonReader.StringReader.readField(parser, fieldName, content);
                }
                else if (fieldName.equals("web")) {
                    web = JsonReader.StringReader.readField(parser, fieldName, web);
                }
                else if (fieldName.equals("notify")) {
                    notify = JsonReader.StringReader.readField(parser, fieldName, notify);
                }
                else {
                    throw new JsonReadException("unknown field", parser.getCurrentLocation());
                }
            }
            catch (JsonReadException ex) {
                throw ex.addFieldContext(fieldName);
            }
        }

        JsonReader.expectObjectEnd(parser);

        if (api == null) throw new JsonReadException("missing field \"api\"", top);
        if (content == null) throw new JsonReadException("missing field \"content\"", top);
        if (web == null) throw new JsonReadException("missing field \"web\"", top);
        if (notify == null) throw new JsonReadException("missing field \"notify\"", top);

        return new DbxHost(api, content, web, notify);
    } else {
        throw new JsonReadException("expecting a string or an object", parser.getTokenLocation());
    }
}
 
Example 19
Source File: JsonUtilities.java    From azure-storage-android with Apache License 2.0 2 votes vote down vote up
/***
 * Reserved for internal use. Asserts that the current token of the parser is the start of an object.
 * 
 * @param parser
 *            The {@link JsonParser} whose current token to check.
 */
public static void assertIsStartObjectJsonToken(final JsonParser parser) throws JsonParseException {
    if (!(parser.getCurrentToken() == JsonToken.START_OBJECT)) {
        throw new JsonParseException(SR.EXPECTED_START_OBJECT, parser.getCurrentLocation());
    }
}
 
Example 20
Source File: JsonUtilities.java    From azure-storage-android with Apache License 2.0 2 votes vote down vote up
/***
 * Reserved for internal use. Asserts that the current token of the parser is the end of an object.
 * 
 * @param parser
 *            The {@link JsonParser} whose current token to check.
 */
public static void assertIsEndObjectJsonToken(final JsonParser parser) throws JsonParseException {
    if (!(parser.getCurrentToken() == JsonToken.END_OBJECT)) {
        throw new JsonParseException(SR.EXPECTED_END_OBJECT, parser.getCurrentLocation());
    }
}