Search in sources :

Example 11 with JsonStructure

use of javax.json.JsonStructure in project java-driver by datastax.

the class Jsr353JsonRow method selectJsonRow.

// Retrieving User instances from table rows using SELECT JSON
private static void selectJsonRow(Session session) {
    // Reading the whole row as a JSON object
    Statement stmt = select().json().from("examples", "json_jsr353_row").where(in("id", 1, 2));
    ResultSet rows = session.execute(stmt);
    for (Row row : rows) {
        // SELECT JSON returns only one column for each row, of type VARCHAR,
        // containing the row as a JSON payload.
        // Note that the codec requires that the type passed to the get() method
        // be always JsonStructure, and not a subclass of it, such as JsonObject,
        // hence the need to downcast to JsonObject manually
        JsonObject user = (JsonObject) row.get(0, JsonStructure.class);
        System.out.printf("Retrieved user: %s%n", user);
    }
}
Also used : JsonObject(javax.json.JsonObject) JsonStructure(javax.json.JsonStructure)

Example 12 with JsonStructure

use of javax.json.JsonStructure in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class Utils method testJSONDataLayer.

/**
 * Provided a {@link ComponentData} object and an {@code expectedJsonResource} identifying a JSON file in the class path, this method will
 * test the JSON of the data layer and compare it to the JSON object provided by the {@code expectedJsonResource}.
 *
 * @param data                 the component data
 * @param expectedJsonResource the class path resource providing the expected JSON object
 */
public static void testJSONDataLayer(final ComponentData data, String expectedJsonResource) {
    InputStream is = Utils.class.getResourceAsStream(expectedJsonResource);
    try (JsonReader jsonReader = Json.createReader(new StringReader(Objects.requireNonNull(data.getJson())))) {
        if (is != null) {
            JsonStructure expected = Json.createReader(is).read();
            JsonObject actual = jsonReader.readObject();
            assertEquals(expected, actual);
        } else {
            fail("Unable to find test file " + expectedJsonResource + ".");
        }
    } finally {
        IOUtils.closeQuietly(is);
    }
}
Also used : InputStream(java.io.InputStream) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) JsonStructure(javax.json.JsonStructure)

Example 13 with JsonStructure

use of javax.json.JsonStructure in project Payara by payara.

the class GuiUtil method tryToFindOriginalErrorMessage.

