Example usage for javax.json JsonArray get

List of usage examples for javax.json JsonArray get

Introduction

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

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

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

/**
 * Convert a json array to a list of integers.
 * if arr is null, then an empty List<Integer> instance is returned.
 * //  www  .j  ava 2s.  c  o m
 * This is more safe than JsonArray.getValuesAs() as this method
 * has built-in type checking and will throw a ClassCastException if 
 * the type is incorrect or null.
 * 
 * @param arr array
 * @return a list
 * @throws ClassCastException if any element in arr is not an integer
 */
public static List<Integer> jsonArrayToIntList(final JsonArray arr) {
    final List<Integer> out = new ArrayList<>();
    if (arr == null)
        return out;

    for (int i = 0; i < arr.size(); i++) {
        final Integer j;
        try {
            j = arr.getInt(i);
        } catch (ClassCastException e) {
            APILog.error(LOG, e, arr.get(i));
            continue;
        }

        if (j == null) {
            throw new ClassCastException(
                    "Element at position " + String.valueOf(i) + " is null - Integer required");
        }

        out.add(j);
    }

    return out;
}

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

/**
 * Convert a json array to a list of Strings.
 * if arr is null, then an empty List<String> instance is returned.
 * /* ww w .  j av a2s .c  o  m*/
 * This is more safe than JsonArray.getValuesAs() as this method
 * has built-in type checking and will throw a ClassCastException if 
 * the type is incorrect or null.
 * 
 * @param arr array
 * @return a list
 * @throws ClassCastException if any element in arr is not an string
 */
public static List<String> jsonArrayToStringList(final JsonArray arr) {
    final List<String> out = new ArrayList<>();
    if (arr == null)
        return out;

    for (int i = 0; i < arr.size(); i++) {
        final String s;
        try {
            s = arr.getString(i);
        } catch (ClassCastException e) {
            APILog.error(LOG, e, arr.get(i));
            continue;
        }

        if (s == null) {
            throw new ClassCastException(
                    "Element at position " + String.valueOf(i) + " is null - String required");
        }

        out.add(s);
    }

    return out;
}

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 {/*  w  ww .  j  av  a  2  s.  c o 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:io.bibleget.HTTPCaller.java

public int idxOf(String needle, JsonArray haystack) {
    int count = 0;
    for (JsonValue i : haystack) {
        JsonArray m = (JsonArray) i;
        if (m.get(0).getValueType() == ARRAY) {
            for (JsonValue x : m) {
                //System.out.println("looking for '"+needle+"' in "+x.toString());
                if (x.toString().contains("\"" + needle + "\"")) {
                    return count;
                }/*from  w  w w  . j  av  a  2s  .c  o m*/
            }
        } else {
            if (m.toString().contains("\"" + needle + "\"")) {
                return count;
            }
        }
        count++;
    }
    return -1;
}

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   www  .  j  a v a 2 s. co  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: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;/* w ww.ja  v  a 2s  .  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:org.apache.johnzon.maven.plugin.ExampleToModelMojo.java

private void handleArray(final Writer writer, final String prefix, final Map<String, JsonObject> nestedTypes,
        final JsonValue value, final String jsonField, final String fieldName, final int arrayLevel,
        final Collection<String> imports) throws IOException {
    final JsonArray array = JsonArray.class.cast(value);
    if (array.size() > 0) { // keep it simple for now - 1 level, we can have an awesome recursive algo later if needed
        final JsonValue jsonValue = array.get(0);
        switch (jsonValue.getValueType()) {
        case OBJECT:
            final String javaName = toJavaName(fieldName);
            nestedTypes.put(javaName, JsonObject.class.cast(jsonValue));
            fieldGetSetMethods(writer, jsonField, fieldName, javaName, prefix, arrayLevel, imports);
            break;
        case TRUE:
        case FALSE:
            fieldGetSetMethods(writer, jsonField, fieldName, "Boolean", prefix, arrayLevel, imports);
            break;
        case NUMBER:
            fieldGetSetMethods(writer, jsonField, fieldName, "Double", prefix, arrayLevel, imports);
            break;
        case STRING:
            fieldGetSetMethods(writer, jsonField, fieldName, "String", prefix, arrayLevel, imports);
            break;
        case ARRAY:
            handleArray(writer, prefix, nestedTypes, jsonValue, jsonField, fieldName, arrayLevel + 1, imports);
            break;
        case NULL:
        default:/*from  ww w  .  ja v a 2  s.  co m*/
            throw new UnsupportedOperationException("Unsupported " + value + ".");
        }
    } else {
        getLog().warn("Empty arrays are ignored");
    }
}

