Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.nubits.nubot.pricefeeds.feedservices.ExchangeratelabPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*from  w ww .  java  2s . com*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            JSONArray array = (JSONArray) httpAnswerJson.get("rates");

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();

            boolean found = false;
            double rate = -1;
            for (int i = 0; i < array.size(); i++) {
                JSONObject temp = (JSONObject) array.get(i);
                String tempCurrency = (String) temp.get("to");
                if (tempCurrency.equalsIgnoreCase(lookingfor)) {
                    found = true;
                    rate = Utils.getDouble((Double) temp.get("rate"));
                    rate = Utils.round(1 / rate, 8);
                }
            }

            lastRequest = System.currentTimeMillis();

            if (found) {

                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(rate, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warn("Cannot find currency " + lookingfor + " on feed " + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (Exception ex) {
            LOG.error(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

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 ww.  j  a  v  a 2  s .  com*/
}

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

public static List<String> getEmotes() {
    List<String> emotes = new LinkedList<String>();
    try {//from w w w . j  a v a2  s  .co m
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager.getRemoteContent("http://direct.twitchemotes.com/global.json"));

        JSONObject jsonObject = (JSONObject) obj;

        for (Object o : jsonObject.keySet()) {
            String name = (String) o;
            if (name.length() > 0)
                emotes.add(name);
        }
        Object obj1 = parser.parse(BotManager.getRemoteContent("https://api.betterttv.net/emotes"));

        JSONObject jsonObject1 = (JSONObject) obj1;

        JSONArray emotesObj = (JSONArray) jsonObject1.get("emotes");
        for (int i = 0; i < emotesObj.size(); i++) {
            JSONObject emoteObject = (JSONObject) emotesObj.get(i);
            String emoteStr = (String) emoteObject.get("regex");
            emotes.add(emoteStr);
        }

        emotes.add(":)");
        emotes.add(":o");
        emotes.add(":(");
        emotes.add(";)");
        emotes.add(":/");
        emotes.add(";p");
        emotes.add(">(");
        emotes.add("B)");
        emotes.add("O_o");
        emotes.add("O_O");
        emotes.add("R)");
        emotes.add(":D");
        emotes.add(":z");
        emotes.add("D:");
        emotes.add(":p");
        emotes.add(":P");
    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        return emotes;
    }

}

From source file:com.db.comserv.main.utilities.HttpCaller.java

private Boolean matchPattern(final String url, String multiplierStr, String method) {
    JSONArray jsonArr = (JSONArray) Utility.parse(multiplierStr);
    for (int i = 0; i < jsonArr.size(); i++) {
        JSONObject obj = (JSONObject) jsonArr.get(i);
        String regex = obj.get("path").toString();
        String methodStr = obj.get("method").toString();
        Pattern pattern = Pattern.compile(regex);
        Matcher match = pattern.matcher(url);
        boolean found = match.find();
        if (found && methodStr.contains(method)) {
            return (found && methodStr.contains(method));
        }/*  w  w  w . jav  a 2 s . co  m*/
    }
    return false;
}

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);//from   w  w  w  .  j a  va2 s . c  o m
            }
        } 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:com.codelanx.playtime.update.UpdateHandler.java

/**
 * Gets the {@link JSONObject} from the CurseAPI of the newest project version.
 * /*from w w  w .  j ava 2  s.  co  m*/
 * @since 1.4.5
 * @version 1.4.5
 */
private void getJSON() {
    InputStream stream = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    String json = null;
    try {
        URL call = new URL(this.VERSION_URL);
        stream = call.openStream();
        isr = new InputStreamReader(stream);
        reader = new BufferedReader(isr);
        json = reader.readLine();
    } catch (MalformedURLException ex) {
        plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : "");
        this.result = Result.ERROR_BADID;
        this.latest = null;
    } catch (IOException ex) {
        plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : "");
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            this.plugin.getLogger().log(Level.SEVERE, "Error closing updater streams!",
                    this.debug >= 3 ? ex : "");
        }
    }
    if (json != null) {
        JSONArray arr = (JSONArray) JSONValue.parse(json);
        this.latest = (JSONObject) arr.get(arr.size() - 1);
    } else {
        this.latest = null;
    }
}

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

