Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:inventory.StockTransferPendingReport.java

private void setData() throws IOException {
    lb.addGlassPane(this);
    JsonObject call = inventoryAPI.getDataHeader(lb.ConvertDateFormetForDB(jtxtFromDate.getText()),
            lb.ConvertDateFormetForDB(jtxtToDate.getText())).execute().body();

    lb.removeGlassPane(StockTransferPendingReport.this);
    if (call != null) {
        System.out.println(call.toString());
        if (call.get("result").getAsInt() == 1) {
            JsonArray header = call.getAsJsonArray("data");
            dtm.setRowCount(0);// w  w w.  j  a v a  2 s.  c om
            for (int i = 0; i < header.size(); i++) {
                Vector row = new Vector();
                row.add(header.get(i).getAsJsonObject().get("ref_no").getAsString());
                row.add(header.get(i).getAsJsonObject().get("inv_no").getAsString());
                row.add(lb.ConvertDateFormetForDisplay(
                        header.get(i).getAsJsonObject().get("v_date").getAsString()));
                row.add(Constants.BRANCH.get(header.get(i).getAsJsonObject().get("from_loc").getAsInt() - 1)
                        .getBranch_name());
                row.add(Constants.BRANCH.get(header.get(i).getAsJsonObject().get("to_loc").getAsInt() - 1)
                        .getBranch_name());
                row.add(header.get(i).getAsJsonObject().get("approve_by").getAsString());
                row.add(header.get(i).getAsJsonObject().get("QTY").getAsString());
                dtm.addRow(row);
            }
        } else {
            lb.showMessageDailog(call.get("cause").getAsString());
        }
    }
}

From source file:io.apiman.gateway.engine.es.AbstractClientFactory.java

License:Apache License

@SuppressWarnings("nls")
private boolean indexAlreadyExistsException(JestResult response) {
    // ES 1.x//from ww w . j av  a 2s .c  o  m
    if (response.getErrorMessage().startsWith("IndexAlreadyExistsException")) {
        return true;
    }

    // ES 5.x
    // {"error": {"root_cause":[{"type":"index_already_exists_exception","reason": "..."}]}}
    if (response.getJsonObject() == null || !response.getJsonObject().has("error")) {
        return false;
    }

    // Error must be a JSON object.
    JsonObject error = response.getJsonObject().getAsJsonObject("error");
    if (!(error.has("root_cause") && error.get("root_cause").isJsonArray())) {
        return false;
    }

    JsonArray causes = error.getAsJsonArray("root_cause");

    for (JsonElement elem : causes) {
        if (elem.isJsonObject()) {
            JsonElement type = elem.getAsJsonObject().get("type");
            if (type != null && type.getAsString().equals("index_already_exists_exception")) {
                return true;
            }
        }
    }
    return false;
}

From source file:io.crate.testing.CrateTestCluster.java

License:Apache License

private boolean clusterIsReady(CrateTestServer[] servers) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) randomUrlFromServers().openConnection();
    connection.setRequestMethod("POST");

    String query = "{\"stmt\": \"select count(*) as nodes from sys.nodes\"}";
    byte[] body = query.getBytes("UTF-8");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Content-Length", String.valueOf(body.length));
    connection.setDoOutput(true);/*from  ww  w . j  a va 2  s . c  om*/
    connection.getOutputStream().write(body);

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        JsonObject response = parseResponse(connection.getInputStream());
        JsonArray rows = response.getAsJsonArray("rows");
        JsonArray rowsNestedArray = rows.get(0).getAsJsonArray();
        return servers.length == rowsNestedArray.get(0).getAsInt();
    }
    return false;
}

From source file:io.flutter.utils.JsonUtils.java

License:Open Source License

@NotNull
public static List<String> getValues(@NotNull JsonObject json, @NotNull String member) {
    if (!json.has(member)) {
        return Collections.emptyList();
    }//  ww w .j  a  v a  2s .co  m

    final JsonArray rawValues = json.getAsJsonArray(member);
    final ArrayList<String> values = new ArrayList<>(rawValues.size());
    rawValues.forEach(element -> values.add(element.getAsString()));

    return values;
}

From source file:io.github.prison.chat.FancyMessage.java

License:Open Source License

/**
 * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of
 * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs.
 *
 * @param json The JSON string which represents a fancy message.
 * @return A {@code FancyMessage} representing the parameterized JSON message.
 *///www.ja  v a 2s .co  m
