Example usage for org.json.simple JSONArray size

List of usage examples for org.json.simple JSONArray size

Introduction

In this page you can find the example usage for org.json.simple JSONArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:GraphController.java

@RequestMapping("/graphs")
public @ResponseBody Graph graph(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);//from  w w w . j  av a  2s .co m

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "graph.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostids", hostid);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        //         System.out.println(array);
        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            JSONObject objret = new JSONObject();

            objret.put("graphId", tobj.get("graphid"));
            objret.put("graphName", tobj.get("name"));

            String type = (String) tobj.get("graphtype");

            if (type.equals("0")) {
                objret.put("graphType", "normal");
            } else if (type.equals("1")) {
                objret.put("graphType", "stacked");
            } else if (type.equals("2")) {
                objret.put("graphType", "pie");
            } else if (type.equals("3")) {
                objret.put("graphType", "exploded");
            }

            list.add(objret);

        }

        return new Graph(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Graph(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:de.mpg.imeji.presentation.servlet.autocompleter.java

/**
 * Parse a CoNE Vocabulary (read the title value)
 * //from  w w w. j a v a  2s.  c o m
 * @param cone
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private String parseConeVocabulary(String cone) throws IOException {
    Object obj = JSONValue.parse(cone);
    JSONArray array = (JSONArray) obj;
    JSONArray result = new JSONArray();
    for (int i = 0; i < array.size(); ++i) {
        JSONObject parseObject = (JSONObject) array.get(i);
        JSONObject sendObject = new JSONObject();
        sendObject.put("label", parseObject.get("http_purl_org_dc_elements_1_1_title"));
        sendObject.put("value", parseObject.get("http_purl_org_dc_elements_1_1_title"));
        result.add(sendObject);
    }
    StringWriter out = new StringWriter();
    result.writeJSONString(out);
    return out.toString();
}

From source file:me.timothy.ddd.acheivements.AchievementManager.java

public AchievementManager() {
    logger = LogManager.getLogger();
    achievements = new ArrayList<>();
    toDisplay = new LinkedList<Achievement>();

    bkndColor = new Color(49, 45, 150);
    titleColor = new Color(215, 208, 39);
    textColor = new Color(215, 135, 39);

    final File achievs = new File("achievements_acquired.json");
    if (achievs.exists()) {
        try (FileReader fr = new FileReader(achievs)) {
            JSONArray jArr = (JSONArray) (new JSONParser().parse(fr));
            for (int i = 0; i < jArr.size(); i++) {
                Achievement ach = new Achievement();
                ach.loadFrom((JSONObject) jArr.get(i));
                achievements.add(ach);//w  ww . j ava  2s  . c  om
            }
        } catch (IOException | ParseException e) {
            logger.throwing(e);
            throw new RuntimeException(e);
        }
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            JSONArray jArr = new JSONArray();
            for (Achievement ach : achievements) {
                JSONObject jObj = new JSONObject();
                ach.saveTo(jObj);
                jArr.add(jObj);
            }
            try (FileWriter fw = new FileWriter(achievs)) {
                DDDUtils.writeJSONPretty(fw, jArr);
            } catch (IOException e) {
            }
        }

    }));
}

From source file:net.bashtech.geobot.JSONUtil.java

public static String whatShouldIPlay(String userID) {
    String api_key = BotManager.getInstance().SteamAPIKey;

    try {/*  w  w w .ja va  2s.c o  m*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager
                .getRemoteContent("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key="
                        + api_key + "&steamid=" + userID + "&format=json&include_appinfo=1"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONObject response = (JSONObject) (jsonObject.get("response"));
        JSONArray games = (JSONArray) response.get("games");

        if (games.size() > 0) {
            int randomGame = (int) (Math.random() * games.size() - 1);
            JSONObject index0 = (JSONObject) games.get(randomGame);
            String randomGameName = (String) index0.get("name");
            return randomGameName;
        } else {
            return "User has no games";

        }

    } catch (Exception ex) {
        System.out.println("Failed to query Steam API");
        return "Error querying API";
    }
}

From source file:com.rackspacecloud.blueflood.outputs.serializers.JSONBasicRollupOutputSerializerTest.java

@Test
public void testSets() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeSetRollupPoints(),
            "unknown", MetricData.Type.NUMBER);
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_SET);
    final JSONArray data = (JSONArray) metricDataJSON.get("values");

    Assert.assertEquals(5, data.size());
    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject) data.get(i);

        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertEquals(Sets.newHashSet(i, i % 2, i / 2).size(), dataJSON.get("numPoints"));
    }/*from   w ww . j a v a 2s. co m*/
}

From source file:com.zb.app.biz.service.WeixinTest.java

private boolean compareFakeid(String fakeid, String openid) {
    PostMethod post = new PostMethod(
            "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&token=" + token
                    + "&tofakeid=" + fakeid + "&lang=zh_CN");
    post.setRequestHeader("Cookie", this.cookiestr);
    post.setRequestHeader("Host", "mp.weixin.qq.com");
    post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token="
            + token + "&lang=zh_CN&pagesize=10&pageidx=0&type=0");
    post.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    post.addParameter(new NameValuePair("token", token));
    post.addParameter(new NameValuePair("ajax", "1"));
    try {//from   ww  w  . j av  a 2  s  .com
        int code = httpClient.executeMethod(post);
        if (HttpStatus.SC_OK == code) {
            String str = post.getResponseBodyAsString();
            String msgJson = StringUtils.substringBetween(str, "<script id=\"json-msgList\" type=\"json\">",
                    "</script>");
            JSONParser parser = new JSONParser();
            try {
                JSONArray array = (JSONArray) parser.parse(msgJson);
                for (int i = 0; i < array.size(); i++) {
                    JSONObject obj = (JSONObject) array.get(i);
                    String content = (String) obj.get("content");
                    if (content.contains(openid)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.zb.app.biz.service.WeixinTest.java

private boolean _compareFakeid(String fakeid, String openid) {
    String _url = "http://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&token=" + token
            + "&tofakeid=" + fakeid + "&lang=zh_CN";

    GetMethod get = new GetMethod(_url);
    get.setRequestHeader("Cookie", this.cookiestr);
    get.setRequestHeader("Host", "mp.weixin.qq.com");
    get.setRequestHeader("Referer",
            "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&token="
                    + token + "&lang=zh_CN");
    get.setRequestHeader("Content-Type", "text/html;charset=UTF-8");

    try {/*from w w  w . ja  v a  2s . c o m*/
        int code = httpClient.executeMethod(get);
        if (HttpStatus.SC_OK == code) {
            String str = get.getResponseBodyAsString();
            String msgJson = StringUtils.substringBetween(str, "{\"msg_item\":", "}};");
            JSONParser parser = new JSONParser();
            try {
                JSONArray array = (JSONArray) parser.parse(msgJson);
                for (int i = 0; i < array.size(); i++) {
                    JSONObject obj = (JSONObject) array.get(i);
                    String content = (String) obj.get("content");
                    if (content.contains(openid)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                // log.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        // log.error(e.getMessage(), e);
    }
    return false;
}

From source file:com.rackspacecloud.blueflood.outputs.serializers.JSONBasicRollupOutputSerializerTest.java

@Test
public void setTimers() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeTimerRollups(), "unknown",
            MetricData.Type.NUMBER);

    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_TIMER);
    final JSONArray data = (JSONArray) metricDataJSON.get("values");

    Assert.assertEquals(5, data.size());
    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject) data.get(i);

        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertNotNull(dataJSON.get("average"));
        Assert.assertNotNull(dataJSON.get("rate"));

        // bah. I'm too lazy to check equals.
    }//ww  w.  jav a 2 s .  co  m
}

From source file:io.github.apfelcreme.LitePortals.Bungee.LitePortals.java

/**
 * returns the name of a player/*w ww . j  a v  a 2s. c o m*/
 *
 * @param uuid a players uuid
 * @return his name
 */
public String getNameByUUID(UUID uuid) {
    if (uuidCache.containsValue(uuid)) {
        for (Map.Entry<String, UUID> entry : uuidCache.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
    } else if (getProxy().getPluginManager().getPlugin("UUIDDB") != null) {
        String name = UUIDDB.getInstance().getStorage().getNameByUUID(uuid);
        uuidCache.put(name.toUpperCase(), uuid);
        return name;
    } else {
        try {
            URL url = new URL(LitePortalsConfig.getInstance().getConfiguration().getString("nameUrl")
                    .replace("{0}", uuid.toString().replace("-", "")));
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder json = new StringBuilder();
            int read;
            while ((read = in.read()) != -1) {
                json.append((char) read);
            }
            Object obj = new JSONParser().parse(json.toString());
            JSONArray jsonArray = (JSONArray) obj;
            String name = (String) ((JSONObject) jsonArray.get(jsonArray.size() - 1)).get("name");
            uuidCache.put(name.toUpperCase(), uuid);
            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    return null;
}

From source file:com.rackspacecloud.blueflood.outputs.serializers.JSONBasicRollupOutputSerializerTest.java

@Test
public void testCounters() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeCounterRollupPoints(),
            "unknown", MetricData.Type.NUMBER);
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_COUNTER);
    final JSONArray data = (JSONArray) metricDataJSON.get("values");

    Assert.assertEquals(5, data.size());
    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject) data.get(i);

        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertEquals(i + 1, dataJSON.get("numPoints"));

        Assert.assertNotNull(dataJSON.get("sum"));
        Assert.assertEquals((long) (i + 1000), dataJSON.get("sum"));

        Assert.assertNull(dataJSON.get("rate"));
    }/* w w  w  . j a v  a  2s.  c om*/
}