Example usage for javax.json JsonArrayBuilder build

List of usage examples for javax.json JsonArrayBuilder build

Introduction

In this page you can find the example usage for javax.json JsonArrayBuilder build.

Prototype

JsonArray build();

Source Link

Document

Returns the current array.

Usage

From source file:webservice.restful.creditcard.CreditCardAuthorizationService.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from  w ww  .j  a v a  2s.com*/
public JsonArray getStringList(@QueryParam("accountNumber") String accountNumber) {
    System.out.println("Getting String list with account number:" + accountNumber);
    JsonArrayBuilder arrayBld = Json.createArrayBuilder();
    List<String> strList = new ArrayList<>();
    strList.add("test 1");
    strList.add("test 2");
    strList.add("test 3");
    strList.add("test 4");
    strList.add("test 5");
    for (String str : strList) {
        arrayBld.add(str);
    }

    return arrayBld.build();
}

From source file:org.bsc.confluence.rest.AbstractRESTConfluenceService.java

/**
 *
 * @param inputData//  w w  w  . j  a va2s  .  c  o m
 * @return
 */
protected final void rxAddLabels(String id, String... labels) {

    final JsonArrayBuilder inputBuilder = Json.createArrayBuilder();

    for (String name : labels) {

        inputBuilder.add(Json.createObjectBuilder().add("prefix", "global").add("name", name));

    }

    final JsonArray inputData = inputBuilder.build();

    final MediaType storageFormat = MediaType.parse("application/json");

    final RequestBody inputBody = RequestBody.create(storageFormat, inputData.toString());

    final HttpUrl url = urlBuilder().addPathSegment("content").addPathSegment(id).addPathSegment("label")
            .build();

    fromUrlPOST(url, inputBody, "add label");
}

From source file:searcher.CollStat.java

public String constructJSONForRetrievedSet(IndexReader reader, Query q, ScoreDoc[] hits) throws Exception {
    JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();

    for (ScoreDoc hit : hits) {
        arrayBuilder.add(constructJSONForDoc(reader, q, hit.doc));
    }/*from  w  w  w  .  j  av  a2 s . c om*/
    return arrayBuilder.build().toString();
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAIdentity.java

private JsonObject idToJsonObject() {
    JsonObjectBuilder ob = Json.createObjectBuilder();
    ob.add("id", enrollmentID);
    ob.add("type", type);
    if (null != maxEnrollments) {
        ob.add("max_enrollments", maxEnrollments);
    }//from   w  w  w .java2s  .com
    if (affiliation != null) {
        ob.add("affiliation", affiliation);
    }
    JsonArrayBuilder ab = Json.createArrayBuilder();
    for (Attribute attr : attrs) {
        ab.add(attr.toJsonObject());
    }
    ob.add("attrs", ab.build());
    if (this.secret != null) {
        ob.add("secret", secret);
    }
    if (client.getCAName() != null) {
        ob.add(HFCAClient.FABRIC_CA_REQPROP, client.getCAName());
    }
    return ob.build();
}

From source file:com.product.ProductResource.java

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)/*  ww  w.j ava 2s  .c om*/
public String getproduct(@PathParam("id") int id) throws SQLException {

    if (conn == null) {
        return "not connected";
    } else {
        String query = "Select * from product where product_id = ?";
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, id);
        ResultSet rs = pstmt.executeQuery();
        String result = "";
        JsonArrayBuilder productArr = Json.createArrayBuilder();
        while (rs.next()) {
            JsonObjectBuilder prodMap = Json.createObjectBuilder();
            prodMap.add("productID", rs.getInt("product_id"));
            prodMap.add("name", rs.getString("name"));
            prodMap.add("description", rs.getString("description"));
            prodMap.add("quantity", rs.getInt("quantity"));
            productArr.add(prodMap);
        }
        result = productArr.build().toString();

        return result;
    }

}

From source file:com.open.shift.support.controller.SupportResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from   w w w  . j  a  va  2 s  .c  o  m
@Path("piechart")
public JsonObject generatePieChart() throws Exception {
    URL u = ctx.getResource("/WEB-INF/classes/templates/pie.json");
    String pieJson = null;
    if (OS.indexOf("win") >= 0) {
        pieJson = u.toString().substring(6);
    } else if (OS.indexOf("nux") >= 0) {
        pieJson = u.toString().substring(5);
    }

    JsonReader reader = Json.createReader(new FileReader(pieJson));
    JsonObject main = reader.readObject();
    JsonObjectBuilder title = Json.createObjectBuilder().add("text", "Companies Contribution in Deposits");
    JsonArrayBuilder data = Json.createArrayBuilder().add(Json.createArrayBuilder().add("Infosys").add(45.0))
            .add(Json.createArrayBuilder().add("TCS").add(26.8))
            .add(Json.createArrayBuilder().add("Oracle").add(8.5))
            .add(Json.createArrayBuilder().add("Accenture").add(6.2)).add(Json.createObjectBuilder()
                    .add("name", "IBM").add("y", 12.8).add("sliced", true).add("selected", true));
    JsonArrayBuilder series = Json.createArrayBuilder().add(
            Json.createObjectBuilder().add("type", "pie").add("name", "Deposit Contributed").add("data", data));

    JsonObjectBuilder mainJsonObj = Json.createObjectBuilder();
    for (Map.Entry<String, JsonValue> entrySet : main.entrySet()) {
        String key = entrySet.getKey();
        JsonValue value = entrySet.getValue();
        mainJsonObj.add(key, value);
    }
    mainJsonObj.add("title", title.build()).add("series", series.build());

    return mainJsonObj.build();
}

