Java Code Examples for javax.json.bind.JsonbBuilder

The following examples show how to use javax.json.bind.JsonbBuilder. These examples are extracted from open source projects. 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 Project: Java-EE-8-Sampler   Source File: MagazineSerializerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenSerialize_shouldSerialiseMagazine() {

    Magazine magazine = new Magazine();
    magazine.setId("1234-QWERT");
    magazine.setTitle("Fun with Java");
    magazine.setAuthor(new Author("Alex","Theedom"));

    String expectedJson = "{\"name\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}}";

    JsonbConfig config = new JsonbConfig().withSerializers(new MagazineSerializer());
    Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build();
    String actualJson = jsonb.toJson(magazine);
    assertThat(actualJson).isEqualTo(expectedJson);

}
 
Example 2
Source Project: camel-quarkus   Source File: JsonComponentsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void jacksonXml() {
    final String xml = "<PojoA>\n  <name>Joe</name>\n</PojoA>\n";
    final String json = JsonbBuilder.create().toJson(new PojoA("Joe"));
    RestAssured.given()
            .contentType(ContentType.JSON)
            .body(json)
            .post("/dataformats-json/jacksonxml/marshal")
            .then()
            .statusCode(200)
            .body(equalTo(xml));

    RestAssured.given()
            .contentType("text/xml")
            .body(xml)
            .post("/dataformats-json/jacksonxml/unmarshal")
            .then()
            .statusCode(200)
            .body(equalTo(json));
}
 
Example 3
Source Project: component-runtime   Source File: DefaultServiceProvider.java    License: Apache License 2.0 6 votes vote down vote up
private JsonbBuilder createPojoJsonbBuilder(final String id, final Supplier<Jsonb> jsonb) {
    final JsonbBuilder jsonbBuilder = JsonbBuilder
            .newBuilder()
            .withProvider(new PreComputedJsonpProvider(id, jsonpProvider, jsonpParserFactory, jsonpWriterFactory,
                    jsonpBuilderFactory,
                    new RecordJsonGenerator.Factory(Lazy.lazy(() -> recordBuilderFactoryProvider.apply(id)), jsonb,
                            emptyMap()),
                    jsonpReaderFactory))
            .withConfig(jsonbConfig);
    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;
}
 
Example 4
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: 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 5
Source Project: tutorials   Source File: JsonbUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() {
    JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
    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 = 
        "{\"email\":\"[email protected]\"," +
         "\"id\":1," +
         "\"person-name\":\"Jhon\"," +
         "\"registered_date\":\"07-09-2019\"," +
         "\"salary\":\"1000.0\"}";
    // @formatter:on
    assertTrue(jsonExpected.equals(jsonPerson));
}
 
Example 6
@GET
   @Path("/v1/appointments/list/{patId}")
   @Produces(MediaType.APPLICATION_JSON)
   public Response appointments(@PathParam("patId") String patId) {
       List<AppointmentList> results = entityManager.createNamedQuery("Appointment.getAppointments", AppointmentList.class)
               .setParameter("pid", patId)
               .getResultList();
       Jsonb jsonb = JsonbBuilder.create();

       
       String appointmentBlob = "{\"ResultSet Output\": " + jsonb.toJson(results)
       + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";

       int returnCode = 0;
       if (results.size() == 0) {
           returnCode=1;
       }
       
       logger.info("Appointment blob: " + appointmentBlob);

       JsonReader jsonReader = Json.createReader(new StringReader(appointmentBlob));
           
       JsonObject jresponse  = jsonReader.readObject();
       jsonReader.close();
	return Response.ok(jresponse).build();
}
 
Example 7
Source Project: component-runtime   Source File: PluralRecordExtension.java    License: 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 8
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void stringRoundTrip(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final Record record = recordBuilderFactory.newRecordBuilder().withString("value", "yes").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));
        assertEquals("yes", json.getString("value"));
        final Record toRecord = converter
                .toRecord(new RecordConverters.MappingMetaRegistry(), json, () -> jsonb,
                        () -> recordBuilderFactory);
        assertEquals("yes", toRecord.getString("value"));
    }
}
 
