Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:jmm.api.tmdb.TMDBMovieWrapper.java

License:Open Source License

private void addActorsAndDirector(JsonElement rootElement, TMDBVideoFile videoFile) {
    //handle response
    if (!rootElement.isJsonNull()) {
        JsonElement value;/*from   w w w . j ava  2  s .c om*/
        //Publisher
        value = rootElement.getAsJsonObject().get("casts");
        if (value != null && !value.isJsonNull()) {
            value = value.getAsJsonObject().get("cast");
            if (value.isJsonArray()) {
                JsonArray cast = value.getAsJsonArray();
                Iterator<JsonElement> castIterator = cast.iterator();
                while (castIterator.hasNext()) {
                    JsonElement actorElement = castIterator.next();
                    value = actorElement.getAsJsonObject().get("name");
                    if (!value.isJsonNull()) {
                        Actor actor = new Actor(value.getAsString());

                        value = actorElement.getAsJsonObject().get("id");
                        if (!value.isJsonNull()) {
                            actor.setTmdbID(value.getAsInt());
                        }
                        value = actorElement.getAsJsonObject().get("profile_path");
                        if (!value.isJsonNull()) {
                            actor.setProfilePicturePath(
                                    API_BASE_IMAGEURL + Profile_Sizes.w185 + value.getAsString());
                        }
                        videoFile.addActor(actor);
                    }
                }
            }
            value = rootElement.getAsJsonObject().get("casts");
            value = value.getAsJsonObject().get("crew");
            if (value.isJsonArray()) {
                JsonArray crew = value.getAsJsonArray();
                //Look for director
                Iterator<JsonElement> crewIterator = crew.iterator();
                while (crewIterator.hasNext()) {
                    JsonElement crewElement = crewIterator.next();
                    value = crewElement.getAsJsonObject().get("job");
                    if (!value.isJsonNull() && (value.getAsString().equalsIgnoreCase("Director"))) {
                        value = crewElement.getAsJsonObject().get("name");
                        if (!value.isJsonNull()) {
                            videoFile.setDirector(value.getAsString());
                        }
                    }
                }
            }
        }
    }
}

From source file:jp.pay.model.EventDataDeserializer.java

License:Open Source License

private Object[] deserializeJsonArray(JsonArray arr) {
    Object[] elems = new Object[arr.size()];
    Iterator<JsonElement> elemIter = arr.iterator();
    int i = 0;//from  w ww .  j av  a  2 s  .c  o  m
    while (elemIter.hasNext()) {
        JsonElement elem = elemIter.next();
        elems[i++] = deserializeJsonElement(elem);
    }
    return elems;
}

From source file:JsonParser.ParseJson.java

public static void dumpJSONElement(JsonElement element, String type) {
    if (element.isJsonObject()) {
        //System.out.println("Is an object");
        JsonObject obj = element.getAsJsonObject();
        java.util.Set<java.util.Map.Entry<String, JsonElement>> entries = obj.entrySet();
        java.util.Iterator<java.util.Map.Entry<String, JsonElement>> iter = entries.iterator();
        while (iter.hasNext()) {
            java.util.Map.Entry<String, JsonElement> entry = iter.next();
            //  System.out.println("Key: " + entry.getKey());
            if (entry.getKey().toString().equals("instances")) {
                System.out.println("............Topic: ");
                dumpJSONElement(entry.getValue(), "topic");

            }/*from   w ww.  jav a2s  .co  m*/
            if (entry.getKey().toString().equals("aspects")) {
                System.out.println("............aspects: ");
                dumpJSONElement(entry.getValue(), "aspect");

            } else if (entry.getKey().toString().equals("positives")) {
                System.out.println(".............Positive Words ");
                dumpJSONElement(entry.getValue(), "positive");
            } else if (entry.getKey().toString().equals("negatives")) {
                System.out.println(".............negatives Words ");
                dumpJSONElement(entry.getValue(), "negative");
            } else {
                dumpJSONElement(entry.getValue(), "");
            }

        }

    } else if (element.isJsonArray()) {
        JsonArray array = element.getAsJsonArray();
        //System.out.println("Is an array. Number of values: " + array.size());
        java.util.Iterator<JsonElement> iter = array.iterator();
        while (iter.hasNext()) {
            JsonElement entry = iter.next();

            dumpJSONElement(entry, "");
        }
    } else if (element.isJsonPrimitive()) {
        //System.out.println("Is a primitive");
        JsonPrimitive value = element.getAsJsonPrimitive();
        if (value.isBoolean()) {
            //System.out.println("Is boolean: " + value.getAsBoolean());
        } else if (value.isNumber()) {
            //  System.out.println("Is number: " + value.getAsNumber());
        } else if (value.isString()) {
            //if(!value.getAsString().equals("empty"))
            //{
            //if(type.equals("topic"))
            //{
            System.out.println(type + " :" + value.getAsString());
            //}
        }
    } else if (element.isJsonNull()) {
        System.out.println("Is NULL");
    } else {
        System.out.println("Error. Unknown type of element");
    }
}

