javax.json.JsonBuilderFactory Java Examples

The following examples show how to use javax.json.JsonBuilderFactory. 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: SiteToSiteBulletinReportingTask.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
static JsonObject serialize(final JsonBuilderFactory factory, final JsonObjectBuilder builder, final Bulletin bulletin, final DateFormat df,
    final String platform, final String nodeIdentifier) {

    addField(builder, "objectId", UUID.randomUUID().toString());
    addField(builder, "platform", platform);
    addField(builder, "bulletinId", bulletin.getId());
    addField(builder, "bulletinCategory", bulletin.getCategory());
    addField(builder, "bulletinGroupId", bulletin.getGroupId());
    addField(builder, "bulletinLevel", bulletin.getLevel());
    addField(builder, "bulletinMessage", bulletin.getMessage());
    addField(builder, "bulletinNodeAddress", bulletin.getNodeAddress());
    addField(builder, "bulletinNodeId", nodeIdentifier);
    addField(builder, "bulletinSourceId", bulletin.getSourceId());
    addField(builder, "bulletinSourceName", bulletin.getSourceName());
    addField(builder, "bulletinSourceType", bulletin.getSourceType() == null ? null : bulletin.getSourceType().name());
    addField(builder, "bulletinTimestamp", df.format(bulletin.getTimestamp()));

    return builder.build();
}
 
Example #2
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void convertListObject(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final Record record = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(),
                        Json
                                .createObjectBuilder()
                                .add("list",
                                        Json
                                                .createArrayBuilder()
                                                .add(Json.createObjectBuilder().add("name", "a").build())
                                                .add(Json.createObjectBuilder().add("name", "b").build())
                                                .build())
                                .build(),
                        () -> jsonb, () -> new RecordBuilderFactoryImpl("test"));
        final Collection<Record> list = record.getArray(Record.class, "list");
        assertEquals(asList("a", "b"), list.stream().map(it -> it.getString("name")).collect(toList()));
    }
}
 
Example #3
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void bigDecimalsInArray(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final BigDecimal pos1 = new BigDecimal("48.8480275637");
    final BigDecimal pos2 = new BigDecimal("2.25369456784");
    final List<BigDecimal> expected = asList(pos1, pos2);
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json = jsonBuilderFactory
                .createObjectBuilder()
                .add("points", jsonBuilderFactory.createArrayBuilder().add(pos1).add(pos2).build())
                .build();
        final Record record =
                converter.toRecord(new MappingMetaRegistry(), json, () -> jsonb, () -> recordBuilderFactory);
        assertEquals(expected, record.getArray(BigDecimal.class, "points"));
    }
}
 
