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

The following examples show how to use com.fasterxml.jackson.databind.node.NullNode. 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: 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 #2
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 #3
Source File: IRequestParameter.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
public Object extract(ObjectNode node, RakamHttpRequest request)
{
    JsonNode value = node.get(name);
    Object o;
    if (value == null) {
        o = null;
    }
    else {
        try {
            o = mapper.convertValue(value, type);
        }
        catch (IllegalArgumentException e) {
            throw new HttpRequestException(name +
                    " body parameter cannot be cast to " + type.toString() + ": "+e.getMessage(), BAD_REQUEST);
        }
    }

    if (required && (o == null || o == NullNode.getInstance())) {
        throw new HttpRequestException(name + " body parameter is required", BAD_REQUEST);
    }

    return o;
}
 
Example #4
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 #5
Source File: Json.java    From immutables with Apache License 2.0 6 votes vote down vote up
JsonNode valueOrNull(String name) {
  Objects.requireNonNull(name, "name");

  if (fields != null && fields.has(name)) {
    JsonNode field = fields.get(name);
    if (field.isArray()) {
      // return first element (or null)
      Iterator<JsonNode> iter = field.elements();
      return iter.hasNext() ? iter.next() : null;
    }

    return field;
  }

  JsonNode found = source().at(name);
  return found.isMissingNode() ? NullNode.getInstance() : found;
}
 
Example #6
Source File: BuiltinFunctions.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode call(JsonNode input, JsonNode[] arguments) {
  String json = NodeUtils.toString(arguments[0], true);
  if (json == null)
    return NullNode.instance;

  try {
    JsonNode parsed = NodeUtils.mapper.readTree(json);
    if (parsed == null) // if input is "", for example
      return NullNode.instance;
    return parsed;
  } catch (Exception e) {
    if (arguments.length == 2)
      return arguments[1]; // return fallback on parse fail
    else
      throw new JsltException("from-json can't parse " + json + ": " + e);
  }
}
 
Example #7
Source File: AllMapKeysTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
private static ObjectNode hasNullMapsNode() {
  ObjectNode node = newObjectNode();
  node.set("int32Map", NullNode.getInstance());
  node.set("int64Map", NullNode.getInstance());
  node.set("uint32Map", NullNode.getInstance());
  node.set("uint64Map", NullNode.getInstance());
  node.set("sint32Map", NullNode.getInstance());
  node.set("sint64Map", NullNode.getInstance());
  node.set("fixed32Map", NullNode.getInstance());
  node.set("fixed64Map", NullNode.getInstance());
  node.set("sfixed32Map", NullNode.getInstance());
  node.set("sfixed64Map", NullNode.getInstance());
  node.set("boolMap", NullNode.getInstance());
  node.set("stringMap", NullNode.getInstance());
  return node;
}
 
Example #8
Source File: DivideOperator.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isNull() || v2.isNull())
    return NullNode.instance;

  // we only support the numeric operation and nothing else
  v1 = NodeUtils.number(v1, true, location);
  v2 = NodeUtils.number(v2, true, location);

  if (v1.isIntegralNumber() && v2.isIntegralNumber()) {
    long l1 = v1.longValue();
    long l2 = v2.longValue();
    if (l1 % l2 == 0)
      return new LongNode(l1 / l2);
    else
      return new DoubleNode((double) l1 / (double) l2);
  } else
    return new DoubleNode(perform(v1.doubleValue(), v2.doubleValue()));
}
 
Example #9
Source File: Ports.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Ports deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    Ports out = new Ports();
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {

        Map.Entry<String, JsonNode> portNode = it.next();
        JsonNode bindingsArray = portNode.getValue();
        if (bindingsArray.equals(NullNode.getInstance())) {
            out.bind(ExposedPort.parse(portNode.getKey()), null);
        } else {
            for (int i = 0; i < bindingsArray.size(); i++) {
                JsonNode bindingNode = bindingsArray.get(i);
                if (!bindingNode.equals(NullNode.getInstance())) {
                    String hostIp = bindingNode.get("HostIp").textValue();
                    String hostPort = bindingNode.get("HostPort").textValue();
                    out.bind(ExposedPort.parse(portNode.getKey()), new Binding(hostIp, hostPort));
                }
            }
        }
    }
    return out;
}
 
