Java Code Examples for javax.json.bind.JsonbBuilder#create()

The following examples show how to use javax.json.bind.JsonbBuilder#create() . 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: 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 2
Source File: RecordConvertersTest.java    From component-runtime with 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 3
Source File: DefaultEventSerializationServiceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testSerializationStructure() throws Exception {
    when(mockEvent.getTypes()).thenReturn(asList(Create, Activity));

    final String json = svc.serialize(mockEvent);

    final Jsonb jsonb = JsonbBuilder.create();
    @SuppressWarnings("unchecked")
    final Map<String, Object> map = jsonb.fromJson(json, Map.class);
    assertTrue(map.containsKey("@context"), "@context property not in JSON structure!");
    assertTrue(map.containsKey("id"), "id property not in JSON structure!");
    assertTrue(map.containsKey("type"), "type property not in JSON structure!");
    assertTrue(map.containsKey("inbox"), "inbox property not in JSON structure!");
    assertTrue(map.containsKey("actor"), "actor property not in JSON structure!");
    assertTrue(map.containsKey("object"), "object property not in JSON structure!");
    assertTrue(map.containsKey("published"), "published property not in JSON structure!");

    final List<?> types = (List<?>) map.get("type");
    assertTrue(types.contains("Create"), "as:Create not in type list!");
    assertTrue(types.contains(Activity.getIRIString()), "prov:Activity not in type list!");

    assertTrue(AS.getNamespace().contains((String) map.get("@context")), "AS namespace not in @context!");

    final List<?> actor = (List<?>) map.get("actor");
    assertTrue(actor.contains("info:user/test"), "actor property has incorrect value!");

    assertEquals("info:event/12345", map.get("id"), "id property has incorrect value!");
    assertEquals("info:ldn/inbox", map.get("inbox"), "inbox property has incorrect value!");
    assertEquals(time.toString(), map.get("published"), "published property has incorrect value!");
}
 
Example 4
Source File: VertxJsonTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    JsonbConfig config = new JsonbConfig()
            .withSerializers(new VertxJson.JsonObjectSerializer(), new VertxJson.JsonArraySerializer())
            .withDeserializers(new VertxJson.JsonObjectDeserializer(), new VertxJson.JsonArrayDeserializer());
    jsonb = JsonbBuilder.create(config);
}
 
Example 5
Source File: RecordConvertersTest.java    From component-runtime with 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 6
Source File: MinimalExample.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
public Book deserializeBook() {
    Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom");
    Jsonb jsonb = JsonbBuilder.create();
    String json = jsonb.toJson(book);
    book = jsonb.fromJson(json, Book.class);
    return book;
}
 
Example 7
Source File: JmsSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    factory = new ActiveMQJMSConnectionFactory(
            "tcp://localhost:61616",
            null, null);
    jms = factory.createContext();
    json = JsonbBuilder.create();
    executor = Executors.newFixedThreadPool(3);
}
 
Example 8
Source File: JsonbSerializersTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setup() {
    JsonbConfig config = new JsonbConfig();
    config.withSerializers(new HalEntityWrapperJsonbSerializer(new BookHalLinksProvider()));
    config.withSerializers(new HalCollectionWrapperJsonbSerializer(new BookHalLinksProvider()));
    jsonb = JsonbBuilder.create(config);
}
 
Example 9
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@GET
   @Path("/v1/countCities")
   @Produces(MediaType.APPLICATION_JSON)
   public Response countCities() {

       List<CityCounts> results = entityManager.createNamedQuery("Patient.getPop", CityCounts.class).getResultList();
       /* Output format
       "ResultSet Output": [
           {
               "CITY": "Akron",
               "POSTCODE": "44223",
               "NUM_IN_CITY": 13
           }],
           "StatusCode": 200,
           "StatusDescription": "Execution Successful”
           } 
       */

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

       JsonReader jsonReader = Json.createReader(new StringReader(cityBlob));
           
       JsonObject jresponse  = jsonReader.readObject();
       jsonReader.close();

       return Response.ok(jresponse).build();
}
 
