Search in sources :

Example 1 with JsonWriterFactory

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

the class HealthCheckService method constructResponse.

private void constructResponse(HttpServletResponse httpResponse, Set<HealthCheckResponse> healthCheckResponses, HealthCheckType type, String enablePrettyPrint) throws IOException {
    httpResponse.setContentType("application/json");
    // For each HealthCheckResponse we got from executing the health checks...
    JsonArrayBuilder checksArray = Json.createArrayBuilder();
    for (HealthCheckResponse healthCheckResponse : healthCheckResponses) {
        JsonObjectBuilder healthCheckObject = Json.createObjectBuilder();
        // Add the name and status
        healthCheckObject.add("name", healthCheckResponse.getName());
        healthCheckObject.add("status", healthCheckResponse.getStatus().toString());
        // Add data if present
        JsonObjectBuilder healthCheckData = Json.createObjectBuilder();
        if (healthCheckResponse.getData().isPresent() && !healthCheckResponse.getData().get().isEmpty()) {
            for (Map.Entry<String, Object> dataMapEntry : healthCheckResponse.getData().get().entrySet()) {
                healthCheckData.add(dataMapEntry.getKey(), dataMapEntry.getValue().toString());
            }
        }
        healthCheckObject.add("data", healthCheckData);
        // Add finished Object to checks array
        checksArray.add(healthCheckObject);
        // Check if we need to set the response as 503. Check against status 200 so we don't repeatedly set it
        if (httpResponse.getStatus() == 200 && healthCheckResponse.getStatus().equals(HealthCheckResponse.Status.DOWN)) {
            httpResponse.setStatus(503);
        }
    }
    // Create the final aggregate object
    JsonObjectBuilder responseObject = Json.createObjectBuilder();
    // Set the aggregate status
    responseObject.add("status", httpResponse.getStatus() == 200 ? "UP" : "DOWN");
    // Add all of the checks
    responseObject.add("checks", checksArray);
    String prettyPrinting = enablePrettyPrint == null || enablePrettyPrint.equals("false") ? "" : JsonGenerator.PRETTY_PRINTING;
    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(singletonMap(prettyPrinting, ""));
    StringWriter stringWriter = new StringWriter();
    try (JsonWriter jsonWriter = jsonWriterFactory.createWriter(stringWriter)) {
        jsonWriter.writeObject(responseObject.build());
    }
    // Print the outcome
    httpResponse.getOutputStream().print(stringWriter.toString());
}
Also used : HealthCheckResponse(org.eclipse.microprofile.health.HealthCheckResponse) StringWriter(java.io.StringWriter) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Collections.singletonMap(java.util.Collections.singletonMap) JsonWriter(javax.json.JsonWriter) JsonWriterFactory(javax.json.JsonWriterFactory)

Example 2 with JsonWriterFactory

use of javax.json.JsonWriterFactory in project meecrowave by apache.

the class ConfigurableBus method initProviders.