Example #4
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void serializeRemoteProcessGroupStatus(final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory,
        final RemoteProcessGroupStatus status, final DateFormat df, final String hostname, final String applicationName,
        final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentType = "RemoteProcessGroup";
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate,
                componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "activeRemotePortCount", status.getActiveRemotePortCount(), allowNullValues);
        addField(builder, "activeThreadCount", status.getActiveThreadCount(), allowNullValues);
        addField(builder, "inactiveRemotePortCount", status.getInactiveRemotePortCount(), allowNullValues);
        addField(builder, "receivedContentSize", status.getReceivedContentSize(), allowNullValues);
        addField(builder, "receivedCount", status.getReceivedCount(), allowNullValues);
        addField(builder, "sentContentSize", status.getSentContentSize(), allowNullValues);
        addField(builder, "sentCount", status.getSentCount(), allowNullValues);
        addField(builder, "averageLineageDuration", status.getAverageLineageDuration(), allowNullValues);
        addField(builder, "transmissionStatus", status.getTransmissionStatus() == null ? null : status.getTransmissionStatus().name(), allowNullValues);
        addField(builder, "targetURI", status.getTargetUri(), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
Example #5
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void serializePortStatus(final String componentType, final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory, final PortStatus status,
        final DateFormat df, final String hostname, final String applicationName, final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate,
                componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "activeThreadCount", status.getActiveThreadCount(), allowNullValues);
        addField(builder, "bytesReceived", status.getBytesReceived(), allowNullValues);
        addField(builder, "bytesSent", status.getBytesSent(), allowNullValues);
        addField(builder, "flowFilesReceived", status.getFlowFilesReceived(), allowNullValues);
        addField(builder, "flowFilesSent", status.getFlowFilesSent(), allowNullValues);
        addField(builder, "inputBytes", status.getInputBytes(), allowNullValues);
        addField(builder, "inputCount", status.getInputCount(), allowNullValues);
        addField(builder, "outputBytes", status.getOutputBytes(), allowNullValues);
        addField(builder, "outputCount", status.getOutputCount(), allowNullValues);
        addField(builder, "runStatus", status.getRunStatus() == null ? null : status.getRunStatus().name(), allowNullValues);
        addField(builder, "transmitting", status.isTransmitting(), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
Example #6
Source File: DefaultServices.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
public static Object lookup(final String type) {
    if (type.equals(JsonBuilderFactory.class.getName())) {
        return ComponentManager.instance().getJsonpBuilderFactory();
    }
    if (type.equals(JsonReaderFactory.class.getName())) {
        return ComponentManager.instance().getJsonpReaderFactory();
    }
    if (type.equals(JsonGeneratorFactory.class.getName())) {
        return ComponentManager.instance().getJsonpGeneratorFactory();
    }
    if (type.equals(JsonParserFactory.class.getName())) {
        return ComponentManager.instance().getJsonpParserFactory();
    }
    if (type.equals(JsonWriterFactory.class.getName())) {
        return ComponentManager.instance().getJsonpWriterFactory();
    }
    if (type.equals(RecordBuilderFactory.class.getName())) {
        final Function<String, RecordBuilderFactory> provider =
                ComponentManager.instance().getRecordBuilderFactoryProvider();
        return provider.apply(null);
    }
    throw new IllegalArgumentException(type + " can't be a global service, didn't you pass a null plugin?");
}
 
Example #7
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void notRowStructIntRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter, final Jsonb jsonb)
        throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withInt("myInt", 2).build();
    // run the round trip
    final IntWrapper wrapper = IntWrapper.class
            .cast(converter
                    .toType(new RecordConverters.MappingMetaRegistry(), record, IntWrapper.class,
                            () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory));
    assertEquals(2, wrapper.myInt);
    final Record toRecord = converter
            .toRecord(new RecordConverters.MappingMetaRegistry(), wrapper, () -> jsonb, () -> recordBuilderFactory);
    assertEquals(Schema.Type.INT, toRecord.getSchema().getEntries().iterator().next().getType());
    assertEquals(2, toRecord.getInt("myInt"));
}
 
Example #8
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, Long> values, final Boolean allowNullValues) {

        if (values != null) {

            final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
            for (final Map.Entry<String, Long> entry : values.entrySet()) {

                if (entry.getKey() == null ) {
                    continue;
                }else if(entry.getValue() == null ){
                    if(allowNullValues)
                        mapBuilder.add(entry.getKey(),JsonValue.NULL);
                }else{
                    mapBuilder.add(entry.getKey(), entry.getValue());
                }
            }

            builder.add(key, mapBuilder);

        }else if(allowNullValues){
            builder.add(key,JsonValue.NULL);
        }
    }
 
Example #9
Source File: SiteToSiteProvenanceReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, String> values, Boolean allowNullValues) {
    if (values != null) {

        final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
        for (final Map.Entry<String, String> entry : values.entrySet()) {

            if (entry.getKey() == null ) {
                continue;
            }else if(entry.getValue() == null ){
                if(allowNullValues) {
                    mapBuilder.add(entry.getKey(), JsonValue.NULL);
                }
            }else {
                mapBuilder.add(entry.getKey(), entry.getValue());
            }
        }

        builder.add(key, mapBuilder);

    }else if(allowNullValues){
        builder.add(key,JsonValue.NULL);
    }
}
 
