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:eu.sisob.uma.NPL.Researchers.Freebase.LocationDataResolver_Method2.java

License:Open Source License

private locationSet getLocationFromMid(String mid) {
    locationSet location = null;//  w  w  w  .ja  v  a  2  s . c  om

    String query = "[{" + "\"name\":[]," + "\"mid\":\"" + mid + "\"," + "\"/location/location/containedby\":"
            + "[{" + "\"id\": null," + "\"name\": null," + "\"/common/topic/alias\":[],"
            + "\"type\": \"/location/citytown\"," + "\"/location/location/containedby\":" + "[{"
            + "\"id\": null," + "\"name\": null," + "\"/common/topic/alias\":[],"
            + "\"type\": \"/location/administrative_division\"," + "\"/location/location/containedby\":" + "[{"
            + "\"id\": null," + "\"name\": null," + "\"/common/topic/alias\":[],"
            + "\"type\": \"/location/country\"" + "}]" + "}]" + "}]" + "}]";

    JsonArray results = Utils.getResultsFromMQLReadCall(query);

    if (results != null) {
        //We assume one result
        if (results.size() == 0) {
        } else if (results.size() == 1) {
            JsonObject result = results.iterator().next().getAsJsonObject();
            location = getLocationsFromJsonObject1(result);
        } else {
            int k = 0;
            k = 0;
        }
    }

    return location;
}

From source file:fi.vtt.nubomedia.armodule.Ar3DHandler.java

License:Open Source License

private java.util.List<ArThing> createArThings(JsonObject jsonObjects) {
    System.err.println("*createARThings:#" + jsonObjects + "#");
    List<ArThing> arThings = new ArrayList<ArThing>();
    JsonArray jsonArray = jsonObjects.getAsJsonArray("augmentables");

    Iterator<JsonElement> itr = jsonArray.iterator();
    while (itr.hasNext()) {
        JsonElement jsonElm = itr.next();
        if (jsonElm.isJsonNull()) {
            System.err.println("Really Skip null");
            continue;
        }//ww  w  .  j a  v a2s  .c  o m
        System.err.println("Got: " + jsonElm);

        JsonObject jsonObject = jsonElm.getAsJsonObject();

        int id = jsonObject.get("id").getAsInt();
        OverlayType augmentableType;
        switch (jsonObject.get("type").getAsString()) {
        case "2D":
            augmentableType = OverlayType.TYPE2D;
            break;
        case "3D":
            augmentableType = OverlayType.TYPE3D;
            break;
        default:
            throw new RuntimeException("Bizarre OverlayType: " + jsonObject.get("type").getAsString());
        }
        List<ArKvpString> strings = new ArrayList<ArKvpString>();
        List<ArKvpFloat> floats = new ArrayList<ArKvpFloat>();
        List<ArKvpInteger> integers = new ArrayList<ArKvpInteger>();
        createKVPs(jsonObject, strings, integers, floats);

        ArThing arThing = new ArThing(id, augmentableType, strings, integers, floats);
        arThings.add(arThing);
    }
    System.err.println("*ResultArThigs: " + arThings.size() + "#" + arThings);
    return arThings;
}

From source file:fi.vtt.nubomedia.armodule.Ar3DHandler.java

License:Open Source License

