Example usage for com.google.gson JsonElement getAsLong

List of usage examples for com.google.gson JsonElement getAsLong

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsLong.

Prototype

public long getAsLong() 

Source Link

Document

convenience method to get this element as a primitive long value.

Usage

From source file:com.vmware.admiral.compute.container.maintenance.ContainerStatsEvaluator.java

License:Open Source License

private static void setMemoryUsage(ContainerStats state, Map<String, JsonElement> stats) {
    try {/* www. jav a 2 s.  c  o m*/
        JsonElement jsonElement = stats.get("memory_stats");
        if (jsonElement == null) {
            return;
        }
        JsonObject memory_stats = jsonElement.getAsJsonObject();
        JsonElement limitValue = memory_stats.get("limit");
        if (limitValue != null) {
            state.memLimit = limitValue.getAsLong();
        }
        JsonElement usage = memory_stats.get("usage");
        if (usage != null) {
            state.memUsage = usage.getAsLong();
        }
    } catch (Exception e) {
        Utils.logWarning("Error during container stats memory usage parsing: %s", Utils.toString(e));
    }
}

From source file:com.vmware.admiral.compute.container.maintenance.ContainerStatsEvaluator.java

License:Open Source License

private static void calculateCpuUsage(ContainerStats state, Map<String, JsonElement> stats) {
    try {//from  www  . j  av  a  2s . co m
        JsonElement cpu_stats_json = stats.get("cpu_stats");
        if (cpu_stats_json == null || cpu_stats_json.isJsonNull()) {
            Utils.logWarning("cpu_stats is null.");
            return;
        }
        JsonObject cpu_stats = cpu_stats_json.getAsJsonObject();

        JsonElement systemCpuUsageValue = cpu_stats.get("system_cpu_usage");
        if (systemCpuUsageValue == null || systemCpuUsageValue.isJsonNull()) {
            Utils.logWarning("system_cpu_usage is null.");
            return;
        }
        long system_cpu_usage = systemCpuUsageValue.getAsLong();

        JsonElement cpu_usage_json = cpu_stats.get("cpu_usage");
        if (cpu_usage_json == null || cpu_usage_json.isJsonNull()) {
            Utils.logWarning("cpu_usage is null.");
            return;
        }
        JsonObject cpu_usage = cpu_usage_json.getAsJsonObject();

        JsonElement totalUsageValue = cpu_usage.get("total_usage");
        if (totalUsageValue == null || totalUsageValue.isJsonNull()) {
            Utils.logWarning("totalUsageValue is null.");
            return;
        }
        long total_usage = totalUsageValue.getAsLong();

        JsonElement percpu_usage_json = cpu_usage.get("percpu_usage");
        if (percpu_usage_json == null || percpu_usage_json.isJsonNull()) {
            Utils.logWarning("percpu_usage is null.");
            return;
        }
        JsonArray percpu_usage = percpu_usage_json.getAsJsonArray();

        JsonElement precpu_stats_json = stats.get("precpu_stats");
        if (precpu_stats_json == null || precpu_stats_json.isJsonNull()) {
            Utils.logWarning("precpu_stats is null.");
            return;
        }
        JsonObject precpu_stats = precpu_stats_json.getAsJsonObject();

        JsonElement system_cpu_usage_json = precpu_stats.get("system_cpu_usage");
        if (system_cpu_usage_json == null || system_cpu_usage_json.isJsonNull()) {
            Utils.logWarning("system_cpu_usage is null.");
            return;
        }
        long presystem_cpu_usage = system_cpu_usage_json.getAsLong();

        JsonElement precpu_usage_json = precpu_stats.get("cpu_usage");
        if (precpu_usage_json == null || precpu_usage_json.isJsonNull()) {
            Utils.logWarning("precpu_usage is null.");
            return;
        }
        JsonObject precpu_usage = precpu_usage_json.getAsJsonObject();

        JsonElement pretotal_usage_json = precpu_usage.get("total_usage");
        if (pretotal_usage_json == null || pretotal_usage_json.isJsonNull()) {
            Utils.logWarning("total_usage is null.");
            return;
        }

        long pretotal_usage = pretotal_usage_json.getAsLong();

        long cpuDelta = total_usage - pretotal_usage;
        long systemDelta = system_cpu_usage - presystem_cpu_usage;

        if (systemDelta > 0 && cpuDelta > 0) {
            double cpuUsage = (((double) cpuDelta / systemDelta) * percpu_usage.size()) * 100.0;
            state.cpuUsage = Math.round(cpuUsage * 100d) / 100d;
        }

    } catch (Exception e) {
        Utils.logWarning("Error during container stats CPU usage calculations: %s", Utils.toString(e));
    }
}