Example #10
Source File: NotificationRetryBean.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
@Retry(maxRetries = 2)
@Fallback(NotificationFallbackHandler.class)
public OccasionResponse makeNotificationConnection(
    String message,
    Orchestrator orchestrator,
    String jwtTokenString,
    String notification11ServiceUrl,
    String twitterHandle,
    String notificationServiceUrl)
    throws IOException {

  JsonBuilderFactory factory = Json.createBuilderFactory(null);
  JsonObjectBuilder builder = factory.createObjectBuilder();
  JsonObject notificationRequestPayload = builder.add(JSON_KEY_NOTIFICATION, message).build();
  Response notificationResponse =
      orchestrator.makeConnection(
          "POST", notificationServiceUrl, notificationRequestPayload.toString(), jwtTokenString);
  OccasionResponse occasionResponse =
      new OccasionResponse(notificationResponse, OccasionResponse.NOTIFICATION_TYPE_LOG, null);

  return occasionResponse;
}
 
Example #11
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void booleanRoundTripPojo(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withBoolean("value", true).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final BoolStruct struct = BoolStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, BoolStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), struct, () -> jsonb,
                        () -> recordBuilderFactory);
        assertEquals(Schema.Type.BOOLEAN, toRecord.getSchema().getEntries().iterator().next().getType());
        assertTrue(toRecord.getBoolean("value"));
    }
}
 
Example #12
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void intRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withInt("value", 2).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final IntStruct struct = IntStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, IntStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), struct, () -> jsonb,
                        () -> recordBuilderFactory);
        assertEquals(Schema.Type.INT, toRecord.getSchema().getEntries().iterator().next().getType());
        assertEquals(2, toRecord.getInt("value"));
    }
}
 
Example #13
Source File: JsonToIndexedRecordTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    final JsonBuilderFactory factory = ComponentManager.instance().getJsonpBuilderFactory();
    PAssert
            .that(pipeline
                    .apply(Create
                            .of(factory
                                    .createObjectBuilder()
                                    .add("name", "first")
                                    .add("foo", factory.createObjectBuilder().add("age", 30))
                                    .build(),
                                    factory
                                            .createObjectBuilder()
                                            .add("name", "second")
                                            .add("foo", factory.createObjectBuilder().add("age", 20).build())
                                            .build())
                            .withCoder(JsonpJsonObjectCoder.of(null)))
                    .apply(new JsonToIndexedRecord(createSchema())))
            .satisfies(values -> {
                final List<IndexedRecord> records =
                        StreamSupport.stream(values.spliterator(), false).collect(toList());
                assertEquals(2, records.size());
                return null;
            });
    assertEquals(PipelineResult.State.DONE, pipeline.run().waitUntilFinish());
}
 
Example #14
Source File: AvroRecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void avroRecordArrays() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final RecordBuilderFactory factory = new AvroRecordBuilderFactoryProvider().apply("test");
        final RecordConverters converters = new RecordConverters();
        final JsonBuilderFactory builderFactory = Json.createBuilderFactory(emptyMap());
        final Record record =
                converters
                        .toRecord(new RecordConverters.MappingMetaRegistry(),
                                builderFactory
                                        .createObjectBuilder()
                                        .add("value", builderFactory
                                                .createObjectBuilder()
                                                .add("somekey", builderFactory.createArrayBuilder().build()))
                                        .build(),
                                () -> jsonb, () -> factory);
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record, buffer);
        assertTrue(SchemaRegistryCoder
                .of()
                .decode(new ByteArrayInputStream(buffer.toByteArray()))
                .getRecord("value")
                .getArray(Object.class, "somekey")
                .isEmpty());
    }
}
 
Example #15
Source File: SiteToSiteProvenanceReportingTask.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, String> values) {
    if (values == null) {
        return;
    }

    final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
    for (final Map.Entry<String, String> entry : values.entrySet()) {
        if (entry.getKey() == null || entry.getValue() == null) {
            continue;
        }

        mapBuilder.add(entry.getKey(), entry.getValue());
    }

    builder.add(key, mapBuilder);
}
 