Example 10
Source File: DefaultEventSerializationServiceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testSerializationStructureNoEmptyElements() throws Exception {
    when(mockEvent.getInbox()).thenReturn(empty());
    when(mockEvent.getAgents()).thenReturn(emptyList());
    when(mockEvent.getObjectTypes()).thenReturn(emptyList());

    final String json = svc.serialize(mockEvent);

    final Jsonb jsonb = JsonbBuilder.create();
    @SuppressWarnings("unchecked")
    final Map<String, Object> map = jsonb.fromJson(json, Map.class);
    assertTrue(map.containsKey("@context"), "@context property not in JSON structure!");
    assertTrue(map.containsKey("id"), "id property not in JSON structure!");
    assertTrue(map.containsKey("type"), "type property not in JSON strucutre!");
    assertFalse(map.containsKey("inbox"), "inbox property unexpectedly in JSON structure!");
    assertFalse(map.containsKey("actor"), "actor property unexpectedly in JSON structure!");
    assertTrue(map.containsKey("object"), "object property not in JSON structure!");
    assertTrue(map.containsKey("published"), "published property not in JSON structure!");

    final List<?> types = (List<?>) map.get("type");
    assertTrue(types.contains("Create"), "as:Create type not in type list!");

    @SuppressWarnings("unchecked")
    final Map<String, Object> obj = (Map<String, Object>) map.get("object");
    assertTrue(obj.containsKey("id"), "object id property not in JSON structure!");
    assertFalse(obj.containsKey("type"), "empty object type unexpectedly in JSON structure!");

    assertTrue(AS.getNamespace().contains((String) map.get("@context")), "AS namespace not in @context!");

    assertEquals("info:event/12345", map.get("id"), "id property has incorrect value!");
    assertEquals(time.toString(), map.get("published"), "published property has incorrect value!");
}
 
Example 11
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 12
Source File: JsonbFactory.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Produces
@ComponentServer
@ApplicationScoped
Jsonb jsonb() {
    return JsonbBuilder.create(new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL));
}
 
Example 13
Source File: JsonbHttpMessageConverter.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Construct a new {@code JsonbHttpMessageConverter} with default configuration.
 */
public JsonbHttpMessageConverter() {
	this(JsonbBuilder.create());
}
 
Example 14
Source File: Processing.java    From quarkus-deep-dive with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init() {
    jsonb = JsonbBuilder.create();
}
 
Example 15
Source File: JsonProvider.java    From quarkus-deep-dive with Apache License 2.0 4 votes vote down vote up
@Produces
Jsonb json() {
    return JsonbBuilder.create();
}
 
Example 16
Source File: Main.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        Jsonb jsonb = JsonbBuilder.create();
        HttpClient client = HttpClient.newHttpClient();

        System.out.println("-------------------------------------");
        System.out.println("-------------Get a user--------------");
        System.out.println("-------------------------------------");

        HttpRequest requestGet = HttpRequest.newBuilder()
                .uri(URI.create("https://reqres.in/api/users/2"))
                .build();

        HttpResponse<User> responseGet = client.send(requestGet,
                JsonBodyHandler.jsonBodyHandler(jsonb, User.class));

        System.out.println("Status code: " + responseGet.statusCode());

        User user = responseGet.body();
        System.out.println(user);

        System.out.println();
        System.out.println("-------------------------------------");
        System.out.println("-------------Update user-------------");
        System.out.println("-------------------------------------");

        user.getData().setEmail("[email protected]");

        HttpRequest requestPut = HttpRequest.newBuilder()
                .header("Content-Type", "application/json")
                .uri(URI.create("https://reqres.in/api/users"))
                .PUT(HttpRequest.BodyPublishers.ofString(jsonb.toJson(user)))
                .build();

        HttpResponse<User> responsePut = client.send(
                requestPut, JsonBodyHandler.jsonBodyHandler(jsonb, User.class));

        System.out.println("Status code: " + responsePut.statusCode());

        User updatedUser = responsePut.body();
        System.out.println(updatedUser);

        System.out.println();
        System.out.println("-------------------------------------");
        System.out.println("-------------Post new user------------");
        System.out.println("-------------------------------------");

        Data data = new Data();
        data.setId(10);
        data.setFirstName("John");
        data.setLastName("Year");
        data.setAvatar("https://johnyear.com/jy.png");

        User newUser = new User();
        newUser.setData(data);

        HttpRequest requestPost = HttpRequest.newBuilder()
                .header("Content-Type", "application/json")
                .uri(URI.create("https://reqres.in/api/users"))
                .POST(HttpRequest.BodyPublishers.ofString(jsonb.toJson(user)))
                .build();

        HttpResponse<Void> responsePost = client.send(
                requestPost, HttpResponse.BodyHandlers.discarding());

        System.out.println("Status code: " + responsePost.statusCode());
    }
 