Example #10
Source File: WebSocketRouter.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the given json message to the identified client. If the client is not connected on the web socket,
 * nothing happens.
 *
 * @param uri     the websocket's url
 * @param client  the client that is going to receive the message
 * @param message the data (json)
 */
@Override
public void send(String uri, String client, JsonNode message) {
    for (WebSocketDispatcher dispatcher : dispatchers) {
        if (message == null) {
            dispatcher.send(uri, client, NullNode.getInstance().toString());
        } else {
            dispatcher.send(uri, client, message.toString());
        }
    }
}
 
Example #11
Source File: ViewResponse.java    From tasmo with Apache License 2.0 5 votes vote down vote up
public ViewResponse(@JsonProperty("statusCode") StatusCode statusCode,
    @JsonProperty("viewBody") JsonNode viewBody) {
    this.statusCode = statusCode;
    if (viewBody instanceof ObjectNode) {
        this.viewBody = (ObjectNode) viewBody;
    } else if (viewBody instanceof NullNode || viewBody == null) {
        this.viewBody = null;
    } else {
        throw new IllegalArgumentException("Unsupported type of viewBody - " + viewBody.getClass().getName());
    }
}
 
Example #12
Source File: EntityImpl.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public void putMetadata(String namespace, String key, Object object) {
    checkAlreadyEmitted();
    validateNotNull(namespace);
    validateNotNull(key);
    if (null == object) {
        object = NullNode.instance;
    }
    metadata.computeIfAbsent(namespace, (n) -> {
        return new ConcurrentHashMap<String, Object>();
    }).put(key, object);
}
 
Example #13
Source File: StoredAsJsonTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedFieldWithDefaultNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.put("annotatedFieldWithDefault", NullNode.getInstance());

  StoredAsJsonBean bean = Rosetta.getMapper().treeToValue(node, StoredAsJsonBean.class);
  assertThat(bean.getAnnotatedFieldWithDefault().getStringProperty()).isEqualTo("value");
}
 
Example #14
Source File: IsJsonObject.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
private static Matcher<JsonNode> createNodeMatcher(final JsonNode value) {
  final JsonNodeType nodeType = value.getNodeType();
  switch (nodeType) {
    case ARRAY:
      return IsJsonArray.jsonArray((ArrayNode) value);
    case BINARY:
      throw new UnsupportedOperationException(
          "Expected value contains a binary node, which is not implemented.");
    case BOOLEAN:
      return IsJsonBoolean.jsonBoolean((BooleanNode) value);
    case MISSING:
      return IsJsonMissing.jsonMissing((MissingNode) value);
    case NULL:
      return IsJsonNull.jsonNull((NullNode) value);
    case NUMBER:
      return IsJsonNumber.jsonNumber((NumericNode) value);
    case OBJECT:
      return IsJsonObject.jsonObject((ObjectNode) value);
    case POJO:
      throw new UnsupportedOperationException(
          "Expected value contains a POJO node, which is not implemented.");
    case STRING:
      return IsJsonText.jsonText((TextNode) value);
    default:
      throw new UnsupportedOperationException("Unsupported node type " + nodeType);
  }
}
 
Example #15
Source File: StoredAsJsonTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedFieldNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.put("annotatedField", NullNode.getInstance());

  StoredAsJsonBean bean = Rosetta.getMapper().treeToValue(node, StoredAsJsonBean.class);
  assertThat(bean.getAnnotatedField()).isNull();
}
 
Example #16
Source File: HeaderDeserializerTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetNullStringWhenParsingNullNode() throws Exception {
    Map<String, JsonNode> tree = new HashMap<>();
    NullNode node = NullNode.getInstance();
    tree.put("key", node);

    String text = deserializer.getString(tree, "key");
    assertThat(text, is(nullValue()));
}
 
Example #17
Source File: CustomSerializationTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedGetterNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.set("annotatedGetter", NullNode.getInstance());

  CustomSerializationBean bean = Rosetta.getMapper().treeToValue(node, CustomSerializationBean.class);
  assertThat(bean.getAnnotatedField())
      .isNull();
}
 
Example #18
Source File: ExposedPort.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ExposedPort deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    if (!node.equals(NullNode.getInstance())) {
        Map.Entry<String, JsonNode> field = node.fields().next();
        return ExposedPort.parse(field.getKey());
    } else {
        return null;
    }
}
 
