Java Code Examples for com.fasterxml.jackson.core.JsonToken#VALUE_NUMBER_FLOAT

The following examples show how to use com.fasterxml.jackson.core.JsonToken#VALUE_NUMBER_FLOAT . 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: TableDeserializer.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
private static EdmType evaluateEdmType(JsonToken token, String value) {
    EdmType edmType = null;

    if (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) {
        edmType = EdmType.BOOLEAN;
    }
    else if (token == JsonToken.VALUE_NUMBER_FLOAT) {
        edmType = EdmType.DOUBLE;
    }
    else if (token == JsonToken.VALUE_NUMBER_INT) {
        edmType = EdmType.INT32;
    }
    else {
        edmType = EdmType.STRING;
    }

    return edmType;
}
 
Example 2
Source File: MincodeParser.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
private JsonToken nextNumberRecord() throws IOException {
    // First process the body of the record, as a string,
    // and convert to a BigDecimal.
    _finishString();
    JsonToken token;
    try {
        final BigDecimal number = _textBuffer.contentsAsDecimal();
        // We have a number, but don't know yet if it's an integer or floating point.
        // Jackson uses floating point to mean a decimal and/or exponent is present.
        // Our best heuristic for this is to check if the scale is 0.
        if (0 == number.scale()) {
            token = JsonToken.VALUE_NUMBER_INT;
            setNumberValue(number.unscaledValue());
        } else {
            token = JsonToken.VALUE_NUMBER_FLOAT;
            _numTypesValid = NR_BIGDECIMAL;
            _numberBigDecimal = number;
            // Unlike integer types, Jackson will convert to double/float on demand.
        }
    } catch (final NumberFormatException e) {
        _wrapError("Invalid number record", e);
        // Unreachable.
        token = null;
    }
    return token;
}
 
Example 3
Source File: XmlXContentParser.java    From elasticsearch-xml 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 4
Source File: JsonXContentParser.java    From crate 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 5
Source File: JSONBindingFactory.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public Long deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonToken t = parser.getCurrentToken();
    // it should be ok to coerce (although may fail, too)
    if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT || t == JsonToken.VALUE_STRING) {
        return rangeCheckedLong(parser, context);
    }
    if (t == JsonToken.VALUE_NULL) {
        return null;
    }
    // Otherwise, no can do:
    throw context.mappingException(_valueClass);
}
 
Example 6
Source File: DeserializeJSONJackson.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private cfData	parseArray(JsonParser jp, cfArrayData array, boolean bStrictMapping ) throws JsonParseException, IOException, cfmRunTimeException{
	
	JsonToken	token	= jp.nextToken();
	while ( token != JsonToken.END_ARRAY ){
		
		if ( token == JsonToken.START_ARRAY ){
			array.addElement( parseArray(jp,cfArrayData.createArray(1),bStrictMapping ) );
		}else if ( token == JsonToken.START_OBJECT ){
			array.addElement( parseObject(jp,new cfStructData(),bStrictMapping) );
		}else if ( token == JsonToken.VALUE_NUMBER_INT ){
			
			if ( jp.getNumberType() == NumberType.INT )
				array.addElement( new cfNumberData(jp.getIntValue()) );
			else if ( jp.getNumberType() == NumberType.LONG || jp.getNumberType() == NumberType.BIG_INTEGER )
				array.addElement( new cfNumberData(jp.getLongValue()) );

		}else if ( token == JsonToken.VALUE_NUMBER_FLOAT ){
	
			if ( jp.getNumberType() == NumberType.FLOAT )
				array.addElement( new cfNumberData(jp.getFloatValue()) );
			else if ( jp.getNumberType() == NumberType.DOUBLE )
				array.addElement( new cfNumberData(jp.getDoubleValue()) );

		} else if ( token == JsonToken.VALUE_FALSE ){
			array.addElement( cfBooleanData.FALSE );
		} else if ( token == JsonToken.VALUE_TRUE ){
			array.addElement( cfBooleanData.TRUE );
		} else if ( token == JsonToken.VALUE_NULL ){
			array.addElement( cfNullData.NULL );
		}else
			array.addElement(  getString(jp.getText()) );
	
		token	= jp.nextToken();
	}
	
	return array;
}
 
Example 7
Source File: ConstantTensorJsonValidator.java    From vespa with Apache License 2.0 5 votes vote down vote up
private void validateTensorValue() throws IOException {
    JsonToken token = parser.nextToken();

    if (token != JsonToken.VALUE_NUMBER_FLOAT && token != JsonToken.VALUE_NUMBER_INT) {
        throw new InvalidConstantTensor(parser, String.format("Tensor value is not a number (%s)", token.toString()));
    }
}
 
