Example usage for com.fasterxml.jackson.databind.node JsonNodeFactory instance

List of usage examples for com.fasterxml.jackson.databind.node JsonNodeFactory instance

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node JsonNodeFactory instance.

Prototype

JsonNodeFactory instance

To view the source code for com.fasterxml.jackson.databind.node JsonNodeFactory instance.

Click Source Link

Usage

From source file:org.springframework.cloud.aws.messaging.support.converter.NotificationRequestConverterTest.java

@Test
public void testWrongTypeSupplied() throws Exception {
    this.expectedException.expect(MessageConversionException.class);
    this.expectedException.expectMessage("is not a valid notification");
    ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
    jsonObject.put("Type", "Subscription");
    jsonObject.put("Message", "Hello World!");
    String payload = jsonObject.toString();
    new NotificationRequestConverter().fromMessage(MessageBuilder.withPayload(payload).build(), null);
}

From source file:org.onosproject.sdxl3.config.SdxParticipantsConfig.java

/**
 * Adds new BGP peer details to the configuration.
 *
 * @param peer BGP peer configuration entry
 *///from  www.ja v  a2  s.  co m

public void addPeer(PeerConfig peer) {
    ObjectNode peerNode = JsonNodeFactory.instance.objectNode();

    if (peer.name().isPresent()) {
        peerNode.put(NAME, peer.name().get());
    }
    peerNode.put(IP, peer.ip().toString());
    peerNode.put(CONN_POINT,
            peer.connectPoint().elementId().toString() + "/" + peer.connectPoint().port().toString());
    peerNode.put(INTF_NAME, peer.interfaceName());

    ArrayNode peersArray = bgpPeers().isEmpty() ? initPeersConfiguration() : (ArrayNode) object.get(PEERS);
    peersArray.add(peerNode);
}

From source file:com.datamountaineer.streamreactor.connect.json.SimpleJsonConverter.java

/**
 * Convert this object, in the org.apache.kafka.connect.data format, into a JSON object, returning both the schema
 * and the converted object./*from  w  ww  .ja v a  2  s . co  m*/
 */
private static JsonNode convertToJson(Schema schema, Object logicalValue) {
    if (logicalValue == null) {
        if (schema == null) // Any schema is valid and we don't have a default, so treat this as an optional schema
            return null;
        if (schema.defaultValue() != null)
            return convertToJson(schema, schema.defaultValue());
        if (schema.isOptional())
            return JsonNodeFactory.instance.nullNode();
        throw new DataException(
                "Conversion error: null value for field that is required and has no default value");
    }

    Object value = logicalValue;
    try {
        final Schema.Type schemaType;
        if (schema == null) {
            schemaType = ConnectSchema.schemaType(value.getClass());
            if (schemaType == null)
                throw new DataException(
                        "Java class " + value.getClass() + " does not have corresponding schema type.");
        } else {
            schemaType = schema.type();
        }
        switch (schemaType) {
        case INT8:
            return JsonNodeFactory.instance.numberNode((Byte) value);
        case INT16:
            return JsonNodeFactory.instance.numberNode((Short) value);
        case INT32:
            if (schema != null && Date.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.textNode(ISO_DATE_FORMAT.format((java.util.Date) value));
            }
            if (schema != null && Time.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.textNode(TIME_FORMAT.format((java.util.Date) value));
            }
            return JsonNodeFactory.instance.numberNode((Integer) value);
        case INT64:
            String schemaName = schema.name();
            if (Timestamp.LOGICAL_NAME.equals(schemaName)) {
                return JsonNodeFactory.instance
                        .numberNode(Timestamp.fromLogical(schema, (java.util.Date) value));
            }
            return JsonNodeFactory.instance.numberNode((Long) value);
        case FLOAT32:
            return JsonNodeFactory.instance.numberNode((Float) value);
        case FLOAT64:
            return JsonNodeFactory.instance.numberNode((Double) value);
        case BOOLEAN:
            return JsonNodeFactory.instance.booleanNode((Boolean) value);
        case STRING:
            CharSequence charSeq = (CharSequence) value;
            return JsonNodeFactory.instance.textNode(charSeq.toString());
        case BYTES:
            if (Decimal.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.numberNode((BigDecimal) value);
            }

            byte[] valueArr = null;
            if (value instanceof byte[])
                valueArr = (byte[]) value;
            else if (value instanceof ByteBuffer)
                valueArr = ((ByteBuffer) value).array();

            if (valueArr == null)
                throw new DataException("Invalid type for bytes type: " + value.getClass());

            return JsonNodeFactory.instance.binaryNode(valueArr);

        case ARRAY: {
            Collection collection = (Collection) value;
            ArrayNode list = JsonNodeFactory.instance.arrayNode();
            for (Object elem : collection) {
                Schema valueSchema = schema == null ? null : schema.valueSchema();
                JsonNode fieldValue = convertToJson(valueSchema, elem);
                list.add(fieldValue);
            }
            return list;
        }
        case MAP: {
            Map<?, ?> map = (Map<?, ?>) value;
            // If true, using string keys and JSON object; if false, using non-string keys and Array-encoding
            boolean objectMode;
            if (schema == null) {
                objectMode = true;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    if (!(entry.getKey() instanceof String)) {
                        objectMode = false;
                        break;
                    }
                }
            } else {
                objectMode = schema.keySchema().type() == Schema.Type.STRING;
            }
            ObjectNode obj = null;
            ArrayNode list = null;
            if (objectMode)
                obj = JsonNodeFactory.instance.objectNode();
            else
                list = JsonNodeFactory.instance.arrayNode();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                Schema keySchema = schema == null ? null : schema.keySchema();
                Schema valueSchema = schema == null ? null : schema.valueSchema();
                JsonNode mapKey = convertToJson(keySchema, entry.getKey());
                JsonNode mapValue = convertToJson(valueSchema, entry.getValue());

                if (objectMode)
                    obj.set(mapKey.asText(), mapValue);
                else
                    list.add(JsonNodeFactory.instance.arrayNode().add(mapKey).add(mapValue));
            }
            return objectMode ? obj : list;
        }
        case STRUCT: {
            Struct struct = (Struct) value;
            if (struct.schema() != schema)
                throw new DataException("Mismatching schema.");
            ObjectNode obj = JsonNodeFactory.instance.objectNode();
            for (Field field : schema.fields()) {
                obj.set(field.name(), convertToJson(field.schema(), struct.get(field)));
            }
            return obj;
        }
        }

        throw new DataException("Couldn't convert " + value + " to JSON.");
    } catch (ClassCastException e) {
        throw new DataException("Invalid type for " + schema.type() + ": " + value.getClass());
    }
}

