Example usage for javax.json JsonArray size

List of usage examples for javax.json JsonArray size

Introduction

In this page you can find the example usage for javax.json JsonArray size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

private static void buildOrderItems(final Builder b, final JsonArray json) throws JetException {
    if (json == null)
        return;/*from  ww w. ja  va 2s .  c o  m*/

    final List<OrderItemRec> l = new ArrayList<>();

    for (int i = 0; i < json.size(); i++) {
        l.add(OrderItemRec.fromJson(json.getJsonObject(i)));
    }

    b.setOrderItems(l);
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java

private Result convertJsonArrayToResultSet(JsonArray exacJSONResults, Result result) {

    FileResultSet mrs = (FileResultSet) result.getData();
    try {//from  ww w  .  j  a  v a2s  .  c  o m
        if (exacJSONResults.size() == 0) {
            result.setData(mrs);
            return result;
        }
        // Setup columns
        JsonObject columnObject = (JsonObject) exacJSONResults.get(0);

        List<String> fields = getNames("", columnObject);
        for (String field : fields) {
            Column column = new Column();
            column.setName(field);
            column.setDataType(PrimitiveDataType.STRING);
            mrs.appendColumn(column);
        }

        // Add data
        for (JsonValue val : exacJSONResults) {
            JsonObject obj = (JsonObject) val;
            mrs.appendRow();
            for (String field : fields) {
                mrs.updateString(field, getValue(obj, field));
            }
        }
    } catch (ResultSetException | PersistableException e) {
        e.printStackTrace();
    }

    result.setData(mrs);
    return result;
}

From source file:org.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Recursively read out all key/values from this etcd JSON array.
 *
 * @param result map with key, values and metadata.
 * @param node   the node to parse./*from  w  w  w .j  a  v  a2 s .  c o  m*/
 */
private void addNodes(Map<String, String> result, JsonObject node) {
    if (!node.containsKey("dir") || "false".equals(node.get("dir").toString())) {
        final String key = node.getString("key").substring(1);
        result.put(key, node.getString("value"));
        if (node.containsKey("createdIndex")) {
            result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex")));
        }
        if (node.containsKey("modifiedIndex")) {
            result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex")));
        }
        if (node.containsKey("expiration")) {
            result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration")));
        }
        if (node.containsKey("ttl")) {
            result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl")));
        }
        result.put("_" + key + ".source", "[etcd]" + serverURL);
    } else {
        final JsonArray nodes = node.getJsonArray("nodes");
        if (nodes != null) {
            for (int i = 0; i < nodes.size(); i++) {
                addNodes(result, nodes.getJsonObject(i));
            }
        }
    }
}

From source file:io.hops.hopsworks.common.util.WebCommunication.java

public List<NodesTableItem> getNdbinfoNodesTable(String hostAddress, String agentPassword)
        throws GenericException {
    List<NodesTableItem> resultList = new ArrayList<NodesTableItem>();

    String url = createUrl("mysql", hostAddress, "ndbinfo", "nodes");
    String jsonString = fetchContent(url, agentPassword);
    InputStream stream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
    try {/*from   www  .  j  a  v  a  2  s.  co m*/
        JsonArray json = Json.createReader(stream).readArray();
        if (json.get(0).equals("Error")) {
            resultList.add(new NodesTableItem(null, json.getString(1), null, null, null));
            return resultList;
        }
        for (int i = 0; i < json.size(); i++) {
            JsonArray node = json.getJsonArray(i);
            Integer nodeId = node.getInt(0);
            Long uptime = node.getJsonNumber(1).longValue();
            String status = node.getString(2);
            Integer startPhase = node.getInt(3);
            Integer configGeneration = node.getInt(4);
            resultList.add(new NodesTableItem(nodeId, status, uptime, startPhase, configGeneration));
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception: {0}", ex);
        resultList.add(new NodesTableItem(null, "Error", null, null, null));
    }
    return resultList;
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets a list of all the posted ballots of the given election form the bulletin board and returns it
 * @param election//from w ww.  j  av  a  2s .c o m
 * Election for which the list of ballots should be retrieved 
 * @return 
 * the list of all posted ballots to the given election
 */
public List<Ballot> getBallotsByElection(Election election) {
    List<Ballot> ballots = new ArrayList<Ballot>();
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + election.getId() + "/ballots");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //transforms the recieved json string into a list of ballot objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            LocalDateTime timeStamp = LocalDateTime.parse(result.getString("timestamp"), format);

            JsonObject jsonData = result.getJsonObject("jsonData");
            List<String> selectedOptions = new ArrayList<String>();
            JsonArray optionsArray = jsonData.getJsonArray("e");
            for (int i = 0; i < optionsArray.size(); i++) {
                selectedOptions.add(optionsArray.getString(i));
            }
            String u_HatString = jsonData.getString("u_Hat");
            String cString = jsonData.getString("c");
            String dString = jsonData.getString("d");
            String pi1String = jsonData.getString("pi1");
            String pi2String = jsonData.getString("pi2");
            String pi3String = jsonData.getString("pi3");
            //create ballot object and add it to the list
            Ballot ballot = new Ballot(id, election, selectedOptions, u_HatString, cString, dString, pi1String,
                    pi2String, pi3String, timeStamp);
            System.out.println(ballot.isValid());
            ballots.add(ballot);
        }

    } catch (IOException x) {
        System.err.println(x);
    }
    return ballots;

}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets the information for the given ElectionID from the bulletin board and returns it as a election object
 * @param electionId/*  w  w w.  j av  a 2 s  .co m*/
 * the identifier (id) for the desired election
 * @return returns tje election object for a given id
 */
