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:de.chemist.gw2.io.ResourceManager.java

License:Open Source License

private static void parseResourceFile(String json) throws IOException {
    JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
    parseImages(jsonObject.getAsJsonArray("images"));
}

From source file:dmadmin.DMSession.java

License:Open Source License

JSONObject getBuildHistoryJenkins(int builderid, int buildjobid) {
    System.out.println("getBuildHistoryJenkins builderid=" + builderid + " buildjobid=" + buildjobid);
    String sql2 = "select projectname from dm.dm_buildjob where id=?";
    String sql3 = "select a.buildnumber,b.id,b.name,b.parentid from dm.dm_buildhistory a,dm.dm_component b where a.compid=b.id and   a.buildjobid=? order by buildnumber desc";
    JSONObject ret = new JSONObject();
    try {//from w ww.  j ava  2  s. com
        Builder builder = getBuilder(builderid);
        Credential cred = builder.getCredential();
        PreparedStatement stmt2 = m_conn.prepareStatement(sql2);
        PreparedStatement stmt3 = m_conn.prepareStatement(sql3);
        stmt2.setInt(1, buildjobid);
        stmt3.setInt(1, buildjobid);
        String serverURL = getBuildServerURL(builderid);
        if (serverURL != null) {
            System.out.println("Server URL=" + serverURL);
            ResultSet rs2 = stmt2.executeQuery();
            if (rs2.next()) {
                String jobname = rs2.getString(1).replaceAll(" ", "%20");
                if (jobname.length() > 0) {
                    //
                    // Get all the builds we know about for this build job and assemble the
                    // JSON Array of components associated with each build number
                    //
                    Hashtable<Integer, JSONArray> complist = new Hashtable<Integer, JSONArray>();
                    ResultSet rs3 = stmt3.executeQuery();
                    while (rs3.next()) {
                        int buildno = rs3.getInt(1);
                        // Have we seen this build before?
                        JSONArray ja = complist.get(buildno);
                        if (ja == null)
                            ja = new JSONArray(); // new build
                        int compid = rs3.getInt(2);
                        String compname = rs3.getString(3);
                        int parentid = getInteger(rs3, 4, 0);
                        JSONObject compdetails = new JSONObject();
                        compdetails.add("id", compid);
                        compdetails.add("name", compname);
                        compdetails.add("type", (parentid > 0) ? "cv" : "co");
                        ja.add(compdetails);
                        complist.put(buildno, ja);
                    }
                    rs3.close();
                    //
                    // Now get "all" the builds from the build server. Not all of these will
                    // relate to builds in DeployHub
                    //
                    boolean commit = false;
                    if (jobname.contains("/"))
                        jobname = jobname.replace("/", "/job/");

                    String res = getJSONFromServer(serverURL + "/job/" + jobname
                            + "/api/json?tree=builds[number,timestamp,result,duration]", cred);
                    System.out.println(res);
                    JsonObject returnedjson = new JsonParser().parse(res).getAsJsonObject();
                    JsonArray builds = returnedjson.getAsJsonArray("builds");
                    JSONArray retBuilds = new JSONArray();
                    for (int i = 0; i < builds.size(); i++) {
                        JsonObject jsonJob = builds.get(i).getAsJsonObject();
                        int buildid = jsonJob.get("number").getAsInt();
                        int duration = jsonJob.get("duration").getAsInt();
                        String result = jsonJob.get("result").getAsString();
                        long timestamp = jsonJob.get("timestamp").getAsLong();
                        System.out.println("buildid=" + buildid + " timestamp=" + timestamp);
                        JSONObject buildobj = new JSONObject();
                        buildobj.add("id", buildid);
                        buildobj.add("result", result);
                        buildobj.add("timestamp", formatDateToUserLocale((int) (timestamp / 1000)));
                        buildobj.add("duration", duration);
                        JSONArray recomps = complist.get(buildid);
                        if (recomps == null)
                            recomps = new JSONArray();
                        buildobj.add("components", recomps);
                        retBuilds.add(buildobj);
                    }
                    ret.add("builds", retBuilds);
                    if (commit)
                        m_conn.commit();
                } else {
                    ret.add("error", "Cannot retrieve Builds - Project Name is not set");
                }
            } else {
                ret.add("error", "Could not retrieve Project Name from build job");
            }
            rs2.close();
        } else {
            // Couldn't find server URL - stick an error into the return object
            ret.add("error", "Build Engine has no Server URL defined");
        }
        stmt2.close();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        ret.add("error", "SQL Failed running getProjectsFromJenkins");
    }
    return ret;
}

