Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:edu.illinois.cs.cogcomp.core.utilities.JsonSerializer.java

License:Open Source License

private static void readAttributes(HasAttributes obj, JsonObject json) {
    if (json.has("properties")) {
        JsonObject properties = json.getAsJsonObject("properties");

        for (Entry<String, JsonElement> entry : properties.entrySet()) {
            obj.addAttribute(entry.getKey(), entry.getValue().getAsString());
        }//from  w w w.j ava 2  s  .c  o  m
    }
}

From source file:edu.illinois.cs.cogcomp.core.utilities.JsonSerializer.java

License:Open Source License

private static void readLabelsToScores(Map<String, Double> obj, JsonObject json) {
    if (json.has(LABEL_SCORE_MAP)) {
        JsonObject map = json.getAsJsonObject(LABEL_SCORE_MAP);
        for (Entry<String, JsonElement> e : map.entrySet()) {
            obj.put(e.getKey(), e.getValue().getAsDouble());
        }//from   w  w  w .  j  ava  2 s .com
    }
}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

private static void addConstraints(Template tpl, String json) {
    JsonElement el = new JsonParser().parse(json);
    for (JsonElement tel : el.getAsJsonArray()) {
        JsonObject triple = tel.getAsJsonObject();
        String subj = triple.getAsJsonObject("subject").get("id").getAsString();
        String pred = triple.getAsJsonObject("predicate").get("id").getAsString();
        JsonObject objitem = triple.getAsJsonObject("object");
        if (objitem.get("value") != null && objitem.get("isLiteral").getAsBoolean()) {
            JsonPrimitive obj = objitem.get("value").getAsJsonPrimitive();
            String objtype = objitem.get("type") != null ? objitem.get("type").getAsString() : null;
            tpl.getConstraintEngine().createNewDataConstraint(subj, pred,
                    obj.isString() ? obj.getAsString() : obj.toString(), objtype);
        } else {//from w  ww .  j a v a2s .c om
            String obj = objitem.get("id").getAsString();
            tpl.getConstraintEngine().createNewConstraint(subj, pred, obj);
        }
    }
}

From source file:edu.jhuapl.dorset.agents.FlickrAgent.java

License:Open Source License

protected String getImageUrl(String json) {
    Gson gson = new Gson();
    JsonObject jsonObj = gson.fromJson(json, JsonObject.class);
    JsonObject photos = jsonObj.getAsJsonObject("photos");
    JsonArray photoArray = photos.getAsJsonArray("photo");
    JsonObject photo = photoArray.get(0).getAsJsonObject();
    String id = photo.get("id").getAsString();
    String secret = photo.get("secret").getAsString();
    String server = photo.get("server").getAsString();
    String farm = photo.get("farm").getAsString();

    return "https://farm" + farm + ".staticflickr.com/" + server + "/" + id + "_" + secret + "_z.jpg";
}

From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java

License:Open Source License

public static void handleControlMeasures(Map.Entry<String, JsonElement> e,
        HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap) {
    /*/*from ww  w. jav a  2 s .  c  o m*/
       Control measures are now an array of objects, not strings.
    */
    JsonElement je = e.getValue();
    if (je instanceof JsonArray) {
        JsonArray elemArray = (JsonArray) je;
        Iterator<JsonElement> elemIter = elemArray.iterator();
        int size = elemArray.size();
        while (elemIter.hasNext()) {
            JsonElement elemi = elemIter.next();
            JsonObject jo = (JsonObject) elemi;
            String value = jo.getAsJsonObject("identifier").getAsJsonPrimitive("identifierDescription")
                    .getAsString();

            uniqueCms.add(value);

            if (cmMap.containsKey(value)) {
                IRI classIri = cmMap.get(value);
                String cmInstanceLabel = value + " control measure by " + fullName;
                String simxInstanceLabel = "simulating of epidemic with " + value + " control measure by "
                        + fullName;
                OWLNamedIndividual simxInd = createNamedIndividualWithTypeAndLabel(odf, oo,
                        iriMap.lookupClassIri("simulatingx"), iriMap.lookupAnnPropIri("editor preferred"),
                        simxInstanceLabel);
                OWLNamedIndividual cmInd = createNamedIndividualWithTypeAndLabel(odf, oo, classIri,
                        iriMap.lookupAnnPropIri("editor preferred"), cmInstanceLabel);
                addAnnotationToIndividual(cmInd, iriMap.lookupAnnPropIri("label"), value, odf, oo);

                createOWLObjectPropertyAssertion(simxInd, iriMap.lookupObjPropIri("achieves objective"),
                        niMap.get("executable"), odf, oo);
                createOWLObjectPropertyAssertion(simxInd, iriMap.lookupObjPropIri("has specified output"),
                        cmInd, odf, oo);
            } else {
                System.err.println("Skipping " + value + " control measure.");
            }
        }
    } else {
        throw new IllegalArgumentException("value of controlMeasures attribute must be array");
    }
}