From source file:org.fuin.esmp.Downloads.java

/**
 * Loads the data from the JSON download versions file.
 * /*  w  w  w. jav a 2 s  .co  m*/
 * @throws IOException
 *             Parsing the event store version file failed.
 */
public final void parse() throws IOException {

    final Reader reader = new FileReader(jsonDownloadsFile);
    try {
        final JsonReader jsonReader = Json.createReader(reader);
        final JsonArray osArray = jsonReader.readArray();
        for (int i = 0; i < osArray.size(); i++) {
            final JsonObject osObj = (JsonObject) osArray.get(i);
            final String os = osObj.getString("os");
            final String currentVersion = osObj.getString("currentVersion");
            final JsonArray downloadsArray = osObj.getJsonArray("downloads");
            final List<DownloadVersion> versions = new ArrayList<>();
            for (int j = 0; j < downloadsArray.size(); j++) {
                final JsonObject downloadObj = (JsonObject) downloadsArray.get(j);
                final String version = downloadObj.getString("version");
                final String url = downloadObj.getString("url");
                versions.add(new DownloadVersion(version, url));
            }
            Collections.sort(versions);
            osList.add(new DownloadOS(os, currentVersion, versions));
        }
        Collections.sort(osList);
    } finally {
        reader.close();
    }

    for (final DownloadOS os : osList) {
        LOG.info("Latest '" + os + "': " + os.getLatestVersion() + " (Versions: " + os.getVersions().size()
                + ")");
    }

}

From source file:org.hyperledger.fabric.sdk.ChaincodeCollectionConfiguration.java

Collection.CollectionConfigPackage parse(JsonArray jsonConfig)
        throws ChaincodeCollectionConfigurationException {

    Collection.CollectionConfigPackage.Builder colcofbuilder = Collection.CollectionConfigPackage.newBuilder();
    for (int i = jsonConfig.size() - 1; i > -1; --i) {

        Collection.StaticCollectionConfig.Builder ssc = Collection.StaticCollectionConfig.newBuilder();

        JsonValue j = jsonConfig.get(i);
        if (j.getValueType() != JsonValue.ValueType.OBJECT) {
            throw new ChaincodeCollectionConfigurationException(format(
                    "Expected StaticCollectionConfig to be Object type but got: %s", j.getValueType().name()));
        }/*from   w w  w . j  a  va 2s  . c om*/

        JsonObject jsonObject = j.asJsonObject();
        JsonObject scf = getJsonObject(jsonObject, "StaticCollectionConfig"); // oneof .. may have different values in the future
        ssc.setName(getJsonString(scf, "name")).setBlockToLive(getJsonLong(scf, "blockToLive"))
                .setMaximumPeerCount(getJsonInt(scf, "maximumPeerCount"))
                .setMemberOrgsPolicy(Collection.CollectionPolicyConfig.newBuilder()
                        .setSignaturePolicy(parseSignaturePolicyEnvelope(scf)).build())
                .setRequiredPeerCount(getJsonInt(scf, "requiredPeerCount"));

        colcofbuilder
                .addConfig(Collection.CollectionConfig.newBuilder().setStaticCollectionConfig(ssc).build());

    }
    return colcofbuilder.build();

}