private void pose(WebSocketSession session, JsonObject jsonMessage) {
    try {//w  ww.  j  ava2 s . co  m
        System.err.println("json POSE from browser");

        ArMarkerdetector arFilter = getArFilter(session);
        if (arFilter == null) {
            log.error("Start the filter first");
            return;
        }

        String json = jsonMessage.getAsJsonPrimitive("pose").getAsString();
        System.err.println("json:\n" + json);
        JsonObject jsonObjects = gson.fromJson(json, JsonObject.class);

        JsonArray jsonArray = jsonObjects.getAsJsonArray("pose");
        Iterator<JsonElement> itr = jsonArray.iterator();
        while (itr.hasNext()) {
            JsonElement jsonElm = itr.next();
            if (jsonElm.isJsonNull()) {
                System.err.println("Really Skip null");
                continue;
            }
            System.err.println("Got: " + jsonElm);

            JsonObject jsonObject = jsonElm.getAsJsonObject();
            int id = jsonObject.get("id").getAsInt();
            int type = jsonObject.get("type").getAsInt();
            //String id = jsonObject.get("id").getAsString();
            //String type = jsonObject.get("type").getAsString();
            float value = jsonObject.get("value").getAsFloat();
            System.err.println("" + id + "#" + type + "#" + value);

            arFilter.setPose(id, type, value);
        }
    } catch (Throwable t) {
        t.printStackTrace();
        error(session, t.getMessage());
    }
}

From source file:fi.vtt.nubomedia.kurento.Ar3DHandler.java

License:Open Source License

private java.util.List<ArThing> createArThings(JsonObject jsonObjects) {
    System.err.println(jsonObjects);
    List<ArThing> arThings = new ArrayList<ArThing>();
    JsonArray jsonArray = jsonObjects.getAsJsonArray("augmentables");

    Iterator<JsonElement> itr = jsonArray.iterator();
    while (itr.hasNext()) {
        JsonElement jsonElm = itr.next();
        if (jsonElm.isJsonNull()) {
            System.err.println("Really Skip null");
            continue;
        }/*from www  . j a v a 2 s  .c  om*/
        System.err.println("Skip: " + jsonElm);

        JsonObject jsonObject = jsonElm.getAsJsonObject();

        int id = jsonObject.get("id").getAsInt();
        OverlayType augmentableType;
        switch (jsonObject.get("type").getAsString()) {
        case "2D":
            augmentableType = OverlayType.TYPE2D;
            break;
        case "3D":
            augmentableType = OverlayType.TYPE3D;
            break;
        default:
            throw new RuntimeException("Bizarre OverlayType: " + jsonObject.get("type").getAsString());
        }
        List<ArKvpString> strings = new ArrayList<ArKvpString>();
        List<ArKvpFloat> floats = new ArrayList<ArKvpFloat>();
        List<ArKvpInteger> integers = new ArrayList<ArKvpInteger>();
        createKVPs(jsonObject, strings, integers, floats);

        ArThing arThing = new ArThing(id, augmentableType, strings, integers, floats);
        arThings.add(arThing);
    }
    return arThings;

    //      return createArThings(new int[]{
    //         0, 
    //         1, 
    //         2
    //          }, 
    //          new OverlayType[]{
    //         OverlayType.TYPE3D, 
    //         OverlayType.TYPE3D, 
    //         OverlayType.TYPE2D
    //          },
    //          new String[]{
    //         
    //         //"http://130.188.198.150:9090/icosahedron.ply", 
    //         "/opt/teapot.ply", 
    //         "/opt/cube.ply", 
    //         "/opt/propex.png"
    //          },
    //          new float[]{
    //         1.0f, 
    //         0.05f, 
    //         1.0f
    //          },
    //          new String[]{
    //         "", 
    //         "", 
    //         "snafu"
    //          });
}

From source file:fi.vtt.nubomedia.kurento.Ar3DHandler.java

License:Open Source License