From source file:edu.washington.iam.tools.netact.NetactDNSVerifier.java

License:Apache License

/**
 * Test if a user has ownership of a domain
 *
 * @param id user's uwnetid// w  ww. j a  va  2s  .  c o m
 * @param domain to test
 * @param return list of owners (can be null)
 */

public boolean isOwner(String dns, String id, List<String> owners) throws DNSVerifyException {

    boolean isOwner = false;
    if (id == null)
        id = "";
    log.debug("looking for owner (" + id + ") in " + dns);

    try {
        String[] urls = { hostUrl, domainUrl };
        for (String url : urls) {
            String respString = webClient.simpleRestGet(url + dns);
            // log.debug("got: " + respString);

            JsonParser parser = new JsonParser();
            JsonElement ele = parser.parse(respString);
            if (ele.isJsonObject()) {
                JsonObject resp = ele.getAsJsonObject();
                if (resp.get("table").isJsonObject()) {
                    JsonObject tbl = resp.getAsJsonObject("table");
                    if (tbl.get("row").isJsonArray()) {
                        JsonArray ids = tbl.getAsJsonArray("row");
                        for (int i = 0; i < ids.size(); i++) {
                            JsonObject idi = ids.get(i).getAsJsonObject();
                            JsonPrimitive oidu = idi.getAsJsonPrimitive("uwnetid");
                            if (oidu == null)
                                continue;
                            String oid = oidu.getAsString();
                            if (oid.equals(id)) {
                                if (owners == null)
                                    return true; // done
                                isOwner = true;
                            }
                            if (owners != null && !owners.contains(oid))
                                owners.add(oid);
                        }
                    } else {
                        String oid = tbl.getAsJsonObject("row").getAsJsonPrimitive("uwnetid").getAsString();
                        if (oid.equals(id)) {
                            if (owners == null)
                                return true; // done
                            isOwner = true;
                        }
                        if (owners != null && !owners.contains(oid))
                            owners.add(oid);
                    }
                }
            }
        }

    } catch (Exception e) {
        log.debug("netact dns lookup error: " + e);
        throw new DNSVerifyException(e.getMessage() + " : " + e.getCause());
    }

    // do substrings too
    dns = dns.replaceFirst("[^\\.]+\\.", "");
    // log.debug("do substrings: " + dns);
    int p = dns.indexOf(".");
    if (p > 0) {
        if (isOwner(dns, id, owners)) {
            if (owners == null)
                return true; // done
            isOwner = true;
        }
    }
    return isOwner;
}

From source file:ee.ria.xroad.asyncdb.messagequeue.RequestInfo.java

License:Open Source License

/**
 * Parses request info out of its JSON representation.
 *
 * @param json - JSON representation of request info.
 * @return - Request info object.//from  w ww.  j  av  a  2  s. co  m
 *
 * @throws CorruptQueueException - if queue includes malformed requests.
 */
