com.fasterxml.jackson.databind.node.DecimalNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.DecimalNode. 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: JsonNodeToPrimitiveObject.java    From yosegi with Apache License 2.0 5 votes vote down vote up
/**
 * Converts JsonNode to PrimitiveObject.
 */
public static PrimitiveObject get( final JsonNode jsonNode ) throws IOException {
  if ( jsonNode instanceof TextNode ) {
    return new StringObj( ( (TextNode)jsonNode ).textValue() );
  } else if ( jsonNode instanceof BooleanNode ) {
    return new BooleanObj( ( (BooleanNode)jsonNode ).booleanValue() );
  } else if ( jsonNode instanceof IntNode ) {
    return new IntegerObj( ( (IntNode)jsonNode ).intValue() );
  } else if ( jsonNode instanceof LongNode ) {
    return new LongObj( ( (LongNode)jsonNode ).longValue() );
  } else if ( jsonNode instanceof DoubleNode ) {
    return new DoubleObj( ( (DoubleNode)jsonNode ).doubleValue() );
  } else if ( jsonNode instanceof BigIntegerNode ) {
    return new StringObj( ( (BigIntegerNode)jsonNode ).bigIntegerValue().toString() );
  } else if ( jsonNode instanceof DecimalNode ) {
    return new StringObj( ( (DecimalNode)jsonNode ).decimalValue().toString() );
  } else if ( jsonNode instanceof BinaryNode ) {
    return new BytesObj( ( (BinaryNode)jsonNode ).binaryValue() );
  } else if ( jsonNode instanceof POJONode ) {
    return new BytesObj( ( (POJONode)jsonNode ).binaryValue() );
  } else if ( jsonNode instanceof NullNode ) {
    return NullObj.getInstance();
  } else if ( jsonNode instanceof MissingNode ) {
    return NullObj.getInstance();
  } else {
    return new StringObj( jsonNode.toString() );
  }
}
 
Example #2
Source File: EnumValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
    debug(logger, node, rootNode, at);

    Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
    if (node.isNumber()) node = DecimalNode.valueOf(node.decimalValue());
    if (!nodes.contains(node) && !(config.isTypeLoose() && isTypeLooseContainsInEnum(node))) {
        errors.add(buildValidationMessage(at, error));
    }

    return Collections.unmodifiableSet(errors);
}
 
Example #3
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public Number serialize(Object dataFetcherResult) {
    if (dataFetcherResult instanceof DecimalNode) {
        return ((DecimalNode) dataFetcherResult).numberValue();
    }
    throw serializationException(dataFetcherResult, DecimalNode.class);
}
 
Example #4
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public DecimalNode parseValue(Object input) {
    if (input instanceof Number || input instanceof String) {
        return (DecimalNode) JsonNodeFactory.instance.numberNode(new BigDecimal(input.toString()));
    }
    if (input instanceof DecimalNode) {
        return (DecimalNode) input;
    }
    throw valueParsingException(input, Number.class, String.class, DecimalNode.class);
}
 
Example #5
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public DecimalNode parseLiteral(Object input) {
    if (input instanceof IntValue) {
        return (DecimalNode) JsonNodeFactory.instance.numberNode(((IntValue) input).getValue());
    } else if (input instanceof FloatValue) {
        return (DecimalNode) JsonNodeFactory.instance.numberNode(((FloatValue) input).getValue());
    } else {
        throw new CoercingParseLiteralException(errorMessage(input, IntValue.class, FloatValue.class));
    }
}
 
Example #6
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static Map<Type, GraphQLScalarType> getScalarMapping() {
    Map<Type, GraphQLScalarType> scalarMapping = new HashMap<>();
    scalarMapping.put(TextNode.class, JsonTextNode);
    scalarMapping.put(BooleanNode.class, JsonBooleanNode);
    scalarMapping.put(BinaryNode.class, JsonBinaryNode);
    scalarMapping.put(BigIntegerNode.class, JsonBigIntegerNode);
    scalarMapping.put(IntNode.class, JsonIntegerNode);
    scalarMapping.put(ShortNode.class, JsonShortNode);
    scalarMapping.put(DecimalNode.class, JsonDecimalNode);
    scalarMapping.put(FloatNode.class, JsonFloatNode);
    scalarMapping.put(DoubleNode.class, JsonDoubleNode);
    scalarMapping.put(NumericNode.class, JsonDecimalNode);
    return Collections.unmodifiableMap(scalarMapping);
}
 
Example #7
Source File: JacksonModule.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp(SetupContext context) {
    if (!getTypeMappers().isEmpty()) {
        context.getSchemaGenerator().withTypeMappersPrepended(getTypeMappers().toArray(new TypeMapper[0]));
    }
    if (!getOutputConverters().isEmpty()) {
        context.getSchemaGenerator().withOutputConvertersPrepended(getOutputConverters().toArray(new OutputConverter[0]));
    }
    if (!getInputConverters().isEmpty()) {
        context.getSchemaGenerator().withInputConvertersPrepended(getInputConverters().toArray(new InputConverter[0]));
    }
    context.getSchemaGenerator().withTypeComparators(new SynonymBaseTypeComparator(ObjectNode.class, POJONode.class));
    context.getSchemaGenerator().withTypeComparators(new SynonymBaseTypeComparator(DecimalNode.class, NumericNode.class));
}
 