Example 9
Source Project: thorntail   Source File: JavaxJsonbTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void testJavaxJsonb() throws IOException {
    Dog dog = new Dog();
    dog.name = "Falco";
    dog.age = 4;
    dog.bitable = false;

    Jsonb jsonb = JsonbBuilder.create();
    String json = jsonb.toJson(dog);

    String response = Request.Post("http://localhost:8080/").body(new StringEntity(json))
        .execute().returnContent().asString().trim();
    Dog dog2 = jsonb.fromJson(response, Dog.class);
    assertThat(dog2.name).isEqualTo(dog.name);
    assertThat(dog2.age).isEqualTo(dog.age);
    assertThat(dog2.bitable).isTrue();
}
 
Example 10
Source Project: blog-tutorials   Source File: JmsMessageReader.java    License: 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 11
@Test
@Disabled("we only support one schema per array for now")
void notHomogeneousArray() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final RecordBuilderFactory factory = new AvroRecordBuilderFactoryProvider().apply("test");
        final RecordConverters converters = new RecordConverters();
        final JsonReaderFactory readerFactory = Json.createReaderFactory(emptyMap());
        final Record record = converters
                .toRecord(new RecordConverters.MappingMetaRegistry(), readerFactory
                        .createReader(new StringReader(
                                "{\"custom_attributes\":[" + "{\"attribute_code\":\"color\",\"value\":\"49\"},"
                                        + "{\"attribute_code\":\"category_ids\",\"value\":[]}]}"))
                        .readObject(), () -> jsonb, () -> factory);
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record, buffer);
        final Record decoded = SchemaRegistryCoder.of().decode(new ByteArrayInputStream(buffer.toByteArray()));
        final List<Record> array = new ArrayList<>(decoded.getArray(Record.class, "custom_attributes"));
        assertTrue(array.get(1).getArray(Object.class, "value2").isEmpty());
    }
}
 
Example 12
Source Project: component-runtime   Source File: PropertiesConverterTest.java    License: 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 13
Source Project: javaee8-cookbook   Source File: SysConfigBean.java    License: Apache License 2.0 6 votes vote down vote up
public String getSysConfig() throws SQLException, NamingException, Exception {
    String sql = "SELECT variable, value FROM sys_config";

    try (Connection conn = ConnectionPool.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            Jsonb jsonb = JsonbBuilder.create()) {

        List<SysConfig> list = new ArrayList<>();
        while (rs.next()) {
            list.add(new SysConfig(rs.getString("variable"), rs.getString("value")));
        }

        String json = jsonb.toJson(list);
        return json;
    }
}
 
Example 14
Source Project: component-runtime   Source File: JoinInputFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Object map(final Object next) {
    if (next == null || Record.class.isInstance(next)) { // directly ok
        return next;
    }

    if (String.class.isInstance(next) || next.getClass().isPrimitive()) { // primitives
        return next;
    }

    if (jsonb == null) {
        synchronized (this) {
            if (jsonb == null) {
                jsonb = JsonbBuilder.create(new JsonbConfig().setProperty("johnzon.cdi.activated", false));
                registry = new RecordConverters.MappingMetaRegistry();
            }
        }
    }

    return new RecordConverters()
            .toRecord(registry, next, () -> jsonb,
                    () -> ComponentManager.instance().getRecordBuilderFactoryProvider().apply(null));
}
 
Example 15
Source Project: tutorials   Source File: JsonbUnitTest.java    License: 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 16
@OnMessage
public List<Customer>  addCustomer(String message, Session session) {
    Jsonb jsonb = JsonbBuilder.create();

    Customer customer = jsonb.fromJson(message, Customer.class);
    customerRepository.createCustomer(customer);
    return customerRepository.findAll();
}
 