From source file:monasca.common.middleware.FilterUtils.java

License:Apache License

private static void wrapRequestFromHttpV3Response(ServletRequest req, String data) {
    StringBuilder tenants = new StringBuilder();
    StringBuilder nonTenants = new StringBuilder();
    JsonParser jp = new JsonParser();
    JsonObject token = jp.parse(data).getAsJsonObject().get("token").getAsJsonObject();
    // Domain Scoped Token
    if (token.get("domain") != null) {
        JsonObject domain = token.get("domain").getAsJsonObject();
        req.setAttribute(AUTH_DOMAIN_ID, domain.get("id").getAsString());
        if (domain.get("name") != null) {
            req.setAttribute(AUTH_DOMAIN_NAME, domain.get("name").getAsString());
        }/*from  w  w  w.  j av a2s.c  om*/
    }
    // Project Scoped Token
    if (token.get("project") != null) {
        JsonObject project = token.get("project").getAsJsonObject();
        req.setAttribute(AUTH_PROJECT_ID, project.get("id").getAsString());
        req.setAttribute(AUTH_PROJECT_NAME, project.get("name").getAsString());

        JsonObject projectDomain = project.get("domain").getAsJsonObject();
        // special case where the value of id is null and the
        // projectDomain.get("id") != null
        if (!projectDomain.get("id").equals(JsonNull.INSTANCE)) {
            req.setAttribute(AUTH_PROJECT_DOMAIN_ID, projectDomain.get("id").getAsString());
        }
        if (projectDomain.get("name") != null) {
            req.setAttribute(AUTH_PROJECT_DOMAIN_NAME, projectDomain.get("name"));
        }
    }
    // User info
    if (token.get("user") != null) {
        JsonObject user = token.get("user").getAsJsonObject();
        req.setAttribute(AUTH_USER_ID, user.get("id").getAsString());
        req.setAttribute(AUTH_USER_NAME, user.get("name").getAsString());

        JsonObject userDomain = user.get("domain").getAsJsonObject();
        if (userDomain.get("id") != null) {
            req.setAttribute(AUTH_USER_DOMAIN_ID, userDomain.get("id").getAsString());
        }
        if (userDomain.get("name") != null) {
            req.setAttribute(AUTH_USER_DOMAIN_NAME, userDomain.get("name").getAsString());
        }

    }
    // Roles
    JsonArray roles = token.getAsJsonArray("roles");
    if (roles != null) {
        Iterator<JsonElement> it = roles.iterator();
        StringBuilder roleBuilder = new StringBuilder();
        while (it.hasNext()) {

            //Changed to meet my purposes
            JsonObject role = it.next().getAsJsonObject();
            String currentRole = role.get("name").getAsString();
            roleBuilder.append(currentRole).append(",");
        }
        //My changes to meet my needs
        req.setAttribute(AUTH_ROLES, roleBuilder.toString());
    }
    String tenantRoles = (tenants.length() > 0) ? tenants.substring(1) : tenants.toString();
    String nonTenantRoles = (nonTenants.length() > 0) ? nonTenants.substring(1) : nonTenants.toString();
    if (!tenantRoles.equals("")) {
        req.setAttribute(AUTH_ROLES, tenantRoles);
    }
    if (!nonTenantRoles.equals("")) {
        req.setAttribute(AUTH_HP_IDM_ROLES, nonTenantRoles);
    }
    // Catalog
    if (token.get("catalog") != null && appConfig.isIncludeCatalog()) {
        JsonArray catalog = token.get("catalog").getAsJsonArray();
        req.setAttribute(AUTH_SERVICE_CATALOG, catalog.toString());
    }
}

