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

The following examples show how to use com.fasterxml.jackson.databind.node.IntNode. 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: ObjectToJsonNode.java    From yosegi with Apache License 2.0 6 votes vote down vote up
/**
 * Judge Java objects and create JsonNode.
 */
public static JsonNode get( final Object obj ) throws IOException {
  if ( obj instanceof PrimitiveObject ) {
    return PrimitiveObjectToJsonNode.get( (PrimitiveObject)obj );
  } else if ( obj instanceof String ) {
    return new TextNode( (String)obj );
  } else if ( obj instanceof Boolean ) {
    return BooleanNode.valueOf( (Boolean)obj );
  } else if ( obj instanceof Short ) {
    return IntNode.valueOf( ( (Short)obj ).intValue() );
  } else if ( obj instanceof Integer ) {
    return IntNode.valueOf( (Integer)obj );
  } else if ( obj instanceof Long ) {
    return new LongNode( (Long)obj );
  } else if ( obj instanceof Float ) {
    return new DoubleNode( ( (Float)obj ).doubleValue() );
  } else if ( obj instanceof Double ) {
    return new DoubleNode( (Double)obj );
  } else if ( obj instanceof byte[] ) {
    return new BinaryNode( (byte[])obj );
  } else if ( obj == null ) {
    return NullNode.getInstance();
  } else {
    return new TextNode( obj.toString() );
  }
}
 
Example #2
Source File: TsdbResult.java    From splicer with Apache License 2.0 6 votes vote down vote up
@Override
public Points deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	TreeNode n = jp.getCodec().readTree(jp);
	Map<String, Object> points = new HashMap<>();
	Iterator<String> namesIter = n.fieldNames();
	while(namesIter.hasNext()) {
		String field = namesIter.next();
		TreeNode child = n.get(field);

		Object o;
		if (child instanceof DoubleNode || child instanceof FloatNode) {
			o = ((NumericNode) child).doubleValue();
		} else if (child instanceof IntNode || child instanceof LongNode) {
			o = ((NumericNode) child).longValue();
		} else {
			throw new MergeException("Unsupported Type, " + child.getClass());
		}

		points.put(field, o);
	}
	return new Points(points);
}
 
Example #3
Source File: TableAnswerElementTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
/** Does evaluateAssertion do the right thing for counting assertions? */
@Test
public void testEvaluateAssertionCount() {
  Assertion twoCount = new Assertion(AssertionType.countequals, new IntNode(2));

  TableAnswerElement oneRow =
      new TableAnswerElement(
          new TableMetadata(
              ImmutableList.of(new ColumnMetadata("col", Schema.STRING, "desc")), "no desc"));
  oneRow.addRow(Row.builder().put("col", "val").build());

  TableAnswerElement twoRows =
      new TableAnswerElement(
          new TableMetadata(
              ImmutableList.of(new ColumnMetadata("col", Schema.STRING, "desc")), "no desc"));
  twoRows.addRow(Row.builder().put("col", "val").build());
  twoRows.addRow(Row.builder().put("col", "val").build());

  assertThat(oneRow.evaluateAssertion(twoCount), equalTo(false));
  assertThat(twoRows.evaluateAssertion(twoCount), equalTo(true));
}
 
Example #4
Source File: TableAnswerElementTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
/** Does computerSummary compute the correct summary? */
@Test
public void testComputeSummary() {
  // generate an answer with two rows
  TableAnswerElement answer =
      new TableAnswerElement(
          new TableMetadata(
              ImmutableList.of(new ColumnMetadata("col", Schema.STRING, "desc")), "no desc"));
  answer.addRow(Row.builder().put("col", "val").build());
  answer.addRow(Row.builder().put("col", "val").build());

  Assertion assertion = new Assertion(AssertionType.countequals, new IntNode(1)); // wrong count
  AnswerSummary summary = answer.computeSummary(assertion);

  assertThat(summary.getNumResults(), equalTo(2));
  assertThat(summary.getNumFailed(), equalTo(1));
  assertThat(summary.getNumPassed(), equalTo(0));
}
 
