Search in sources :

Example 16 with JsonArray

use of com.eclipsesource.json.JsonArray in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method getWalletPublicAddressesWithUnspentOutputs.

// ./src/zcash-cli listunspent only returns T addresses it seems
public synchronized String[] getWalletPublicAddressesWithUnspentOutputs() throws WalletCallException, IOException, InterruptedException {
    JsonArray jsonUnspentOutputs = executeCommandAndGetJsonArray("listunspent", "0");
    Set<String> addresses = new HashSet<>();
    for (int i = 0; i < jsonUnspentOutputs.size(); i++) {
        JsonObject outp = jsonUnspentOutputs.get(i).asObject();
        addresses.add(outp.getString("address", "ERROR!"));
    }
    return addresses.toArray(new String[0]);
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) JsonObject(com.eclipsesource.json.JsonObject) HashSet(java.util.HashSet)

Example 17 with JsonArray

use of com.eclipsesource.json.JsonArray in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method sendCash.

// Returns OPID
public synchronized String sendCash(String from, String to, String amount, String memo, String transactionFee) throws WalletCallException, IOException, InterruptedException {
    StringBuilder hexMemo = new StringBuilder();
    for (byte c : memo.getBytes("UTF-8")) {
        String hexChar = Integer.toHexString((int) c);
        if (hexChar.length() < 2) {
            hexChar = "0" + hexChar;
        }
        hexMemo.append(hexChar);
    }
    JsonObject toArgument = new JsonObject();
    toArgument.set("address", to);
    if (hexMemo.length() >= 2) {
        toArgument.set("memo", hexMemo.toString());
    }
    // The JSON Builder has a problem with double values that have no fractional part
    // it serializes them as integers that ZCash does not accept. So we do a replacement
    // TODO: find a better/cleaner way to format the amount
    toArgument.set("amount", "\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF");
    JsonArray toMany = new JsonArray();
    toMany.add(toArgument);
    String amountPattern = "\"amount\":\"\uFFFF\uFFFF\uFFFF\uFFFF\uFFFF\"";
    // Make sure our replacement hack never leads to a mess up
    String toManyBeforeReplace = toMany.toString();
    int firstIndex = toManyBeforeReplace.indexOf(amountPattern);
    int lastIndex = toManyBeforeReplace.lastIndexOf(amountPattern);
    if ((firstIndex == -1) || (firstIndex != lastIndex)) {
        throw new WalletCallException("Error in forming z_sendmany command: " + toManyBeforeReplace);
    }
    DecimalFormatSymbols decSymbols = new DecimalFormatSymbols(Locale.ROOT);
    // Properly format teh transaction fee as a number
    if ((transactionFee == null) || (transactionFee.trim().length() <= 0)) {
        // Default value
        transactionFee = "0.0001";
    } else {
        transactionFee = new DecimalFormat("########0.00######", decSymbols).format(Double.valueOf(transactionFee));
    }
    // This replacement is a hack to make sure the JSON object amount has double format 0.00 etc.
    // TODO: find a better way to format the amount
    String toManyArrayStr = toMany.toString().replace(amountPattern, "\"amount\":" + new DecimalFormat("########0.00######", decSymbols).format(Double.valueOf(amount)));
    String[] sendCashParameters = new String[] { this.zcashcli.getCanonicalPath(), "z_sendmany", wrapStringParameter(from), wrapStringParameter(toManyArrayStr), // Default min confirmations for the input transactions is 1
    "1", // transaction fee
    transactionFee };
    // Safeguard to make sure the monetary amount does not differ after formatting
    BigDecimal bdAmout = new BigDecimal(amount);
    JsonArray toManyVerificationArr = Json.parse(toManyArrayStr).asArray();
    BigDecimal bdFinalAmount = new BigDecimal(toManyVerificationArr.get(0).asObject().getDouble("amount", -1));
    BigDecimal difference = bdAmout.subtract(bdFinalAmount).abs();
    if (difference.compareTo(new BigDecimal("0.000000015")) >= 0) {
        throw new WalletCallException("Error in forming z_sendmany command: Amount differs after formatting: " + amount + " | " + toManyArrayStr);
    }
    Log.info("The following send command will be issued: " + sendCashParameters[0] + " " + sendCashParameters[1] + " " + sendCashParameters[2] + " " + sendCashParameters[3] + " " + sendCashParameters[4] + " " + sendCashParameters[5] + ".");
    // Create caller to send cash
    CommandExecutor caller = new CommandExecutor(sendCashParameters);
    String strResponse = caller.execute();
    if (strResponse.trim().toLowerCase(Locale.ROOT).startsWith("error:") || strResponse.trim().toLowerCase(Locale.ROOT).startsWith("error code:")) {
        throw new WalletCallException("Error response from wallet: " + strResponse);
    }
    Log.info("Sending cash with the following command: " + sendCashParameters[0] + " " + sendCashParameters[1] + " " + sendCashParameters[2] + " " + sendCashParameters[3] + " " + sendCashParameters[4] + " " + sendCashParameters[5] + "." + " Got result: [" + strResponse + "]");
    return strResponse.trim();
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat) JsonObject(com.eclipsesource.json.JsonObject) BigDecimal(java.math.BigDecimal)