From source file:net.caseif.flint.common.util.helper.CommonPlayerHelper.java

License:Open Source License

public static boolean checkOfflineFlag(UUID player) {
    try {//from w  ww .  j a v a  2  s . c o m
        File playerStore = CommonDataFiles.OFFLINE_PLAYER_STORE.getFile();
        if (!playerStore.exists()) {
            return false;
        }

        JsonArray json;
        try (FileReader reader = new FileReader(playerStore)) {
            JsonElement el = new JsonParser().parse(reader);
            if (!el.isJsonArray()) {
                return false;
            }
            json = el.getAsJsonArray();
        }

        if (json.size() > 0) {
            JsonArray newArray = new JsonArray();

            Iterator<JsonElement> it = json.iterator();
            boolean found = false;
            while (it.hasNext()) {
                JsonElement el = it.next();
                if (el.getAsString().equals(player.toString())) {
                    found = true;
                } else {
                    newArray.add(el);
                }
            }

            if (found) {
                try (FileWriter writer = new FileWriter(playerStore)) {
                    writer.write(newArray.toString());
                }
                return true;
            }
        }
        return false;
    } catch (IOException ex) {
        CommonCore.logSevere("Failed to mark player as offline!");
        throw new RuntimeException(ex);
    }
}

From source file:net.petercashel.jmsDd.auth.DataSystems.JsonDataSystem.JsonDataSystem.java

License:Apache License