Example #5
Source File: DataDragon.java    From orianna with MIT License 6 votes vote down vote up
@Override
public JsonNode apply(final JsonNode championTree) {
    if(championTree == null) {
        return championTree;
    }

    // Swap key and id. They're reversed between ddragon and the API.
    if(championTree.has("key") && championTree.has("id")) {
        final ObjectNode champion = (ObjectNode)championTree;
        final String id = champion.get("key").asText();
        champion.set("key", champion.get("id"));
        champion.set("id", new IntNode(Integer.parseInt(id)));
    }

    // Fix spell coeff field
    final JsonNode temp = championTree.get("spells");
    if(temp == null) {
        return championTree;
    }

    for(final JsonNode spell : temp) {
        SPELL_PROCESSOR.apply(spell);
    }
    return championTree;
}
 
Example #6
Source File: StaticTests.java    From jslt with Apache License 2.0 6 votes vote down vote up
@Test
public void testNamedModule() {
  Map<String, Function> functions = new HashMap();
  functions.put("test", new TestFunction());
  ModuleImpl module = new ModuleImpl(functions);

  Map<String, Module> modules = new HashMap();
  modules.put("the test module", module);

  StringReader jslt = new StringReader(
    "import \"the test module\" as t t:test()"
  );
  Expression expr = new Parser(jslt)
    .withNamedModules(modules)
    .compile();

  JsonNode result = expr.apply(null);
  assertEquals(new IntNode(42), result);
}
 
Example #7
Source File: DistributedNetworkConfigStore.java    From onos with Apache License 2.0 6 votes vote down vote up
@Activate
public void activate() {
    KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
            .register(KryoNamespaces.API)
            .register(ConfigKey.class, ObjectNode.class, ArrayNode.class,
                      JsonNodeFactory.class, LinkedHashMap.class,
                      TextNode.class, BooleanNode.class,
                      LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class,
                      NullNode.class);

    configs = storageService.<ConfigKey, JsonNode>consistentMapBuilder()
            .withSerializer(Serializer.using(kryoBuilder.build()))
            .withName("onos-network-configs")
            .withRelaxedReadConsistency()
            .build();
    configs.addListener(listener);
    log.info("Started");
}
 
Example #8
Source File: StratumMessageTest.java    From java-stratum with Apache License 2.0 6 votes vote down vote up
@Test
public void deserialize() throws Exception {
    StratumMessage m1 = readValue("{\"id\":123, \"method\":\"a.b\", \"params\":[1, \"x\", null]}");
    assertEquals(123L, (long)m1.id);
    assertEquals("a.b", m1.method);
    assertEquals(Lists.newArrayList(new IntNode(1), new TextNode("x"), NullNode.getInstance()), m1.params);
    StratumMessage m2 = readValue("{\"id\":123, \"result\":{\"x\": 123}}");
    assertTrue(m2.isResult());
    assertEquals(123L, (long)m2.id);
    assertEquals(mapper.createObjectNode().put("x", 123), m2.result);

    StratumMessage m3 = readValue("{\"id\":123, \"result\":[\"x\"]}");
    assertEquals(123L, (long)m3.id);
    //noinspection AssertEqualsBetweenInconvertibleTypes
    assertEquals(mapper.createArrayNode().add("x"), m3.result);
}
 
Example #9
Source File: IntegerSampler.java    From log-synth with Apache License 2.0 6 votes vote down vote up
@Override
public JsonNode sample() {
    synchronized (this) {
        if (dist == null) {
            int r = power >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            if (power >= 0) {
                for (int i = 0; i <= power; i++) {
                    r = Math.min(r, min + base.nextInt(max - min));
                }
            } else {
                int n = -power;
                for (int i = 0; i <= n; i++) {
                    r = Math.max(r, min + base.nextInt(max - min));
                }
            }
            if (format == null) {
                return new IntNode(r);
            } else {
                return new TextNode(String.format(format, r));
            }
        } else {
            return new LongNode(dist.sample());
        }
    }
}
 