From source file:dmadmin.DMSession.java

License:Open Source License

JSONObject getBuildHistoryBamboo(int builderid, int buildjobid) {
    System.out.println("getBuildHistoryBamboo builderid=" + builderid + " buildjobid=" + buildjobid);
    String sql1 = "select value,encrypted from dm.dm_buildengineprops where name='Server URL' and builderid = ?";
    String sql2 = "select projectname from dm.dm_buildjob where id=?";
    String sql3 = "select a.buildnumber,b.id,b.name,b.parentid from dm.dm_buildhistory a,dm.dm_component b where a.compid=b.id and   a.buildjobid=? order by buildnumber desc";
    JSONObject ret = new JSONObject();
    try {/* w ww  . ja v  a2s. c o m*/
        Builder builder = getBuilder(builderid);
        Credential cred = builder.getCredential();
        PreparedStatement stmt1 = m_conn.prepareStatement(sql1);
        PreparedStatement stmt2 = m_conn.prepareStatement(sql2);
        PreparedStatement stmt3 = m_conn.prepareStatement(sql3);
        stmt1.setInt(1, builderid);
        stmt2.setInt(1, buildjobid);
        stmt3.setInt(1, buildjobid);
        ResultSet rs1 = stmt1.executeQuery();
        if (rs1.next()) {
            // Got the Server URL
            String serverURL = rs1.getString(1);
            String encrypted = rs1.getString(2);
            System.out.println("Server URL=" + serverURL);
            if (encrypted != null && encrypted.equalsIgnoreCase("y")) {
                serverURL = new String(Decrypt3DES(serverURL, m_passphrase));
                System.out.println("Decrypted server URL=" + serverURL);
            }
            ResultSet rs2 = stmt2.executeQuery();
            if (rs2.next()) {
                String jobname = rs2.getString(1).replaceAll(" ", "%20");
                if (jobname.length() > 0) {
                    //
                    // Get all the builds we know about for this build job and assemble the
                    // JSON Array of components associated with each build number
                    //
                    Hashtable<Integer, JSONArray> complist = new Hashtable<Integer, JSONArray>();
                    ResultSet rs3 = stmt3.executeQuery();
                    while (rs3.next()) {
                        int buildno = rs3.getInt(1);
                        // Have we seen this build before?
                        JSONArray ja = complist.get(buildno);
                        if (ja == null)
                            ja = new JSONArray(); // new build
                        int compid = rs3.getInt(2);
                        String compname = rs3.getString(3);
                        int parentid = getInteger(rs3, 4, 0);
                        JSONObject compdetails = new JSONObject();
                        compdetails.add("id", compid);
                        compdetails.add("name", compname);
                        compdetails.add("type", (parentid > 0) ? "cv" : "co");
                        ja.add(compdetails);
                        complist.put(buildno, ja);
                    }
                    rs3.close();
                    //
                    // Now get "all" the builds from the build server. Not all of these will
                    // relate to builds in DeployHub
                    //
                    boolean commit = false;
                    String res = getJSONFromServer(serverURL + "/rest/api/latest/job/" + jobname
                            + "/api/json?tree=builds[number,timestamp,result,duration]", cred);
                    JsonObject returnedjson = new JsonParser().parse(res).getAsJsonObject();
                    JsonArray builds = returnedjson.getAsJsonArray("builds");
                    JSONArray retBuilds = new JSONArray();
                    for (int i = 0; i < builds.size(); i++) {
                        JsonObject jsonJob = builds.get(i).getAsJsonObject();
                        int buildid = jsonJob.get("number").getAsInt();
                        int duration = jsonJob.get("duration").getAsInt();
                        String result = jsonJob.get("result").getAsString();
                        long timestamp = jsonJob.get("timestamp").getAsLong();
                        System.out.println("buildid=" + buildid + " timestamp=" + timestamp);
                        JSONObject buildobj = new JSONObject();
                        buildobj.add("id", buildid);
                        buildobj.add("result", result);
                        buildobj.add("timestamp", formatDateToUserLocale((int) (timestamp / 1000)));
                        buildobj.add("duration", duration);
                        JSONArray recomps = complist.get(buildid);
                        if (recomps == null)
                            recomps = new JSONArray();
                        buildobj.add("components", recomps);
                        retBuilds.add(buildobj);
                    }
                    ret.add("builds", retBuilds);
                    if (commit)
                        m_conn.commit();
                } else {
                    ret.add("error", "Cannot retrieve Builds - Project Name is not set");
                }
            } else {
                ret.add("error", "Could not retrieve Project Name from build job");
            }
            rs2.close();
        } else {
            // Couldn't find server URL - stick an error into the return object
            ret.add("error", "Build Engine has no Server URL defined");
        }
        rs1.close();
        stmt1.close();

        stmt2.close();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        ret.add("error", "SQL Failed running getProjectsFromBamboo");
    }
    return ret;
}