Example 8
Source File: InstantSerializerBase.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Override
protected JsonToken serializationShape(SerializerProvider provider) {
    if (useTimestamp(provider)) {
        if (useNanoseconds(provider)) {
            return JsonToken.VALUE_NUMBER_FLOAT;
        }
        return JsonToken.VALUE_NUMBER_INT;
    }
    return JsonToken.VALUE_STRING;
}
 
Example 9
Source File: DurationSerializer.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Override
protected JsonToken serializationShape(SerializerProvider provider) {
    if (useTimestamp(provider)) {
        if (useNanoseconds(provider)) {
            return JsonToken.VALUE_NUMBER_FLOAT;
        }
        return JsonToken.VALUE_NUMBER_INT;
    }
    return JsonToken.VALUE_STRING;
}
 
Example 10
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 11
Source File: WriteHolders.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public void write(Float4Writer writer, JsonToken token, JsonParser parser) throws IOException {
  if (token == JsonToken.VALUE_NUMBER_FLOAT || token == JsonToken.VALUE_NUMBER_INT) {
    writer.writeFloat4(parser.getFloatValue());
  } else {
    writer.writeFloat4(Float.parseFloat(parser.getValueAsString()));
  }
}
 
Example 12
Source File: IonParser.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
private JsonToken getJsonToken() {
    if (reader.isNullValue()) {
        return JsonToken.VALUE_NULL;
    }

    IonType currentType = reader.getType();
    switch (currentType) {
        case BLOB:
        case CLOB:
            return JsonToken.VALUE_EMBEDDED_OBJECT;
        case BOOL:
            return reader.booleanValue() ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE;
        case DECIMAL:
            return JsonToken.VALUE_NUMBER_FLOAT;
        case FLOAT:
            return JsonToken.VALUE_NUMBER_FLOAT;
        case INT:
            return JsonToken.VALUE_NUMBER_INT;
        case LIST:
            return JsonToken.START_ARRAY;
        case SEXP:
            return JsonToken.START_ARRAY;
        case STRING:
            return JsonToken.VALUE_STRING;
        case STRUCT:
            return JsonToken.START_OBJECT;
        case SYMBOL:
            return JsonToken.VALUE_STRING;
        case TIMESTAMP:
            return JsonToken.VALUE_EMBEDDED_OBJECT;
        default:
            throw new SdkClientException(String.format("Unhandled Ion type %s", currentType));
    }
}
 
Example 13
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 14
Source File: CustomProtobufParser.java    From caravan with Apache License 2.0 5 votes vote down vote up
@Override // since 2.9
public boolean isNaN() {
  if (_currToken == JsonToken.VALUE_NUMBER_FLOAT) {
    if ((_numTypesValid & NR_DOUBLE) != 0) {
      // 10-Mar-2017, tatu: Alas, `Double.isFinite(d)` only added in JDK 8
      double d = _numberDouble;
      return Double.isNaN(d) || Double.isInfinite(d);
    }
    if ((_numTypesValid & NR_FLOAT) != 0) {
      float f = _numberFloat;
      return Float.isNaN(f) || Float.isInfinite(f);
    }
  }
  return false;
}
 
Example 15
Source File: BsonParser.java    From immutables with Apache License 2.0 5 votes vote down vote up
private JsonToken toJsonToken(BsonType type) {
  switch (type) {
    case END_OF_DOCUMENT:
      reader.readEndDocument();
      return JsonToken.END_OBJECT;
    case DOCUMENT:
      reader.readStartDocument();
      return JsonToken.START_OBJECT;
    case ARRAY:
      reader.readStartArray();
      return JsonToken.START_ARRAY;
    case OBJECT_ID:
      return JsonToken.VALUE_EMBEDDED_OBJECT;
    case BOOLEAN:
      final boolean value  = reader.readBoolean();
      return value ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE;
    case DATE_TIME:
      return JsonToken.VALUE_EMBEDDED_OBJECT;
    case NULL:
      reader.readNull();
      return JsonToken.VALUE_NULL;
    case REGULAR_EXPRESSION:
      return JsonToken.VALUE_EMBEDDED_OBJECT;
    case SYMBOL:
    case STRING:
      return JsonToken.VALUE_STRING;
    case INT32:
    case INT64:
      return JsonToken.VALUE_NUMBER_INT;
    case DECIMAL128:
      return JsonToken.VALUE_NUMBER_FLOAT;
    case DOUBLE:
      return JsonToken.VALUE_NUMBER_FLOAT;
    case BINARY:
      return JsonToken.VALUE_EMBEDDED_OBJECT;
    default:
      throw new IllegalStateException(String.format("Unknown type %s", type));
  }
}
 
