javax.json.bind.Jsonb Java Examples

The following examples show how to use javax.json.bind.Jsonb. 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: JmsMessageReader.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Override
public void onMessage(Message message) {

    TextMessage textMessage = (TextMessage) message;

    try {
        String incomingText = textMessage.getText();
        System.out.println("-- a new message arrived: " + incomingText);

        Jsonb jsonb = JsonbBuilder.create();

        CustomMessage parsedMessage = jsonb.fromJson(incomingText, CustomMessage.class);
        entityManager.persist(parsedMessage);

    } catch (JMSException e) {
        System.err.println(e.getMessage());
    }
}
 
Example #2
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void convertListString(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.createValue("a"))
                                                .add(Json.createValue("b"))
                                                .build())
                                .build(),
                        () -> jsonb, () -> new RecordBuilderFactoryImpl("test"));
        final Collection<String> list = record.getArray(String.class, "list");
        assertEquals(asList("a", "b"), list);
    }
}
 
Example #3
Source File: ComponentManager.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void onClose(final Container container) {
    // ensure we don't keep any data/ref after the classloader of the container is
    // released
    ofNullable(container.get(ContainerComponentRegistry.class)).ifPresent(r -> {
        final ContainerComponentRegistry registry = container.remove(ContainerComponentRegistry.class);
        registry.getComponents().clear();
        registry
                .getServices()
                .stream()
                .filter(i -> !Proxy.isProxyClass(i.getInstance().getClass()))
                .forEach(s -> doInvoke(container.getId(), s.getInstance(), PreDestroy.class));
        registry.getServices().clear();
    });
    ofNullable(container.get(AllServices.class))
            .map(s -> s.getServices().get(Jsonb.class))
            .map(Jsonb.class::cast)
            .ifPresent(jsonb -> {
                try {
                    jsonb.close();
                } catch (final Exception e) {
                    log.warn(e.getMessage(), e);
                }
            });
}
 
Example #4
Source File: EventSerializer.java    From scalable-coffee-shop with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] serialize(final String topic, final CoffeeEvent event) {
    try {
        if (event == null)
            return null;

        final JsonbConfig config = new JsonbConfig()
                .withAdapters(new UUIDAdapter())
                .withSerializers(new EventJsonbSerializer());

        final Jsonb jsonb = JsonbBuilder.create(config);

        return jsonb.toJson(event, CoffeeEvent.class).getBytes(StandardCharsets.UTF_8);
    } catch (Exception e) {
        logger.severe("Could not serialize event: " + e.getMessage());
        throw new SerializationException("Could not serialize event", e);
    }
}
 
Example #5
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 #6
Source File: JsonSchemaConverterTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void enumValues() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create();
            final InputStream stream =
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("config.json")) {
        final ConfigTypeNodes nodes = jsonb.fromJson(stream, ConfigTypeNodes.class);
        final Ui payload = new UiSpecService<>(null, jsonb)
                .convert("test", "en", nodes.getNodes().get("U2VydmljZU5vdyNkYXRhc2V0I3RhYmxl"), null)
                .toCompletableFuture()
                .get();
        final JsonSchema jsonSchema = payload.getJsonSchema();
        final JsonSchema schema = jsonSchema
                .getProperties()
                .get("tableDataSet")
                .getProperties()
                .get("commonConfig")
                .getProperties()
                .get("tableName");
        assertEquals(5, schema.getEnumValues().size());
    }
}
 
Example #7
Source File: MyJsonBContextResolver.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Override
public Jsonb getContext(Class<?> type) {
    JsonbConfig config = new JsonbConfig().
            withPropertyVisibilityStrategy(new PropertyVisibilityStrategy(){

                @Override
                public boolean isVisible(Field f) {
                    return true;
                }

                @Override
                public boolean isVisible(Method m) {
                    return false;
                }
            });
    return JsonbBuilder.newBuilder().
            withConfig(config).
            build();
}
 