From source file:dmadmin.DMSession.java

License:Open Source License

String recurseProjectsFromJenkins(String ServerURL, String currentFolder, Credential cred,
        ArrayList<String> jobList) {
    System.out.println("recurseProjectsFromJenkins");

    String encFolder = currentFolder.replaceAll(" ", "%20") + "/api/json";

    String res = getJSONFromServer(ServerURL + encFolder, cred);

    System.out.println("Server URL=" + ServerURL + encFolder);
    if (res.startsWith("Could not connect")) {
        return res;
    } else {//from  www  .  ja  va2s  . c  o m
        JsonObject returnedjson = new JsonParser().parse(res).getAsJsonObject();
        JsonArray jobs = returnedjson.getAsJsonArray("jobs");
        JSONArray retJobs = new JSONArray();

        for (int i = 0; i < jobs.size(); i++) {
            JsonObject jsonJob = jobs.get(i).getAsJsonObject();

            if (!jsonJob.get("_class").getAsString().contains("Folder")) {
                String name = currentFolder + "/" + jsonJob.get("name").getAsString();
                name = name.replaceAll("\\/job\\/", "/").substring(1);
                jobList.add(name);
            } else {
                String newFolder = currentFolder + "/job/" + jsonJob.get("name").getAsString();
                recurseProjectsFromJenkins(ServerURL, newFolder, cred, jobList);
            }
        }
    }
    return "";
}

From source file:dmadmin.DMSession.java

License:Open Source License