public static FancyMessage deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    FancyMessage returnVal = new FancyMessage();
    returnVal.messageParts.clear();
    for (JsonElement mPrt : extra) {
        MessagePart component = new MessagePart();
        JsonObject messagePart = mPrt.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
            // Deserialize text
            if (TextualComponent.isTextKey(entry.getKey())) {
                // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
                Map<String, Object> serializedMapForm = new HashMap<String, Object>(); // Must be object due to Bukkit serializer API compliance
                serializedMapForm.put("key", entry.getKey());
                if (entry.getValue().isJsonPrimitive()) {
                    // Assume string
                    serializedMapForm.put("value", entry.getValue().getAsString());
                } else {
                    // Composite object, but we assume each element is a string
                    for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue()
                            .getAsJsonObject().entrySet()) {
                        serializedMapForm.put("value." + compositeNestedElement.getKey(),
                                compositeNestedElement.getValue().getAsString());
                    }
                }
                component.text = TextualComponent.deserialize(serializedMapForm);
            } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
                if (entry.getValue().getAsBoolean()) {
                    component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
                }
            } else if (entry.getKey().equals("color")) {
                component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
            } else if (entry.getKey().equals("clickEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.clickActionName = object.get("action").getAsString();
                component.clickActionData = object.get("value").getAsString();
            } else if (entry.getKey().equals("hoverEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.hoverActionName = object.get("action").getAsString();
                if (object.get("value").isJsonPrimitive()) {
                    // Assume string
                    component.hoverActionData = new JsonString(object.get("value").getAsString());
                } else {
                    // Assume composite type
                    // The only composite type we currently store is another FancyMessage
                    // Therefore, recursion time!
                    component.hoverActionData = deserialize(object.get("value")
                            .toString() /* This should properly serialize the JSON object as a JSON string */);
                }
            } else if (entry.getKey().equals("insertion")) {
                component.insertionData = entry.getValue().getAsString();
            } else if (entry.getKey().equals("with")) {
                for (JsonElement object : entry.getValue().getAsJsonArray()) {
                    if (object.isJsonPrimitive()) {
                        component.translationReplacements.add(new JsonString(object.getAsString()));
                    } else {
                        // Only composite type stored in this array is - again - FancyMessages
                        // Recurse within this function to parse this as a translation replacement
                        component.translationReplacements.add(deserialize(object.toString()));
                    }
                }
            }
        }
        returnVal.messageParts.add(component);
    }
    return returnVal;
}

From source file:io.github.victorhsr.pos.twitter.business.MentionsCalculator.java

private void updateMentionCountage(JsonObject jsonObject) throws Exception {

    long tweetId = jsonObject.get("id").getAsLong();

    JsonObject tweetObject = tweetManager.getTweetDatails(tweetId);

    JsonObject tweetEntitie = tweetObject.getAsJsonObject("entities");
    JsonArray tweetMentions = tweetEntitie.getAsJsonArray("user_mentions");

    tweetMentions.forEach(mentionElement -> {
        JsonObject mentionObject = mentionElement.getAsJsonObject();
        long userId = mentionObject.get("id").getAsLong();

        if (followersMentions.containsKey(userId)) {
            int count = followersMentions.get(userId);
            followersMentions.replace(userId, ++count);
        }//from   w  w w .  j a v  a  2 s  . co  m

    });

}

From source file:io.github.victorhsr.pos.twitter.FollowersManager.java

public List<Long> getFollowers() throws Exception {

    String jsonResponse = doGetRequest(follwersWt);

    JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);

    JsonArray jsonArray = jsonObject.getAsJsonArray("ids");
    List<Long> follwers = new ArrayList<>();

    jsonArray.forEach(element -> {//  ww w  . j  av  a 2  s  .  c  o  m
        follwers.add(element.getAsLong());
    });

    return follwers;
}

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

/**
 * Checks if the sender is a follower of channel
 * /*from   ww w .j  a va2 s.  co  m*/
 * @param sender - the user who sent the message
 * @param channelNoHash - the channel the message was sent in
 * @return - true if sender is following channel
 */
public static boolean isFollower(String channelNoHash, String sender) {
    try {
        String nextUrl = "https://api.twitch.tv/kraken/channels/" + channelNoHash + "/follows";
        JsonObject obj = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(new URL(nextUrl).openStream()))).getAsJsonObject();
        if (obj.get("error") != null) { // ie it finds it
            return false;
        } else { // it does not find it
            int count = followerCount(channelNoHash);
            int pages = count / 25;
            if (count % 25 != 0) {
                pages++;
            }
            for (int i = 0; i < pages; i++) {
                for (int j = 0; j < 25; j++) {
                    try {
                        if (sender.equalsIgnoreCase(obj.getAsJsonArray("follows").get(j).getAsJsonObject()
                                .get("user").getAsJsonObject().getAsJsonPrimitive("name").getAsString())) {
                            return true;
                        }
                    } catch (IndexOutOfBoundsException e) {
                        return false;
                    }
                }
                nextUrl = obj.getAsJsonObject("_links").getAsJsonPrimitive("next").getAsString();
                obj = new JsonParser()
                        .parse(new JsonReader(new InputStreamReader(new URL(nextUrl).openStream())))
                        .getAsJsonObject();
            }
            return false;
        }
    } catch (FileNotFoundException e) {
        WLogger.log(channelNoHash + "Does not have any followers.");
    } catch (JsonIOException | JsonSyntaxException | IOException e) {
        logger.log(Level.SEVERE, "An error occurred checking if " + sender + " is following " + channelNoHash,
                e);
        WLogger.logError(e);
    }
    return false;
}

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