Example 17
Source Project: Java-EE-8-Sampler   Source File: CustomiseDateFormatTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenDateInJsonDocument_whenDateFormatConfigured_shouldDeserialise() {
    String json = "{\"published\":\"10/10/2018\",\"author\":\"Alex Theedom\",\"title\":\"Fun with JSON-B\"}";
    JsonbConfig jsonbConfig = new JsonbConfig().withDateFormat("MM/dd/yyyy", Locale.ENGLISH);
    Book book = JsonbBuilder.create(jsonbConfig).fromJson(json, Book.class);
    assertThat(book.getPublished()).isEqualTo(LocalDate.of(2018, Month.OCTOBER, 10));
}
 
Example 18
Source Project: camel-quarkus   Source File: JsonDataformatsResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/unmarshal/{direct-id}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String testXmlUnmarshalDefinition(@PathParam("direct-id") String directId, String statement) {
    LOG.infof("Invoking testXmlUnmarshalDefinition(%s, %s)", directId, statement);
    Object object = producerTemplate.requestBody("direct:" + directId, statement);
    String answer = JsonbBuilder.create().toJson(object);

    return answer;
}
 
Example 19
Source Project: Java-EE-8-Sampler   Source File: BasicTypeExampleTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenJsonData_whenDeserialiseFieldAtomicInteger_shouldThrowException() {

    Jsonb jsonb = JsonbBuilder.create();

    assertThatThrownBy(() -> jsonb.fromJson(
            jsonb.toJson(new SimpleBook(new AtomicInteger(10))),
            SimpleBook.class))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("argument type mismatch");

}
 
Example 20
Source Project: camel-quarkus   Source File: XstreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void xstream() {
    final String xml = "<org.apache.camel.quarkus.component.xstream.it.PojoA><name>Joe</name></org.apache.camel.quarkus.component.xstream.it.PojoA>";
    final String json = JsonbBuilder.create().toJson(new PojoA("Joe"));
    // See https://issues.apache.org/jira/browse/CAMEL-14679
    final String xstreamJson = "{\"org.apache.camel.quarkus.component.xstream.it.PojoA\":{\"name\":\"Joe\"}}";

    RestAssured.given()
            .contentType(ContentType.JSON)
            .body(json)
            .post("/xstream/xml/marshal")
            .then()
            .statusCode(200)
            .body(endsWith(xml)); // endsWith because we do not care for the <?xml ...?> preamble

    RestAssured.given()
            .contentType("text/xml")
            .body(xml)
            .post("/xstream/xml/unmarshal")
            .then()
            .statusCode(200)
            .body(equalTo(json));

    RestAssured.given()
            .contentType(ContentType.JSON)
            .body(json)
            .post("/xstream/json/marshal")
            .then()
            .statusCode(200)
            .body(equalTo(xstreamJson));

    RestAssured.given()
            .contentType(ContentType.JSON)
            .body(xstreamJson)
            .post("/xstream/json/unmarshal")
            .then()
            .statusCode(200)
            .body(equalTo(json));
}
 
Example 21
Source Project: Java-EE-8-Sampler   Source File: BasicTypeExampleTest.java    License: MIT License 5 votes vote down vote up
@Test
public void serializeBook() {

    String expectedJson = "{\"count\":4,\"firstname\":\"John\",\"inPrint\":true,\"lastname\":\"Smith\",\"middleInitial\":\"J\",\"pages\":200,\"price\":59.99,\"title\":\"Fun with Java\",\"version\":5}";

    Book book = new Book();
    book.setTitle("Fun with Java");
    book.setFirstname("John");
    book.setMiddleInitial('J');
    book.setLastname("Smith");
    book.setPrice(59.99f);
    book.setInPrint(true);
    book.setPages(200);
    book.setVersion((byte) 5);
    book.setCount(new AtomicInteger(4));

    String actualJson = JsonbBuilder.create().toJson(book);

    assertThat(actualJson).isEqualTo(expectedJson);

    /*
        {
          "count": 4,
          "firstname": "John",
          "inPrint": true,
          "lastname": "Smith",
          "middleInitial": "J",
          "pages": 200,
          "price": 59.99,
          "title": "Fun with Java",
          "version": 5
        }
     */
}
 