Example #19
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldReturnBaseClaimWhenParsingNullNode() throws Exception {
    JsonNode value = NullNode.getInstance();
    Claim claim = claimFromNode(value);

    assertThat(claim, is(notNullValue()));
    assertThat(claim, is(instanceOf(NullClaim.class)));
    assertThat(claim.isNull(), is(true));
}
 
Example #20
Source File: ReflectionUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void setArrayItem(ArrayNode list, int index, JsonNode valNode) {
    if (index == -1) {
        // append to end of array
        list.add(valNode);
        return;
    }
    // make sure items up to index exist
    for (int i = list.size(); i < index+1; i++) {
        list.add(NullNode.instance);
    }
    list.set(index, valNode);
}
 
Example #21
Source File: StoredAsJsonTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testBinaryFieldNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.put("binaryField", NullNode.getInstance());

  StoredAsJsonBean bean = Rosetta.getMapper().treeToValue(node, StoredAsJsonBean.class);
  assertThat(bean.getBinaryField()).isNull();
}
 
Example #22
Source File: RubiconBidderTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void makeHttpRequestsShouldProcessMetricsAndFillViewabilityVendor() {
    // given
    final BidRequest bidRequest = givenBidRequest(
            builder -> builder.video(Video.builder().build())
                    .metric(asList(Metric.builder().vendor("somebody").type("viewability").value(0.9f).build(),
                            Metric.builder().vendor("moat").type("viewability").value(0.3f).build(),
                            Metric.builder().vendor("comscore").type("unsupported").value(0.5f).build(),
                            Metric.builder().vendor("activeview").type("viewability").value(0.6f).build(),
                            Metric.builder().vendor("somebody").type("unsupported").value(0.7f).build())));

    // when
    final Result<List<HttpRequest<BidRequest>>> result = rubiconBidder.makeHttpRequests(bidRequest);

    // then
    assertThat(result.getErrors()).isEmpty();
    assertThat(result.getValue()).hasSize(1).doesNotContainNull()
            .extracting(httpRequest -> mapper.readValue(httpRequest.getBody(), BidRequest.class))
            .flatExtracting(BidRequest::getImp).doesNotContainNull()
            .flatExtracting(Imp::getMetric).doesNotContainNull()
            .containsOnly(Metric.builder().type("viewability").value(0.9f).vendor("somebody").build(),
                    Metric.builder().type("viewability").value(0.3f).vendor("seller-declared").build(),
                    Metric.builder().type("unsupported").value(0.5f).vendor("comscore").build(),
                    Metric.builder().type("viewability").value(0.6f).vendor("seller-declared").build(),
                    Metric.builder().type("unsupported").value(0.7f).vendor("somebody").build());
    assertThat(result.getValue()).hasSize(1).doesNotContainNull()
            .extracting(httpRequest -> mapper.readValue(httpRequest.getBody(), BidRequest.class))
            .flatExtracting(BidRequest::getImp).doesNotContainNull()
            .extracting(Imp::getExt).doesNotContainNull()
            .extracting(ext -> mapper.treeToValue(ext, RubiconImpExt.class))
            .containsOnly(RubiconImpExt.of(RubiconImpExtRp.of(null,
                    NullNode.getInstance(),
                    RubiconImpExtRpTrack.of("", "")), asList("moat.com", "doubleclickbygoogle.com")));
}
 
Example #23
Source File: AuctionRequestFactoryTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotSetDefaultPriceGranularityIfThereIsAMediaTypePriceGranularityForImpType() {
    // given
    final ExtMediaTypePriceGranularity mediaTypePriceGranularity = ExtMediaTypePriceGranularity.of(
            mapper.valueToTree(ExtPriceGranularity.of(2, singletonList(ExtGranularityRange.of(
                    BigDecimal.valueOf(20), BigDecimal.valueOf(0.1))))), null, null);
    givenBidRequest(BidRequest.builder()
            .imp(singletonList(Imp.builder().banner(Banner.builder().build())
                    .ext(mapper.createObjectNode()).build()))
            .ext(mapper.valueToTree(ExtBidRequest.of(ExtRequestPrebid.builder()
                    .targeting(ExtRequestTargeting.builder()
                            .mediatypepricegranularity(mediaTypePriceGranularity)
                            .build())
                    .build())))
            .build());

    // when
    final BidRequest request = factory.fromRequest(routingContext, 0L).result().getBidRequest();

    // then
    assertThat(singletonList(request))
            .extracting(BidRequest::getExt)
            .extracting(ext -> mapper.treeToValue(ext, ExtBidRequest.class))
            .extracting(ExtBidRequest::getPrebid)
            .extracting(ExtRequestPrebid::getTargeting)
            .extracting(ExtRequestTargeting::getPricegranularity)
            .containsOnly(NullNode.getInstance());
}
 