Example 16
Source File: FloatNodeCalc.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
static NodeCalc parseJson(JsonParser parser) throws IOException {
    JsonToken token;
    while ((token = parser.nextToken()) != null) {
        if (token == JsonToken.VALUE_NUMBER_FLOAT) {
            return new FloatNodeCalc(parser.getFloatValue());
        } else if (token == JsonToken.VALUE_NUMBER_INT) {
            return new FloatNodeCalc(parser.getIntValue());
        } else {
            throw NodeCalc.createUnexpectedToken(token);
        }
    }
    throw new TimeSeriesException("Invalid float node calc JSON");
}
 
Example 17
Source File: RecordStoreUtilities.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * Convert a JSON {@link InputStream} into a {@link RecordStore}.
 * <p>
 * The specified JSON stream should contain an array of objects, with each
 * object being converted to a record in the resulting {@link RecordStore}.
 * Each field in each object is converted to an entry in the corresponding
 * record.
 *
 * @param in An {@link InputStream} through which the JSON document will be
 * transported.
 * @return A {@link RecordStore} derived from the JSON document.
 * @throws IOException If something goes wrong while reading the JSON
 * document.
 */
public static RecordStore fromJson(final InputStream in) throws IOException {
    final RecordStore recordStore;
    try (final JsonParser parser = new MappingJsonFactory().createParser(in)) {
        recordStore = new GraphRecordStore();
        JsonToken currentToken = parser.nextToken();
        if (currentToken != JsonToken.START_ARRAY) {
            return null;
        }
        while (true) {
            currentToken = parser.nextToken();
            if (currentToken == JsonToken.START_OBJECT) {
                recordStore.add();

                while (true) {
                    currentToken = parser.nextToken();
                    if (currentToken == JsonToken.FIELD_NAME) {
                        String fieldName = parser.getCurrentName();

                        String fieldValue;
                        currentToken = parser.nextToken();
                        if (currentToken == JsonToken.VALUE_STRING || currentToken == JsonToken.VALUE_NUMBER_INT || currentToken == JsonToken.VALUE_NUMBER_FLOAT) {
                            fieldValue = parser.getValueAsString();
                        } else {
                            return null;
                        }

                        recordStore.set(fieldName, fieldValue);

                    } else if (currentToken == JsonToken.END_OBJECT) {
                        break;
                    } else {
                        return null;
                    }
                }
            } else if (currentToken == JsonToken.END_ARRAY) {
                break;
            } else {
                return null;
            }
        }
    }

    return recordStore;
}
 
Example 18
Source File: JsonRecordSupport.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public static void jsonStreamToRecords(Set<String> indexes, JsonParser jp, String path, Consumer<JsonRecord> consumer) throws IOException {
    boolean inArray = false;
    int arrayIndex = 0;
    while (true) {
        JsonToken nextToken = jp.nextToken();

        String currentPath = path;

        if (nextToken == FIELD_NAME) {
            if (inArray) {
                currentPath = path + toArrayIndexPath(arrayIndex) + "/";
            }
            jsonStreamToRecords(indexes, jp, currentPath + validateKey(jp.getCurrentName()) + "/", consumer);
        } else if (nextToken == VALUE_NULL) {
            if (inArray) {
                currentPath = path + toArrayIndexPath(arrayIndex) + "/";
            }
            consumer.accept(JsonRecord.of(currentPath, String.valueOf(NULL_VALUE_PREFIX), "null", indexFieldValue(indexes, currentPath)));
            if( inArray ) {
                arrayIndex++;
            } else {
                return;
            }
        } else if (nextToken.isScalarValue()) {
            if (inArray) {
                currentPath = path + toArrayIndexPath(arrayIndex) + "/";
            }

            String value = jp.getValueAsString();
            String ovalue = null;

            if( nextToken == JsonToken.VALUE_STRING ) {
                value = STRING_VALUE_PREFIX + value; //NOPMD
            } else if( nextToken == JsonToken.VALUE_NUMBER_INT || nextToken == JsonToken.VALUE_NUMBER_FLOAT ) {
                ovalue = value; // hold on to the original number in th ovalue field.
                value = toLexSortableString(value); // encode it so we can lexically sort.
            } else if( nextToken == JsonToken.VALUE_TRUE ) {
                ovalue = value;
                value = String.valueOf(TRUE_VALUE_PREFIX);
            } else if( nextToken == JsonToken.VALUE_FALSE ) {
                ovalue = value;
                value = String.valueOf(FALSE_VALUE_PREFIX);
            }

            consumer.accept(JsonRecord.of(currentPath, value, ovalue, indexFieldValue(indexes, currentPath)));
            if( inArray ) {
                arrayIndex++;
            } else {
                return;
            }
        } else if (nextToken == END_OBJECT) {
            if( inArray ) {
                arrayIndex++;
            } else {
                return;
            }
        } else if (nextToken == START_ARRAY) {
            inArray = true;
        } else if (nextToken == END_ARRAY) {
            return;
        }
    }
}
 