Example #8
Source File: Instructions.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
private static void emitJsonNode(StringBuilder buf, JsonNode node) {
  if (node.isNumber()) {
    // Formatting of numbers depending on type
    switch (node.numberType()) {
      case BIG_INTEGER:
        buf.append(((BigIntegerNode)node).bigIntegerValue().toString());
        break;

      case BIG_DECIMAL:
        buf.append(((DecimalNode)node).decimalValue().toPlainString());
        break;

      case INT:
      case LONG:
        buf.append(node.asLong());
        break;

      case FLOAT:
      case DOUBLE:
        double val = node.asDouble();
        buf.append(Double.toString(val));
        break;

      default:
        break;
    }

  } else if (node.isArray()) {
    // JavaScript Array.toString() will comma-delimit the elements.
    for (int i = 0, size = node.size(); i < size; i++) {
      if (i >= 1) {
        buf.append(",");
      }
      buf.append(node.path(i).asText());
    }

  } else if (!node.isNull() && !node.isMissingNode()) {
    buf.append(node.asText());
  }
}
 
Example #9
Source File: DecimalFormatterTest.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
private void run(String locale, String number, String args, String expected) {
  try {
    String json = new DecimalNode(new BigDecimal(number)).toString();
    String actual = format(locale, mk.args(args), json);
    Assert.assertEquals(actual, expected);
  } catch (CodeException e) {
    fail("formatter raised an error", e);
  }
}
 
Example #10
Source File: JsonExampleDeserializer.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
private Example createExample(JsonNode node) {
    if (node instanceof ObjectNode) {
        ObjectExample obj = new ObjectExample();
        ObjectNode on = (ObjectNode) node;
        for (Iterator<Entry<String, JsonNode>> x = on.fields(); x.hasNext(); ) {
            Entry<String, JsonNode> i = x.next();
            String key = i.getKey();
            JsonNode value = i.getValue();
            obj.put(key, createExample(value));
        }
        return obj;
    } else if (node instanceof ArrayNode) {
        ArrayExample arr = new ArrayExample();
        ArrayNode an = (ArrayNode) node;
        for (JsonNode childNode : an) {
            arr.add(createExample(childNode));
        }
        return arr;
    } else if (node instanceof DoubleNode) {
        return new DoubleExample(node.doubleValue());
    } else if (node instanceof IntNode || node instanceof ShortNode) {
        return new IntegerExample(node.intValue());
    } else if (node instanceof FloatNode) {
        return new FloatExample(node.floatValue());
    } else if (node instanceof BigIntegerNode) {
        return new BigIntegerExample(node.bigIntegerValue());
    } else if (node instanceof DecimalNode) {
        return new DecimalExample(node.decimalValue());
    } else if (node instanceof LongNode) {
        return new LongExample(node.longValue());
    } else if (node instanceof BooleanNode) {
        return new BooleanExample(node.booleanValue());
    } else {
        return new StringExample(node.asText());
    }
}
 
Example #11
Source File: TestJsonNodeToPrimitiveObject.java    From yosegi with Apache License 2.0 4 votes vote down vote up
@Test
public void T_get_decimalObject() throws IOException {
  PrimitiveObject obj = JsonNodeToPrimitiveObject.get( DecimalNode.valueOf( new BigDecimal( "100" ) ) );
  assertTrue( ( obj instanceof StringObj ) );
}
 