From source file:com.assignment4.productdetails.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *//*  ww w.  j a  v a2s .c  om*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (conn == null) {
        return "it is not connected";
    } else {
        String query = "Select * from products";
        PreparedStatement pstmt = conn.prepareStatement(query);
        ResultSet res = pstmt.executeQuery();
        String results = "";
        JsonArrayBuilder podtAr = Json.createArrayBuilder();
        while (res.next()) {
            // Map pdtmap = new LinkedHashMap();
            JsonObjectBuilder obj = Json.createObjectBuilder();//using json object for using json api
            obj.add("productID", res.getInt("product_id"));
            obj.add("name", res.getString("name"));
            obj.add("description", res.getString("description"));
            obj.add("quantity", res.getInt("quantity"));
            podtAr.add(obj);
        }
        results = podtAr.build().toString();
        return results.replace("},", "},\n");
    }

}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public JsonObject selectAll_havahol(String filter_h_id) throws SQLException {
    checkConnection();//from   w ww.  jav  a  2s . c om

    String h_id = "h_id";
    String visual_name = "visual_name";
    String file = "file";
    PreparedStatement st = conn.prepareStatement("SELECT h_id, visual_name FROM havahol WHERE h_id ~ ?;");
    if (filter_h_id == null) {
        st.setString(1, ".*");
    } else {
        st.setString(1, filter_h_id);
    }
    ResultSet rs = st.executeQuery();
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    while (rs.next()) {
        JsonObjectBuilder job = Json.createObjectBuilder();
        job.add(h_id, rs.getString(h_id));
        job.add(visual_name, rs.getString(visual_name));

        jsonArrayBuilder.add(job.build());
    }

    rs.close();
    st.close();
    return Json.createObjectBuilder().add("havahol", jsonArrayBuilder.build()).build();
}

From source file:org.apache.nifi.reporting.SiteToSiteProvenanceReportingTask.java

@Override
public void onTrigger(final ReportingContext context) {
    final boolean isClustered = context.isClustered();
    final String nodeId = context.getClusterNodeIdentifier();
    if (nodeId == null && isClustered) {
        getLogger().debug(/*from  w w  w .  j  a va  2s  . c  om*/
                "This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. "
                        + "Will wait for Node Identifier to be established.");
        return;
    }

    final ProcessGroupStatus procGroupStatus = context.getEventAccess().getControllerStatus();
    final String rootGroupName = procGroupStatus == null ? null : procGroupStatus.getName();
    final Map<String, String> componentMap = createComponentMap(procGroupStatus);

    final String nifiUrl = context.getProperty(INSTANCE_URL).evaluateAttributeExpressions().getValue();
    URL url;
    try {
        url = new URL(nifiUrl);
    } catch (final MalformedURLException e1) {
        // already validated
        throw new AssertionError();
    }

    final String hostname = url.getHost();
    final String platform = context.getProperty(PLATFORM).evaluateAttributeExpressions().getValue();

    final Map<String, ?> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();

    final DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("Z"));

    consumer.consumeEvents(context.getEventAccess(), context.getStateManager(), events -> {
        final long start = System.nanoTime();
        // Create a JSON array of all the events in the current batch
        final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
        for (final ProvenanceEventRecord event : events) {
            final String componentName = componentMap.get(event.getComponentId());
            arrayBuilder.add(serialize(factory, builder, event, df, componentName, hostname, url, rootGroupName,
                    platform, nodeId));
        }
        final JsonArray jsonArray = arrayBuilder.build();

        // Send the JSON document for the current batch
        try {
            final Transaction transaction = getClient().createTransaction(TransferDirection.SEND);
            if (transaction == null) {
                getLogger().debug("All destination nodes are penalized; will attempt to send data later");
                return;
            }

            final Map<String, String> attributes = new HashMap<>();
            final String transactionId = UUID.randomUUID().toString();
            attributes.put("reporting.task.transaction.id", transactionId);
            attributes.put("mime.type", "application/json");

            final byte[] data = jsonArray.toString().getBytes(StandardCharsets.UTF_8);
            transaction.send(data, attributes);
            transaction.confirm();
            transaction.complete();

            final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
            getLogger().info(
                    "Successfully sent {} Provenance Events to destination in {} ms; Transaction ID = {}; First Event ID = {}",
                    new Object[] { events.size(), transferMillis, transactionId, events.get(0).getEventId() });
        } catch (final IOException e) {
            throw new ProcessException(
                    "Failed to send Provenance Events to destination due to IOException:" + e.getMessage(), e);
        }
    });

}

From source file:searcher.CollStat.java

JsonArray constructJSONForDoc(IndexReader reader, Query q, int docid) throws Exception {
    Document doc = reader.document(docid);

    JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
    JsonObjectBuilder objectBuilder = factory.createObjectBuilder();
    objectBuilder.add("title", doc.get(WTDocument.WTDOC_FIELD_TITLE));
    objectBuilder.add("snippet", getSnippet(q, doc, docid));
    objectBuilder.add("id", doc.get(TrecDocIndexer.FIELD_ID));
    objectBuilder.add("url", doc.get(WTDocument.WTDOC_FIELD_URL));
    //objectBuilder.add("html", getBase64EncodedHTML(doc));
    arrayBuilder.add(objectBuilder);//from  w w w  . j a va 2 s.c om
    return arrayBuilder.build();
}