Example 19
Source File: BsonParser.java    From immutables with Apache License 2.0 4 votes vote down vote up
/**
 * Read next token in the stream
 */
private JsonToken readToken() throws JsonParseException {
  switch (type()) {
    case END_OF_DOCUMENT:
      reader.readEndDocument();
      return JsonToken.END_OBJECT;
    case DOCUMENT:
      reader.readStartDocument();
      return JsonToken.START_OBJECT;
    case ARRAY:
      reader.readStartArray();
      return JsonToken.START_ARRAY;
    case BOOLEAN:
      final boolean value  = reader.readBoolean();
      context.setValue(value);
      return value ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE;
    case DATE_TIME:
    case TIMESTAMP:
      return JsonToken.VALUE_EMBEDDED_OBJECT;
    case NULL:
      reader.readNull();
      context.setValue(null);
      return JsonToken.VALUE_NULL;
    case SYMBOL:
    case STRING:
      return JsonToken.VALUE_STRING;
    case INT32:
    case INT64:
      return JsonToken.VALUE_NUMBER_INT;
    case DECIMAL128:
    case DOUBLE:
      return JsonToken.VALUE_NUMBER_FLOAT;
    case UNDEFINED:
      reader.readUndefined();
      context.setValue(null);
      return JsonToken.VALUE_NULL;
    case OBJECT_ID:
    case BINARY:
    case REGULAR_EXPRESSION:
    default:
      return JsonToken.VALUE_EMBEDDED_OBJECT;
  }
}
 
Example 20
Source File: Util.java    From incubator-nemo with Apache License 2.0 4 votes vote down vote up
/**
 * Utility method for parsing the resource specification string.
 *
 * @param resourceSpecificationString the input resource specification string.
 * @return the parsed list of resource specifications. The Integer indicates how many of the specified nodes are
 * required, followed by the ResourceSpecification that indicates the specifications of the nodes.
 */
public static List<Pair<Integer, ResourceSpecification>> parseResourceSpecificationString(
  final String resourceSpecificationString) {
  final List<Pair<Integer, ResourceSpecification>> resourceSpecifications = new ArrayList<>();
  try {
    if (resourceSpecificationString.trim().startsWith("[")) {
      final TreeNode jsonRootNode = new ObjectMapper().readTree(resourceSpecificationString);

      for (int i = 0; i < jsonRootNode.size(); i++) {
        final TreeNode resourceNode = jsonRootNode.get(i);
        final int executorNum = resourceNode.path("num").traverse().nextIntValue(1);
        final String type = resourceNode.get("type").traverse().nextTextValue();
        final int capacity = resourceNode.get("capacity").traverse().getIntValue();
        final int memory = resourceNode.get("memory_mb").traverse().getIntValue();
        final OptionalDouble maxOffheapRatio;
        final OptionalInt poisonSec;

        if (resourceNode.path("max_offheap_ratio").traverse().nextToken() == JsonToken.VALUE_NUMBER_FLOAT) {
          maxOffheapRatio = OptionalDouble.of(resourceNode.path("max_offheap_ratio").traverse().getDoubleValue());
        } else {
          maxOffheapRatio = OptionalDouble.empty();
        }

        if (resourceNode.path("poison_sec").traverse().nextToken() == JsonToken.VALUE_NUMBER_INT) {
          poisonSec = OptionalInt.of(resourceNode.path("poison_sec").traverse().getIntValue());
        } else {
          poisonSec = OptionalInt.empty();
        }

        resourceSpecifications.add(
          Pair.of(executorNum, new ResourceSpecification(type, capacity, memory, maxOffheapRatio, poisonSec)));
      }
    } else {
      throw new UnsupportedOperationException("Executor Info file should be a JSON file.");
    }

    return resourceSpecifications;
  } catch (final Exception e) {
    throw new JsonParseException(e);
  }
}