Example 18 with JsonArray

use of com.eclipsesource.json.JsonArray in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method isSendingOperationComplete.

public synchronized boolean isSendingOperationComplete(String opID) throws WalletCallException, IOException, InterruptedException {
    JsonArray response = this.executeCommandAndGetJsonArray("z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
    JsonObject jsonStatus = response.get(0).asObject();
    String status = jsonStatus.getString("status", "ERROR");
    Log.info("Operation " + opID + " status is " + response + ".");
    if (status.equalsIgnoreCase("success") || status.equalsIgnoreCase("error") || status.equalsIgnoreCase("failed")) {
        return true;
    } else if (status.equalsIgnoreCase("executing") || status.equalsIgnoreCase("queued")) {
        return false;
    } else {
        throw new WalletCallException("Unexpected status response from wallet: " + response.toString());
    }
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) JsonObject(com.eclipsesource.json.JsonObject)

Example 19 with JsonArray

use of com.eclipsesource.json.JsonArray in project zencash-swing-wallet-ui by ZencashOfficial.

the class ZCashClientCaller method getMemoField.

public synchronized String getMemoField(String acc, String txID) throws WalletCallException, IOException, InterruptedException {
    JsonArray jsonTransactions = this.executeCommandAndGetJsonArray("z_listreceivedbyaddress", wrapStringParameter(acc));
    for (int i = 0; i < jsonTransactions.size(); i++) {
        if (jsonTransactions.get(i).asObject().getString("txid", "ERROR!").equals(txID)) {
            if (jsonTransactions.get(i).asObject().get("memo") == null) {
                return null;
            }
            String memoHex = jsonTransactions.get(i).asObject().getString("memo", "ERROR!");
            String decodedMemo = Util.decodeHexMemo(memoHex);
            // if we have loopback send etc.
            if (decodedMemo != null) {
                return decodedMemo;
            }
        }
    }
    return null;
}
Also used : JsonArray(com.eclipsesource.json.JsonArray)

Example 20 with JsonArray

use of com.eclipsesource.json.JsonArray in project box-java-sdk by box.

the class BoxFile method getVersions.

/**
 * Gets any previous versions of this file. Note that only users with premium accounts will be able to retrieve
 * previous versions of their files. `fields` parameter is optional, if specified only requested fields will
 * be returned:
 * <pre>
 * {@code
 * new BoxFile(api, file_id).getVersions()       // will return all default fields
 * new BoxFile(api, file_id).getVersions("name") // will return only specified fields
 * }
 * </pre>
 * @param fields the fields to retrieve. If nothing provided default fields will be returned.
 *               You can find list of available fields at {@link BoxFile#ALL_VERSION_FIELDS}
 * @return a list of previous file versions.
 */
public Collection<BoxFileVersion> getVersions(String... fields) {
    URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
    try {
        if (fields.length > 0) {
            QueryStringBuilder builder = new QueryStringBuilder(url.getQuery());
            builder.appendParam("fields", fields);
            url = builder.addToURL(url);
        }
    } catch (MalformedURLException e) {
        throw new BoxAPIException("Couldn't append a query string to the provided URL.", e);
    }
    BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject jsonObject = Json.parse(response.getJSON()).asObject();
    JsonArray entries = jsonObject.get("entries").asArray();
    Collection<BoxFileVersion> versions = new ArrayList<>();
    for (JsonValue entry : entries) {
        versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID()));
    }
    return versions;
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) URL(java.net.URL)

Aggregations

JsonArray (com.eclipsesource.json.JsonArray)111 JsonObject (com.eclipsesource.json.JsonObject)96 JsonValue (com.eclipsesource.json.JsonValue)32 Test (org.junit.Test)30 URL (java.net.URL)28 ArrayList (java.util.ArrayList)27 HashMap (java.util.HashMap)11 Matchers.containsString (org.hamcrest.Matchers.containsString)6 JsonUtil.getString (com.hazelcast.util.JsonUtil.getString)5 Map (java.util.Map)5 Link (org.eclipse.leshan.Link)4 Date (java.util.Date)3 LwM2mResource (org.eclipse.leshan.core.node.LwM2mResource)3 ClientEndPointDTO (com.hazelcast.internal.management.dto.ClientEndPointDTO)2 MalformedURLException (java.net.MalformedURLException)2 DecimalFormat (java.text.DecimalFormat)2 DecimalFormatSymbols (java.text.DecimalFormatSymbols)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)2