public static RequestInfo fromJson(String json) throws CorruptQueueException {
    JsonObject rawRequest;

    try {
        rawRequest = (JsonObject) new JsonParser().parse(json);
    } catch (ClassCastException e) {
        throw new CorruptQueueException("Json string '" + json + "' cannot be parsed into RequestInfo.");
    }

    JsonObject rawSender = rawRequest.getAsJsonObject("sender");
    ClientId sender = ClientId.create(JsonUtils.getStringPropertyValue(rawSender, "xRoadInstance"),
            JsonUtils.getStringPropertyValue(rawSender, "memberClass"),
            JsonUtils.getStringPropertyValue(rawSender, "memberCode"),
            JsonUtils.getStringPropertyValue(rawSender, "subsystemCode"));

    JsonObject rawService = rawRequest.getAsJsonObject("service");

    ServiceId service = createServiceId(rawService);

    RequestInfo result = new RequestInfo(JsonUtils.getIntPropertyValue(rawRequest, "orderNo"),
            JsonUtils.getStringPropertyValue(rawRequest, "id"),
            JsonUtils.getDatePropertyValue(rawRequest, "receivedTime"),
            JsonUtils.getDatePropertyValue(rawRequest, "removedTime"), sender,
            JsonUtils.getStringPropertyValue(rawRequest, "user"), service);

    result.sending = JsonUtils.getBooleanPropertyValue(rawRequest, "sending");

    return result;
}

From source file:esiptestbed.mudrod.metadata.pre.ApiHarvester.java

License:Apache License

/**
 * harvestMetadatafromWeb: Harvest metadata from PO.DAAC web service.
 *///from  w  w w . j a  va 2 s.com
private void harvestMetadatafromWeb() {
    int startIndex = 0;
    int doc_length = 0;
    JsonParser parser = new JsonParser();
    do {
        String searchAPI = "https://podaac.jpl.nasa.gov/api/dataset?startIndex=" + Integer.toString(startIndex)
                + "&entries=10&sortField=Dataset-AllTimePopularity&sortOrder=asc&id=&value=&search=";
        HttpRequest http = new HttpRequest();
        String response = http.getRequest(searchAPI);

        JsonElement json = parser.parse(response);
        JsonObject responseObject = json.getAsJsonObject();
        JsonArray docs = responseObject.getAsJsonObject("response").getAsJsonArray("docs");

        doc_length = docs.size();

        File file = new File(props.getProperty(MudrodConstants.RAW_METADATA_PATH));
        if (!file.exists()) {
            if (file.mkdir()) {
                LOG.info("Directory is created!");
            } else {
                LOG.error("Failed to create directory!");
            }
        }
        for (int i = 0; i < doc_length; i++) {
            JsonElement item = docs.get(i);
            int docId = startIndex + i;
            File itemfile = new File(
                    props.getProperty(MudrodConstants.RAW_METADATA_PATH) + "/" + docId + ".json");

            try (FileWriter fw = new FileWriter(itemfile.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);) {
                itemfile.createNewFile();
                bw.write(item.toString());
            } catch (IOException e) {
                LOG.error("Error writing metadata to local file!", e);
            }
        }

        startIndex += 10;

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            LOG.error("Error entering Elasticsearch Mappings!", e);
            Thread.currentThread().interrupt();
        }

    } while (doc_length != 0);
}

From source file:eu.betaas.service.extendedservice.api.impl.LEZProcessor.java

License:Apache License