Example #24
Source File: FileSystemResourceResolverTest.java    From jslt with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveImportsFromFilesystemWithEncoding() throws IOException {
  FileSystemResourceResolver resolver = new FileSystemResourceResolver(
    new File("./src/test/resources"), StandardCharsets.ISO_8859_1
  );
  Expression e = parse("./src/test/resources/character-encoding-master.jslt", resolver);

  JsonNode result = e.apply(NullNode.instance);
  assertEquals("Hei på deg", result.asText());
}
 
Example #25
Source File: EvalTest.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
@Test
public void getNullTests() throws DatatypeConfigurationException, JsonProcessingException, IOException {
  String javascript = "var myNull; myNull";
  ServerEvaluationCall call = Common.evalClient.newServerEval().javascript(javascript)
    .addVariable("myNull", (String) null);

  try (EvalResultIterator results = call.eval()) {
     assertEquals("myNull looks wrong", null, results.next().getString());
  }

  try (EvalResultIterator results = call.eval()) {
    assertEquals("myNull looks wrong", null, results.next().get(new StringHandle()).get());
  }

  try (EvalResultIterator results = call.eval()) {
    assertEquals("myNull looks wrong", null, results.next().get(new BytesHandle()).get());
  }

  try (EvalResultIterator results = call.eval()) {
    NullNode jsonNullNode = new ObjectMapper().createObjectNode().nullNode();
    assertEquals("myNull looks wrong", jsonNullNode, results.next().get(new JacksonHandle()).get());
  }

  try (EvalResultIterator results = call.eval()) {
    ReaderHandle valueReader = results.next().get(new ReaderHandle());
    String value = HandleAccessor.contentAsString(valueReader);
    assertEquals("myNull looks wrong", "null", value);
  }
}
 
Example #26
Source File: StoredAsJsonTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedSetterWithDefaultNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.put("annotatedSetterWithDefault", NullNode.getInstance());

  StoredAsJsonBean bean = Rosetta.getMapper().treeToValue(node, StoredAsJsonBean.class);
  assertThat(bean.getAnnotatedSetterWithDefault().getStringProperty()).isEqualTo("value");
}
 
Example #27
Source File: StoredAsJsonTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonNodeNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.put("jsonNodeField", NullNode.getInstance());

  StoredAsJsonBean bean = Rosetta.getMapper().treeToValue(node, StoredAsJsonBean.class);
  assertThat(bean.getJsonNodeField()).isEqualTo(NullNode.getInstance());
}
 
Example #28
Source File: IfExpression.java    From jslt with Apache License 2.0 5 votes vote down vote up
public JsonNode apply(Scope scope, JsonNode input) {
  if (NodeUtils.isTrue(test.apply(scope, input))) {
    NodeUtils.evalLets(scope, input, thenlets);
    return then.apply(scope, input);
  }

  // test was false, so return null or else
  if (orelse != null) {
    NodeUtils.evalLets(scope, input, elselets);
    return orelse.apply(scope, input);
  } else
    return NullNode.instance;
}
 
Example #29
Source File: NumericOperator.java    From jslt with Apache License 2.0 5 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isNull() || v2.isNull())
    return NullNode.instance;

  v1 = NodeUtils.number(v1, true, location);
  v2 = NodeUtils.number(v2, true, location);

  if (v1.isIntegralNumber() && v2.isIntegralNumber())
    return new LongNode(perform(v1.longValue(), v2.longValue()));
  else
    return new DoubleNode(perform(v1.doubleValue(), v2.doubleValue()));
}
 
Example #30
Source File: CustomSerializationTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotatedFieldNullDeserialization() throws JsonProcessingException {
  ObjectNode node = Rosetta.getMapper().createObjectNode();
  node.set("annotatedField", NullNode.getInstance());

  CustomSerializationBean bean = Rosetta.getMapper().treeToValue(node, CustomSerializationBean.class);
  assertThat(bean.getAnnotatedField())
      .isNull();
}