Search in sources :

Example 11 with JsonArrayBuilder

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

the class JsonRenderer method prettyPrint.

/**
     * Make a prettyprinted JSON text of this JSONObject.
     * <p>
     * Warning: This method assumes that the data structure is acyclical.
     * @return a printable, displayable, transmittable
     *  representation of the object, beginning
     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     *  with <code>}</code>&nbsp;<small>(right brace)</small>.
     * @throws IllegalArgumentException If the object contains an invalid number.
     */
public String prettyPrint(JsonObject jo, Options opt) {
    int n = jo.size();
    if (n == 0) {
        return "{}";
    }
    final JsonArrayBuilder children = Json.createArrayBuilder();
    Iterator<String> keys = jo.keySet().iterator();
    StringBuilder sb = new StringBuilder("{");
    int newindent = opt.initialIndent + opt.indent;
    String o;
    if (n == 1) {
        o = keys.next();
        final Object v = jo.get(o);
        if (!skipChildObject(children, opt, o, v)) {
            sb.append(quote(o));
            sb.append(": ");
            sb.append(valueToString(v, opt));
        }
    } else {
        while (keys.hasNext()) {
            o = keys.next();
            final Object v = jo.get(o);
            if (skipChildObject(children, opt, o, v)) {
                continue;
            }
            if (sb.length() > 1) {
                sb.append(",\n");
            } else {
                sb.append('\n');
            }
            indent(sb, newindent);
            sb.append(quote(o.toString()));
            sb.append(": ");
            sb.append(valueToString(v, options().withIndent(opt.indent).withInitialIndent(newindent)));
        }
        if (sb.length() > 1) {
            sb.append('\n');
            indent(sb, newindent);
        }
    }
    /** Render children if any were skipped (in "children in arrays" mode) */
    JsonArray childrenArray = children.build();
    if (childrenArray.size() > 0) {
        if (sb.length() > 1) {
            sb.append(",\n");
        } else {
            sb.append('\n');
        }
        final Options childOpt = new Options(opt);
        childOpt.withInitialIndent(childOpt.initialIndent + newindent);
        indent(sb, childOpt.initialIndent);
        sb.append(quote(opt.childrenKey)).append(":");
        sb.append(prettyPrint(childrenArray, childOpt));
    }
    sb.append('}');
    return sb.toString();
}
Also used : JsonArray(javax.json.JsonArray) JsonObject(javax.json.JsonObject) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonString(javax.json.JsonString)

Example 12 with JsonArrayBuilder

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

the class JSONResponse method getJson.

JsonObject getJson() {
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    for (Map.Entry<String, Object> entry : json.entrySet()) {
        if (entry.getValue() != null) {
            jsonBuilder.add(entry.getKey(), entry.getValue().toString());
        } else {
            jsonBuilder.addNull(entry.getKey());
        }
    }
    if (this.error != null) {
        jsonBuilder.add("error", Json.createObjectBuilder().add("class", error.getClass().getName()).add("message", error.getMessage()));
    }
    JsonArrayBuilder changesBuilder = Json.createArrayBuilder();
    for (Map<String, Object> entry : changes) {
        JsonObjectBuilder entryBuilder = Json.createObjectBuilder();
        entryBuilder.add(PROP_TYPE, (String) entry.get(PROP_TYPE));
        Object arguments = entry.get(PROP_ARGUMENT);
        if (arguments != null) {
            if (arguments instanceof List) {
                JsonArrayBuilder argumentsBuilder = Json.createArrayBuilder();
                for (String argument : ((List<String>) arguments)) {
                    argumentsBuilder.add(argument);
                }
                entryBuilder.add(PROP_ARGUMENT, argumentsBuilder);
            } else {
                entryBuilder.add(PROP_ARGUMENT, (String) arguments);
            }
        }
        changesBuilder.add(entryBuilder);
    }
    jsonBuilder.add(PROP_CHANGES, changesBuilder);
    return jsonBuilder.build();
}
Also used : JsonObject(javax.json.JsonObject) List(java.util.List) ArrayList(java.util.ArrayList) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Map(java.util.Map) HashMap(java.util.HashMap)

Example 13 with JsonArrayBuilder

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

the class JsonObjectCreator method createProperty.

/**
     * Write a single property
     */