public void initProviders(final Configuration builder, final ClassLoader loader) {
    final List<Object> providers = ofNullable(builder.getJaxrsDefaultProviders()).map(s -> Stream.of(s.split(" *, *")).map(String::trim).filter(p -> !p.isEmpty()).map(name -> {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(name).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new IllegalArgumentException(name + " can't be created");
        }
    }).collect(Collectors.<Object>toList())).orElseGet(() -> {
        // ensure both providers share the same memory reuse logic
        final JsonProvider provider = JsonProvider.provider();
        final JsonReaderFactory readerFactory = provider.createReaderFactory(new HashMap<String, Object>() {

            {
                put(JsonParserFactoryImpl.SUPPORTS_COMMENTS, builder.isJsonpSupportsComment());
                Optional.of(builder.getJsonpMaxStringLen()).filter(v -> v > 0).ifPresent(s -> put(JsonParserFactoryImpl.MAX_STRING_LENGTH, s));
                Optional.of(builder.getJsonpMaxReadBufferLen()).filter(v -> v > 0).ifPresent(s -> put(JsonParserFactoryImpl.BUFFER_LENGTH, s));
                ofNullable(builder.getJsonpBufferStrategy()).ifPresent(s -> put(AbstractJsonFactory.BUFFER_STRATEGY, s));
            }
        });
        final JsonWriterFactory writerFactory = provider.createWriterFactory(new HashMap<String, Object>() {

            {
                put(JsonGenerator.PRETTY_PRINTING, builder.isJsonpPrettify());
                Optional.of(builder.getJsonpMaxWriteBufferLen()).filter(v -> v > 0).ifPresent(v -> put(JsonGeneratorFactoryImpl.GENERATOR_BUFFER_LENGTH, v));
                ofNullable(builder.getJsonpBufferStrategy()).ifPresent(s -> put(AbstractJsonFactory.BUFFER_STRATEGY, s));
            }
        });
        return Stream.<Object>of(new ConfiguredJsonbJaxrsProvider(builder.getJsonbEncoding(), builder.isJsonbNulls(), builder.isJsonbIJson(), builder.isJsonbPrettify(), builder.getJsonbBinaryStrategy(), builder.getJsonbNamingStrategy(), builder.getJsonbOrderStrategy(), new DelegateJsonProvider(provider, readerFactory, writerFactory))).collect(toList());
    });
    if (builder.isJaxrsAutoActivateBeanValidation()) {
        try {
            // we don't need the jaxrsbeanvalidationfeature since bean validation cdi extension handles it normally
            loader.loadClass("javax.validation.Validation");
            final Object instance = loader.loadClass("org.apache.cxf.jaxrs.validation.ValidationExceptionMapper").getConstructor().newInstance();
            // validate bval can be used, check NoClassDefFoundError javax.validation.ValidationException
            instance.getClass().getGenericInterfaces();
            providers.add(instance);
        } catch (final Exception | NoClassDefFoundError e) {
        // no-op
        }
    }
    // client
    if (getProperty("org.apache.cxf.jaxrs.bus.providers") == null) {
        setProperty("skip.default.json.provider.registration", "true");
        setProperty("org.apache.cxf.jaxrs.bus.providers", providers);
    }
}
Also used : JsonReaderFactory(javax.json.JsonReaderFactory) JsonWriterFactory(javax.json.JsonWriterFactory) Produces(javax.ws.rs.Produces) Provider(javax.ws.rs.ext.Provider) JsonParserFactoryImpl(org.apache.johnzon.core.JsonParserFactoryImpl) JsonBuilderFactory(javax.json.JsonBuilderFactory) Collections.singletonList(java.util.Collections.singletonList) JsonProvider(javax.json.spi.JsonProvider) JsonValue(javax.json.JsonValue) BigDecimal(java.math.BigDecimal) JsonStructure(javax.json.JsonStructure) MediaType(javax.ws.rs.core.MediaType) JsonNumber(javax.json.JsonNumber) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) BigInteger(java.math.BigInteger) ClientLifeCycleManagerImpl(org.apache.cxf.bus.managers.ClientLifeCycleManagerImpl) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) Collection(java.util.Collection) JsonGeneratorFactory(javax.json.stream.JsonGeneratorFactory) Reader(java.io.Reader) AbstractJsonFactory(org.apache.johnzon.core.AbstractJsonFactory) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) Type(java.lang.reflect.Type) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonGenerator(javax.json.stream.JsonGenerator) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonPatch(javax.json.JsonPatch) ClientLifeCycleManager(org.apache.cxf.endpoint.ClientLifeCycleManager) HashMap(java.util.HashMap) JsonParserFactory(javax.json.stream.JsonParserFactory) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) JsonbJaxrsProvider(org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider) OutputStream(java.io.OutputStream) JsonParser(javax.json.stream.JsonParser) JsonReader(javax.json.JsonReader) Optional.ofNullable(java.util.Optional.ofNullable) JsonArray(javax.json.JsonArray) JsonMergePatch(javax.json.JsonMergePatch) Configuration(org.apache.meecrowave.configuration.Configuration) JsonGeneratorFactoryImpl(org.apache.johnzon.core.JsonGeneratorFactoryImpl) JsonString(javax.json.JsonString) Collectors.toList(java.util.stream.Collectors.toList) JsonPatchBuilder(javax.json.JsonPatchBuilder) JsonWriter(javax.json.JsonWriter) Jsonb(javax.json.bind.Jsonb) JsonPointer(javax.json.JsonPointer) InputStream(java.io.InputStream) JsonString(javax.json.JsonString) JsonProvider(javax.json.spi.JsonProvider) JsonObject(javax.json.JsonObject) JsonWriterFactory(javax.json.JsonWriterFactory) JsonReaderFactory(javax.json.JsonReaderFactory)

