Example usage for com.google.gson JsonObject has

List of usage examples for com.google.gson JsonObject has

Introduction

In this page you can find the example usage for com.google.gson JsonObject has.

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:com.exorath.buycraftconsumer.commandHandlers.RankAPIHandler.java

License:Apache License

@Override
public boolean handle(JsonObject command, DuePlayer duePlayer, DueCommand dueCommand) {
    try {/*  w  w w .j  a va  2 s  . co m*/
        if (!command.has("rank"))
            return false;
        Success success = rankServiceAPI.setPlayerRank(duePlayer.getUuid(),
                new RankPlayer(command.get("rank").getAsString()));
        if (!success.isSuccess())
            System.out.println("RankAPI error: " + success.getCode() + ": " + success.getError());
        return success.isSuccess();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.exorath.commons.ItemStackSerialize.java

License:Apache License

public static ItemStack toItemStack(JsonObject object) {
    Material mat = Material.getMaterial(object.get("material").getAsString());

    int amount = object.has("amount") ? object.get("amount").getAsInt() : 1;
    short durability = object.has("durability") ? object.get("durability").getAsShort() : 0;
    ItemStack item = new ItemStack(mat, amount, durability);
    ItemMeta meta = item.getItemMeta();/*  w w w.ja v a2  s.c  o m*/
    if (object.has("displayName"))
        meta.setDisplayName(object.get("displayName").getAsString());
    if (object.has("lore")) {
        List<String> lore = new ArrayList<>();
        for (JsonElement el : object.get("lore").getAsJsonArray())
            lore.add(el.getAsString());
        meta.setLore(lore);
    }
    if (object.get("enchantments") != null) {
        for (JsonElement el : object.get("enchantments").getAsJsonArray()) {
            JsonObject enchantment = el.getAsJsonObject();
            meta.addEnchant(Enchantment.getByName(enchantment.get("enchantment").getAsString()),
                    enchantment.get("level").getAsInt(), true);
        }
    }
    item.setItemMeta(meta);
    return item;
}

From source file:com.exorath.plugin.map.impl.MapServiceMapUploadProvider.java

License:Apache License

@Override
public String upload(final File worldDir, String mapId, String envId) {
    //This is a piped stream solution: see http://blog.ostermiller.org/convert-java-outputstream-inputstream for more info
    try (PipedInputStream in = new PipedInputStream()) {
        try (PipedOutputStream out = new PipedOutputStream(in)) {

            new Thread(() -> {
                zip(worldDir, out);/*from  w  w w  .j a v a 2  s  .  c  o  m*/
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            HttpRequestWithBody req = Unirest.post(address + "/accounts/{accountId}/maps/{mapId}/env/{envId}")
                    .routeParam("accountId", accountId).routeParam("mapId", mapId).routeParam("envId", envId);
            req.field("file", in, ContentType.MULTIPART_FORM_DATA, "file");
            HttpResponse<String> res = req.asString();
            String body = res.getBody();
            if (res.getStatus() < 200 || res.getStatus() >= 300 || body == null)
                return null;
            JsonObject jsonObject = GSON.fromJson(body, JsonObject.class);
            if (jsonObject == null || !jsonObject.has("success")
                    || jsonObject.get("success").getAsBoolean() == false || !jsonObject.has("versionId"))
                return null;
            return jsonObject.get("versionId").getAsString();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.exorath.simpleapi.impl.serverlist.GameServerImpl.java

License:Apache License

public static boolean canDeserialize(JsonObject object) {
    return object.has("bungee");
}

From source file:com.exorath.simpleapi.impl.serverlist.GameServerImpl.java

License:Apache License

public static GameServer deserialize(JsonObject object) {
    GameServerImpl gameServer = new GameServerImpl(object.get("bungee").getAsString());

    if (object.has("joinable"))
        gameServer.setJoinable(object.get("joinable").getAsBoolean());
    if (object.has("playable"))
        gameServer.setPlayable(object.get("playable").getAsBoolean());
    if (object.has("maxplayers"))
        gameServer.setMaxPlayerAmount(object.get("maxplayers").getAsInt());

    JsonArray players = object.has("players") ? object.get("players").getAsJsonArray() : new JsonArray();
    players.forEach(//from  w  w  w .j a  v  a  2  s  .co  m
            e -> gameServer.getPlayers().add(SerializedPlayerImpl.deserialize(e.getAsJsonObject().toString())));
    JsonArray extraLore = object.has("extra") ? object.get("extra").getAsJsonArray() : new JsonArray();
    extraLore.forEach(e -> gameServer.getExtraLore().add(e.getAsString()));

    return gameServer;
}

From source file:com.exorath.simpleapi.impl.serverlist.ServerListManagerImpl.java

License:Apache License

/**
 * Validates whether or not the provided Game-Discovery-Message is valid (Contains required keys).
 *
 * @param message Game-Discovery-Message to validate
 * @return true if the message is valid/*from ww w . ja  v  a2s.co  m*/
 */
private static boolean validateGameDiscoveryMessage(JsonObject message) {
    return message.has("expire") && message.has("gameserver")
            && GameServerImpl.canDeserialize(message.get("gameserver").getAsJsonObject());
}

From source file:com.exorath.simpleapi.impl.serverlist.ServerListManagerImpl.java

License:Apache License

/**
 * Validates whether or not the provided Hub-Discovery-Message is valid (Contains required keys).
 *
 * @param message Game-Discovery-Message to validate
 * @return true if the message is valid/*w ww  .j  a  va  2s .  c om*/
 */
private static boolean validateHubDiscoveryMessage(JsonObject message) {
    return message.has("expire") && message.has("hubserver")
            && GameServerImpl.canDeserialize(message.get("hubserver").getAsJsonObject());
}

From source file:com.facebook.ads.sdk.AdAccount.java

License:Open Source License

public static AdAccount loadJSON(String json, APIContext context) {
    AdAccount adAccount = getGson().fromJson(json, AdAccount.class);
    if (context.isDebug()) {
        JsonParser parser = new JsonParser();
        JsonElement o1 = parser.parse(json);
        JsonElement o2 = parser.parse(adAccount.toString());
        if (o1.getAsJsonObject().get("__fb_trace_id__") != null) {
            o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__"));
        }// w w w  .ja va 2 s. co  m
        if (!o1.equals(o2)) {
            context.log("[Warning] When parsing response, object is not consistent with JSON:");
            context.log("[JSON]" + o1);
            context.log("[Object]" + o2);
        }
        ;
    }
    adAccount.context = context;
    adAccount.rawValue = json;
    JsonParser parser = new JsonParser();
    JsonObject o = parser.parse(json).getAsJsonObject();
    if (o.has("account_id")) {
        String accountId = o.get("account_id").getAsString();
        if (accountId != null) {
            adAccount.mId = accountId;
        }
    }
    if (adAccount.mId != null) {
        adAccount.mId = adAccount.mId.replaceAll("act_", "");
    }
    return adAccount;
}

From source file:com.facebook.ads.sdk.AdAccount.java

License:Open Source License

public static APINodeList<AdAccount> parseResponse(String json, APIContext context, APIRequest request)
        throws MalformedResponseException {
    APINodeList<AdAccount> adAccounts = new APINodeList<AdAccount>(request, json);
    JsonArray arr;// w w w. j a  v  a 2s.co m
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccounts.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccounts;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccounts.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccounts.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccounts.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccounts.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccounts;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccounts.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccounts;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccounts.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccounts;
                }

                // Sixth, check if it's pure JsonObject
                adAccounts.clear();
                adAccounts.add(loadJSON(json, context));
                return adAccounts;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.ads.sdk.AdAccountDeliveryEstimate.java

License:Open Source License

public static APINodeList<AdAccountDeliveryEstimate> parseResponse(String json, APIContext context,
        APIRequest request) throws MalformedResponseException {
    APINodeList<AdAccountDeliveryEstimate> adAccountDeliveryEstimates = new APINodeList<AdAccountDeliveryEstimate>(
            request, json);//from w w w.j a  va 2 s  .  co  m
    JsonArray arr;
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                adAccountDeliveryEstimates.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return adAccountDeliveryEstimates;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    adAccountDeliveryEstimates.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        adAccountDeliveryEstimates
                                .add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                adAccountDeliveryEstimates.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        adAccountDeliveryEstimates.add(loadJSON(obj.toString(), context));
                    }
                }
                return adAccountDeliveryEstimates;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    adAccountDeliveryEstimates.add(loadJSON(entry.getValue().toString(), context));
                }
                return adAccountDeliveryEstimates;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        adAccountDeliveryEstimates.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return adAccountDeliveryEstimates;
                }

                // Sixth, check if it's pure JsonObject
                adAccountDeliveryEstimates.clear();
                adAccountDeliveryEstimates.add(loadJSON(json, context));
                return adAccountDeliveryEstimates;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}