Example #16
Source File: JsonSchemaModulesGenerator.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void generate(JsonStructureWriter<T, C> writer) {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider.createBuilderFactory(null);
	for (final Module<T, C> module : this.modules.getModules()) {
		if (!module.isEmpty()) {
			for (JsonSchema jsonSchema : module.getJsonSchemas()) {
				final JsonSchemaModuleCompiler<T, C> moduleCompiler = new JsonSchemaModuleCompiler<T, C>(
						builderFactory, modules, module, jsonSchema);
				final JsonSchemaBuilder moduleSchema = moduleCompiler.compile();
				final JsonObject moduleSchemaJsonObject = moduleSchema.build(builderFactory);
				writer.writeJsonStructure(module, moduleSchemaJsonObject, jsonSchema.getFileName());
			}
		}
	}
}
 
Example #17
Source File: SchemalessJsonToIndexedRecordTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    final JsonBuilderFactory factory = ComponentManager.instance().getJsonpBuilderFactory();
    for (int i = 0; i < 2; i++) { // tested if done twice - generated name issue check
        PAssert
                .that(pipeline
                        .apply("JSON Source", Create
                                .of(factory
                                        .createObjectBuilder()
                                        .add("name", "first")
                                        .add("foo", factory.createObjectBuilder().add("age", 30))
                                        .build(),
                                        factory
                                                .createObjectBuilder()
                                                .add("name", "second")
                                                .add("foo", factory.createObjectBuilder().add("age", 20).build())
                                                .build())
                                .withCoder(JsonpJsonObjectCoder.of(null)))
                        .apply(new SchemalessJsonToIndexedRecord("Root"))
                        .setCoder(AvroCoder.of(IndexedRecord.class, createSchema())))
                .satisfies(values -> {
                    final List<IndexedRecord> records =
                            StreamSupport.stream(values.spliterator(), false).collect(toList());
                    assertEquals(2, records.size());
                    records.forEach(it -> assertTrue(it.toString().startsWith("{\"name\":")));
                    records.forEach(it -> assertTrue(it.toString().contains("\"foo\": {\"age\":")));
                    return null;
                });
        assertEquals(PipelineResult.State.DONE, pipeline.run().waitUntilFinish());
    }
}
 
Example #18
Source File: JsonSchemaMappingCompiler.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public JsonSchemaMappingCompiler(JsonBuilderFactory jsonBuilderFactory, Modules<T, C> modules, Module<T, C> module,
		Mapping<T, C> mapping) {
	Validate.notNull(jsonBuilderFactory);
	Validate.notNull(modules);
	Validate.notNull(module);
	Validate.notNull(mapping);
	this.jsonBuilderFactory = jsonBuilderFactory;
	this.modules = modules;
	this.module = module;
	this.mapping = mapping;
}
 
Example #19
Source File: AzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static JsonArrayBuilder createJsonArray(JsonBuilderFactory factory, final Collection<String> values) {
        final JsonArrayBuilder builder = factory.createArrayBuilder();
        for (final String value : values) {
                if (value != null) {
                        builder.add(value);
                }
        }
        return builder;
}
 
Example #20
Source File: ProcessorImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private JsonBuilderFactory jsonBuilderFactory() {
    if (jsonBuilderFactory == null) {
        synchronized (this) {
            if (jsonBuilderFactory == null) {
                jsonBuilderFactory =
                        ContainerFinder.Instance.get().find(plugin()).findService(JsonBuilderFactory.class);
            }
            if (jsonBuilderFactory == null) {
                jsonBuilderFactory = Json.createBuilderFactory(emptyMap());
            }
        }
    }
    return jsonBuilderFactory;
}
 
Example #21
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void bytesRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final byte[] bytes = new byte[] { 1, 2, 3 };
    final Record record = recordBuilderFactory.newRecordBuilder().withBytes("value", bytes).build();
    try (final Jsonb jsonb =
            JsonbBuilder.create(new JsonbConfig().withBinaryDataStrategy(BinaryDataStrategy.BASE_64))) {
        final JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertEquals(Base64.getEncoder().encodeToString(bytes), json.getString("value"));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertArrayEquals(bytes, toRecord.getBytes("value"));

        // now studio generator kind of convertion
        final BytesStruct struct = jsonb.fromJson(json.toString(), BytesStruct.class);
        assertArrayEquals(bytes, struct.value);
        final String jsonFromStruct = jsonb.toJson(struct);
        assertEquals("{\"value\":\"AQID\"}", jsonFromStruct);
        final Record structToRecordFromJson = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertArrayEquals(bytes, structToRecordFromJson.getBytes("value"));
    }
}
 