/**
 * Checks if the sender is subscribed to channel
 * //from w  w  w  .  jav  a2  s .co m
 * @param sender - user who sent the message
 * @param channelNoHash - channel the message was sent in
 * @return - true if sender is subscribed to channel
 */
public static boolean isSubscriber(String sender, String channelNoHash) {
    try {
        String userOAuth = Database.getUserOAuth(channelNoHash);
        String nextUrl = "https://api.twitch.tv/kraken/channels/" + channelNoHash
                + "/subscriptions/?oauth_token=" + userOAuth;
        if (userOAuth == null) {
            return false;
        }
        JsonObject obj = null;
        try {
            obj = new JsonParser().parse(new JsonReader(new InputStreamReader(new URL(nextUrl).openStream())))
                    .getAsJsonObject();
        } catch (IOException e) {
            if (e.getLocalizedMessage().equalsIgnoreCase(
                    "Server returned HTTP response code: 422 for URL: https://api.twitch.tv/kraken/channels/"
                            + channelNoHash + "/subscriptions/?oauth_token=" + userOAuth)) {
                return false;
            }
            logger.log(Level.SEVERE, String.format("There was an issue checking is %s is subscribed to %s",
                    sender, channelNoHash), e);
            WLogger.logError(e);
        }
        if (obj.get("error") != null) { // ie it finds it
            return false;
        } else { // it does not find it
            int count = subscriberCount(channelNoHash, userOAuth);
            int pages = count / 25;
            if (count % 25 != 0) {
                pages++;
            }
            for (int i = 0; i < pages; i++) {
                for (int j = 0; j < 25; j++) {
                    if (sender.equalsIgnoreCase(obj.getAsJsonArray("subscriptions").get(j).getAsJsonObject()
                            .getAsJsonPrimitive("display_name").getAsString())) {
                        return true;
                    }
                }
                nextUrl = obj.getAsJsonObject("_links").getAsJsonPrimitive().getAsString() + "?oauth_token="
                        + userOAuth;
                obj = new JsonParser()
                        .parse(new JsonReader(new InputStreamReader(new URL(nextUrl).openStream())))
                        .getAsJsonObject();
            }
            return false;
        }
    } catch (FileNotFoundException e) {
        WLogger.log(channelNoHash + "Does not have any subscribers or is not partnered.");
    } catch (JsonIOException | JsonSyntaxException | IOException e) {
        logger.log(Level.SEVERE, "An error occurred checking if " + sender + " is following " + channelNoHash,
                e);
        WLogger.logError(e);
    }
    return false;
}

From source file:io.imoji.sdk.objects.json.AttributionDeserializer.java

License:Open Source License

@Override
public Category.Attribution deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject root = json.getAsJsonObject();
    Artist artist = context.deserialize(root, Artist.class);

    String attributionId = root.has("packId") ? root.get("packId").getAsString() : null;
    Uri uri = root.has("packURL") ? Uri.parse(root.get("packURL").getAsString()) : null;
    Category.URLCategory urlCategory = root.has("packURLCategory")
            ? URL_CATEGORY_MAP.get(root.get("packURLCategory").getAsString())
            : null;//w ww.j av a2s  . c  o m

    Imoji.LicenseStyle licenseStyle = Imoji.LicenseStyle.NonCommercial;
    if (root.has("licenseStyle")) {
        String licenseStyleStr = root.get("licenseStyle").getAsString();
        if ("commercialPrint".equals((licenseStyleStr))) {
            licenseStyle = Imoji.LicenseStyle.CommercialPrint;
        }
    }
    JsonArray relatedTagsArray = root.getAsJsonArray("relatedTags");
    List<String> relatedTags;

    if (relatedTagsArray != null && relatedTagsArray.size() > 0) {
        relatedTags = new ArrayList<>(relatedTagsArray.size());
        for (JsonElement tag : relatedTagsArray) {
            relatedTags.add(tag.getAsString());
        }
    } else {
        relatedTags = Collections.emptyList();
    }

    if (urlCategory == null && uri != null) {
        urlCategory = Category.URLCategory.Website;
    }

    return new Category.Attribution(attributionId, artist, uri, relatedTags, urlCategory, licenseStyle);
}