public synchronized void managePositionData(JsonObject data) {
    JsonObject jsonObj;/*from   w w  w . j  a  v  a2  s.c  o m*/
    JsonElement jsonElement;
    String lat, lon, userId;
    double latVal, lonVal;

    mLogger.info("Received position data");

    try {
        JsonObject serviceResult = data.getAsJsonObject(JSON_FIELD_SERVICE_RESULT);
        if (serviceResult == null) {
            mLogger.error("Cannot get ServiceResult");
            return;
        }

        JsonArray dataList = serviceResult.getAsJsonArray(JSON_FIELD_DATALIST);
        if (dataList == null) {
            mLogger.error("Cannot get dataList");
            return;
        }

        // scan all received points
        for (int i = 0; i < dataList.size(); i++) {
            jsonObj = dataList.get(i).getAsJsonObject();
            if (jsonObj == null) {
                mLogger.error("Cannot get data element n. " + i);
                return;
            }
            jsonElement = jsonObj.get(JSON_FIELD_USER_ID);
            if (jsonElement == null) {
                mLogger.error("Cannot get user ID from element n. " + i);
                return;
            }
            userId = jsonElement.toString();
            if (userId == null) {
                mLogger.error("Got null user ID from element n. " + i);
                return;
            }
            if (userId.startsWith("\""))
                userId = userId.substring(1);
            if (userId.endsWith("\""))
                userId = userId.substring(0, userId.length() - 1);
            if (userId.isEmpty()) {
                mLogger.error("Got empty user ID from element n. " + i);
                return;
            }

            try {
                jsonElement = jsonObj.get(JSON_FIELD_LAT);
                if (jsonElement == null) {
                    mLogger.error("Cannot get lat from element n. " + i);
                    return;
                }
                lat = jsonElement.toString();
                latVal = Double.parseDouble(lat);

                jsonElement = jsonObj.get(JSON_FIELD_LON);
                if (jsonElement == null) {
                    mLogger.error("Cannot get lon from element n. " + i);
                    return;
                }
                lon = jsonElement.toString();
                lonVal = Double.parseDouble(lon);

            } catch (Exception efe) {
                throw new Exception("Invalid numberic conversion on element n." + i + ": " + efe.getMessage());
            }

            processUserPosition(userId, latVal, lonVal);
        }

    } catch (Exception e) {
        mLogger.error("Cannot manage received position data: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:eu.betaas.service.extendedservice.api.impl.LEZProcessor.java

License:Apache License

public synchronized void manageTrafficData(JsonObject data) {
    JsonObject jsonObj;//from   ww w .jav  a  2s. c  o m
    JsonElement jsonElement;
    String carsMinute, lat, lon;
    double latVal, lonVal;
    float carsMinuteVal;

    mLogger.info("Received traffic data");

    try {
        JsonObject serviceResult = data.getAsJsonObject(JSON_FIELD_SERVICE_RESULT);
        if (serviceResult == null) {
            mLogger.error("Cannot get ServiceResult");
            return;
        }

        JsonArray dataList = serviceResult.getAsJsonArray(JSON_FIELD_DATALIST);
        if (dataList == null) {
            mLogger.error("Cannot get dataList");
            return;
        }

        // scan all received elements
        for (int i = 0; i < dataList.size(); i++) {
            jsonObj = dataList.get(i).getAsJsonObject();
            if (jsonObj == null) {
                mLogger.error("Cannot get data element n. " + i);
                return;
            }

            try {
                jsonElement = jsonObj.get(JSON_FIELD_MEASUREMENT);
                if (jsonElement == null) {
                    mLogger.error("Cannot get measurement from element n. " + i);
                    return;
                }
                carsMinute = jsonElement.toString();
                if (carsMinute.startsWith("\""))
                    carsMinute = carsMinute.substring(1);
                if (carsMinute.endsWith("\""))
                    carsMinute = carsMinute.substring(0, carsMinute.length() - 1);
                carsMinuteVal = Float.parseFloat(carsMinute);

                jsonElement = jsonObj.get(JSON_FIELD_LAT);
                if (jsonElement == null) {
                    mLogger.error("Cannot get lat from element n. " + i);
                    return;
                }
                lat = jsonElement.toString();
                latVal = Double.parseDouble(lat);

                jsonElement = jsonObj.get(JSON_FIELD_LON);
                if (jsonElement == null) {
                    mLogger.error("Cannot get lon from element n. " + i);
                    return;
                }
                lon = jsonElement.toString();
                lonVal = Double.parseDouble(lon);

            } catch (Exception efe) {
                throw new Exception("Invalid numeric conversion on element n." + i + ": " + efe.getMessage());
            }

            processTrafficIntensity(latVal, lonVal, carsMinuteVal);
        }

    } catch (Exception e) {
        mLogger.error("Cannot manage received traffic data: " + e.getMessage());
    }
}