Example #12
Source File: EnumValidator.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
public EnumValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.ENUM, validationContext);

    if (schemaNode != null && schemaNode.isArray()) {
        nodes = new HashSet<JsonNode>();
        StringBuilder sb = new StringBuilder();

        sb.append('[');
        String separator = "";

        for (JsonNode n : schemaNode) {
            if (n.isNumber()) {
                // convert to DecimalNode for number comparison
                nodes.add(DecimalNode.valueOf(n.decimalValue()));
            } else {
                nodes.add(n);
            }

            sb.append(separator);
            sb.append(n.asText());
            separator = ", ";
        }

        // check if the parent schema declares the fields as nullable
        if (config.isHandleNullableField()) {
            JsonNode nullable = parentSchema.getSchemaNode().get("nullable");
            if (nullable != null && nullable.asBoolean()) {
                nodes.add(NullNode.getInstance());
                separator = ", ";
                sb.append(separator);
                sb.append("null");
            }
        }
        //
        sb.append(']');

        error = sb.toString();
    } else {
        nodes = Collections.emptySet();
        error = "[none]";
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example #13
Source File: IsJsonNumberTest.java    From java-hamcrest with Apache License 2.0 4 votes vote down vote up
@Test
public void testLiteralBigDecimal() throws Exception {
  final Matcher<JsonNode> sut = jsonNumber(DecimalNode.valueOf(BigDecimal.ONE));

  assertThat(NF.numberNode(BigDecimal.ONE), is(sut));
}
 
Example #14
Source File: MessageFormatsTest.java    From template-compiler with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicArgs() {
  String actual;
  CLDR cldr = CLDR.get("en");
  MessageFormats formats = new MessageFormats(cldr);
  formats.setTimeZone("America/New_York");
  String message = "{0 select abc {ABC} def {DEF} true {T} false {F}}";

  actual = formats.formatter().format(message, args().add(new TextNode("abc")));
  assertEquals(actual, "ABC");

  actual = formats.formatter().format(message, args().add(new TextNode("def")));
  assertEquals(actual, "DEF");

  actual = formats.formatter().format(message, args().add(new TextNode("ghi")));
  assertEquals(actual, "");

  actual = formats.formatter().format(message, args().add(new LongNode(123)));
  assertEquals(actual, "");

  actual = formats.formatter().format(message, args().add(BooleanNode.TRUE));
  assertEquals(actual, "T");

  actual = formats.formatter().format(message, args().add(BooleanNode.FALSE));
  assertEquals(actual, "F");

  actual = formats.formatter().format(message, args().add(NullNode.getInstance()));
  assertEquals(actual, "");

  actual = formats.formatter().format(message, args().add(MissingNode.getInstance()));
  assertEquals(actual, "");

  actual = formats.formatter().format(message, args().add(JsonUtils.createArrayNode()));
  assertEquals(actual, "");

  actual = formats.formatter().format(message, args().add(JsonUtils.createObjectNode()));
  assertEquals(actual, "");

  message = "{0 plural one {ONE} other {OTHER}}";

  actual = formats.formatter().format(message, args().add("123"));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add("1"));
  assertEquals(actual, "ONE");

  actual = formats.formatter().format(message, args().add("undefined"));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add(new LongNode(123)));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add(new LongNode(1)));
  assertEquals(actual, "ONE");

  actual = formats.formatter().format(message, args().add(BooleanNode.TRUE));
  assertEquals(actual, "ONE");

  actual = formats.formatter().format(message, args().add(BooleanNode.FALSE));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add(MissingNode.getInstance()));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add(NullNode.getInstance()));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add(new TextNode("abc")));
  assertEquals(actual, "OTHER");

  actual = formats.formatter().format(message, args().add(JsonUtils.createObjectNode()));
  assertEquals(actual, "OTHER");

  ObjectNode money = JsonUtils.createObjectNode();
  money.put("decimalValue", new DecimalNode(new BigDecimal("1.2320001")));
  actual = formats.formatter().format(message, args().add(money));
  assertEquals(actual, "OTHER");

  money.put("decimalValue", new DecimalNode(new BigDecimal("1")));
  actual = formats.formatter().format(message, args().add(money));
  assertEquals(actual, "ONE");
}
 
Example #15
Source File: DistributedWorkplaceStore.java    From onos with Apache License 2.0 4 votes vote down vote up
@Activate
public void activate() {

    appId = coreService.registerApplication("org.onosproject.workplacestore");
    log.info("appId=" + appId);

    KryoNamespace workplaceNamespace = KryoNamespace.newBuilder()
            .register(KryoNamespaces.API)
            .register(WorkflowData.class)
            .register(Workplace.class)
            .register(DefaultWorkplace.class)
            .register(WorkflowContext.class)
            .register(DefaultWorkflowContext.class)
            .register(SystemWorkflowContext.class)
            .register(WorkflowState.class)
            .register(ProgramCounter.class)
            .register(DataModelTree.class)
            .register(JsonDataModelTree.class)
            .register(List.class)
            .register(ArrayList.class)
            .register(JsonNode.class)
            .register(ObjectNode.class)
            .register(TextNode.class)
            .register(LinkedHashMap.class)
            .register(ArrayNode.class)
            .register(BaseJsonNode.class)
            .register(BigIntegerNode.class)
            .register(BinaryNode.class)
            .register(BooleanNode.class)
            .register(ContainerNode.class)
            .register(DecimalNode.class)
            .register(DoubleNode.class)
            .register(FloatNode.class)
            .register(IntNode.class)
            .register(JsonNodeType.class)
            .register(LongNode.class)
            .register(MissingNode.class)
            .register(NullNode.class)
            .register(NumericNode.class)
            .register(POJONode.class)
            .register(ShortNode.class)
            .register(ValueNode.class)
            .register(JsonNodeCreator.class)
            .register(JsonNodeFactory.class)
            .build();

    localWorkplaceMap.clear();
    workplaceMap = storageService.<String, WorkflowData>consistentMapBuilder()
            .withSerializer(Serializer.using(workplaceNamespace))
            .withName("workplace-map")
            .withApplicationId(appId)
            .build();
    workplaceMap.addListener(workplaceMapEventListener);

    localContextMap.clear();
    contextMap = storageService.<String, WorkflowData>consistentMapBuilder()
            .withSerializer(Serializer.using(workplaceNamespace))
            .withName("workflow-context-map")
            .withApplicationId(appId)
            .build();
    contextMap.addListener(contextMapEventListener);

    workplaceMapEventListener.syncLocal();
    contextMapEventListener.syncLocal();
    log.info("Started");
}