From source file:com.vmware.admiral.test.upgrade.version2.UpgradeNewService3StateConverter.java

License:Open Source License

@Override
public JsonElement serialize(UpgradeNewService3State state, Type typeOfSrc, JsonSerializationContext context) {

    String version = ThreadLocalVersionHolder.getVersion();

    String json = JSON_MAPPER.toJson(state);
    JsonElement jsonElement = JSON_PARSER.parse(json);

    if (ReleaseConstants.API_VERSION_0_9_1.equals(version)) {

        /*// w w w  .j a  v a  2  s .com
         * Handle the backward compatibility with the previous version
         */
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        // "field3" upgrade: Long -> String

        JsonElement field3 = jsonObject.remove("field3");
        Long oldField3Value = field3.getAsLong();
        String newField3Value = (oldField3Value == 42L) ? "fortytwo" : "";
        jsonObject.addProperty("field3", newField3Value);

        // "field5" upgrade: Map ("a=a", "b=b", "c=c") -> List ("a", "b", "c")

        // JsonElement field5 = jsonObject.remove("field5");
        // Map<String, String> oldField5Value = Utils.fromJson(field5, Map.class);
        // List<String> newField5Value = new ArrayList<>(oldField5Value.keySet());
        // jsonObject.add("field5", JSON_PARSER.parse(Utils.toJson(newField5Value)));
    }

    return jsonElement;
}

From source file:com.wallellen.wechat.common.util.json.GsonHelper.java

License:Open Source License

public static Long getAsLong(JsonElement element) {
    return isNull(element) ? null : element.getAsLong();
}

From source file:com.wialon.core.Session.java

License:Apache License

/**
 * Handle item search result from server
 *///from   w  w w .j  a  va  2 s.c  om
private void onSearchItemResult(String result, ResponseHandler callback) {
    if (result == null) {
        // error
        callback.onFailure(6, null);
        return;
    }
    //Send string result
    callback.onSuccess(result);
    // create result
    // construct item
    JsonElement responseJson = jsonParser.parse(result);
    if (responseJson == null || !responseJson.isJsonObject()) {
        return;
    }
    JsonElement itemJson = responseJson.getAsJsonObject().get("item");
    JsonElement itemFlags = responseJson.getAsJsonObject().get("flags");
    if (itemJson == null || !itemJson.isJsonObject() || itemFlags == null || itemFlags.getAsNumber() == null) {
        return;
    }
    if (callback instanceof SearchResponseHandler)
        ((SearchResponseHandler) callback)
                .onSuccessSearch(constructItem(itemJson.getAsJsonObject(), itemFlags.getAsLong()));
}

From source file:com.wialon.core.Session.java

License:Apache License

/**
 * Handle items search result from server
 * callback require 2nd parameter in form: {items: [], dataFlags: 0x10, totalItemsCount: 100, indexFrom: 0, indexTo: 9, searchSpec: {...}}
 *//*from   w w w .java2  s  .c om*/