Example #10
Source File: QuestionSettingsJsonPathResourceTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutQuestionSettingsPresentDepth2Success() throws IOException {
  String settings = "{}";
  String oldKey = "foo";
  int oldVal = 1;

  Main.getWorkMgr()
      .writeQuestionSettings(
          NETWORK,
          QUESTION,
          ImmutableList.of(),
          BatfishObjectMapper.mapper().readTree(String.format("{\"%s\":%d}", oldKey, oldVal)));

  JsonNode settingsNode = BatfishObjectMapper.mapper().readTree(settings);
  JsonNodeFactory factory = BatfishObjectMapper.mapper().getNodeFactory();
  ObjectNode rootSettingsNode = new ObjectNode(factory);
  ObjectNode leafNode = new ObjectNode(factory);
  leafNode.set(PROP2, settingsNode);
  rootSettingsNode.set(PROP1, leafNode);
  rootSettingsNode.set(oldKey, new IntNode(oldVal));
  try (Response response =
      getQuestionSettingsJsonPathTarget(QUESTION, String.format("%s/%s", PROP1, PROP2))
          .put(Entity.entity(settingsNode, MediaType.APPLICATION_JSON))) {
    assertThat(response.getStatus(), equalTo(Status.OK.getStatusCode()));
  }
  assertThat(
      BatfishObjectMapper.mapper().readTree(_storage._questionSettings),
      equalTo(rootSettingsNode));
}
 
Example #11
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 #12
Source File: UiExtensionManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Activate
public void activate() {
    Serializer serializer = Serializer.using(KryoNamespaces.API,
                 ObjectNode.class, ArrayNode.class,
                 JsonNodeFactory.class, LinkedHashMap.class,
                 TextNode.class, BooleanNode.class,
                 LongNode.class, DoubleNode.class, ShortNode.class,
                 IntNode.class, NullNode.class, UiSessionToken.class);

    prefsConsistentMap = storageService.<String, ObjectNode>consistentMapBuilder()
            .withName(ONOS_USER_PREFERENCES)
            .withSerializer(serializer)
            .withRelaxedReadConsistency()
            .build();
    prefsConsistentMap.addListener(prefsListener);
    prefs = prefsConsistentMap.asJavaMap();

    tokensConsistentMap = storageService.<UiSessionToken, String>consistentMapBuilder()
            .withName(ONOS_SESSION_TOKENS)
            .withSerializer(serializer)
            .withRelaxedReadConsistency()
            .build();
    tokens = tokensConsistentMap.asJavaMap();

    register(core);

    log.info("Started");
}
 
Example #13
Source File: JsonDataModelInjector.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Inhales integer data model on the filed of work-let.
 *
 * @param worklet work-let
 * @param context workflow context
 * @param field   the field of work-let
 * @param model   integer data model for the field
 * @throws WorkflowException workflow exception
 */
private static void inhaleInteger(Worklet worklet, WorkflowContext context, Field field, JsonDataModel model)
        throws WorkflowException {
    if (!(Objects.equals(field.getType(), Integer.class))) {
        throw new WorkflowException("Target field (" + field + ") is not Integer");
    }

    Integer number;
    try {
        field.setAccessible(true);
        number = (Integer) field.get(worklet);
    } catch (IllegalAccessException e) {
        throw new WorkflowException(e);
    }

    if (Objects.isNull(number)) {
        return;
    }

    JsonDataModelTree tree = (JsonDataModelTree) context.data();
    JsonNode jsonNode = tree.nodeAt(model.path());

    if (Objects.isNull(jsonNode) || jsonNode instanceof MissingNode) {
        tree.setAt(model.path(), number);
    } else if (!(jsonNode instanceof IntNode)) {
        throw new WorkflowException("Invalid integer data model on (" + model.path() + ")");
    } else {
        tree.remove(model.path());
        tree.setAt(model.path(), number);
    }
}
 
Example #14
Source File: JSONBindingFactoryTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testByteConversion() {
    ObjectMapper mapper = new JSONBindingFactory().createBaseObjectMapper();
    JsonNode paramValue = new IntNode(128);
    JavaType javaType = SimpleType.construct(byte.class);
    mapper.convertValue(paramValue, javaType);
}
 
Example #15
Source File: ItemDeserializerOnClass.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * {"id":1,"itemNr":"theItem","owner":2}
 */
@Override
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    final JsonNode node = jp.getCodec()
        .readTree(jp);
    final int id = (Integer) ((IntNode) node.get("id")).numberValue();
    final String itemName = node.get("itemName")
        .asText();
    final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();

    return new ItemWithSerializer(id, itemName, new User(userId, null));
}
 