@Override
public void load() {

    String content = "";
    try {//w  w  w  .j av  a 2  s . c o m
        content = readFile(new File(Configuration.configDir, "userConfig.json").toPath().toString(),
                StandardCharsets.US_ASCII);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    JsonElement jelement = new JsonParser().parse(content);
    // JsonObject jobject = jelement.getAsJsonObject();
    JsonArray jarray = jelement.getAsJsonArray();

    Iterator<JsonElement> iterator = jarray.iterator();
    while (iterator.hasNext()) {
        JsonElement e = iterator.next();
        JsonObject s = e.getAsJsonObject();
        Gson gson = new GsonBuilder().create();
        UserData r = gson.fromJson(s, UserData.class);
        userList.put(r.Username, r);
    }

}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog221.java

License:Apache License

protected String addCheckCommandTimeoutParam(String source) {
    JsonObject sourceJson = new JsonParser().parse(source).getAsJsonObject();
    JsonArray parametersJson = sourceJson.getAsJsonArray("parameters");

    boolean parameterExists = parametersJson != null && !parametersJson.isJsonNull();

    if (parameterExists) {
        Iterator<JsonElement> jsonElementIterator = parametersJson.iterator();
        while (jsonElementIterator.hasNext()) {
            JsonElement element = jsonElementIterator.next();
            JsonElement name = element.getAsJsonObject().get("name");
            if (name != null && !name.isJsonNull() && name.getAsString().equals("check.command.timeout")) {
                return sourceJson.toString();
            }/*w ww  .j  a va  2  s  . c o  m*/
        }
    }

    JsonObject checkCommandTimeoutParamJson = new JsonObject();
    checkCommandTimeoutParamJson.add("name", new JsonPrimitive("check.command.timeout"));
    checkCommandTimeoutParamJson.add("display_name", new JsonPrimitive("Check command timeout"));
    checkCommandTimeoutParamJson.add("value", new JsonPrimitive(60.0));
    checkCommandTimeoutParamJson.add("type", new JsonPrimitive("NUMERIC"));
    checkCommandTimeoutParamJson.add("description",
            new JsonPrimitive("The maximum time before check command will be killed by timeout"));
    checkCommandTimeoutParamJson.add("units", new JsonPrimitive("seconds"));

    if (!parameterExists) {
        parametersJson = new JsonArray();
        parametersJson.add(checkCommandTimeoutParamJson);
        sourceJson.add("parameters", parametersJson);
    } else {
        parametersJson.add(checkCommandTimeoutParamJson);
        sourceJson.remove("parameters");
        sourceJson.add("parameters", parametersJson);
    }

    return sourceJson.toString();
}

From source file:org.apache.gobblin.converter.csv.CsvToJsonConverterV2.java

License:Apache License

@VisibleForTesting
JsonObject createOutput(JsonArray outputSchema, String[] inputRecord, List<String> customOrder) {

    Preconditions.checkArgument(outputSchema.size() == customOrder.size(),
            "# of columns mismatch. Input " + outputSchema.size() + " , output: " + customOrder.size());
    JsonObject outputRecord = new JsonObject();
    Iterator<JsonElement> outputSchemaIterator = outputSchema.iterator();
    Iterator<String> customOrderIterator = customOrder.iterator();

    while (outputSchemaIterator.hasNext() && customOrderIterator.hasNext()) {
        JsonObject field = outputSchemaIterator.next().getAsJsonObject();
        String key = field.get(COLUMN_NAME_KEY).getAsString();
        int i = Integer.parseInt(customOrderIterator.next());
        Preconditions.checkArgument(i < inputRecord.length,
                "Index out of bound detected in customer order. Index: " + i + " , # of CSV columns: "
                        + inputRecord.length);
        if (i < 0 || null == inputRecord[i] || JSON_NULL_VAL.equalsIgnoreCase(inputRecord[i])) {
            outputRecord.add(key, JsonNull.INSTANCE);
            continue;
        }/*from   w w  w .j a v a2  s. c  o  m*/
        outputRecord.add(key, convertValue(inputRecord[i], field.getAsJsonObject(DATA_TYPE_KEY)));
    }

    return outputRecord;
}

From source file:org.apache.gobblin.salesforce.SalesforceSource.java

License:Apache License

/**
 * Get the row count for a time range//from   w  w  w  .java  2  s  . c  o m
 */
private int getCountForRange(TableCountProbingContext probingContext, StrSubstitutor sub,
        Map<String, String> subValues, long startTime, long endTime) {
    String startTimeStr = Utils.dateToString(new Date(startTime),
            SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);
    String endTimeStr = Utils.dateToString(new Date(endTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);

    subValues.put("start", startTimeStr);
    subValues.put("end", endTimeStr);

    String query = sub.replace(PROBE_PARTITION_QUERY_TEMPLATE);

    log.debug("Count query: " + query);
    probingContext.probeCount++;

    JsonArray records = getRecordsForQuery(probingContext.connector, query);
    Iterator<JsonElement> elements = records.iterator();
    JsonObject element = elements.next().getAsJsonObject();

    return element.get("cnt").getAsInt();
}

From source file:org.apache.gobblin.salesforce.SalesforceSource.java

License:Apache License

/**
 * Parse the query results into a {@link Histogram}
 *//*from  ww  w.  j a  v  a 2 s  .c o  m*/
private Histogram parseDayBucketingHistogram(JsonArray records) {
    log.info("Parse day-based histogram");

    Histogram histogram = new Histogram();

    Iterator<JsonElement> elements = records.iterator();
    JsonObject element;

    while (elements.hasNext()) {
        element = elements.next().getAsJsonObject();
        String time = element.get("time").getAsString() + ZERO_TIME_SUFFIX;
        int count = element.get("cnt").getAsInt();

        histogram.add(new HistogramGroup(time, count));
    }

    return histogram;
}