Java Code Examples for javax.json.bind.Jsonb

The following examples show how to use javax.json.bind.Jsonb. 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: component-runtime   Source File: JsonSchemaConverterTest.java    License: 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 2
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: 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 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 4
Source Project: component-runtime   Source File: Generator.java    License: 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 5
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 6
Source Project: BotServiceStressToolkit   Source File: BaseBotSampler.java    License: 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 7
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 8
Source Project: component-runtime   Source File: JsonSchemaConverterTest.java    License: 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 9
@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 10
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: 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 11
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 12
Source Project: thorntail   Source File: JaxrsJsonbTest.java    License: 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 13
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 14
@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 15
Source Project: component-runtime   Source File: RecordConvertersTest.java    License: 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 16
Source Project: scalable-coffee-shop   Source File: EventSerializer.java    License: 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 17
Source Project: component-runtime   Source File: ComponentManager.java    License: 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 18
@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 19
Source Project: component-runtime   Source File: UiSchemaConverterTest.java    License: 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 20
Source Project: component-runtime   Source File: Generator.java    License: Apache License 2.0 5 votes vote down vote up
private static void writeServerOpenApi(final File output, final String resource, final String version)
        throws Exception {
    try (final InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
            final Jsonb jsonb = JsonbBuilder.create(new JsonbConfig())) {
        final String newJson = IO.slurp(source);
        String oldJson = !output.exists() ? "{}" : String.join("\n", Files.readAllLines(output.toPath()));
        final int start = oldJson.indexOf(".swaggerUi = ");
        if (start > 0) {
            oldJson = oldJson.substring(start + ".swaggerUi = ".length());
        }

        final int end = oldJson.indexOf(";</script>");
        if (end > 0) {
            oldJson = oldJson.substring(0, end);
        }
        final JsonBuilderFactory builderFactory = Json.createBuilderFactory(emptyMap());
        final JsonObject oldApi = !oldJson.startsWith("{") ? builderFactory.createObjectBuilder().build()
                : jsonb.fromJson(oldJson, JsonObject.class);
        final JsonObject newApi = builderFactory
                .createObjectBuilder(jsonb.fromJson(newJson, JsonObject.class))
                .add("servers", builderFactory
                        .createArrayBuilder()
                        .add(builderFactory
                                .createObjectBuilder()
                                .add("url", String
                                        .format("https://talend.github.io/component-runtime/main/%s/examples/apidemo",
                                                version))))
                .build();
        if (!oldJson.startsWith("{") || !areEqualsIgnoringOrder(oldApi, newApi)) {
            try (final OutputStream writer = new WriteIfDifferentStream(output)) {
                writer
                        .write(("= Component Server API\n:page-talend_swaggerui:\n\n++++\n<script>\n"
                                + "(window.talend " + "= (window.talend || {})).swaggerUi = " + newApi.toString()
                                + ";</script>\n" + "<div id=\"swagger-ui\"></div>\n++++\n")
                                        .getBytes(StandardCharsets.UTF_8));
            }
        }
    }
}
 
Example 21
Source Project: component-runtime   Source File: RecordJsonGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void arrayOfDouble(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.writeStartArray("a");
    generator.write(1.0);
    generator.write(2.0);
    generator.writeEnd();
    generator.writeEnd();
    generator.close();
    assertEquals("{\"a\":[1.0,2.0]}", out.getRecord().toString());
}
 
Example 22
Source Project: component-runtime   Source File: InputImpl.java    License: Apache License 2.0 5 votes vote down vote up
private Jsonb jsonb() {
    if (jsonb == null) {
        synchronized (this) {
            if (jsonb == null) {
                final LightContainer container = ContainerFinder.Instance.get().find(plugin());
                jsonb = container.findService(Jsonb.class);
            }
        }
    }
    return jsonb;
}
 