Example #16
Source File: ItemDeserializer.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * {"id":1,"itemNr":"theItem","owner":2}
 */
@Override
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    final JsonNode node = jp.getCodec()
        .readTree(jp);
    final int id = (Integer) ((IntNode) node.get("id")).numberValue();
    final String itemName = node.get("itemName")
        .asText();
    final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();

    return new Item(id, itemName, new User(userId, null));
}
 
Example #17
Source File: ItemDeserializerOnClass.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * {"id":1,"itemNr":"theItem","owner":2}
 */
@Override
public ItemWithDeserializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    final JsonNode node = jp.getCodec()
        .readTree(jp);
    final int id = (Integer) ((IntNode) node.get("id")).numberValue();
    final String itemName = node.get("itemName")
        .asText();
    final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();

    return new ItemWithDeserializer(id, itemName, new User(userId, null));
}
 
Example #18
Source File: SequenceSampler.java    From log-synth with Apache License 2.0 5 votes vote down vote up
private FieldSampler exponential(final double length) {
    return new FieldSampler() {
        @Override
        public JsonNode sample() {
            int n = (int) Math.floor(-length * Math.log(gen.nextDouble()));
            return new IntNode(n);
        }
    };
}
 
Example #19
Source File: DataDragon.java    From orianna with MIT License 5 votes vote down vote up
@Override
public JsonNode apply(final JsonNode spellTree) {
    if(spellTree == null) {
        return spellTree;
    }

    // Swap key and id. They're reversed between ddragon and the API.
    if(spellTree.has("key") && spellTree.has("id")) {
        final ObjectNode spell = (ObjectNode)spellTree;
        final String id = spell.get("key").asText();
        spell.set("key", spell.get("id"));
        spell.set("id", new IntNode(Integer.parseInt(id)));
    }

    final JsonNode temp = spellTree.get("vars");
    if(temp == null) {
        return spellTree;
    }

    for(final JsonNode vars : temp) {
        if(vars == null) {
            continue;
        }

        final JsonNode coeff = vars.get("coeff");
        if(coeff == null) {
            continue;
        } else if(!coeff.isArray()) {
            ((ObjectNode)vars).putArray("coeff").add(coeff.asDouble());
        }
    }
    return spellTree;
}
 
Example #20
Source File: AssertInputCase.java    From tasmo with Apache License 2.0 5 votes vote down vote up
private AssertionResult assertCountField(IntNode leaf, String field, int expectedFieldValue) {
    if (leaf.intValue() == expectedFieldValue) {
        return new AssertionResult(true, "");
    } else {
        return new AssertionResult(false, "Unexpected value for field " + field + " - found " + leaf);
    }
}
 
Example #21
Source File: QuestionHelperTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void validateTemplateExtraParameter() throws JSONException, IOException {
  JSONObject template =
      new JSONObject(readResource("org/batfish/client/extraParameter.json", UTF_8));

  _thrown.expect(BatfishException.class);
  _thrown.expectMessage("Unrecognized field");

  QuestionHelper.validateTemplate(
      template,
      ImmutableSortedMap.of("parameter1", new IntNode(2), "parameter2", new IntNode(2)));
}
 
Example #22
Source File: QuestionHelperTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void fillTemplate() throws JSONException, IOException {
  JSONObject template =
      new JSONObject(readResource("org/batfish/client/goodTemplate.json", UTF_8));
  JSONObject filledTempate =
      QuestionHelper.fillTemplate(
          template, ImmutableSortedMap.of("parameter1", new IntNode(2)), "qname");
  QuestionHelperTestQuestion question =
      (QuestionHelperTestQuestion) Question.parseQuestion(filledTempate.toString());

  // the mandatory parameter should get the value we gave, and the optional one should get default
  assertThat(question.getParameterMandatory(), equalTo(2));
  assertThat(question.getParameterOptional(), equalTo(QuestionHelperTestQuestion.DEFAULT_VALUE));
}
 