public Election getElectionById(int electionId) {
    Election election = null;
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + electionId);

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Parameters parameters = this.getParameters();

        //gets the json string and transforms it into a election object

        //translates the header information of the election
        String title = obj.getString("electionTitle");
        LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format);
        LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format);
        String appVersion = obj.getString("appVersion");
        String coefficientsString = obj.getString("coefficients");
        String h_HatString = obj.getString("electionGenerator");
        List<Voter> voterlist = new ArrayList<Voter>();

        //get th list of voters
        for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) {

            String voterEmail = result.getString("email");
            String voterPublicCredential = result.getString("publicCredential");
            String voterAppVersion = result.getString("appVersion");

            Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion);
            voterlist.add(voter);
        }
        //get the votingTopic
        JsonObject electionTopicObj = obj.getJsonObject("votingTopic");

        String topic = electionTopicObj.getString("topic");
        int pick = electionTopicObj.getInt("pick");

        ElectionTopic electionTopic = new ElectionTopic(topic, pick);
        JsonArray optionsArray = electionTopicObj.getJsonArray("options");
        for (int i = 0; i < optionsArray.size(); i++) {
            electionTopic.addOption(optionsArray.getString(i));
        }

        election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic,
                appVersion, h_HatString, coefficientsString);

    } catch (IOException x) {
        System.err.println(x);
    }
    return election;
}

From source file:com.oncore.calorders.rest.service.extension.OrderHistoryFacadeRESTExtension.java

/**
 * Creates an order, containing the ordered products and related services.
 *
 * @param orderjson The order, represented as a JSON string
 * @throws DataAccessException//ww w . j a  v a  2  s .  c o  m
 */
@POST
@Path("createOrder")
@Consumes({ MediaType.APPLICATION_JSON })
public void createOrder(String orderjson) throws DataAccessException {

    try {
        JsonReader reader = Json.createReader(new StringReader(orderjson));
        JsonObject orderObject = reader.readObject();
        reader.close();

        OrderHistory order = new OrderHistory();

        order.setUpdateTs(new Date());
        order.setUpdateUserId(orderObject.getString("updateUserId", null));
        order.setCreateTs(new Date());
        order.setCreateUserId(orderObject.getString("createUserId", null));

        OrdStatusCd ordStatusCd = this.ordStatusCdFacadeREST.find(orderObject.getString("orderStatusCd", null));

        if (ordStatusCd == null) {
            throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString());
        } else {
            order.setOrdStatusCd(ordStatusCd);
        }

        Party party = this.partyFacadeRESTExtension.find(Integer.valueOf(orderObject.getString("partyUid")));

        if (party == null) {
            throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString());
        } else {
            order.setPtyUidFk(party);

            order.setDepUidFk(
                    party.getGroupPartyAssocCollection().iterator().next().getGrpUidFk().getDepUidFk());
        }

        order.setOrderProductAssocCollection(new ArrayList<OrderProductAssoc>());

        JsonArray productList = orderObject.getJsonArray("products");

        for (int i = 0; i < productList.size(); i++) {
            JsonObject productObject = productList.getJsonObject(i);
            OrderProductAssoc orderProductAssoc = new OrderProductAssoc();

            Product product = this.productFacadeRESTExtension.find(productObject.getInt("prdUid"));

            orderProductAssoc.setPrdUidFk(product);
            orderProductAssoc.setOrdUidFk(order);
            orderProductAssoc.setUpdateTs(new Date());
            orderProductAssoc.setUpdateUserId(productObject.getString("updateUserId", null));
            orderProductAssoc.setCreateTs(new Date());
            orderProductAssoc.setCreateUserId(productObject.getString("createUserId", null));
            orderProductAssoc.setOpaQuantity(productObject.getInt("quantity"));
            orderProductAssoc.setOpaPrice(product.getPrdCntrUnitPrice()
                    .multiply(BigDecimal.valueOf(productObject.getInt("quantity"))));

            order.getOrderProductAssocCollection().add(orderProductAssoc);
        }

        super.create(order);
    } catch (Exception ex) {
        Logger.error(LOG, FormatHelper.getStackTrace(ex));
        throw new DataAccessException(ex, ErrorCode.DATAACCESSERROR);
    }

}

From source file:com.buffalokiwi.aerodrome.jet.JetAPI.java

/**
 * Turn a jet api response into a list of tokens 
 * @param a Json array //from   w ww  . j av a  2  s. co m
 * @param includePath Toggle including the entire uri or only the rightmost
 * part.
 * @return tokens 
 */