Example 23
@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 24
@GET
   @Path("/v1/showAllergies")
   @Produces(MediaType.APPLICATION_JSON)
   public Response showAllergies() {
       /*
       "ResultSet Output": [
           {
               "CITY": "Albany              ",
               "POSTCODE": "12202     ",
               "PATIENT_NUM": 1437,
               "BIRTHDATE": "1961-11-26",
               "ALLERGY_START": "1991-10-08",
               "ALLERGY_STOP": null,
               "DESCRIPTION": "Allergy to fish"
           } ],
       "StatusCode": 200,
       "StatusDescription": "Execution Successful"
   }     
   */   


   // select Patients.patient_id, Patients.birthdate, Patients.city, Patients.postcode, Allergies.description, Allergies.allergy_start, Allergies.allergy_stop from Patients JOIN Allergies ON Patients.patient_id = Allergies.patient_id;

       List<AllergyList> results = entityManager.createNamedQuery("Allergy.getAllergies", AllergyList.class).getResultList();

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

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

       return Response.ok(jresponse).build();
}
 
Example 25
@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 26
Source Project: robozonky   Source File: InvestmentImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void deserializeDefaulted() throws Exception {
    try (Jsonb jsonb = JsonbBuilder.create()) {
        Investment investment = jsonb.fromJson(DEFAULTED_INVESTMENT_JSON, InvestmentImpl.class);
        SoftAssertions.assertSoftly(softly -> {
            softly.assertThat(investment.getId())
                .isEqualTo(414819);
            softly.assertThat(investment.getLoanId())
                .isEqualTo(42122);
            softly.assertThat(investment.getCurrentTerm())
                .isEmpty();
        });
    }
}
 
Example 27
@POST
  @Path("/v1/login/user")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response login(String body) {
      // {"UID":username,"PASS":password}
       Jsonb jsonb = JsonbBuilder.create();
       Credentials c = jsonb.fromJson(body, Credentials.class);
      List<Patient> results = entityManager.createNamedQuery("Patient.login", Patient.class)
              .setParameter("userId", c.UID)
              .setParameter("password", c.PASS)
              .getResultList();
      logger.info("Found this many patients: " + results.size());
      int returnCode = 0;
      if (results.size() == 0) {
          returnCode=1;
      }

      /*
          "ResultSet Output": [
          {
              "PATIENTID": 1
          }
          ],
      "StatusCode": 200,
      "StatusDescription": "Execution Successful"
  }*/
      if (returnCode==1) {
          return Response.status(Status.NOT_FOUND).build();
      }
      
      String loginBlob = "{\"ResultSet Output\":" + jsonb.toJson(results) 
      + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";

      logger.info("login blob: " + loginBlob);
      JsonReader jsonReader = Json.createReader(new StringReader(loginBlob));
      JsonObject jresponse  = jsonReader.readObject();
      jsonReader.close();
return Response.ok(jresponse).build();         
  }
 
Example 28
Source Project: smallrye-graphql   Source File: ArgumentHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is used once we have a valid jsonString, either from above or from complex default value from graphql-java
 *
 * @param jsonString the object represented as a json String
 * @param field the field as created while scanning
 * @return the correct object
 */
private Object correctComplexObjectFromJsonString(String jsonString, Field field) throws AbstractDataFetcherException {
    Class ownerClass = classloadingService.loadClass(field.getReference().getClassName());
    try {
        Jsonb jsonb = JsonBCreator.getJsonB(field.getReference().getClassName());
        return jsonb.fromJson(jsonString, ownerClass);
    } catch (JsonbException jbe) {
        throw new TransformException(jbe, field, jsonString);
    }
}
 
Example 29
Source Project: smallrye-graphql   Source File: SchemaBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
static String toString(Schema schema) {

        JsonbConfig config = new JsonbConfig()
                .withFormatting(true);

        Jsonb jsonb = JsonbBuilder.create(config);
        return jsonb.toJson(schema);
    }
 
Example 30
Source Project: tutorials   Source File: JsonbUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() {
    Jsonb jsonb = JsonbBuilder.create();
    Person person = new Person(1, "Jhon", "[email protected]", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
    // @formatter:off
    String jsonPerson = 
        "{\"email\":\"[email protected]\"," + 
         "\"id\":1," + 
         "\"person-name\":\"Jhon\"," + 
         "\"registeredDate\":\"07-09-2019\"," + 
         "\"salary\":\"1000.0\"}";
    // @formatter:on
    assertTrue(jsonb.fromJson(jsonPerson, Person.class)
        .equals(person));
}