Example 3 with JsonWriterFactory

use of javax.json.JsonWriterFactory in project iaf by ibissource.

the class ApiListenerServlet method returnJson.

public void returnJson(HttpServletResponse response, int status, JsonObject json) throws IOException {
    response.setStatus(status);
    Map<String, Boolean> config = new HashMap<>();
    config.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory factory = Json.createWriterFactory(config);
    try (JsonWriter jsonWriter = factory.createWriter(response.getOutputStream(), StreamUtil.DEFAULT_CHARSET)) {
        jsonWriter.write(json);
    }
}
Also used : HashMap(java.util.HashMap) JsonWriter(javax.json.JsonWriter) JsonWriterFactory(javax.json.JsonWriterFactory)

Example 4 with JsonWriterFactory

use of javax.json.JsonWriterFactory in project meecrowave by apache.

the class ConfigurableBus method initProviders.

public void initProviders(final Meecrowave.Builder builder, final ClassLoader loader) {
    final List<Object> providers = ofNullable(builder.getJaxrsDefaultProviders()).map(s -> Stream.of(s.split(" *, *")).map(String::trim).filter(p -> !p.isEmpty()).map(name -> {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(name).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new IllegalArgumentException(name + " can't be created");
        }
    }).collect(Collectors.<Object>toList())).orElseGet(() -> {
        // ensure both providers share the same memory reuse logic
        final JsonProvider provider = JsonProvider.provider();
        final JsonReaderFactory readerFactory = provider.createReaderFactory(new HashMap<String, Object>() {

            {
                put(JsonParserFactoryImpl.SUPPORTS_COMMENTS, builder.isJsonpSupportsComment());
                of(builder.getJsonpMaxStringLen()).filter(v -> v > 0).ifPresent(s -> put(JsonParserFactoryImpl.MAX_STRING_LENGTH, s));
                of(builder.getJsonpMaxReadBufferLen()).filter(v -> v > 0).ifPresent(s -> put(JsonParserFactoryImpl.BUFFER_LENGTH, s));
                ofNullable(builder.getJsonpBufferStrategy()).ifPresent(s -> put(AbstractJsonFactory.BUFFER_STRATEGY, s));
            }
        });
        final JsonWriterFactory writerFactory = provider.createWriterFactory(new HashMap<String, Object>() {

            {
                put(JsonGenerator.PRETTY_PRINTING, builder.isJsonpPrettify());
                of(builder.getJsonpMaxWriteBufferLen()).filter(v -> v > 0).ifPresent(v -> put(JsonGeneratorFactoryImpl.GENERATOR_BUFFER_LENGTH, v));
                ofNullable(builder.getJsonpBufferStrategy()).ifPresent(s -> put(AbstractJsonFactory.BUFFER_STRATEGY, s));
            }
        });
        return Stream.<Object>of(new ConfiguredJsonbJaxrsProvider(builder.getJsonbEncoding(), builder.isJsonbNulls(), builder.isJsonbIJson(), builder.isJsonbPrettify(), builder.getJsonbBinaryStrategy(), builder.getJsonbNamingStrategy(), builder.getJsonbOrderStrategy(), new DelegateJsonProvider(provider, readerFactory, writerFactory)), new ConfiguredJsrProvider(readerFactory, writerFactory)).collect(toList());
    });
    if (builder.isJaxrsAutoActivateBeanValidation()) {
        try {
            // we don't need the jaxrsbeanvalidationfeature since bean validation cdi extension handles it normally
            loader.loadClass("javax.validation.Validation");
            final Object instance = loader.loadClass("org.apache.cxf.jaxrs.validation.ValidationExceptionMapper").getConstructor().newInstance();
            // validate bval can be used, check NoClassDefFoundError javax.validation.ValidationException
            instance.getClass().getGenericInterfaces();
            providers.add(instance);
        } catch (final Exception | NoClassDefFoundError e) {
        // no-op
        }
    }
    // client
    if (getProperty("org.apache.cxf.jaxrs.bus.providers") == null) {
        setProperty("skip.default.json.provider.registration", "true");
        setProperty("org.apache.cxf.jaxrs.bus.providers", providers);
    }
}
Also used : JsonReaderFactory(javax.json.JsonReaderFactory) Arrays(java.util.Arrays) JsonWriterFactory(javax.json.JsonWriterFactory) Produces(javax.ws.rs.Produces) Provider(javax.ws.rs.ext.Provider) JsonParserFactoryImpl(org.apache.johnzon.core.JsonParserFactoryImpl) JsonBuilderFactory(javax.json.JsonBuilderFactory) Optional.of(java.util.Optional.of) JsonProvider(javax.json.spi.JsonProvider) JsonValue(javax.json.JsonValue) BigDecimal(java.math.BigDecimal) JsonStructure(javax.json.JsonStructure) MediaType(javax.ws.rs.core.MediaType) JsonNumber(javax.json.JsonNumber) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) BigInteger(java.math.BigInteger) ClientLifeCycleManagerImpl(org.apache.cxf.bus.managers.ClientLifeCycleManagerImpl) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) Collection(java.util.Collection) JsonGeneratorFactory(javax.json.stream.JsonGeneratorFactory) Reader(java.io.Reader) AbstractJsonFactory(org.apache.johnzon.core.AbstractJsonFactory) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) Writer(java.io.Writer) Meecrowave(org.apache.meecrowave.Meecrowave) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonGenerator(javax.json.stream.JsonGenerator) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonPatch(javax.json.JsonPatch) ClientLifeCycleManager(org.apache.cxf.endpoint.ClientLifeCycleManager) HashMap(java.util.HashMap) JsonParserFactory(javax.json.stream.JsonParserFactory) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) DelegateProvider(org.apache.johnzon.jaxrs.DelegateProvider) JsonbJaxrsProvider(org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider) JsrMessageBodyReader(org.apache.johnzon.jaxrs.JsrMessageBodyReader) OutputStream(java.io.OutputStream) JsonParser(javax.json.stream.JsonParser) JsonReader(javax.json.JsonReader) Optional.ofNullable(java.util.Optional.ofNullable) JsonArray(javax.json.JsonArray) JsonMergePatch(javax.json.JsonMergePatch) JsrMessageBodyWriter(org.apache.johnzon.jaxrs.JsrMessageBodyWriter) JsonGeneratorFactoryImpl(org.apache.johnzon.core.JsonGeneratorFactoryImpl) JsonString(javax.json.JsonString) Collectors.toList(java.util.stream.Collectors.toList) JsonPatchBuilder(javax.json.JsonPatchBuilder) JsonWriter(javax.json.JsonWriter) Jsonb(javax.json.bind.Jsonb) JsonPointer(javax.json.JsonPointer) InputStream(java.io.InputStream) JsonString(javax.json.JsonString) JsonProvider(javax.json.spi.JsonProvider) JsonObject(javax.json.JsonObject) JsonWriterFactory(javax.json.JsonWriterFactory) JsonReaderFactory(javax.json.JsonReaderFactory)

Example 5 with JsonWriterFactory

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

the class JsonWriter method serialize.

protected void serialize(JsonObject payload) throws IOException {
    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(null);
    jsonWriterFactory.createWriter(writer).writeObject(payload);
}
Also used : JsonWriterFactory(javax.json.JsonWriterFactory)

Aggregations

JsonWriterFactory (javax.json.JsonWriterFactory)7 HashMap (java.util.HashMap)6 JsonWriter (javax.json.JsonWriter)6 JsonObject (javax.json.JsonObject)4 JsonReader (javax.json.JsonReader)4 StringWriter (java.io.StringWriter)3 Map (java.util.Map)3 JsonArrayBuilder (javax.json.JsonArrayBuilder)3 JsonObjectBuilder (javax.json.JsonObjectBuilder)3 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 Reader (java.io.Reader)2 StringReader (java.io.StringReader)2 Writer (java.io.Writer)2 BigDecimal (java.math.BigDecimal)2 BigInteger (java.math.BigInteger)2 Collection (java.util.Collection)2 List (java.util.List)2 Optional.ofNullable (java.util.Optional.ofNullable)2 Collectors (java.util.stream.Collectors)2