@Test
public void testEnums() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeEnumRollupPoints(),
            "unknown", MetricData.Type.ENUM);
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_STATS);
    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);
        final Map<String, Long> evJSON = (Map<String, Long>) dataJSON.get("enum_values");
        Set<String> keys = evJSON.keySet();

        Assert.assertEquals(1, keys.size());
        for (String key : keys) {
            Assert.assertEquals(key, "enum_value_" + i);
            Assert.assertEquals((long) evJSON.get(key), 1);
        }/* www  .  ja va2 s  .  c o  m*/
        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertEquals(1, dataJSON.get("numPoints"));
        Assert.assertEquals(MetricData.Type.ENUM, dataJSON.get("type"));
    }
}

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

@Test
public void testGauges() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeGaugeRollups(), "unknown",
            MetricData.Type.NUMBER);
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_GAUGE);
    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(1L, dataJSON.get("numPoints"));
        Assert.assertNotNull("latest");
        Assert.assertEquals(i, dataJSON.get("latest"));

        // other fields were filtered out.
        Assert.assertNull(dataJSON.get(MetricStat.AVERAGE.toString()));
        Assert.assertNull(dataJSON.get(MetricStat.VARIANCE.toString()));
        Assert.assertNull(dataJSON.get(MetricStat.MIN.toString()));
        Assert.assertNull(dataJSON.get(MetricStat.MAX.toString()));
    }//from www . j a  va 2 s .  co m
}

From source file:de.thejeterlp.bukkit.updater.Updater.java

/**
 * Index:/*from ww  w. java  2s . c  o  m*/
 * 0: downloadUrl
 * 1: name
 * 2: releaseType
 *
 * @return
 */
protected String[] read() {
    debug("Method: read()");
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() == 0)
            return null;
        Map<?, ?> map = (Map) array.get(array.size() - 1);
        String downloadUrl = (String) map.get("downloadUrl");
        String name = (String) map.get("name");
        String releaseType = (String) map.get("releaseType");
        return new String[] { downloadUrl, name, releaseType };
    } catch (Exception e) {
        main.getLogger().severe("Error on trying to check remote versions. Error: " + e);
        return null;
    }
}

From source file:de.tuttas.config.Config.java

/**
        /*from  w w  w  .  j  a va2s .co  m*/
 */

private Config() {
    BufferedReader br = null;
    try {
        String pathConfig = System.getProperty("catalina.base") + File.separator + "config.json";

        br = new BufferedReader(new FileReader(pathConfig));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String conf = sb.toString();
        JSONParser parser = new JSONParser();
        JSONObject jo = (JSONObject) parser.parse(conf);
        debug = (boolean) jo.get("debug");

        auth = (boolean) jo.get("auth");
        IMAGE_FILE_PATH = (String) jo.get("IMAGE_FILE_PATH");
        ATEST_FILE_PATH = (String) jo.get("ATEST_FILE_PATH");
        TEMPLATE_FILE_PATH = (String) jo.get("TEMPLATE_FILE_PATH");
        Log.d("IMage_File_Path=" + IMAGE_FILE_PATH);
        JSONArray ja = (JSONArray) jo.get("adminusers");
        adminusers = new String[ja.size()];
        for (int i = 0; i < adminusers.length; i++) {
            adminusers[i] = (String) ja.get(i);
        }
        ja = (JSONArray) jo.get("verwaltung");
        verwaltung = new String[ja.size()];
        for (int i = 0; i < verwaltung.length; i++) {
            verwaltung[i] = (String) ja.get(i);
            Log.d("Setzte Verwaltung " + (String) ja.get(i));
        }

        AUTH_TOKE_TIMEOUT = (long) jo.get("AUTH_TOKE_TIMEOUT");

        // LDAP Konfiguration
        ldaphost = (String) jo.get("ldaphost");
        bindUser = (String) jo.get("binduser");
        bindPassword = (String) jo.get("bindpassword");
        userContext = (String) jo.get("context");

        // SMTP Server Konfiguration
        smtphost = (String) jo.get("smtphost");
        port = (String) jo.get("port");
        user = (String) jo.get("user");
        pass = (String) jo.get("pass");

        // Client Configuration
        clientConfig = (JSONObject) jo.get("clientConfig");
        clientConfig.put("VERSION", Config.VERSION);

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        ex.printStackTrace();
        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException ex) {
            Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}