Example #22
Source File: TestAzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddField2() throws IOException, InterruptedException, InitializationException {

    final Map<String, Object> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    Map<String, String> values = new HashMap<String, String>();
    values.put("TestKeyString1", "StringValue1");
    values.put("TestKeyString2", "StringValue2");
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, factory, "TestKeyString", values, true);
    javax.json.JsonObject actualJson = builder.build();
    String expectedjsonString = "{\"TestKeyString\":{\"TestKeyString2\":\"StringValue2\",\"TestKeyString1\":\"StringValue1\"}}";
    JsonObject expectedJson = new Gson().fromJson(expectedjsonString, JsonObject.class);
    assertEquals(expectedJson.toString(), actualJson.toString());
}
 
Example #23
Source File: AzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key,
                final Collection<String> values, Boolean allowNullValues) {
        if (values != null) {
                builder.add(key, createJsonArray(factory, values));
        } else if (allowNullValues) {
                builder.add(key, JsonValue.NULL);
        }
}
 
Example #24
Source File: RecordConverters.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private JsonArray toArray(final JsonBuilderFactory factory, final Function<Object, JsonValue> valueFactory,
        final Collection<?> collection) {
    final Collector<JsonValue, JsonArrayBuilder, JsonArray> collector = Collector
            .of(factory::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::addAll,
                    JsonArrayBuilder::build);
    return collection.stream().map(valueFactory).collect(collector);
}
 
Example #25
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void studioTypes(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final SimpleRowStruct record = new SimpleRowStruct();
    record.character = 'a';
    record.character2 = 'a';
    record.notLong = 100;
    record.notLong2 = 100;
    record.binary = 100;
    record.binary2 = 100;
    record.bd = BigDecimal.TEN;
    record.today = new Date(0);
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL))) {
        final Record recordModel = Record.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, Record.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertEquals(
                "{\"bd\":10.0,\"binary\":100.0,\"binary2\":100.0," + "\"character\":\"a\",\"character2\":\"a\","
                        + "\"notLong\":100.0,\"notLong2\":100.0," + "\"today\":\"1970-01-01T00:00:00Z[UTC]\"}",
                recordModel.toString());
        final SimpleRowStruct deserialized = SimpleRowStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), recordModel, SimpleRowStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        if (record.bd.doubleValue() == deserialized.bd.doubleValue()) { // equals fails on this one
            deserialized.bd = record.bd;
        }
        assertEquals(record, deserialized);
    }
}
 
Example #26
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void serializeConnectionStatus(final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory, final ConnectionStatus status, final DateFormat df,
        final String hostname, final String applicationName, final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentType = "Connection";
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate,
                componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "sourceId", status.getSourceId(), allowNullValues);
        addField(builder, "sourceName", status.getSourceName(), allowNullValues);
        addField(builder, "destinationId", status.getDestinationId(), allowNullValues);
        addField(builder, "destinationName", status.getDestinationName(), allowNullValues);
        addField(builder, "maxQueuedBytes", status.getMaxQueuedBytes(), allowNullValues);
        addField(builder, "maxQueuedCount", status.getMaxQueuedCount(), allowNullValues);
        addField(builder, "queuedBytes", status.getQueuedBytes(), allowNullValues);
        addField(builder, "queuedCount", status.getQueuedCount(), allowNullValues);
        addField(builder, "inputBytes", status.getInputBytes(), allowNullValues);
        addField(builder, "inputCount", status.getInputCount(), allowNullValues);
        addField(builder, "outputBytes", status.getOutputBytes(), allowNullValues);
        addField(builder, "outputCount", status.getOutputCount(), allowNullValues);
        addField(builder, "backPressureBytesThreshold", status.getBackPressureBytesThreshold(), allowNullValues);
        addField(builder, "backPressureObjectThreshold", status.getBackPressureObjectThreshold(), allowNullValues);
        addField(builder, "backPressureDataSizeThreshold", status.getBackPressureDataSizeThreshold(), allowNullValues);
        addField(builder, "isBackPressureEnabled", Boolean.toString((status.getBackPressureObjectThreshold() > 0 && status.getBackPressureObjectThreshold() <= status.getQueuedCount())
                || (status.getBackPressureBytesThreshold() > 0 && status.getBackPressureBytesThreshold() <= status.getMaxQueuedBytes())), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
Example #27
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void pojo2Record(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter, final Jsonb jsonb)
        throws Exception {
    final Wrapper record = new Wrapper();
    record.value = "hey";
    final Record json = Record.class
            .cast(converter
                    .toType(new RecordConverters.MappingMetaRegistry(), record, Record.class,
                            () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb, () -> recordBuilderFactory));
    assertEquals("hey", json.getString("value"));
}
 
Example #28
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void nullSupport(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withString("value", null).build();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertNull(json.getJsonString("value"));
    }
}
 
