com.fasterxml.jackson.core.JsonToken Java Examples

The following examples show how to use com.fasterxml.jackson.core.JsonToken. 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: AbstractEventSerializer.java    From aws-cloudtrail-processing-library with Apache License 2.0 6 votes vote down vote up
/**
 * Parses attributes as a Map<String, Double>, used to parse InsightStatistics
 *
 * @return attributes for insight statistics
 * @throws IOException
 */
private Map<String, Double> parseAttributesWithDoubleValues() throws IOException {
    if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
        throw new JsonParseException("Not an Attributes object", jsonParser.getCurrentLocation());
    }

    Map<String, Double> attributes = new HashMap<>();

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = jsonParser.getCurrentName();
        Double value = jsonParser.getValueAsDouble();
        attributes.put(key, value);
    }

    return attributes;
}
 
Example #2
Source File: JsonReader.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
/**
 * Helper to read and parse the optional ".tag" field. If one is found, positions the parser
 * at the next field (or the closing brace); otherwise leaves the parser position unchanged.
 * Returns null if there isn't a ".tag" field; otherwise an array of strings (the tags).
 * Initially the parser must be positioned right after the opening brace.
 */
public static String[] readTags(JsonParser parser)
    throws IOException, JsonReadException
{
    if (parser.getCurrentToken() != JsonToken.FIELD_NAME) {
        return null;
    }
    if (!".tag".equals(parser.getCurrentName())) {
        return null;
    }
    parser.nextToken();
    if (parser.getCurrentToken() != JsonToken.VALUE_STRING) {
        throw new JsonReadException("expected a string value for .tag field", parser.getTokenLocation());
    }
    String tag = parser.getText();
    parser.nextToken();
    return tag.split("\\.");
}
 
Example #3
Source File: AbstractPrimitiveBindTransform.java    From kripton with Apache License 2.0 6 votes vote down vote up
@Override
public void generateParseOnJacksonAsString(BindTypeContext context, MethodSpec.Builder methodBuilder, String parserName, TypeName beanClass, String beanName, BindProperty property) {
	if (nullable && property.isNullable()) {
		methodBuilder.beginControlFlow("if ($L.currentToken()!=$T.VALUE_NULL)", parserName, JsonToken.class);
	}

	if (property.hasTypeAdapter()) {
		// there's an type adapter
		methodBuilder.addCode("// using type adapter $L\n", property.typeAdapter.adapterClazz);

		methodBuilder.addStatement(setter(beanClass, beanName, property, PRE_TYPE_ADAPTER_TO_JAVA + "$T.read$L($L.getText(), $L)" + POST_TYPE_ADAPTER), TypeAdapterUtils.class,
				TypeUtility.typeName(property.typeAdapter.adapterClazz), PrimitiveUtils.class, PRIMITIVE_UTILITY_TYPE, parserName, DEFAULT_VALUE);
	} else {
		// without type adapter
		methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.read$L($L.getText(), $L)"), PrimitiveUtils.class, PRIMITIVE_UTILITY_TYPE, parserName, DEFAULT_VALUE);
	}

	if (nullable && property.isNullable()) {
		methodBuilder.endControlFlow();
	}
}
 
Example #4
Source File: ClientCsdlIncludeAnnotations.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
protected IncludeAnnotations doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

  final ClientCsdlIncludeAnnotations member = new ClientCsdlIncludeAnnotations();

  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("TermNamespace".equals(jp.getCurrentName())) {
        member.setTermNamespace(jp.nextTextValue());
      } else if ("Qualifier".equals(jp.getCurrentName())) {
        member.setQualifier(jp.nextTextValue());
      } else if ("TargetNamespace".equals(jp.getCurrentName())) {
        member.setTargetNamespace(jp.nextTextValue());
      }
    }
  }
  return member;
}
 
Example #5
Source File: CayenneExpParser.java    From agrest with Apache License 2.0 6 votes vote down vote up
private static Object extractValue(JsonNode valueNode) {
    JsonToken type = valueNode.asToken();

    switch (type) {
        case VALUE_NUMBER_INT:
            return valueNode.asInt();
        case VALUE_NUMBER_FLOAT:
            return valueNode.asDouble();
        case VALUE_TRUE:
            return Boolean.TRUE;
        case VALUE_FALSE:
            return Boolean.FALSE;
        case VALUE_NULL:
            return null;
        case START_ARRAY:
            return extractArray(valueNode);
        default:
            // String parameters may need to be parsed further. Defer parsing
            // until it is placed in the context of an expression...
            return valueNode;
    }
}
 