JSONObject getProjectsFromBamboo(int builderid) {
    System.out.println("getProjectsFromBamboo");
    String sql = "select value,encrypted from dm.dm_buildengineprops where name='Server URL' and builderid = ?";
    JSONObject ret = new JSONObject();
    try {/*www  .  ja  va 2  s.c  om*/
        Builder builder = getBuilder(builderid);
        Credential cred = builder.getCredential();
        PreparedStatement stmt = m_conn.prepareStatement(sql);
        stmt.setInt(1, builderid);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            // Got the Server URL
            String serverURL = rs.getString(1);
            if (rs.getString(2).equalsIgnoreCase("y")) {
                // Server URL is encrypted
                serverURL = new String(Decrypt3DES(serverURL, m_passphrase));
            }
            System.out.println("Server URL=" + serverURL);
            String res = getJSONFromServer(serverURL + "/rest/api/latest/plan.json", cred);
            if (res.startsWith("Could not connect")) {
                ret.add("error", res);
            } else {
                JsonObject returnedjson = new JsonParser().parse(res).getAsJsonObject();
                JsonObject plans = returnedjson.getAsJsonObject("plans");
                JsonArray plan = plans.getAsJsonArray("plan");
                JSONArray retJobs = new JSONArray();
                if (plan.size() == 0) {
                    ret.add("error", "No Projects found on Bamboo Server " + serverURL);
                }
                for (int i = 0; i < plan.size(); i++) {
                    JsonObject jsonPlan = plan.get(i).getAsJsonObject();
                    String planname = jsonPlan.get("shortName").getAsString();
                    JSONObject jobobj = new JSONObject();
                    jobobj.add("name", planname);
                    retJobs.add(jobobj);
                }
                ret.add("jobs", retJobs);
            }
        } else {
            // Couldn't find server URL - stick an error into the return object
            ret.add("error", "Build Engine has no Server URL defined");
        }
        rs.close();
        stmt.close();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        ret.add("error", "SQL Failed running getProjectsFromBamboo");
    }
    return ret;
}

From source file:DS.Model.java

private String parseResponse(String json) {
    JsonParser parser = new JsonParser();
    JsonElement jsonTree = parser.parse(json); //Parse json from yelp
    JsonObject jsonReply = new JsonObject();
    JsonArray jsonReplyArray = new JsonArray(); //The json that will be sent to Android

    //Check to see if the json element is a json object
    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonArray jarray = jsonObject.getAsJsonArray("businesses");

        //Loop through the businesses that were sent in the json array
        Iterator i = jarray.iterator();
        while (i.hasNext()) {
            //get the name, rating, and address from the business
            //Add the information to the replyBusiness json which will be sent to Android
            JsonObject replyBusiness = new JsonObject();
            JsonObject business = (JsonObject) i.next();

            String name = business.get("name").getAsString();
            replyBusiness.addProperty("name", name);

            String rating = business.get("rating").getAsString();
            replyBusiness.addProperty("rating", rating);

            JsonElement location = business.get("location");
            JsonObject locObject = location.getAsJsonObject();
            JsonArray addressArray = locObject.getAsJsonArray("display_address");
            Iterator i2 = addressArray.iterator();
            String displayAddress = "";

            //The address is split across multiple lines, so retrieve all lines and combine into one line
            while (i2.hasNext()) {
                JsonElement line = (JsonElement) i2.next();
                displayAddress += line.toString();
            }//from  w w w  .j  a v a2  s.  co m
            displayAddress = displayAddress.replaceAll("\\\"+", " ").trim();
            replyBusiness.addProperty("address", displayAddress);
            jsonReplyArray.add(replyBusiness);

            //Try and log the restaurant to the mongodb database
            try {
                MongoConnect();
                logRestaurant(name, Double.parseDouble(rating), displayAddress);
            } finally {
                CloseMongo();
            }
        }
        jsonReply.add("businesses", jsonReplyArray);
    }

    //Returns the json string containing 3 restaurants to android
    return jsonReply.toString();
}

From source file:dy.fi.maja.httpclient.Wapice.java

public WapiceDevice[] getDevices(int limit) {
    String existingDevicesString = client.get("devices?limit=" + String.valueOf(limit), String.class);
    JsonParser parser = new JsonParser();
    JsonObject rootObject = parser.parse(existingDevicesString).getAsJsonObject();
    JsonArray array = rootObject.getAsJsonArray("items");
    return new Gson().fromJson(array, WapiceDevice[].class);
}

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

License:Open Source License