Example 17
Source File: ActionExecutor.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) {
    if (args.length != 6) {
        System.err
                .println(
                        "Usage\n   app <component_gav> <lang> <action_family> <action_type> <action_name> <payload>");
        return;
    }

    System
            .setProperty("talend.component.manager.m2.repository",
                    System
                            .getProperty("talend.component.manager.m2.repository",
                                    System.getProperty("user.home") + "/.m2/repository"));
    System
            .setProperty("talend.component.manager.classpathcontributor.skip",
                    System.getProperty("talend.component.manager.classpathcontributor.skip", "true"));
    System
            .setProperty("talend.component.manager.localconfiguration.skip",
                    System.getProperty("talend.component.manager.localconfiguration.skip", "true"));
    System
            .setProperty("talend.component.manager.jmx.skip",
                    System.getProperty("talend.component.manager.jmx.skip", "true"));
    System.setProperty("talend.component.impl.mode", System.getProperty("talend.component.impl.mode", "UNSAFE"));

    try (final Jsonb jsonb = JsonbBuilder.create()) {
        try {
            final ComponentManager instance = ComponentManager.instance();
            final String plugin = instance.addPlugin(args[0]);
            final Container container = instance
                    .findPlugin(plugin)
                    .orElseThrow(() -> new IllegalArgumentException("plugin '" + plugin + "' incorrectly started"));

            final Properties props = new Properties();
            try (final StringReader reader = new StringReader(args[5])) {
                props.load(reader);
            }
            final Map<String, String> runtimeParams = new HashMap<>(1 + props.size());
            runtimeParams.put("$lang", args[1]);
            runtimeParams
                    .putAll(props.stringPropertyNames().stream().collect(toMap(identity(), props::getProperty)));

            final Object result = container
                    .get(ContainerComponentRegistry.class)
                    .getServices()
                    .stream()
                    .flatMap(sm -> sm.getActions().stream())
                    .filter(act -> Objects.equals(args[2], act.getFamily())
                            && Objects.equals(args[3], act.getType()) && Objects.equals(args[4], act.getAction()))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("Invalid action, not found"))
                    .getInvoker()
                    .apply(runtimeParams);

            onResult(jsonb, result);
        } catch (final RuntimeException re) {
            onError(jsonb, re);
            System.exit(1);
        }
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 18
Source File: AbstractLogger.java    From microprofile-sandbox with Apache License 2.0 4 votes vote down vote up
public AbstractLogger(final String name, Supplier<T> supplier) {
  this.name = name;
  this.supplier = supplier;
  this.jsonB = JsonbBuilder.create();
  initTracer();
}
 
Example 19
Source File: QuoteGenerator.java    From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 4 votes vote down vote up
private String generateQuote(int type, int company, int amount) {
    Jsonb jsonb = JsonbBuilder.create();
    Operation operation = new Operation(type, Company.values()[company], amount);
    return jsonb.toJson(operation);
}
 
Example 20
Source File: JsonBCreator.java    From smallrye-graphql with Apache License 2.0 3 votes vote down vote up
private static Jsonb createJsonB(Map<String, String> customFieldNameMapping) {

        JsonbConfig config = createDefaultConfig()
                .withPropertyNamingStrategy(new GraphQLNamingStrategy(customFieldNameMapping));

        return JsonbBuilder.create(config);
    }