Example #6
Source File: AbstractCipherResourceEncryptor.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
protected String decryptWithJacksonParser(String text, String name, String[] profiles,
		JsonFactory factory) throws IOException {
	Set<String> valsToDecrpyt = new HashSet<String>();
	JsonParser parser = factory.createParser(text);
	JsonToken token;

	while ((token = parser.nextToken()) != null) {
		if (token.equals(JsonToken.VALUE_STRING)
				&& parser.getValueAsString().startsWith(CIPHER_MARKER)) {
			valsToDecrpyt.add(parser.getValueAsString().trim());
		}
	}

	for (String value : valsToDecrpyt) {
		String decryptedValue = decryptValue(value.replace(CIPHER_MARKER, ""), name,
				profiles);
		text = text.replace(value, decryptedValue);
	}

	return text;
}
 
Example #7
Source File: VespaSimpleJsonInputFormat.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    FileSplit fileSplit = (FileSplit) split;
    FSDataInputStream stream = FileSystem.get(context.getConfiguration()).open(fileSplit.getPath());
    if (fileSplit.getStart() != 0) {
        stream.seek(fileSplit.getStart());
    }

    remaining = fileSplit.getLength();

    JsonFactory factory = new JsonFactory().disable(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES);
    parser = factory.createParser(new BufferedInputStream(stream));
    parser.setCodec(new ObjectMapper());
    parser.nextToken();
    if (parser.currentToken() == JsonToken.START_ARRAY) {
        parser.nextToken();
    }
}
 
Example #8
Source File: FactoryBasedEnumDeserializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected Object deserializeEnumUsingPropertyBased(final JsonParser p, final DeserializationContext ctxt,
		final PropertyBasedCreator creator) throws IOException
{
    PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, null);

    JsonToken t = p.getCurrentToken();
    for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
        String propName = p.getCurrentName();
        p.nextToken(); // to point to value

        SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
        if (creatorProp != null) {
            buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp));
            continue;
        }
        if (buffer.readIdProperty(propName)) {
            continue;
        }
    }
    return creator.build(ctxt, buffer);
}
 
Example #9
Source File: ClientCsdlLabeledElement.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
protected ClientCsdlLabeledElement doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
    throws IOException {
  final ClientCsdlLabeledElement element = new ClientCsdlLabeledElement();
  for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
    final JsonToken token = jp.getCurrentToken();
    if (token == JsonToken.FIELD_NAME) {
      if ("Name".equals(jp.getCurrentName())) {
        element.setName(jp.nextTextValue());
      } else if ("Annotation".equals(jp.getCurrentName())) {
        element.getAnnotations().add(jp.readValueAs(ClientCsdlAnnotation.class));
      } else {
        element.setValue(jp.readValueAs(ClientCsdlDynamicExpression.class));
      }
    }
  }
  return element;
}
 
Example #10
Source File: CreateApplicationResultJsonUnmarshaller.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
public CreateApplicationResult unmarshall(JsonUnmarshallerContext context) throws Exception {
  CreateApplicationResult createApplicationResult = new CreateApplicationResult();

  int originalDepth = context.getCurrentDepth();
  String currentParentElement = context.getCurrentParentElement();
  int targetDepth = originalDepth + 1;

  JsonToken token = context.getCurrentToken();
  if (token == null)
    token = context.nextToken();
  if (token == VALUE_NULL) {
    return createApplicationResult;
  }

  while (true) {
    if (token == null)
      break;

    createApplicationResult.setApplication(ApplicationJsonUnmarshaller.getInstance().unmarshall(context));
    token = context.nextToken();
  }

  return createApplicationResult;
}
 
Example #11
Source File: GenericConverter.java    From agrest with Apache License 2.0 6 votes vote down vote up
@Override
public Object value(JsonNode valueNode) {
	JsonToken type = valueNode.asToken();

	switch (type) {
	case VALUE_NUMBER_INT:
		return valueNode.asInt();
	case VALUE_NUMBER_FLOAT:
		return valueNode.asDouble();
	case VALUE_TRUE:
		return Boolean.TRUE;
	case VALUE_FALSE:
		return Boolean.FALSE;
	case VALUE_NULL:
		return null;
	default:
		return valueNode.asText();
	}
}
 