protected List<String> jsonArrayToTokenList(final JsonArray a, final boolean includePath) {
    final List<String> out = new ArrayList<>();

    if (a != null) {
        for (int i = 0; i < a.size(); i++) {
            out.add(processTokenPath(a.getString(i, ""), includePath));
        }
    }

    return out;
}

From source file:com.floreantpos.ui.views.payment.SettleTicketDialog.java

public void submitMyKalaDiscount() {
    if (ticket.hasProperty(LOYALTY_ID)) {
        POSMessageDialog.showError(Application.getPosWindow(), Messages.getString("SettleTicketDialog.18")); //$NON-NLS-1$
        return;/*from  w  ww.  j  a  v a2  s.  c  o m*/
    }

    try {
        String loyaltyid = JOptionPane.showInputDialog(Messages.getString("SettleTicketDialog.19")); //$NON-NLS-1$

        if (StringUtils.isEmpty(loyaltyid)) {
            return;
        }

        ticket.addProperty(LOYALTY_ID, loyaltyid);

        String transactionURL = buildLoyaltyApiURL(ticket, loyaltyid);

        String string = IOUtils.toString(new URL(transactionURL).openStream());

        JsonReader reader = Json.createReader(new StringReader(string));
        JsonObject object = reader.readObject();
        JsonArray jsonArray = (JsonArray) object.get("discounts"); //$NON-NLS-1$
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            addCoupon(ticket, jsonObject);
        }

        updateModel();

        OrderController.saveOrder(ticket);

        POSMessageDialog.showMessage(Application.getPosWindow(), Messages.getString("SettleTicketDialog.21")); //$NON-NLS-1$
        paymentView.updateView();
    } catch (Exception e) {
        POSMessageDialog.showError(Application.getPosWindow(), Messages.getString("SettleTicketDialog.22"), e); //$NON-NLS-1$
    }
}

From source file:httputils.RavelloHttpClient.java

public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay,
        String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized)
        throws RavelloException, InterruptedException {
    JsonObject value = null;/*from   w  w  w  . ja v a  2  s .com*/
    HttpResponse response = null;

    try {
        response = this.getBlueprint(blueprintId);
        if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: "
                    + response.getStatusLine().toString());
        }
        JsonObject vmTemp = HttpUtil.convertResponseToJson(response);
        EntityUtils.consume(response.getEntity());

        JsonBuilderFactory factory = Json.createBuilderFactory(null);
        Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator();
        JsonObjectBuilder builder = factory.createObjectBuilder();
        Map.Entry<String, JsonValue> ent;
        while (it.hasNext()) {
            ent = it.next();
            if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) {
                builder.add(ent.getKey(), ent.getValue());
            }
        }
        builder.add("name", applicationName);
        value = builder.build();
        vmTemp = null;

        response = this.createApplication(value);
        this.verifyResponseAndConsume(response, "Failed to create application - error: ");

        value = HttpUtil.convertResponseToJson(response);
        EntityUtils.consumeQuietly(response.getEntity());

        int appId = value.getInt("id");

        if (costOptimized) {
            value = factory.createObjectBuilder().add("startAllVms", startAllVms).build();
        } else {
            value = factory.createObjectBuilder().add("startAllVms", startAllVms)
                    .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion)
                    .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build();
        }
        response = this.post("/applications/" + appId + "/publish", value);
        this.verifyResponseAndConsume(response, "Failed to publish application - error: ");

        value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build();
        response = this.post("/applications/" + appId + "/setExpiration", value);
        if (!HttpUtil.verifyResponseAndConsume(response)) {
            throw new RavelloException("Failed to set expiration time for application - error: "
                    + response.getStatusLine().toString() + "\n"
                    + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED");
        }

        if (!startAllVms) {
            response = this.getApplication(appId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException(
                        "Failed to get application status - error: " + response.getStatusLine().toString());
            }
            value = HttpUtil.convertResponseToJson(response);

            return value;
        }

        String state;
        JsonArray jArr;
        boolean allStarted;
        while (true) {
            allStarted = true;
            response = this.getApplication(appId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException(
                        "Failed to get application status - error: " + response.getStatusLine().toString());
            }
            value = HttpUtil.convertResponseToJson(response);

            jArr = value.getJsonObject("deployment").getJsonArray("vms");
            for (int jt = 0; jt < jArr.size(); jt++) {
                state = jArr.getJsonObject(jt).getString("state");
                allStarted = state.equals("STARTED");
                if (state.equals("ERROR")) {
                    throw new RavelloException(
                            "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start");
                }
                if (!allStarted) {
                    break;
                }
            }

            if (allStarted) {
                break;
            } else {
                EntityUtils.consumeQuietly(response.getEntity());
                Thread.sleep(20000);
            }
        }

    } catch (ClientProtocolException e) {
        throw new RavelloException("ClientProtocolException - " + e.getMessage());
    } catch (IOException e) {
        throw new RavelloException("IOException - " + e.getMessage());
    } catch (NullPointerException e) {
        throw new RavelloException("NullPointerException - " + e.getMessage());
    }

    Thread.sleep(startupDelay * 1000);

    return value;
}