private void pose(WebSocketSession session, JsonObject jsonMessage) {
    try {/*w  ww  .  j  a v  a  2s  .com*/
        System.err.println("json POSE from browser");

        String json = jsonMessage.getAsJsonPrimitive("pose").getAsString();
        System.err.println("json:\n" + json);
        JsonObject jsonObjects = gson.fromJson(json, JsonObject.class);

        JsonArray jsonArray = jsonObjects.getAsJsonArray("pose");
        Iterator<JsonElement> itr = jsonArray.iterator();
        while (itr.hasNext()) {
            JsonElement jsonElm = itr.next();
            if (jsonElm.isJsonNull()) {
                System.err.println("Really Skip null");
                continue;
            }
            System.err.println("Got: " + jsonElm);

            JsonObject jsonObject = jsonElm.getAsJsonObject();
            int id = jsonObject.get("id").getAsInt();
            int type = jsonObject.get("type").getAsInt();
            //String id = jsonObject.get("id").getAsString();
            //String type = jsonObject.get("type").getAsString();
            float value = jsonObject.get("value").getAsFloat();
            System.err.println("" + id + "#" + type + "#" + value);
            if (arFilter != null) {
                arFilter.setPose(id, type, value);
            } else {
                System.err.println("Start the filter first");
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        sendError(session, t.getMessage());
    }
}

From source file: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()) {
        String key = outputSchemaIterator.next().getAsJsonObject().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  www .  j  a  v  a  2  s .  c  o m*/
        outputRecord.addProperty(key, inputRecord[i]);
    }

    return outputRecord;
}

From source file:gobblin.salesforce.SalesforceExtractor.java

License:Apache License

@Override
public Iterator<JsonElement> getData(CommandOutput<?, ?> response) throws DataRecordException {
    log.debug("Get data records from response");

    String output;//from   w  w  w  .ja v a  2s . co m
    Iterator<String> itr = (Iterator<String>) response.getResults().values().iterator();
    if (itr.hasNext()) {
        output = itr.next();
    } else {
        throw new DataRecordException("Failed to get data from salesforce; REST response has no output");
    }

    List<JsonElement> rs = Lists.newArrayList();
    JsonElement element = GSON.fromJson(output, JsonObject.class);
    JsonArray partRecords;
    try {
        JsonObject jsonObject = element.getAsJsonObject();

        partRecords = jsonObject.getAsJsonArray("records");
        if (jsonObject.get("done").getAsBoolean()) {
            setPullStatus(false);
        } else {
            setNextUrl(this.sfConnector.getFullUri(jsonObject.get("nextRecordsUrl").getAsString()
                    .replaceAll(this.sfConnector.getServicesDataEnvPath(), "")));
        }

        JsonArray array = Utils.removeElementFromJsonArray(partRecords, "attributes");
        Iterator<JsonElement> li = array.iterator();
        while (li.hasNext()) {
            JsonElement recordElement = li.next();
            rs.add(recordElement);
        }
        return rs.iterator();
    } catch (Exception e) {
        throw new DataRecordException("Failed to get records from salesforce; error - " + e.getMessage(), e);
    }
}

From source file:gobblin.salesforce.SalesforceSource.java

License:Apache License

private Histogram parseHistogram(CommandOutput<?, ?> response) throws DataRecordException {
    log.info("Parse histogram");
    Histogram histogram = new Histogram();

    String output;//from   w  w  w  . ja  v a 2  s . c  o m
    Iterator<String> itr = (Iterator<String>) response.getResults().values().iterator();
    if (itr.hasNext()) {
        output = itr.next();
    } else {
        throw new DataRecordException("Failed to get data from salesforce; REST response has no output");
    }
    JsonArray records = GSON.fromJson(output, JsonObject.class).getAsJsonArray("records");
    Iterator<JsonElement> elements = records.iterator();
    JsonObject element;
    while (elements.hasNext()) {
        element = elements.next().getAsJsonObject();
        histogram.add(new HistogramGroup(element.get("time").getAsString(), element.get("cnt").getAsInt()));
    }

    return histogram;
}

From source file:gov.pnnl.goss.gridappsd.configuration.GLDSimulationOutputConfigurationHandler.java

License:Open Source License