Example #12
Source File: TupleDeserializer.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    List<Object> list = new ArrayList<>();
    int ptr = 0;

    for (JsonToken jsonToken = p.nextToken(); jsonToken != END_ARRAY; jsonToken = p.nextToken()) {
        if (ptr >= deserializersCount()) {
            throw mappingException(ctxt, javaType.getRawClass(), jsonToken);
        }
        JsonDeserializer<?> deserializer = deserializer(ptr++);
        Object value = (jsonToken != VALUE_NULL) ? deserializer.deserialize(p, ctxt) : deserializer.getNullValue(ctxt);
        list.add(value);
    }
    if (list.size() == deserializersCount()) {
        return create(list, ctxt);
    } else {
        throw mappingException(ctxt, javaType.getRawClass(), null);
    }
}
 
Example #13
Source File: JsonXContentParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public Object objectText() throws IOException {
    JsonToken currentToken = parser.getCurrentToken();
    if (currentToken == JsonToken.VALUE_STRING) {
        return text();
    } else if (currentToken == JsonToken.VALUE_NUMBER_INT || currentToken == JsonToken.VALUE_NUMBER_FLOAT) {
        return parser.getNumberValue();
    } else if (currentToken == JsonToken.VALUE_TRUE) {
        return Boolean.TRUE;
    } else if (currentToken == JsonToken.VALUE_FALSE) {
        return Boolean.FALSE;
    } else if (currentToken == JsonToken.VALUE_NULL) {
        return null;
    } else {
        return text();
    }
}
 
Example #14
Source File: ByteArraySerializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serializeWithType(byte[] value, JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException
{
    // most likely scalar
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, JsonToken.VALUE_EMBEDDED_OBJECT));
    g.writeBinary(provider.getConfig().getBase64Variant(),
            value, 0, value.length);
    typeSer.writeTypeSuffix(g, typeIdDef);

    /* OLD impl
    typeSer.writeTypePrefixForScalar(value, g);
    g.writeBinary(provider.getConfig().getBase64Variant(),
            value, 0, value.length);
    typeSer.writeTypeSuffixForScalar(value, g);
    */
}
 
Example #15
Source File: MapReader.java    From vespa with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "cast", "unchecked" })
public static void fillMapFromObject(TokenBuffer buffer, MapFieldValue parent) {
    JsonToken token = buffer.currentToken();
    int initNesting = buffer.nesting();
    expectObjectStart(token);
    token = buffer.next();
    DataType keyType = parent.getDataType().getKeyType();
    DataType valueType = parent.getDataType().getValueType();
    while (buffer.nesting() >= initNesting) {
        FieldValue key = readAtomic(buffer.currentName(), keyType);
        FieldValue value = readSingleValue(buffer, valueType);

        Preconditions.checkState(key != null && value != null, "Missing key or value for map entry.");
        parent.put(key, value);
        token = buffer.next();
    }
    expectObjectEnd(token);
}
 
Example #16
Source File: ProtobufDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
private AssertionError reportWrongToken(
        JsonToken expected,
        DeserializationContext context,
        String message
) throws JsonMappingException {
  context.reportWrongTokenException(this, expected, message);
  // the previous method should have thrown
  throw new AssertionError();
}
 
Example #17
Source File: JSR310LocalDateDeserializer.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    switch(parser.getCurrentToken()) {
        case START_ARRAY:
            if(parser.nextToken() == JsonToken.END_ARRAY) {
                return null;
            }
            int year = parser.getIntValue();

            parser.nextToken();
            int month = parser.getIntValue();

            parser.nextToken();
            int day = parser.getIntValue();

            if(parser.nextToken() != JsonToken.END_ARRAY) {
                throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end.");
            }
            return LocalDate.of(year, month, day);

        case VALUE_STRING:
            String string = parser.getText().trim();
            if(string.length() == 0) {
                return null;
            }
            return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME);
        default:
            throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
    }
}
 
