Example usage for javax.json JsonArrayBuilder add

List of usage examples for javax.json JsonArrayBuilder add

Introduction

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

Prototype

JsonArrayBuilder add(JsonArrayBuilder builder);

Source Link

Document

Adds a JsonArray from an array builder to the array.

Usage

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

@GET
@Produces(MediaType.APPLICATION_JSON)//from   w  w w  .jav a 2 s . c o m
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.openlmis.converter.FileArrayTypeConverter.java

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    List<String> codes = getArrayValues(value);
    String by = getBy(mapping.getType());

    String parent = configuration.getDirectory();
    String inputFileName = new File(parent, mapping.getEntityName()).getAbsolutePath();
    List<Map<String, String>> csvs = reader.readFromFile(new File(inputFileName));
    csvs.removeIf(map -> !codes.contains(map.get(by)));

    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();

    if (!csvs.isEmpty()) {
        String mappingFileName = inputFileName.replace(".csv", "_mapping.csv");
        List<Mapping> mappings = mappingConverter.getMappingForFile(new File(mappingFileName));

        for (Map<String, String> csv : csvs) {
            String json = converter.convert(csv, mappings).toString();

            try (JsonReader jsonReader = Json.createReader(new StringReader(json))) {
                arrayBuilder.add(jsonReader.readObject());
            }// w  w w  .ja v  a  2  s .c o  m
        }
    }

    builder.add(mapping.getTo(), arrayBuilder);
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImpl.java

@Nonnull
@Override//from   w  w  w. ja v  a2 s . c  o m
public String getEditorJSON() {
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    jsonObjectBuilder.add("title", fragment.getTitle());
    jsonObjectBuilder.add("path", path);
    if (variationName != null) {
        jsonObjectBuilder.add("variation", variationName);
    }
    if (elementNames != null) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (String ele : elementNames) {
            arrayBuilder.add(ele);
        }
        jsonObjectBuilder.add("elements", arrayBuilder);
    }
    Iterator<Resource> associatedContentIter = fragment.getAssociatedContent();
    if (associatedContentIter.hasNext()) {
        JsonArrayBuilder associatedContentArray = Json.createArrayBuilder();
        while (associatedContentIter.hasNext()) {
            Resource resource = associatedContentIter.next();
            ValueMap vm = resource.adaptTo(ValueMap.class);
            JsonObjectBuilder contentObject = Json.createObjectBuilder();
            if (vm != null && vm.containsKey(JCR_TITLE)) {
                contentObject.add("title", vm.get(JCR_TITLE, String.class));
            }
            contentObject.add("path", resource.getPath());
            associatedContentArray.add(contentObject);
        }
        jsonObjectBuilder.add("associatedContent", associatedContentArray);
    }
    return jsonObjectBuilder.build().toString();
}

From source file:com.product.ProductResource.java

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)//from w  w w .  j av  a 2  s .c  o  m
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: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   ww  w.  j  a  v a  2 s. c  o m
                "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:no.sintef.jarfter.PostgresqlInteractor.java

public JsonObject selectAll_havahol(String filter_h_id) throws SQLException {
    checkConnection();/* w w  w  .  j a v a 2s.co m*/

    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:com.assignment4.productdetails.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *///from   w  ww . j a  v a 2s. com
@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:edu.harvard.iq.dataverse.mydata.RoleTagRetriever.java

public JsonArrayBuilder getRolesForCardAsJSON(Long dvObjectId) {
    if (!this.hasRolesForCard(dvObjectId)) {
        return null;
    }//from  w ww .  j  av  a2s.  c  om

    JsonArrayBuilder jsonArray = Json.createArrayBuilder();

    for (String roleName : this.finalIdToRolesHash.get(dvObjectId)) {
        jsonArray.add(roleName);
    }
    return jsonArray;
}

From source file:searcher.CollStat.java

public String constructJSONForRetrievedSet(HashMap<Integer, Integer> indexOrder, String queryStr,
        ScoreDoc[] hits, int indexNum, int pageNum, int[] selection) throws Exception {

    System.out.println("Num Retrieved = " + hits.length);

    Query query = buildQuery(queryStr);

    IndexReader reader = multiReader != null ? multiReader : getReaderInOrder(indexOrder, indexNum);
    JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
    JsonObjectBuilder objectBuilder = factory.createObjectBuilder();

    if (selection != null) {
        for (int i : selection) {
            if (0 <= i && i < hits.length) {
                ScoreDoc hit = hits[i];//from w  w  w . j  a  v a2  s .c o m
                arrayBuilder.add(constructJSONForDoc(reader, query, hit.doc));
            }
        }
    } else {

        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;
        if (start < 0) {
            start = 0;
        }
        if (end >= hits.length) {
            end = hits.length;
        }

        int hasMore = end < hits.length ? 1 : 0;
        for (int i = start; i < end; i++) {
            ScoreDoc hit = hits[i];
            arrayBuilder.add(constructJSONForDoc(reader, query, hit.doc));
        }
        // append the hasMore flag and the number of hits for this query...
        objectBuilder.add("hasmore", hasMore);

    }

    objectBuilder.add("numhits", hits.length);
    arrayBuilder.add(objectBuilder);

    return arrayBuilder.build().toString();
}

From source file:edu.harvard.iq.dataverse.mydata.MyDataFinder.java

/**
 * "publication_statuses" : [ name 1, name 2, etc.]
 * //from   w  w w  .j av a  2 s  . c om
 * @return 
 */
public JsonArrayBuilder getListofSelectedRoles() {

    JsonArrayBuilder jsonArray = Json.createArrayBuilder();

    for (Long roleId : this.filterParams.getRoleIds()) {
        jsonArray.add(this.rolePermissionHelper.getRoleName(roleId));
    }
    return jsonArray;
}