String CreateGldPubs(Reader measurementFileReader, String processId, String username)
        throws FileNotFoundException {
    String jsonObjStr = "";
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonObject gldConfigObj = new JsonObject();
    //      JsonObject gldPublications = new JsonObject();

    try {//w  w  w . ja v  a  2 s . c om
        JsonObject jsonObj = gson.fromJson(measurementFileReader, JsonObject.class);
        JsonArray feeders = (JsonArray) jsonObj.get("feeders");
        Iterator<JsonElement> iter = feeders.iterator();
        while (iter.hasNext()) {
            JsonObject feederInfo = (JsonObject) iter.next();
            JsonArray feederMeasurements = (JsonArray) feederInfo.get("measurements");
            Iterator<JsonElement> feederMeasurementsIter = feederMeasurements.iterator();
            Map<String, JsonArray> measurements = new HashMap<String, JsonArray>();
            while (feederMeasurementsIter.hasNext()) {
                JsonObject feederMeasurement = (JsonObject) feederMeasurementsIter.next();
                parseMeasurement(measurements, feederMeasurement);
            }
            for (Map.Entry<String, JsonArray> entry : measurements.entrySet()) {
                gldConfigObj.add(entry.getKey(), entry.getValue());
            }
            measurements.clear();
        }
        //         gldConfigObj.add("publications", gldPublications);
        jsonObjStr = gson.toJson(gldConfigObj);

    } catch (JsonIOException e) {
        logError("Error while generating simulation output: " + e.getMessage(), processId, username,
                logManager);
        throw e;
    } catch (JsonParseException e) {
        logError("Error while generating simulation output: " + e.getMessage(), processId, username,
                logManager);
        throw e;
    }
    return jsonObjStr;
}

From source file:imapi.OnlineDatabaseActions.java

License:Apache License

private int readJsonUriVals(InputStream inputStream, Vector<String> uriVals) {

    try {//from   w  ww.j a  v  a 2  s . c  o m

        JsonReader rdr = new JsonReader(new InputStreamReader(inputStream));
        JsonParser parser = new JsonParser();
        JsonElement jElement = parser.parse(rdr);

        if (jElement.isJsonObject() == false) {
            showContentsOfInputStream(inputStream);
            return ApiConstants.IMAPIFailCode;
        }

        // read head/vars from json in order to get the names of the
        // select clause in the order that they were declared.
        // Store in headVarNames vector
        Vector<String> headVarNames = new Vector<String>();

        JsonObject jRootObject = jElement.getAsJsonObject();
        JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray();

        Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator();
        while (jVarsIter.hasNext()) {
            JsonElement jVarElement = jVarsIter.next();
            if (jVarElement.isJsonPrimitive()) {
                headVarNames.add(jVarElement.getAsString());
            }
        }

        if (jRootObject.has("results") == false
                || jRootObject.get("results").getAsJsonObject().has("bindings") == false) {
            return ApiConstants.IMAPIFailCode;
        }

        // loop over all json bindings
        JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings")
                .getAsJsonArray();
        Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator();
        while (jBindingsIter.hasNext()) {

            // of the binding
            String uri = "";

            JsonElement jBindingElement = jBindingsIter.next();
            if (jBindingElement.isJsonObject() == false) {
                continue;
            }
            JsonObject jBindingObject = jBindingElement.getAsJsonObject();

            for (int k = 0; k < headVarNames.size(); k++) {

                String currentPropertyName = headVarNames.get(k);
                if (jBindingObject.has(currentPropertyName)) {

                    JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject();

                    String valStr = "";
                    if (jObj.has("value")) {
                        valStr = jObj.get("value").getAsString();
                    }

                    if (k == 0) {
                        uri = valStr;
                    }
                }
            }

            if (uri.length() > 0 && uriVals.contains(uri) == false) {
                uriVals.add(uri);
            }

            // end of asking for all predicates of select clause head/vars names 
        } // edn of while llop that iters across all bindings

    } catch (Exception ex) {
        Utilities.handleException(ex);
        return ApiConstants.IMAPIFailCode;
    }

    return ApiConstants.IMAPISuccessCode;
}