Example #18
Source File: Jackson2Tokenizer.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void processTokenArray(JsonToken token, List<TokenBuffer> result) throws IOException {
	if (!isTopLevelArrayToken(token)) {
		this.tokenBuffer.copyCurrentEvent(this.parser);
	}

	if (this.objectDepth == 0 &&
			(this.arrayDepth == 0 || this.arrayDepth == 1) &&
			(token == JsonToken.END_OBJECT || token.isScalarValue())) {
		result.add(this.tokenBuffer);
		this.tokenBuffer = new TokenBuffer(this.parser);
	}
}
 
Example #19
Source File: SingleValueReader.java    From vespa with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static ValueUpdate readSingleUpdate(TokenBuffer buffer, DataType expectedType, String action) {
    ValueUpdate update;

    switch (action) {
        case UPDATE_ASSIGN:
            update = (buffer.currentToken() == JsonToken.VALUE_NULL)
                    ? ValueUpdate.createClear()
                    : ValueUpdate.createAssign(readSingleValue(buffer, expectedType));
            break;
        // double is silly, but it's what is used internally anyway
        case UPDATE_INCREMENT:
            update = ValueUpdate.createIncrement(Double.valueOf(buffer.currentText()));
            break;
        case UPDATE_DECREMENT:
            update = ValueUpdate.createDecrement(Double.valueOf(buffer.currentText()));
            break;
        case UPDATE_MULTIPLY:
            update = ValueUpdate.createMultiply(Double.valueOf(buffer.currentText()));
            break;
        case UPDATE_DIVIDE:
            update = ValueUpdate.createDivide(Double.valueOf(buffer.currentText()));
            break;
        default:
            throw new IllegalArgumentException("Operation '" + buffer.currentName() + "' not implemented.");
    }
    return update;
}
 
Example #20
Source File: IonRoundtripTest.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(IonParser parser) throws IOException {
    assertEquals(JsonToken.VALUE_NUMBER_INT, parser.nextToken());
    assertEquals(42, parser.getIntValue());
    assertEquals(JsonToken.START_OBJECT, parser.nextToken());
    parser.skipChildren();
    assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("foo", parser.getText());
}
 
Example #21
Source File: JsonReader.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public final /*@Nullable*/T readOptional(JsonParser parser)
    throws IOException, JsonReadException
{
    if (parser.getCurrentToken() == JsonToken.VALUE_NULL) {
        parser.nextToken();
        return null;
    } else {
        return read(parser);
    }
}
 
Example #22
Source File: JsonDomParser.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private SdkJsonNode parseObject(JsonParser parser) throws IOException {
    JsonToken currentToken = parser.nextToken();
    SdkObjectNode.Builder builder = SdkObjectNode.builder();
    while (currentToken != JsonToken.END_OBJECT) {
        String fieldName = parser.getText();
        builder.putField(fieldName, parseToken(parser, parser.nextToken()));
        currentToken = parser.nextToken();
    }
    return builder.build();
}
 
Example #23
Source File: BeanA_2BindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public BeanA_2 parseOnJackson(JsonParser jacksonParser) throws Exception {
  BeanA_2 instance = new BeanA_2();
  String fieldName;
  if (jacksonParser.currentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.currentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "id":
          // field id (mapped with "id")
          instance.id=jacksonParser.getLongValue();
        break;
        case "valueString2":
          // field valueString2 (mapped with "valueString2")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.valueString2=jacksonParser.getText();
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example #24
Source File: OpenRtbNativeJsonReader.java    From openrtb with Apache License 2.0 5 votes vote down vote up
public final NativeResponse.Asset.Video.Builder readRespVideo(JsonParser par)
    throws IOException {
  NativeResponse.Asset.Video.Builder video = NativeResponse.Asset.Video.newBuilder();
  for (startObject(par); endObject(par); par.nextToken()) {
    String fieldName = getCurrentName(par);
    if (par.nextToken() != JsonToken.VALUE_NULL) {
      readRespVideoField(par, video, fieldName);
    }
  }
  return video;
}
 
Example #25
Source File: TypeConversionTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void booleanValue() throws IOException {
  check(Parsers.parserAt(new BsonBoolean(true)).getCurrentToken()).is(JsonToken.VALUE_TRUE);
  check(Parsers.parserAt(new BsonBoolean(false)).getCurrentToken()).is(JsonToken.VALUE_FALSE);
  check(Parsers.parserAt(new BsonBoolean(true)).getText()).is("true");
  check(Parsers.parserAt(new BsonBoolean(false)).getText()).is("false");
  check(Parsers.parserAt(new BsonBoolean(true)).getBooleanValue());
  check(!Parsers.parserAt(new BsonBoolean(false)).getBooleanValue());
}
 
Example #26
Source File: PersonBindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * parse with jackson
 */
@Override
public Person parseOnJacksonAsString(JsonParser jacksonParser) throws Exception {
  Person instance = new Person();
  String fieldName;
  if (jacksonParser.getCurrentToken() == null) {
    jacksonParser.nextToken();
  }
  if (jacksonParser.getCurrentToken() != JsonToken.START_OBJECT) {
    jacksonParser.skipChildren();
    return instance;
  }
  while (jacksonParser.nextToken() != JsonToken.END_OBJECT) {
    fieldName = jacksonParser.getCurrentName();
    jacksonParser.nextToken();

    // Parse fields:
    switch (fieldName) {
        case "id":
          // field id (mapped with "id")
          instance.id=PrimitiveUtils.readLong(jacksonParser.getText(), 0L);
        break;
        case "image":
          // field image (mapped with "image")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.image=Base64Utils.decode(jacksonParser.getValueAsString());
          }
        break;
        case "name":
          // field name (mapped with "name")
          if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
            instance.name=jacksonParser.getText();
          }
        break;
        default:
          jacksonParser.skipChildren();
        break;}
  }
  return instance;
}
 