private void onSearchItemsResult(String result, ResponseHandler callback) {
    if (result == null) {
        callback.onFailure(6, null);
        return;
    }
    //Send string result
    callback.onSuccess(result);
    // construct items
    JsonElement responseJson = jsonParser.parse(result);
    if (responseJson == null || !responseJson.isJsonObject()) {
        return;
    }
    JsonElement dataFlags = responseJson.getAsJsonObject().get("dataFlags");
    JsonElement itemsJson = responseJson.getAsJsonObject().get("items");
    if (itemsJson == null || !itemsJson.isJsonArray() || dataFlags == null || dataFlags.getAsNumber() == null) {
        return;
    }
    JsonArray responseItems = itemsJson.getAsJsonArray();
    Item[] items = new Item[responseItems.size()];
    for (int i = 0; i < responseItems.size(); i++) {
        try {
            JsonObject itemData = responseItems.get(i).getAsJsonObject();
            Item item = constructItem(itemData, dataFlags.getAsLong());
            items[i] = item;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (callback instanceof SearchResponseHandler)
        ((SearchResponseHandler) callback).onSuccessSearch(items);
}

From source file:com.wialon.item.Unit.java

License:Apache License

@Override
public boolean updateItemData(String key, JsonElement data) {
    if (super.updateItemData(key, data))
        return true;
    else {//from w ww.ja  v a2s . co  m
        if (key.equals("uid") && data.getAsString() != null) {
            setUniqueId(data.getAsString());
        } else if (key.equals("hw") && data.getAsNumber() != null) {
            setDeviceTypeId(data.getAsLong());
        } else if (key.equals("ph") && data.getAsString() != null) {
            setPhoneNumber(data.getAsString());
        } else if (key.equals("ph2") && data.getAsString() != null) {
            setPhoneNumber2(data.getAsString());
        } else if (key.equals("psw") && data.getAsString() != null) {
            setAccessPassword(data.getAsString());
        } else if (key.equals("cmds") && data.isJsonArray()) {
            setCommands(Session.getInstance().getGson().fromJson(data, List.class));
        } else if (key.equals("pos") && data.isJsonObject()) {
            setPosition(Session.getInstance().getGson().fromJson(data, UnitData.Position.class));
        } else if (key.equals("lmsg") && data.isJsonObject()) {
            setLastMessage(Session.getInstance().getGson().fromJson(data, UnitData.class));
        } else if (key.equals("cfl") && data.getAsNumber() != null) {
            setCalcFlags(data.getAsLong());
        } else if (key.equals("cnm") && data.getAsNumber() != null) {
            setMileageCounter(data.getAsLong());
        } else if (key.equals("cneh") && data.getAsNumber() != null) {
            setEngineHoursCounter(data.getAsLong());
        } else if (key.equals("cnkb") && data.getAsNumber() != null) {
            setTrafficCounter(data.getAsLong());
        } else if (key.equals("prms") && data.isJsonObject()) {
            Map<String, Object> dataParams = new HashMap<String, Object>();
            dataParams = Session.getInstance().getGson().fromJson(data, dataParams.getClass());
            Map<String, Object> oldParams = getMessageParams();
            if (oldParams == null)
                oldParams = new HashMap<String, Object>();
            for (Map.Entry<String, Object> entry : dataParams.entrySet()) {
                if (entry.getValue() instanceof Number) {
                    Object oldParam = oldParams.get(entry.getKey());
                    if (oldParam != null && oldParam instanceof Map)
                        ((Map) oldParam).put("at", ((Number) entry.getValue()).longValue());
                } else {
                    oldParams.put(entry.getKey(), entry.getValue());
                }
            }
            setMessageParams(oldParams);
        } else
            return false;
        return true;
    }
}

From source file:com.wialon.item.User.java

License:Apache License

@Override
public boolean updateItemData(String key, JsonElement data) {
    if (super.updateItemData(key, data))
        return true;
    else {/* w  w w.ja v a 2  s .c  om*/
        if (key.equals("hm") && data.getAsString() != null) {
            setHostsMask(data.getAsString());
        } else if (key.equals("fl") && data.getAsNumber() != null) {
            setUserFlags(data.getAsLong());
        } else
            return false;
        return true;
    }
}

From source file:com.wibidata.wibidota.DotaMatchBulkImporter.java

License:Apache License

private static Long getNullableLong(JsonElement je) {
    return (je == null ? null : je.getAsLong());
}

From source file:de.azapps.mirakel.model.task.Task.java

License:Open Source License

/**
 * Parses a JSON-Object to a task//from w w  w.j  a  v  a2  s . c om
 * 
 * @param el
 * @return
 */
public static Task parse_json(JsonObject el, AccountMirakel account) {
    Task t = null;
    JsonElement id = el.get("id");
    if (id != null) {
        t = Task.get(id.getAsLong());
    } else {
        id = el.get("uuid");
        if (id != null)
            t = Task.getByUUID(id.getAsString());
    }
    if (t == null) {
        t = new Task();
    }

    // Name
    Set<Entry<String, JsonElement>> entries = el.entrySet();
    for (Entry<String, JsonElement> entry : entries) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        if (key == null || key.equals("id"))
            continue;
        if (key.equals("uuid")) {
            t.setUUID(val.getAsString());
        } else if (key.equals("name") || key.equals("description")) {
            t.setName(val.getAsString());
        } else if (key.equals("content")) {
            String content = val.getAsString();
            if (content == null)
                content = "";
            t.setContent(content);
        } else if (key.equals("priority")) {
            String prioString = val.getAsString().trim();
            if (prioString.equals("L") && t.getPriority() != -1) {
                t.setPriority(-2);
            } else if (prioString.equals("M")) {
                t.setPriority(1);
            } else if (prioString.equals("H")) {
                t.setPriority(2);
            } else if (!prioString.equals("L")) {
                t.setPriority(val.getAsInt());
            }
        } else if (key.equals("list_id")) {
            ListMirakel list = ListMirakel.getList(val.getAsInt());
            if (list == null)
                list = SpecialList.firstSpecial().getDefaultList();
            t.setList(list);
        } else if (key.equals("project")) {
            ListMirakel list = ListMirakel.findByName(val.getAsString());
            if (list == null || list.getAccount().getId() != account.getId()) {
                list = ListMirakel.newList(val.getAsString(), ListMirakel.SORT_BY_OPT, account);
            }
            t.setList(list);
        } else if (key.equals("created_at")) {
            t.setCreatedAt(val.getAsString().replace(":", ""));
        } else if (key.equals("updated_at")) {
            t.setUpdatedAt(val.getAsString().replace(":", ""));
        } else if (key.equals("entry")) {
            t.setCreatedAt(parseDate(val.getAsString(), context.getString(R.string.TWDateFormat)));
        } else if (key.equals("modification")) {
            t.setUpdatedAt(parseDate(val.getAsString(), context.getString(R.string.TWDateFormat)));
        } else if (key.equals("done")) {
            t.setDone(val.getAsBoolean());
        } else if (key.equals("status")) {
            String status = val.getAsString();
            if (status.equals("pending")) {
                t.setDone(false);
            } else if (status.equals("deleted")) {
                t.setSyncState(SYNC_STATE.DELETE);
            } else {
                t.setDone(true);
            }
            t.addAdditionalEntry(key, val.getAsString());
            // TODO don't ignore waiting and recurring!!!
        } else if (key.equals("due")) {
            Calendar due = parseDate(val.getAsString(), "yyyy-MM-dd");
            if (due == null) {
                due = parseDate(val.getAsString(), context.getString(R.string.TWDateFormat));
                if (val.getAsString().contains("T230000Z")) {
                    // Hope this works around a tw-bug
                    // if you add a task with due:today, the task which will be sync will be
                    // due:yesterday:23:00
                    due.add(Calendar.DAY_OF_MONTH, 1);
                }
            }
            t.setDue(due);
        } else if (key.equals("reminder")) {
            Calendar reminder = parseDate(val.getAsString(), "yyyy-MM-dd");
            if (reminder == null) {
                reminder = parseDate(val.getAsString(), context.getString(R.string.TWDateFormat));
            }
            t.setReminder(reminder);
        } else if (key.equals("annotations")) {
            String content = "";
            try {
                JsonArray annotations = val.getAsJsonArray();
                boolean first = true;
                for (JsonElement a : annotations) {
                    if (first)
                        first = false;
                    else
                        content += "\n";
                    content += a.getAsJsonObject().get("description").getAsString();
                }
            } catch (Exception e) {
                Log.e(TAG, "cannot parse json");
            }
            t.setContent(content);
        } else if (key.equals("content")) {
            t.setContent(val.getAsString());
        } else if (key.equals("sync_state")) {
            t.setSyncState(SYNC_STATE.parseInt(val.getAsInt()));
        } else if (key.equals("depends")) {
            t.setDependencies(val.getAsString().split(","));
        } else {
            t.addAdditionalEntry(key, val.getAsString());
        }
    }
    if (t.getList() == null) {
        ListMirakel l = MirakelPreferences.getImportDefaultList(true);
        t.setList(l);
    }
    return t;
}