private static void createProperty(final JsonObjectBuilder obj, final ValueMap valueMap, final String key, final Object value) {
    Object[] values = null;
    if (value.getClass().isArray()) {
        if (value instanceof long[]) {
            values = ArrayUtils.toObject((long[]) value);
        } else if (value instanceof int[]) {
            values = ArrayUtils.toObject((int[]) value);
        } else if (value instanceof double[]) {
            values = ArrayUtils.toObject((double[]) value);
        } else if (value instanceof byte[]) {
            values = ArrayUtils.toObject((byte[]) value);
        } else if (value instanceof float[]) {
            values = ArrayUtils.toObject((float[]) value);
        } else if (value instanceof short[]) {
            values = ArrayUtils.toObject((short[]) value);
        } else if (value instanceof long[]) {
            values = ArrayUtils.toObject((long[]) value);
        } else if (value instanceof boolean[]) {
            values = ArrayUtils.toObject((boolean[]) value);
        } else if (value instanceof char[]) {
            values = ArrayUtils.toObject((char[]) value);
        } else {
            values = (Object[]) value;
        }
        // write out empty array
        if (values.length == 0) {
            obj.add(key, Json.createArrayBuilder());
            return;
        }
    }
    // special handling for binaries: we dump the length and not the data!
    if (value instanceof InputStream || (values != null && values[0] instanceof InputStream)) {
        // in the name, and the value should be the size of the binary data
        try {
            if (values == null) {
                obj.add(":" + key, getLength(valueMap, -1, key, (InputStream) value));
            } else {
                final JsonArrayBuilder result = Json.createArrayBuilder();
                for (int i = 0; i < values.length; i++) {
                    result.add(getLength(valueMap, i, key, (InputStream) values[i]));
                }
                obj.add(":" + key, result);
            }
        } catch (final JsonException ignore) {
            // we ignore this
            LoggerFactory.getLogger(JsonObjectCreator.class).warn("Unable to create JSON value", ignore);
        }
        return;
    }
    try {
        if (!value.getClass().isArray()) {
            obj.add(key, getValue(value));
        } else {
            final JsonArrayBuilder result = Json.createArrayBuilder();
            for (Object v : values) {
                result.add(getValue(v));
            }
            obj.add(key, result);
        }
    } catch (final JsonException ignore) {
        // we ignore this
        LoggerFactory.getLogger(JsonObjectCreator.class).warn("Unable to create JSON value", ignore);
    }
}
Also used : JsonException(javax.json.JsonException) InputStream(java.io.InputStream) JsonObject(javax.json.JsonObject) JsonArrayBuilder(javax.json.JsonArrayBuilder)

Example 14 with JsonArrayBuilder

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

the class CatalogStore method scan.

public JsonArray scan() throws IOException {
    final JsonArrayBuilder builder = Json.createArrayBuilder();
    try (Table table = connection.getTable(TableName.valueOf(tableName))) {
        final Scan scan = new Scan();
        final ResultScanner results = table.getScanner(scan);
        for (final Result result : results) {
            final Cell cell = result.getColumnLatestCell(Bytes.toBytes("c"), Bytes.toBytes("title"));
            builder.add(Json.createObjectBuilder().add("id", Bytes.toString(CellUtil.cloneRow(cell))).add("title", Bytes.toString(CellUtil.cloneValue(cell))));
        }
    }
    return builder.build();
}
Also used : Table(org.apache.hadoop.hbase.client.Table) ResultScanner(org.apache.hadoop.hbase.client.ResultScanner) Scan(org.apache.hadoop.hbase.client.Scan) JsonArrayBuilder(javax.json.JsonArrayBuilder) Cell(org.apache.hadoop.hbase.Cell) Result(org.apache.hadoop.hbase.client.Result)

Example 15 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) 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 state
        healthCheckObject.add("name", healthCheckResponse.getName());
        healthCheckObject.add("state", healthCheckResponse.getState().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.getState().equals(HealthCheckResponse.State.DOWN)) {
            httpResponse.setStatus(503);
        }
    }
    // Create the final aggregate object
    JsonObjectBuilder responseObject = Json.createObjectBuilder();
    // Set the aggregate outcome
    if (httpResponse.getStatus() == 200) {
        responseObject.add("outcome", "UP");
    } else {
        responseObject.add("outcome", "DOWN");
    }
    // Add all of the checks
    responseObject.add("checks", checksArray);
    // Print the outcome
    httpResponse.getOutputStream().print(responseObject.build().toString());
}
Also used : HealthCheckResponse(org.eclipse.microprofile.health.HealthCheckResponse) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map)

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