Example #27
Source File: JSONBindingFactory.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
protected Byte _parseByte(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken t = jp.getCurrentToken();
    Integer value = null;
    if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // coercing should work too
        value = jp.getIntValue();
    }
    else if (t == JsonToken.VALUE_STRING) { // let's do implicit re-parse
        String text = jp.getText().trim();
        try {
            int len = text.length();
            if (len == 0) {
                return getEmptyValue();
            }
            value = NumberInput.parseInt(text);
        } catch (IllegalArgumentException iae) {
            throw ctxt.weirdStringException(_valueClass, "not a valid Byte value");//NOSONAR
        }
    }
    if (value != null) {
        // So far so good: but does it fit?
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            throw ctxt.weirdStringException(_valueClass, "overflow, value can not be represented as 8-bit value");
        }
        return (byte) (int) value;
    }
    if (t == JsonToken.VALUE_NULL) {
        return getNullValue();
    }
    throw ctxt.mappingException(_valueClass, t);
}
 
Example #28
Source File: DbxLongpollDeltaResult.java    From dropbox-sdk-java with 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 #29
Source File: JSONBindingFactory.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonToken t = parser.getCurrentToken();
    if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // coercing should work too
        return rangeCheckedInteger(parser, context);
    }
    if (t == JsonToken.VALUE_STRING) { // let's do implicit re-parse
        String text = parser.getText().trim();
        try {
            int len = text.length();
            if (len > 9) {
                return rangeCheckedInteger(parser, context);
            }
            if (len == 0) {
                return null;
            }
            return Integer.valueOf(NumberInput.parseInt(text));
        } catch (IllegalArgumentException iae) {
            throw context.weirdStringException(_valueClass, "not a valid Integer value");//NOSONAR
        }
    }
    if (t == JsonToken.VALUE_NULL) {
        return null;
    }
    // Otherwise, no can do:
    throw context.mappingException(_valueClass);
}
 
Example #30
Source File: AbstractEmoFieldUDF.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Don't materialize the entire parser content, do a targeted search for the value that matches the path.
 */
private boolean moveParserToField(JsonParser parser, String path)
        throws IOException {
    List<String> segments = getFieldPath(path);

    for (String segment : segments) {
        if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
            // Always expect the path to be fields in a JSON map
            return false;
        }

        boolean found = false;

        JsonToken currentToken = parser.nextToken();
        while (!found && currentToken != JsonToken.END_OBJECT) {
            if (currentToken != JsonToken.FIELD_NAME) {
                // This should always be a field.  Something is amiss.
                throw new IOException("Field not found at expected location");
            }
            String fieldName = parser.getText();
            if (fieldName.equals(segment)) {
                // Move to the next token, which is the field value
                found = true;
                currentToken = parser.nextToken();
            } else {
                parser.nextValue();
                currentToken = skipValue(parser);
            }
        }

        if (!found) {
            // Field was not found
            return false;
        }
    }

    // The current location in the parser is the value.
    return true;
}