Example #23
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 #24
Source File: MultiDateDeserializer.java    From nimble-orm with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	JsonNode node = jp.getCodec().readTree(jp);

	// 针对时间戳做优化
	if(node instanceof LongNode || node instanceof IntNode) {
		long timestamp = node.asLong();
		if(timestamp < 4200000000L) { // 小于42亿认为是秒
			return new Date(timestamp * 1000L);
		} else {
			return new Date(timestamp);
		}
	}

	String date = node.asText();
	if(date == null) {
		return null;
	}
	date = date.trim();
	if(date.isEmpty()) {
		return null;
	}
	
	try {
		return NimbleOrmDateUtils.parseThrowException(date);
	} catch (ParseException e) {
		throw new JsonParseException(jp,
		    "Unparseable date: \"" + date + "\". Supported formats: " 
		    + NimbleOrmDateUtils.DATE_FORMAT_REGEXPS.values());
	}
}
 
Example #25
Source File: ExclusionTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void firstCoversSecondValueMismatch() {
  JsonNode node1 = new TextNode("2");
  JsonNode node2 = new IntNode(2); // different type

  boolean result = Exclusion.firstCoversSecond(node1, node2);

  assertThat(result, equalTo(false));
}
 
Example #26
Source File: JacksonAnyGetterTypeTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeJsonWithAnyGetter() throws IOException {
    JacksonAnyGetterType parsed = objectMapper.readValue(
            "{\"simple_property\": \"simpleValue\", \"other_property\": 3}",
            JacksonAnyGetterType.class);

    assertEquals("simpleValue", parsed.getSimpleProperty());
    assertNotNull(parsed.getUnknownProperties());
    assertEquals(1, parsed.getUnknownProperties().size());
    assertEquals(new IntNode(3), parsed.getUnknownProperties().get("other_property"));
}
 
Example #27
Source File: JacksonAnyGetterTypeTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializeJsonWithAnyGetter() throws JsonProcessingException {
    JacksonAnyGetterType getterType = new JacksonAnyGetterType.Builder()
            .setSimpleProperty("checkValue")
            .putUnknownProperties("propertyOne", new TextNode("abc"))
            .putUnknownProperties("propertyTwo", new IntNode(2)).build();

    String json = objectMapper.writeValueAsString(getterType);
    assertTrue("should contain simple_property",
            json.contains("\"simple_property\":\"checkValue\""));
    assertTrue("should contain propertyOne", json.contains("\"propertyOne\":\"abc\""));
    assertTrue("should contain propertyTwo", json.contains("\"propertyTwo\":2"));
}
 
Example #28
Source File: SerializationTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void unmarshalCRDWithSchema() throws Exception {
  final String input = readYamlToString("/test-crd-schema.yml");
  final CustomResourceDefinition crd = Serialization.unmarshal(input, CustomResourceDefinition.class);
  JSONSchemaProps spec = crd.getSpec()
    .getValidation()
    .getOpenAPIV3Schema()
    .getProperties()
    .get("spec");

  assertEquals(spec.getRequired().size(), 3);
  assertEquals(spec.getRequired().get(0), "builderName");
  assertEquals(spec.getRequired().get(1), "edges");
  assertEquals(spec.getRequired().get(2), "dimensions");

  Map<String, JSONSchemaProps> properties = spec.getProperties();
  assertNotNull(properties.get("builderName"));
  assertEquals(properties.get("builderName").getExample(), new TextNode("builder-example"));
  assertEquals(properties.get("hollow").getDefault(), BooleanNode.FALSE);

  assertNotNull(properties.get("dimensions"));
  assertNotNull(properties.get("dimensions").getProperties().get("x"));
  assertEquals(properties.get("dimensions").getProperties().get("x").getDefault(), new IntNode(10));

  String output = Serialization.asYaml(crd);
  assertEquals(input.trim(), output.trim());
}
 
Example #29
Source File: Serializer.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Long> deserialize(JsonNode json) {
    if (json instanceof LongNode) {
        return Optional.of(json.asLong());
    } else if (json instanceof IntNode) {
        return Optional.of(Long.valueOf(json.asInt()));
    } else {
        return Optional.empty();
    }
}
 
Example #30
Source File: Serializer.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Integer> deserialize(JsonNode json) {
    if (json instanceof IntNode) {
        return Optional.of(json.asInt());
    } else {
        return Optional.empty();
    }
}