From source file:org.apache.taverna.gis.GisActivityFactoryTest.java

@Test
public void testGetOutputPorts() {
    Set<String> expectedOutputs = new HashSet<String>();
    expectedOutputs.add("simpleOutput");
    expectedOutputs.add("moreOutputs");

    Set<ActivityOutputPort> outputPorts = activityFactory.getOutputPorts(configuration);
    assertEquals("Unexpected outputs", expectedOutputs.size(), outputPorts.size());
    for (ActivityOutputPort outputPort : outputPorts) {
        assertTrue("Wrong output : " + outputPort.getName(), expectedOutputs.remove(outputPort.getName()));
    }//from ww w. ja v a2  s .com

    ObjectNode specialConfiguration = JsonNodeFactory.instance.objectNode();
    specialConfiguration.put("exampleString", "specialCase");
    specialConfiguration.put("exampleUri", "http://localhost:8080/myEndPoint");

    assertEquals("Unexpected outputs", 3, activityFactory.getOutputPorts(specialConfiguration).size());
}

From source file:com.turn.shapeshifter.NamedSchemaParserTest.java

@Test
public void testParseWithEmptyObject() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union");
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);//from   w  ww .j  a v a 2s .c o  m
    Union union = Union.newBuilder()
            .mergeFrom(new NamedSchemaParser(schema).parse(new ObjectNode(JsonNodeFactory.instance), registry))
            .build();
    Assert.assertEquals(Union.getDefaultInstance(), union);
}

From source file:com.spotify.hamcrest.jackson.IsJsonObject.java

private static String jsonEscapeString(String string) {
    return JsonNodeFactory.instance.textNode(string).toString();
}

From source file:org.springframework.cloud.aws.messaging.support.NotificationMessageArgumentResolverTest.java

@Test
public void resolveArgument_withValidMessagePayload_shouldReturnNotificationMessage() throws Exception {
    // Arrange/* w  w  w  .  j av  a 2s  .  com*/
    NotificationMessageArgumentResolver notificationMessageArgumentResolver = new NotificationMessageArgumentResolver();
    Method methodWithNotificationMessageArgument = this.getClass()
            .getDeclaredMethod("methodWithNotificationMessageArgument", String.class);
    MethodParameter methodParameter = new MethodParameter(methodWithNotificationMessageArgument, 0);

    ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
    jsonObject.put("Type", "Notification");
    jsonObject.put("Message", "Hello World!");
    String payload = jsonObject.toString();
    Message<String> message = MessageBuilder.withPayload(payload).build();

    // Act
    Object result = notificationMessageArgumentResolver.resolveArgument(methodParameter, message);

    // Assert
    assertTrue(String.class.isInstance(result));
    assertEquals("Hello World!", result);
}

From source file:org.springframework.cloud.aws.messaging.support.NotificationSubjectArgumentResolverTest.java

@Test
public void resolveArgument_withValidRequestPayload_shouldReturnNotificationSubject() throws Exception {
    // Arrange//from  ww  w . j a  v a2 s  .  c om
    NotificationSubjectArgumentResolver notificationSubjectArgumentResolver = new NotificationSubjectArgumentResolver();
    Method methodWithNotificationSubjectArgument = this.getClass()
            .getDeclaredMethod("methodWithNotificationSubjectArgument", String.class);
    MethodParameter methodParameter = new MethodParameter(methodWithNotificationSubjectArgument, 0);

    ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
    jsonObject.put("Type", "Notification");
    jsonObject.put("Subject", "My subject!");
    jsonObject.put("Message", "message");
    String payload = jsonObject.toString();
    Message<String> message = MessageBuilder.withPayload(payload).build();

    // Act
    Object result = notificationSubjectArgumentResolver.resolveArgument(methodParameter, message);

    // Assert
    assertTrue(String.class.isInstance(result));
    assertEquals("My subject!", result);
}

From source file:com.amazonaws.service.apigateway.importer.impl.SchemaTransformer.java

private void replaceRefs(JsonNode root, HashMap<String, String> schemaMap) {

    ObjectNode definitionsNode = new ObjectNode(JsonNodeFactory.instance);

    for (Map.Entry<String, String> entry : schemaMap.entrySet()) {
        JsonNode schemaNode = deserialize(entry.getValue());
        definitionsNode.set(entry.getKey(), schemaNode);
    }//from w  w w  .j  a v a2 s. c o  m

    ((ObjectNode) root).set("definitions", definitionsNode);
}