Example 22
Source Project: tomee   Source File: JSONBConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
public JSONBConfiguration() {
	// jsonbConfig offers a lot of configurations.
	JsonbConfig config = new JsonbConfig().withFormatting(true)
			.withPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE)
			.withDateFormat("yyyy - MM - dd", Locale.ENGLISH);

	jsonb = JsonbBuilder.create(config);
}
 
Example 23
Source Project: Java-EE-8-Sampler   Source File: BookletAdapterTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenBookObject_shouldUseAdapterToSerialise() {
    String expectedJson = "{\"title\":\"Fun with Java\",\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}";
    Booklet booklet = new Booklet("Fun with Java", "Alex", "Theedom");
    JsonbConfig config = new JsonbConfig().withAdapters(new BookletAdapter());
    String actualJson = JsonbBuilder.create(config).toJson(booklet);

    assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example 24
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void bigDecimalsInArrays(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 BigDecimal pos3 = new BigDecimal(25);
    final List<BigDecimal> expected = asList(pos1, pos2, pos1, pos2, pos2, pos1, pos3);
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonObject json =
                jsonBuilderFactory
                        .createObjectBuilder()
                        .add("coordinates", jsonBuilderFactory
                                .createArrayBuilder()
                                .add(jsonBuilderFactory.createArrayBuilder().add(pos1).add(pos2).build())
                                .add(jsonBuilderFactory.createArrayBuilder().add(pos1).add(pos2).build())
                                .add(jsonBuilderFactory.createArrayBuilder().add(pos2).add(pos1).add(pos3).build())
                                .build())
                        .build();
        final Record record =
                converter.toRecord(new MappingMetaRegistry(), json, () -> jsonb, () -> recordBuilderFactory);
        assertEquals(expected,
                record
                        .getArray(ArrayList.class, "coordinates")
                        .stream()
                        .flatMap(a -> a.stream())
                        .flatMap(bd -> Stream.of(bd))
                        .collect(toList()));
    }
}
 
Example 25
Source Project: component-runtime   Source File: StaticResourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void format(final Collection<Route> routes, final OutputStream outputStream) {
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig()
                    .withFormatting(true)
                    .withBinaryDataStrategy(BinaryDataStrategy.BASE_64)
                    .setProperty("johnzon.cdi.activated", false))) {
        jsonb.toJson(routes, outputStream);
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 26
Source Project: component-runtime   Source File: JsonSchemaConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
private Object convert(final String type, final String value) throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final JsonSchemaConverter instance = new JsonSchemaConverter(jsonb, new JsonSchema(), emptyList());
        final Method convertDefaultValue =
                JsonSchemaConverter.class.getDeclaredMethod("convertDefaultValue", String.class, String.class);
        if (!convertDefaultValue.isAccessible()) {
            convertDefaultValue.setAccessible(true);
        }
        return Optional.class.cast(convertDefaultValue.invoke(instance, type, value)).orElse(null);
    }
}
 
Example 27
@Test
public void givenREVERSEPropertyOrderStrategy_shouldOrderLexicographically(){

    String expectedJson = "{\"title\":\"Fun with JSON binding\",\"authorName\":{\"lastName\":\"Theedom\",\"firstName\":\"Alex\"},\"alternativeTitle\":\"01846537\"}";
    JsonbConfig jsonbConfig = new JsonbConfig()
            .withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE);

    String actualJson = JsonbBuilder.create(jsonbConfig).toJson(magazine);

    assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example 28
