Search in sources :

Example 81 with JsonArrayBuilder

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

the class RestMethodMetadata method toJson.

/**
 * Build and return a Json object representing the metadata for the resource method
 * @return
 * @throws JsonException
 */
public JsonObject toJson() throws JsonException {
    JsonObjectBuilder o = Json.createObjectBuilder();
    if (path != null) {
        o.add("path", path);
    }
    JsonObjectBuilder queryParamJson = Json.createObjectBuilder();
    for (ParamMetadata pmd : queryParameters) {
        queryParamJson.add(pmd.getName(), pmd.toJson());
    }
    if (consumes != null) {
        JsonArrayBuilder array = Json.createArrayBuilder();
        for (String type : consumes) {
            array.add(type);
        }
        o.add("accepts", array);
    }
    if (produces != null) {
        JsonArrayBuilder array = Json.createArrayBuilder();
        for (String type : produces) {
            array.add(type);
        }
        o.add("produces", array);
    }
    o.add("queryParams", queryParamJson);
    if (requestPayload != null) {
        JsonObjectBuilder requestProps = Json.createObjectBuilder();
        requestProps.add("isCollection", isCollection);
        requestProps.add("dataType", getTypeString(requestPayload));
        requestProps.add("properties", getProperties(requestPayload));
        o.add("request", requestProps);
    }
    if (returnPayload != null) {
        JsonObjectBuilder returnProps = Json.createObjectBuilder();
        returnProps.add("isCollection", isCollection);
        returnProps.add("dataType", getTypeString(returnPayload));
        returnProps.add("properties", getProperties(returnPayload));
        o.add("response", returnProps);
    }
    return o.build();
}
Also used : JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder)

Example 82 with JsonArrayBuilder

use of javax.json.JsonArrayBuilder 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 83 with JsonArrayBuilder

use of javax.json.JsonArrayBuilder 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 84 with JsonArrayBuilder

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

the class ArrayTypeProcessor method processObject.

private JsonArray processObject(Object[] arrayObject) throws JsonException {
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    for (Object arrayItem : arrayObject) {
        TypeProcessor<?> processor = ProcessorFactory.getTypeProcessor(arrayItem);
        arrayBuilder.add(processor.processObject(arrayItem));
    }
    return arrayBuilder.build();
}
Also used : JsonArrayBuilder(javax.json.JsonArrayBuilder)

Example 85 with JsonArrayBuilder

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

the class Catalog method findBook.

@GET
@Produces(MediaType.APPLICATION_JSON)
@CrossOriginResourceSharing(allowAllOrigins = true)
@Path("/search")
public Response findBook(@Context SearchContext searchContext, @Context final UriInfo uri) throws IOException {
    final IndexReader reader = DirectoryReader.open(directory);
    final IndexSearcher searcher = new IndexSearcher(reader);
    final JsonArrayBuilder builder = Json.createArrayBuilder();
    try {
        visitor.reset();
        visitor.visit(searchContext.getCondition(SearchBean.class));
        final Query query = visitor.getQuery();
        if (query != null) {
            final TopDocs topDocs = searcher.search(query, 1000);
            for (final ScoreDoc scoreDoc : topDocs.scoreDocs) {
                final Document document = reader.document(scoreDoc.doc);
                final String source = document.getField(LuceneDocumentMetadata.SOURCE_FIELD).stringValue();
                builder.add(Json.createObjectBuilder().add("source", source).add("score", scoreDoc.score).add("url", uri.getBaseUriBuilder().path(Catalog.class).path(source).build().toString()));
            }
        }
        return Response.ok(builder.build()).build();
    } finally {
        reader.close();
    }
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) TopDocs(org.apache.lucene.search.TopDocs) Query(org.apache.lucene.search.Query) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TermQuery(org.apache.lucene.search.TermQuery) IndexReader(org.apache.lucene.index.IndexReader) SearchBean(org.apache.cxf.jaxrs.ext.search.SearchBean) JsonArrayBuilder(javax.json.JsonArrayBuilder) Document(org.apache.lucene.document.Document) ScoreDoc(org.apache.lucene.search.ScoreDoc) Path(javax.ws.rs.Path) CrossOriginResourceSharing(org.apache.cxf.rs.security.cors.CrossOriginResourceSharing) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

JsonArrayBuilder (javax.json.JsonArrayBuilder)177 JsonObjectBuilder (javax.json.JsonObjectBuilder)103 JsonObject (javax.json.JsonObject)36 Map (java.util.Map)29 Path (javax.ws.rs.Path)26 GET (javax.ws.rs.GET)24 HashMap (java.util.HashMap)19 JsonArray (javax.json.JsonArray)18 ArrayList (java.util.ArrayList)15 List (java.util.List)15 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)12 IOException (java.io.IOException)12 Dataverse (edu.harvard.iq.dataverse.Dataverse)10 Dataset (edu.harvard.iq.dataverse.Dataset)9 User (edu.harvard.iq.dataverse.authorization.users.User)9 JsonValue (javax.json.JsonValue)9 StringWriter (java.io.StringWriter)8 JsonString (javax.json.JsonString)7 Date (java.util.Date)6 JsonException (javax.json.JsonException)6