Example #8
Source File: PluralRecordExtension.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Jsonb createPojoJsonb() {
    final JsonbBuilder jsonbBuilder = JsonbBuilder.newBuilder().withProvider(new JsonProviderImpl() {

        @Override
        public JsonGeneratorFactory createGeneratorFactory(final Map<String, ?> config) {
            return new RecordJsonGenerator.Factory(() -> new RecordBuilderFactoryImpl("test"),
                    () -> getJsonb(createPojoJsonb()), config);
        }
    });
    try { // to passthrough the writer, otherwise RecoderJsonGenerator is broken
        final Field mapper = jsonbBuilder.getClass().getDeclaredField("builder");
        if (!mapper.isAccessible()) {
            mapper.setAccessible(true);
        }
        MapperBuilder.class.cast(mapper.get(jsonbBuilder)).setDoCloseOnStreams(true);
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
    return jsonbBuilder.build();
}
 
Example #9
Source File: Generator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private static void generatedUi(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_ui.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        stream.println();
        final File api = jarLocation(Ui.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        final ParameterExtensionEnricher enricher = new UiParameterEnricher();
        try (final Jsonb jsonb = newJsonb()) {
            finder
                    .findAnnotatedClasses(Ui.class)
                    .stream()
                    .sorted(Comparator.comparing(Class::getName))
                    .forEach(type -> renderUiDoc(stream, enricher, jsonb, type));
        }
        stream.println();

    }
}
 
Example #10
Source File: PropertiesConverterTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void datalistDefault() throws Exception {
    final Map<String, Object> values = new HashMap<>();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        new PropertiesConverter(jsonb, values, emptyList())
                .convert(completedFuture(new PropertyContext<>(new SimplePropertyDefinition("configuration.foo.bar",
                        "bar", "Bar", "STRING", "def", new PropertyValidation(),
                        singletonMap("action::suggestionS", "yes"), null, new LinkedHashMap<>()), null,
                        new PropertyContext.Configuration())))
                .toCompletableFuture()
                .get();
    }
    assertEquals(2, values.size());
    assertEquals("def", values.get("bar"));
    assertEquals("def", values.get("$bar_name"));
}
 
Example #11
Source File: JaxrsJsonbTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void testJaxrsJsonb() throws Exception {
    Dog dog = new Dog();
    dog.name = "Falco";
    dog.age = 4;
    dog.bitable = false;

    Jsonb jsonb = JsonbBuilder.create();
    
    String response = client.target("http://localhost:8080/jsonb")
                          .request(MediaType.APPLICATION_JSON)
                          .post(Entity.entity(jsonb.toJson(dog), MediaType.APPLICATION_JSON),
                          String.class);
    Dog dog2 = jsonb.fromJson(response, Dog.class);
    Assert.assertEquals(dog.name, dog2.name);
    Assert.assertEquals(dog.age, dog2.age);
    Assert.assertTrue(dog2.bitable);
}
 
Example #12
Source File: RecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void booleanRoundTrip(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 JsonObject json = JsonObject.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, JsonObject.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        assertTrue(json.getBoolean("value"));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertTrue(toRecord.getBoolean("value"));
    }
}
 
Example #13
Source File: JsonbUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() {
    JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE);
    Jsonb jsonb = JsonbBuilder.create(config);
    Person person = new Person(1, "Jhon", "[email protected]", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
    String jsonPerson = jsonb.toJson(person);
    // @formatter:off
    String jsonExpected = 
        "{\"salary\":\"1000.0\","+
         "\"registeredDate\":\"07-09-2019\"," +
         "\"person-name\":\"Jhon\"," +
         "\"id\":1," +
         "\"email\":\"[email protected]\"}";
    // @formatter:on
    assertTrue(jsonExpected.equals(jsonPerson));
}
 