Source Project: Java-EE-8-Sampler   Source File: CustomiseAdapter.java    License: MIT License 5 votes vote down vote up
@Test
public void givenAdaptor_shouldPopulateAuthor() {
    String json = "{\"title\":\"Fun with JSON-B\",\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}";
    JsonbConfig jsonbConfig = new JsonbConfig().withAdapters(new BookletAdapter());
    Booklet booklet = JsonbBuilder.create(jsonbConfig).fromJson(json, Booklet.class);
    assertThat(booklet.getTitle()).isEqualTo("Fun with JSON-B");
    assertThat(booklet.getAuthor().getFirstName()).isEqualTo("Alex");
    assertThat(booklet.getAuthor().getLastName()).isEqualTo("Theedom");
}
 
Example 29
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void studioTypes2(final JsonBuilderFactory jsonBuilderFactory, final JsonProvider jsonProvider,
        final RecordBuilderFactory recordBuilderFactory, final RecordConverters converter) throws Exception {
    final RowStruct rowStruct = new RowStruct();
    rowStruct.col1int = 10;
    rowStruct.col2string = "stringy";
    rowStruct.col3char = 'a';
    rowStruct.col4bool = Boolean.TRUE;
    rowStruct.col5byte = 100;
    rowStruct.col6short = Short.MAX_VALUE;
    rowStruct.col7long = 1971L;
    rowStruct.col8float = 19.71f;
    rowStruct.col9double = 19.234;
    rowStruct.col10bigdec = java.math.BigDecimal.TEN;
    rowStruct.col11date = new java.util.Date();
    try (final Jsonb jsonb = JsonbBuilder
            .create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL))) {
        final Record record = Record.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), rowStruct, Record.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        final RowStruct deserialized = RowStruct.class
                .cast(converter
                        .toType(new RecordConverters.MappingMetaRegistry(), record, RowStruct.class,
                                () -> jsonBuilderFactory, () -> jsonProvider, () -> jsonb,
                                () -> recordBuilderFactory));
        if (rowStruct.col10bigdec.doubleValue() == deserialized.col10bigdec.doubleValue()) {
            deserialized.col10bigdec = rowStruct.col10bigdec;
        }
        if (rowStruct.col11date.equals(deserialized.col11date)) {
            deserialized.col11date = rowStruct.col11date;
        }
        assertEquals(rowStruct, deserialized);
    }
}
 
Example 30
Source Project: BotServiceStressToolkit   Source File: MockChannelCallback.java    License: MIT License 5 votes vote down vote up
@POST
@Path("/conversations/{conversationId}/activities/{activityId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response replyToActivity(@PathParam("conversationId") String conversationId,
		@PathParam("activityId") String activityId, InputStream is) {
	log.info(String.format("replyToActivity(conversationId=%s, activityId=%s)", conversationId, activityId));
	String payload;
	try {
		payload = IOUtils.toString(is, Charset.forName("UTF-8"));
		Jsonb jsonb = JsonbBuilder.create();
		Activity activity = jsonb.fromJson(payload, Activity.class);

		if (activity.getType() == "typing") {
			log.info(String.format(
					"Typing response received, ignoging for replyToActivity(conversationId=%s, activityId=%s) [Activity(replyToId=%s)]",
					conversationId, activityId, activity.getReplyToId()));
		} else {
			activity = ActivityParserFactory.parse(activity.getType(), payload, conversationId, activityId);
			activity.setReplyToId(activityId);

			ActivityRequestReply.getInstance().setResponse(activityId, activity);
			log.info(String.format("replyToActivity(conversationId=%s, activityId=%s) [Activity(replyToId=%s)]",
					conversationId, activityId, activity.getReplyToId()));
		}

		return Response.accepted().build();
	} catch (Exception e) {
		log.error("Error in replyToActivity", e);
		return Response.serverError().entity("Error: " + e).build();
	}
}