private static View readView(JsonObject json, TextAnnotation ta) throws Exception {

    String viewClass = readString("viewType", json);

    String viewName = readString("viewName", json);

    String viewGenerator = readString("generator", json);

    double score = 0;
    if (json.has("score"))
        score = readDouble("score", json);

    View view = createEmptyView(ta, viewClass, viewName, viewGenerator, score);

    List<Constituent> constituents = new ArrayList<>();

    if (json.has("constituents")) {

        JsonArray cJson = json.getAsJsonArray("constituents");

        for (int i = 0; i < cJson.size(); i++) {
            JsonObject cJ = (JsonObject) cJson.get(i);
            Constituent c = readConstituent(cJ, ta, viewName);
            constituents.add(c);/*from   www.jav a  2  s .  co m*/

            // all parse trees should allow duplicate constituents
            if (view.getViewName().contains("PARSE"))
                view.addConstituent(c, true);
            else
                view.addConstituent(c);
        }
    }

    if (json.has("relations")) {
        JsonArray rJson = json.getAsJsonArray("relations");
        for (int i = 0; i < rJson.size(); i++) {
            JsonObject rJ = (JsonObject) rJson.get(i);

            String name = readString("relationName", rJ);

            double s = 0;
            if (rJ.has("score"))
                s = readDouble("score", rJ);

            int src = readInt("srcConstituent", rJ);
            int tgt = readInt("targetConstituent", rJ);

            Map<String, Double> labelsToScores = null;
            if (rJ.has(LABEL_SCORE_MAP)) {
                labelsToScores = new HashMap<>();
                readLabelsToScores(labelsToScores, rJ);
            }

            Relation rel = null;

            if (null == labelsToScores)
                rel = new Relation(name, constituents.get(src), constituents.get(tgt), s);
            else
                rel = new Relation(labelsToScores, constituents.get(src), constituents.get(tgt));

            readAttributes(rel, rJ);

            view.addRelation(rel);
        }
    }
    return view;
}

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

License:Open Source License

/**
 * if serialized TextAnnotation object has Sentence view, delete the View created by the TextAnnotation
 *    constructor and replace it with the one read from the file.  This is to pick up any additional info
 *    specified in the serialized version.
 * @param string/*from  www . j  av a  2 s.  c o m*/
 * @return
 * @throws Exception
 */

TextAnnotation readTextAnnotation(String string) throws Exception {
    JsonObject json = (JsonObject) new JsonParser().parse(string);

    String corpusId = readString("corpusId", json);
    String id = readString("id", json);
    String text = readString("text", json);
    String[] tokens = readStringArray("tokens", json);

    Pair<Pair<String, Double>, int[]> sentences = readSentences(json);

    IntPair[] offsets = null;

    if (json.has(TOKENOFFSETS))
        offsets = readTokenOffsets(json.getAsJsonArray(TOKENOFFSETS), tokens);
    else
        offsets = TokenUtils.getTokenOffsets(text, tokens);

    TextAnnotation ta = new TextAnnotation(corpusId, id, text, offsets, tokens, sentences.getSecond());

    JsonArray views = json.getAsJsonArray("views");
    for (int i = 0; i < views.size(); i++) {
        JsonObject view = (JsonObject) views.get(i);
        String viewName = readString("viewName", view);

        JsonArray viewData = view.getAsJsonArray("viewData");
        List<View> topKViews = new ArrayList<>();

        for (int k = 0; k < viewData.size(); k++) {
            JsonObject kView = (JsonObject) viewData.get(k);
            topKViews.add(readView(kView, ta));
        }

        // replace TextAnnotation constructor's SENTENCE view if specified in json
        if (viewName.equals(ViewNames.SENTENCE))
            ta.removeView(viewName);

        ta.addTopKView(viewName, topKViews);

        if (viewName.equals(ViewNames.SENTENCE))
            ta.setSentences();
    }

    readAttributes(ta, json);

    return ta;
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.FreebaseSearch.java

License:Open Source License

private List<FreebaseAnswer> parseJson(String ans) {
    if (ans == null)
        return null;
    List<FreebaseAnswer> output = Lists.newArrayList();
    JsonElement parse = new JsonParser().parse(ans);
    JsonObject asJsonObject = parse.getAsJsonObject();
    JsonArray jarray = asJsonObject.getAsJsonArray("result");
    for (JsonElement js : jarray) {
        output.add(new FreebaseAnswer(js));
    }//from  w  w w . java2 s . c om
    return output;
}