Example #14
Source File: BaseBotSampler.java    From BotServiceStressToolkit with MIT License 6 votes vote down vote up
protected String getAttachmentsResponseAsJsonString(List<Message> responses) {
	String attachmentsJsonAsString = "";

	Jsonb jsonb = JsonbBuilder.create();

	int i = 1;
	for (Message message : responses) {
		if (message.getAttachments() != null && message.getAttachments().size() > 0) {
			for (Attachment attachment : message.getAttachments()) {
				String attachmentPayload = jsonb.toJson(attachment);
				attachmentsJsonAsString += String.format(ATTACHMENT_NUMBER, i++) + attachmentPayload + NEW_LINE;
			}
		}
	}

	if (attachmentsJsonAsString.length() == 0) {
		attachmentsJsonAsString = null;
		return null;
	}

	return StringUtils.trimToEmpty(attachmentsJsonAsString + NEW_LINE);
}
 
Example #15
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 #16
Source File: JsonSchemaConverterTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void ensurePrimitiveSerialization() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonSchema schema = new JsonSchema();

        schema.setDefaultValue(5);
        assertEquals("{\"default\":5}", jsonb.toJson(schema));

        schema.setDefaultValue("yes");
        assertEquals("{\"default\":\"yes\"}", jsonb.toJson(schema));

        schema.setDefaultValue(asList("a", "b"));
        assertEquals("{\"default\":[\"a\",\"b\"]}", jsonb.toJson(schema));

        final Model model = new Model();
        model.id = "1";
        schema.setDefaultValue(model);
        assertEquals("{\"default\":{\"id\":\"1\"}}", jsonb.toJson(schema));

        schema.setDefaultValue(singletonList(model));
        assertEquals("{\"default\":[{\"id\":\"1\"}]}", jsonb.toJson(schema));
    }
}
 
Example #17
Source File: UiSchemaConverterTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void listOfObject() throws Exception {
    final List<SimplePropertyDefinition> properties = asList(
            new SimplePropertyDefinition("configuration", "configuration", "configuration", "OBJECT", null, NVAL,
                    emptyMap(), null, NPROPS),
            new SimplePropertyDefinition("configuration.list", "list", "list", "ARRAY", null, NVAL, emptyMap(),
                    null, NPROPS),
            new SimplePropertyDefinition("configuration.list[].name", "name", "name", "STRING", null, NVAL,
                    emptyMap(), null, NPROPS));
    final PropertyContext<Object> propertyContext =
            new PropertyContext<>(properties.iterator().next(), null, new PropertyContext.Configuration(false));
    final List<UiSchema> schemas = new ArrayList<>();
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonSchema jsonSchema = new JsonSchema();
        new JsonSchemaConverter(jsonb, jsonSchema, properties)
                .convert(completedFuture(propertyContext))
                .toCompletableFuture()
                .get();
        new UiSchemaConverter(null, "test", schemas, properties, null, jsonSchema, properties, emptyList(), "en",
                emptyList(), new AtomicInteger(1))
                        .convert(completedFuture(propertyContext))
                        .toCompletableFuture()
                        .get();
    }
    assertEquals(1, schemas.size());
    final UiSchema configuration = schemas.iterator().next();
    assertNull(configuration.getKey());
    assertEquals(1, configuration.getItems().size());
    final UiSchema list = configuration.getItems().iterator().next();
    assertEquals("configuration.list", list.getKey());
    assertEquals("collapsibleFieldset", list.getItemWidget());
    assertEquals(1, list.getItems().size());
    final UiSchema name = list.getItems().iterator().next();
    assertEquals("configuration.list[].name", name.getKey());
    assertEquals("text", name.getWidget());
}
 
Example #18
Source File: JobImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private Supplier<Jsonb> jsonb() {
    return () -> {
        if (jsonb == null) {
            synchronized (this) {
                if (jsonb == null) {
                    jsonb = JsonbBuilder.create(new JsonbConfig().setProperty("johnzon.cdi.activated", false));
                }
            }
        }
        return jsonb;
    };
}
 