Example #29
Source File: JsonBuilderUtilsTest.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void addsProperty() {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider
			.createBuilderFactory(null);
	final JsonObjectBuilder builder = builderFactory.createObjectBuilder();
	JsonBuilderUtils.add(builderFactory, builder, "null", null);
	JsonBuilderUtils.add(builderFactory, builder, "true", true);
	JsonBuilderUtils.add(builderFactory, builder, "string", "string");
	JsonBuilderUtils.add(builderFactory, builder, "char", 'c');
	JsonBuilderUtils.add(builderFactory, builder, "bigInteger",
			BigInteger.TEN);
	JsonBuilderUtils.add(builderFactory, builder, "bigDecimal",
			BigDecimal.valueOf(1111, 2));
	JsonBuilderUtils.add(builderFactory, builder, "float", 22f);
	JsonBuilderUtils.add(builderFactory, builder, "double", 22d);
	JsonBuilderUtils.add(builderFactory, builder, "byte", (byte) 33);
	JsonBuilderUtils.add(builderFactory, builder, "int", (int) 44);
	JsonBuilderUtils.add(builderFactory, builder, "short", (int) 55);
	JsonBuilderUtils.add(builderFactory, builder, "list",
			Arrays.<Object> asList("a", 0xbc, "d"));
	JsonBuilderUtils.add(builderFactory, builder, "array", new Object[] {
			1, "2", 3, false });

	JsonBuilderUtils.add(builderFactory, builder, "map",
			Collections.singletonMap("foo", "bar"));
	// provider.createWriter(System.out).write(builder.build());
}
 
Example #30
Source File: SchemaRegistryCoderTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void changingSchema() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final RecordBuilderFactory factory = new AvroRecordBuilderFactoryProvider().apply("test");
        final RecordConverters converters = new RecordConverters();
        final JsonBuilderFactory builderFactory = Json.createBuilderFactory(emptyMap());
        final Record record1 = converters
                .toRecord(new RecordConverters.MappingMetaRegistry(),
                        builderFactory.createObjectBuilder().add("value", "firstSchemaUsesAString").build(),
                        () -> jsonb, () -> factory);
        // go through the encoder with a schema which will change
        final ByteArrayOutputStream buffer1 = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record1, buffer1);

        final Record decoded1 = SchemaRegistryCoder.of().decode(new ByteArrayInputStream(buffer1.toByteArray()));
        assertEquals("firstSchemaUsesAString", decoded1.getString("value"));

        final Record record2 = converters
                .toRecord(new RecordConverters.MappingMetaRegistry(),
                        builderFactory
                                .createObjectBuilder()
                                .add("value",
                                        Json
                                                .createArrayBuilder()
                                                .add(Json.createValue("a"))
                                                .add(Json.createValue("b"))
                                                .build())
                                .build(),
                        () -> jsonb, () -> factory);
        final ByteArrayOutputStream buffer2 = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record2, buffer2);

        final Record decoded2 = SchemaRegistryCoder.of().decode(new ByteArrayInputStream(buffer2.toByteArray()));
        assertEquals(asList("a", "b"), decoded2.getArray(String.class, "value"));
    }
}