Search in sources :

Example 56 with JsonArray

use of com.eclipsesource.json.JsonArray in project universa by UniversaBlockchain.

the class JsonTool method fromJson.

public static <T> T fromJson(JsonValue jsonValue) {
    if (jsonValue.isNumber()) {
        double real = jsonValue.asDouble();
        return real != (int) real ? (T) Double.valueOf(real) : (T) Long.valueOf((long) real);
    }
    if (jsonValue.isString())
        return (T) jsonValue.asString();
    if (jsonValue.isNull())
        return null;
    if (jsonValue.isTrue())
        return (T) Boolean.TRUE;
    if (jsonValue.isFalse())
        return (T) Boolean.FALSE;
    if (jsonValue.isObject()) {
        JsonObject jo = (JsonObject) jsonValue;
        HashMap<String, Object> result = new HashMap<>();
        for (JsonObject.Member m : jo) {
            result.put(m.getName(), fromJson(m.getValue()));
        }
        return (T) result;
    }
    if (jsonValue.isArray()) {
        JsonArray array = (JsonArray) jsonValue;
        ArrayList<Object> result = new ArrayList<>(array.size());
        for (JsonValue value : array) {
            result.add(fromJson(value));
        }
        return (T) result;
    }
    throw new IllegalArgumentException("cant convert this type of value: " + jsonValue);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) JsonArray(com.eclipsesource.json.JsonArray) JsonObject(com.eclipsesource.json.JsonObject)

Example 57 with JsonArray

use of com.eclipsesource.json.JsonArray in project universa by UniversaBlockchain.

the class JsonTool method toJson.

/**
 * Deep convert any suitable Java object to corresponding {@link JsonValue} derivative. Converts
 * collections, arrays, maps in depth, converting all containing objects. Note that the map keys
 * are always converted to strings.
 * <p>
 * <ul> <li> All ingeter Java types are converted to integerr value </li> <li>Any privitive
 * array, Object array or Iterable, e.g. any Collection, to the array</li> <li>Any Map converts
 * to the json object ({key: value}, using key.toSting()</li><li>nulls become nulls ;)</li>
 * </ul>
 *
 * @param object
 *         object to convert
 *
 * @return converted object
 *
 * @throws IllegalArgumentException
 *         if there is no known way to convert the object to JSON
 */
@SuppressWarnings("unchecked")
public static <T extends JsonValue> T toJson(Object object) {
    if (object == null) {
        return (T) Json.NULL;
    }
    if (object instanceof Number) {
        // Note that these are calls to different methods below!
        if (object instanceof Float || object instanceof Double)
            return (T) Json.value(((Number) object).longValue());
        else
            return (T) Json.value(((Number) object).longValue());
    }
    if (object instanceof String) {
        return (T) Json.value((String) object);
    }
    if (object instanceof Boolean) {
        return (T) Json.value((Boolean) object);
    }
    if (object.getClass().isArray()) {
        JsonArray arr = new JsonArray();
        int length = Array.getLength(object);
        for (int i = 0; i < length; i++) {
            arr.add(toJson(Array.get(object, i)));
        }
        return (T) arr;
    }
    if (object instanceof Iterable) {
        JsonArray arr = new JsonArray();
        for (Object x : (Iterable<?>) object) arr.add(toJson(x));
        return (T) arr;
    }
    if (object instanceof Map) {
        Map<?, ?> map = (Map) object;
        JsonObject jsonObject = new JsonObject();
        for (Map.Entry entry : map.entrySet()) {
            jsonObject.set(entry.getKey().toString(), toJson(entry.getValue()));
        }
        return (T) jsonObject;
    }
    if (object instanceof Date) {
        return toJson(Ut.mapFromArray("__type__", "datetime", "unixtime", ((Date) object).getTime() / 1000.0));
    }
    throw new IllegalArgumentException("Cant convert to json " + object + " of type " + object.getClass().getName());
}
Also used : JsonObject(com.eclipsesource.json.JsonObject) Date(java.util.Date) JsonArray(com.eclipsesource.json.JsonArray) JsonObject(com.eclipsesource.json.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 58 with JsonArray

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

the class ZCashClientCaller method sendMessage.

// Returns OPID
public synchronized String sendMessage(String from, String to, double amount, double fee, String memo) throws WalletCallException, IOException, InterruptedException {
    String hexMemo = Util.encodeHexString(memo);
    JsonObject toArgument = new JsonObject();
    toArgument.set("address", to);
    if (hexMemo.length() >= 2) {
        toArgument.set("memo", hexMemo.toString());
    }
    DecimalFormatSymbols decSymbols = new DecimalFormatSymbols(Locale.ROOT);
    // TODO: The JSON Builder has a problem with double values that have no fractional part
    // it serializes them as integers that ZCash does not accept. This will work with the
    // fractional amounts always used for messaging
    toArgument.set("amount", new DecimalFormat("########0.00######", decSymbols).format(amount));
    JsonArray toMany = new JsonArray();
    toMany.add(toArgument);
    String toManyArrayStr = toMany.toString();
    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
    new DecimalFormat("########0.00######", decSymbols).format(fee) };
    // 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 message 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)

Example 59 with JsonArray

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

the class ZCashClientCaller method getOperationFinalErrorMessage.

// May only be called for already failed operations
public synchronized String getOperationFinalErrorMessage(String opID) throws WalletCallException, IOException, InterruptedException {
    JsonArray response = this.executeCommandAndGetJsonArray("z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
    JsonObject jsonStatus = response.get(0).asObject();
    JsonObject jsonError = jsonStatus.get("error").asObject();
    return jsonError.getString("message", "ERROR!");
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) JsonObject(com.eclipsesource.json.JsonObject)

Example 60 with JsonArray

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

the class ZCashClientCaller method isCompletedOperationSuccessful.

public synchronized boolean isCompletedOperationSuccessful(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")) {
        return true;
    } else if (status.equalsIgnoreCase("error") || status.equalsIgnoreCase("failed")) {
        return false;
    } else {
        throw new WalletCallException("Unexpected final operation status response from wallet: " + response.toString());
    }
}
Also used : JsonArray(com.eclipsesource.json.JsonArray) JsonObject(com.eclipsesource.json.JsonObject)

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