Example #19
Source File: BookDeserializerTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenJSON_shouldDeserializeToBook() {
    Book expectedBook = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom");
    String json = "{\"com.readlearncode.devWorks.overview.domain.Book\":{\"author\":\"Alex Theedom\",\"id\":\"SHDUJ-4532\",\"title\":\"Fun with Java\"}}";
    JsonbConfig config = new JsonbConfig().withDeserializers(new BookDeserializer());
    Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build();
    Book actualBook = jsonb.fromJson(json, Book.class);

    assertThat(actualBook).isEqualTo(expectedBook);
}
 
Example #20
Source File: BookDeserializerTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenJSON_shouldDeserializeToBook() {
    String json = "{\"id\":\"QWE-123-RTS\",\"lastName\":\"Theedom\",\"firstName\":\"Alex\",\"title\":\"Fun with Java\"}";
    JsonbConfig config = new JsonbConfig().withDeserializers(new BookDeserializer());
    Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build();
    String id = jsonb.fromJson(json, String.class);
    assertThat(id).isEqualTo("QWE-123-RTS");
}
 
Example #21
Source File: RecordJsonGeneratorTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void objectOfObject(final Jsonb jsonb) {
    final RecordBuilderFactoryImpl factory = new RecordBuilderFactoryImpl("test");
    final OutputRecordHolder out = new OutputRecordHolder();
    final RecordJsonGenerator generator = new RecordJsonGenerator(factory, jsonb, out);
    generator.writeStartObject();
    generator.writeStartObject("a");
    generator.write("b", "1");
    generator.writeEnd();
    generator.writeEnd();
    generator.close();

    final Record record = out.getRecord();
    assertEquals("{\"a\":{\"b\":\"1\"}}", record.toString());
}
 
Example #22
Source File: PluralRecordExtension.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
        throws ParameterResolutionException {
    final Class<?> type = parameterContext.getParameter().getType();
    if (type == Jsonb.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(Jsonb.class, k -> getJsonb(createPojoJsonb()));
    }
    if (type == RecordConverters.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(RecordConverters.class, k -> converter);
    }
    if (type == JsonProvider.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(JsonProvider.class, k -> jsonProvider);
    }
    if (type == JsonBuilderFactory.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(JsonBuilderFactory.class, k -> jsonBuilderFactory);
    }
    if (type == RecordBuilderFactory.class) {
        return extensionContext
                .getStore(GLOBAL_NAMESPACE)
                .getOrComputeIfAbsent(RecordBuilderFactory.class, k -> recordBuilderFactory);
    }
    throw new ParameterResolutionException(
            String.format("Parameter for class %s not managed.", type.getCanonicalName()));
}
 
Example #23
Source File: JsonSchemaSerializationTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void toJson() throws Exception {
    final Schema schema = new AvroSchemaBuilder()
            .withType(RECORD)
            .withEntry(new SchemaImpl.EntryImpl("array", "array", Schema.Type.ARRAY, true, null,
                    new AvroSchemaBuilder().withType(STRING).build(), null))
            .build();
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL))) {
        assertEquals(
                "{\"entries\":[{\"elementSchema\":{\"entries\":[],\"type\":\"STRING\"},\"name\":\"array\",\"nullable\":true,\"rawName\":\"array\",\"type\":\"ARRAY\"}],\"type\":\"RECORD\"}",
                jsonb.toJson(schema));
    }
}
 