public static String tryToFindOriginalErrorMessage(final Object entity) {
    getLogger().finest(() -> String.format("tryToFindOriginalErrorMessage(entity=%s)`; entity.class=%s", entity, entity == null ? null : entity.getClass().getCanonicalName()));
    try {
        if (entity instanceof String) {
            final JsonStructure parsed = Json.createReader(new StringReader(entity.toString())).read();
            if (parsed.getValueType() == ValueType.OBJECT) {
                return parsed.asJsonObject().getString("message");
            }
            getLogger().log(Level.WARNING, "Unsupported response entity, could not find an error message in the following response entity: {0}", parsed.getValueType());
        }
    } catch (Exception e) {
        getLogger().log(Level.SEVERE, "Could not parse a response entity, returning empty string as a fallback.", e);
    }
    return "";
}
Also used : StringReader(java.io.StringReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonStructure(javax.json.JsonStructure)

Example 14 with JsonStructure

use of javax.json.JsonStructure in project Payara by payara.

the class MBeanBulkReadResource method getReadResource.

/**
 * Returns the {@link String} form of the {@link JSONObject} resource from the ResourceHandler.
 *
 * @param content
 *            The JSON request payload, describing the beans and attributes to read.
 * @return The {@link String} representation of the MBeanRead/MBeanAttributeRead {@link JSONObject}.
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
public String getReadResource(final String content) {
    try (JsonReader reader = Json.createReader(new StringReader(content))) {
        // the payload can be either a single request or a bulk one (array)
        JsonStructure struct = reader.read();
        switch(struct.getValueType()) {
            case ARRAY:
                List<JsonObject> objects = struct.asJsonArray().stream().map(value -> handleRequest(value.asJsonObject())).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
                JsonArrayBuilder builder = Json.createArrayBuilder();
                for (JsonObject jsonObject : objects) {
                    builder.add(jsonObject);
                }
                return builder.build().toString();
            case OBJECT:
                return handleRequest(struct.asJsonObject()).orElse(JsonValue.EMPTY_JSON_OBJECT).toString();
            default:
                return "invalid JSON structure";
        }
    }
}
Also used : JsonObject(javax.json.JsonObject) JsonReader(javax.json.JsonReader) JsonArrayBuilder(javax.json.JsonArrayBuilder) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) MBeanAttributesReadHandler(fish.payara.monitoring.rest.app.handler.MBeanAttributesReadHandler) MBeanReadHandler(fish.payara.monitoring.rest.app.handler.MBeanReadHandler) Path(javax.ws.rs.Path) MBeanAttributeReadHandler(fish.payara.monitoring.rest.app.handler.MBeanAttributeReadHandler) Collectors(java.util.stream.Collectors) JsonString(javax.json.JsonString) Inject(javax.inject.Inject) JsonValue(javax.json.JsonValue) List(java.util.List) JsonStructure(javax.json.JsonStructure) MediaType(javax.ws.rs.core.MediaType) StringReader(java.io.StringReader) ReadHandler(fish.payara.monitoring.rest.app.handler.ReadHandler) RequestScoped(javax.enterprise.context.RequestScoped) Optional(java.util.Optional) Json(javax.json.Json) MBeanServerDelegate(fish.payara.monitoring.rest.app.MBeanServerDelegate) Optional(java.util.Optional) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonStructure(javax.json.JsonStructure) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 15 with JsonStructure

use of javax.json.JsonStructure in project cxf by apache.

the class AsyncMethodTest method testInvokesGetOperationWithRegisteredProvidersAsyncCompletionStage.

@Test
public void testInvokesGetOperationWithRegisteredProvidersAsyncCompletionStage() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/echo/test2")).willReturn(aResponse().withBody("{\"name\": \"test\"}")));
    AsyncClientWithCompletionStage api = RestClientBuilder.newBuilder().register(TestClientRequestFilter.class).register(TestClientResponseFilter.class).register(TestMessageBodyReader.class, 3).register(TestMessageBodyWriter.class).register(TestParamConverterProvider.class).register(TestReaderInterceptor.class).register(TestWriterInterceptor.class).register(JsrJsonpProvider.class).baseUri(getBaseUri()).build(AsyncClientWithCompletionStage.class);
    CompletionStage<JsonStructure> cs = api.get();
    // should need <1 second, but 20s timeout in case something goes wrong
    JsonStructure response = cs.toCompletableFuture().get(20, TimeUnit.SECONDS);
    assertThat(response, instanceOf(JsonObject.class));
    final JsonObject jsonObject = (JsonObject) response;
    assertThat(jsonObject.get("name"), instanceOf(JsonString.class));
    assertThat(((JsonString) jsonObject.get("name")).getString(), equalTo("test"));
    assertEquals(TestClientResponseFilter.getAndResetValue(), 1);
    assertEquals(TestClientRequestFilter.getAndResetValue(), 1);
    assertEquals(TestReaderInterceptor.getAndResetValue(), 1);
}
Also used : TestMessageBodyReader(org.eclipse.microprofile.rest.client.tck.providers.TestMessageBodyReader) TestWriterInterceptor(org.eclipse.microprofile.rest.client.tck.providers.TestWriterInterceptor) AsyncClientWithCompletionStage(org.apache.cxf.systest.microprofile.rest.client.mock.AsyncClientWithCompletionStage) JsonObject(javax.json.JsonObject) TestClientRequestFilter(org.eclipse.microprofile.rest.client.tck.providers.TestClientRequestFilter) TestParamConverterProvider(org.eclipse.microprofile.rest.client.tck.providers.TestParamConverterProvider) JsonString(javax.json.JsonString) JsonStructure(javax.json.JsonStructure) Test(org.junit.Test)

Aggregations

JsonStructure (javax.json.JsonStructure)37 JsonObject (javax.json.JsonObject)14 StringReader (java.io.StringReader)7 JsonObjectBuilder (javax.json.JsonObjectBuilder)5 Test (org.junit.Test)5 StringWriter (java.io.StringWriter)4 URL (java.net.URL)4 JsonArrayBuilder (javax.json.JsonArrayBuilder)4 IOException (java.io.IOException)3 Map (java.util.Map)3 JsonReader (javax.json.JsonReader)3 JsonString (javax.json.JsonString)3 PipeForward (nl.nn.adapterframework.core.PipeForward)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 HashMap (java.util.HashMap)2 List (java.util.List)2 JsonArray (javax.json.JsonArray)2 PipeRunResult (nl.nn.adapterframework.core.PipeRunResult)2 Message (nl.nn.adapterframework.stream.Message)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1