Example #24
Source File: JsonbUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() {
    JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
    Jsonb jsonb = JsonbBuilder.create(config);
    Person person = new Person(1, "Jhon", "[email protected]", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
    // @formatter:off
    String jsonPerson = 
        "{\"id\":1," +
         "\"name\":\"Jhon\"}";
    // @formatter:on
    assertTrue(jsonb.fromJson(jsonPerson, Person.class)
        .equals(person));
}
 
Example #25
Source File: RequestParser.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public RequestParser(final ReflectionService reflections, final Jsonb jsonb, final Map<Class<?>, Object> services) {
    this.reflections = reflections;
    this.services = services;
    this.jsonpEncoder = new JsonpEncoder(jsonb);
    this.jsonpDecoder = new JsonpDecoder(jsonb);

}
 
Example #26
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 #27
Source File: ModelWithSerializerAndDeserializerOnFieldResourceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializer() throws IOException {
    Jsonb jsonb = JsonbBuilder.create();

    given()
            .contentType("application/json")
            .body(jsonb.toJson(
                    new ModelWithSerializerAndDeserializerOnField("tester",
                            new ModelWithSerializerAndDeserializerOnField.Inner())))
            .when().post("/fieldserder")
            .then()
            .statusCode(200)
            .body(is("tester/immutable"));
}
 
Example #28
Source File: JobImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void emit(final Object value) {
    outputs
            .computeIfAbsent(name, k -> new ArrayList<>())
            .add(new RecordConverters()
                    .toRecord(registry, value, () -> Jsonb.class.cast(services.get(Jsonb.class)),
                            () -> RecordBuilderFactory.class
                                    .cast(services.get(RecordBuilderFactory.class))));
}
 
Example #29
Source File: UiSpecMapperImplTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void createForm() {
    final Supplier<Ui> form =
            new UiSpecMapperImpl(new UiSpecMapperImpl.Configuration(singletonList(new TitleMapProvider() {

                private int it = 0;

                @Override
                public String reference() {
                    return "vendors";
                }

                @Override
                public Collection<UiSchema.NameValue> get() {
                    return asList(new UiSchema.NameValue.Builder().withName("k" + ++it).withValue("v" + it).build(),
                            new UiSchema.NameValue.Builder().withName("k" + ++it).withValue("v" + it).build());
                }
            }))).createFormFor(ComponentModel.class);

    IntStream.of(1, 2).forEach(it -> {
        try (final Jsonb jsonb = JsonbBuilder
                .create(new JsonbConfig()
                        .withFormatting(true)
                        .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL));
                final BufferedReader reader =
                        new BufferedReader(new InputStreamReader(
                                Thread
                                        .currentThread()
                                        .getContextClassLoader()
                                        .getResourceAsStream("component-model-" + it + ".json"),
                                StandardCharsets.UTF_8))) {
            assertEquals(reader.lines().collect(joining("\n")), jsonb.toJson(form.get()));
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
    });
}
 
Example #30
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static void generatedTypes(final File generatedDir) throws Exception {
    final File file = new File(generatedDir, "generated_configuration-types.adoc");
    try (final PrintStream stream = new PrintStream(new WriteIfDifferentStream(file))) {
        final File api = jarLocation(ConfigurationType.class);
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final ConfigurationTypeParameterEnricher enricher = new ConfigurationTypeParameterEnricher();
        final AnnotationFinder finder = new AnnotationFinder(
                api.isDirectory() ? new FileArchive(loader, api) : new JarArchive(loader, api.toURI().toURL()));
        try (final Jsonb jsonb = newJsonb()) {
            finder
                    .findAnnotatedClasses(ConfigurationType.class)
                    .stream()
                    .sorted(comparing(Class::getName))
                    .forEach(type -> {
                        stream.println();
                        stream.println("= " + capitalizeWords(type.getAnnotation(ConfigurationType.class).value()));
                        stream.println();
                        stream.println(extractDoc(type));
                        stream.println();
                        stream.println("- API: @" + type.getName());
                        stream.println("- Sample:");
                        stream.println();
                        stream.println("[source,js]");
                        stream.println("----");
                        stream
                                .println(jsonb
                                        .toJson(new TreeMap<>(enricher
                                                .onParameterAnnotation("value", String.class,
                                                        generateAnnotation(type)))));
                        stream.println("----");
                        stream.println();
                    });
        }
        stream.println();

    }
}