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:importer.handler.post.stages.SAXSplitter.java

/**
 * Sort an array of path objects//w ww  . ja v  a  2s.  c  o m
 * @param jArr the array of path json objects
 * @return the sorted array
 */
JSONArray sort(JSONArray jArr) {
    int increment = jArr.size() / 2;
    while (increment > 0) {
        for (int i = increment; i < jArr.size(); i++) {
            int j = i;
            JSONObject temp = (JSONObject) jArr.get(i);
            while (j >= increment && compare((JSONObject) jArr.get(j - increment), temp) > 0) {
                jArr.set(j, jArr.get(j - increment));
                j = j - increment;
            }
            jArr.set(j, temp);
        }
        if (increment == 2)
            increment = 1;
        else
            increment *= (5.0 / 11);
    }
    return jArr;
}

From source file:com.orthancserver.DicomDecoder.java

private String[] SortSlicesByNumber(OrthancConnection c, JSONArray instances) throws IOException {
    ArrayList<Slice> slices = new ArrayList<Slice>();

    for (int i = 0; i < instances.size(); i++) {
        String uuid = (String) instances.get(i);
        JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid);
        Long index = (Long) instance.get("IndexInSeries");
        slices.add(new Slice((float) index, uuid));
    }/*w w w. j  av  a  2  s .  co m*/

    return SortSlices(slices);
}

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

@Test
public void testTransformRollupDataString() throws SerializationException {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeStringPoints(), "unknown",
            MetricData.Type.STRING);

    JSONObject metricDataJSON = serializer.transformRollupData(metricData, filterStats);

    final JSONArray data = (JSONArray) metricDataJSON.get("values");

    // Assert that we have some data to test
    Assert.assertTrue(data.size() > 0);

    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject) data.get(i);
        final Points.Point point = (Points.Point) metricData.getData().getPoints()
                .get(dataJSON.get("timestamp"));

        Assert.assertEquals(point.getData(), dataJSON.get("value"));

        Assert.assertNull(dataJSON.get("average"));
        Assert.assertNull(dataJSON.get("min"));
        Assert.assertNull(dataJSON.get("max"));
        Assert.assertNull(dataJSON.get("variance"));
    }// www.  j a v  a  2s.  co m
}

From source file:org.opencastproject.adminui.endpoint.UsersSettingsEndpointTest.java

private void compareIds(String key, JSONObject expected, JSONObject actual) {
    JSONArray expectedArray = (JSONArray) expected.get(key);
    JSONArray actualArray = (JSONArray) actual.get(key);

    Assert.assertEquals(expectedArray.size(), actualArray.size());
    JSONObject exObject;/*w w  w  .  ja  va2  s  . c o m*/
    JSONObject acObject;
    int actualId;
    for (int i = 0; i < actualArray.size(); i++) {
        acObject = (JSONObject) actualArray.get(i);
        actualId = Integer.parseInt(acObject.get("id").toString()) - 1;
        exObject = (JSONObject) expectedArray.get(actualId);
        Set<String> exEntrySet = exObject.keySet();
        Assert.assertEquals(exEntrySet.size(), acObject.size());
        Iterator<String> exIter = exEntrySet.iterator();

        while (exIter.hasNext()) {
            String item = exIter.next();
            Object exValue = exObject.get(item);
            Object acValue = acObject.get(item);
            Assert.assertEquals(exValue, acValue);
        }

    }
}

From source file:chat.com.client.ChatClient.java

private void typeChat(String msg) {
    try {/* ww w .  j a  v  a2 s  .  c  o m*/
        JSONParser jsonParser = new JSONParser();
        JSONObject jsontypeChat = (JSONObject) jsonParser.parse(msg);
        //   jTextAreaChat.append(msg + '\n');
        String type = jsontypeChat.get("type").toString();

        if (type.equals("me")) {
            // get id for user
            id = jsontypeChat.get("id").toString();
            jTextAreaChat.append(id + '\n');
        } else if (type.equals("userOnline")) {
            // add item
            JSONArray jsonArray = (JSONArray) jsontypeChat.get("listUser");
            jComboBoxListUser.removeAllItems();
            jComboBoxListUser.addItem("all");
            for (int i = 0; i < jsonArray.size(); i++) {
                if (!jsonArray.get(i).equals(id)) {
                    //
                    jComboBoxListUser.addItem(jsonArray.get(i));
                }
            }
        } else {
            //(type.equals("chat"))
            String idWho = (String) jsontypeChat.get("id");
            String message = (String) jsontypeChat.get("message");
            jTextAreaChat.append(idWho + " say: " + message + '\n');
        }
    } catch (ParseException ex) {
        Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.respam.comniq.Controller.java

public Task OMDBworker() {
    return new Task() {
        @Override//from  ww w  .ja  v  a  2s.c  o  m
        protected Object call() throws Exception {
            OMDBParser op = new OMDBParser();
            JSONParser parser = new JSONParser();
            String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator
                    + "output";
            try {
                Object obj = parser.parse(new FileReader(path + File.separator + "LocalList.json"));
                JSONArray parsedArr = (JSONArray) obj;

                // Loop JSON Array
                for (int i = 0; i < parsedArr.size(); i++) {
                    JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                    String movieName = (String) parsedObj.get("movie");
                    String movieYear = (String) parsedObj.get("year");
                    System.out.println(movieName + "-" + movieYear);
                    op.requestOMDB(movieName, movieYear);
                    updateProgress(i, parsedArr.size() - 1);
                }
                op.movieInfoWriter();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return true;
        }
    };
}

From source file:com.respam.comniq.Controller.java

public Task createExportWorker() {
    return new Task() {
        @Override//  ww  w  .jav  a  2  s  .  com
        protected Object call() throws Exception {
            JSONParser parser = new JSONParser();
            String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator
                    + "output";

            try {
                POIexcelExporter export = new POIexcelExporter();
                Object obj = parser.parse(new FileReader(path + File.separator + "MovieInfo.json"));
                JSONArray parsedArr = (JSONArray) obj;

                // Loop JSON Array
                for (int i = 0; i < parsedArr.size(); i++) {
                    JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                    if (null != parsedObj.get("Title")) {
                        export.excelWriter(parsedObj, i);
                        System.out.println("Done with " + "\"" + parsedObj.get("Title") + "\"");
                    }
                    updateProgress(i, parsedArr.size() - 1);
                }
                //                    export.addImages(parsedArr);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return true;
        }
    };
}

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

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

    JSONObject metricDataJSON = serializer.transformRollupData(metricData, filterStats);

    final JSONArray data = (JSONArray) metricDataJSON.get("values");

    // Assert that we have some data to test
    Assert.assertTrue(data.size() > 0);

    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject) data.get(i);
        final Points.Point<SimpleNumber> point = (Points.Point<SimpleNumber>) metricData.getData().getPoints()
                .get(dataJSON.get("timestamp"));

        Assert.assertEquals(point.getData().getValue(), dataJSON.get("average"));
        Assert.assertEquals(point.getData().getValue(), dataJSON.get("min"));
        Assert.assertEquals(point.getData().getValue(), dataJSON.get("max"));

        // Assert that variance isn't present
        Assert.assertNull(dataJSON.get("variance"));

        // Assert numPoints isn't present
        Assert.assertNull(dataJSON.get("numPoints"));
    }/*from  w  w w  .  ja v  a  2  s .c  o  m*/
}

From source file:fr.bmartel.speedtest.test.SpeedTestServerTest.java

@Test
public void serverListTest() throws IOException, ParseException, TimeoutException {

    initSocket();/*from w  ww  .  j  a  v  a 2s . c om*/

    final URL url = getClass().getResource("/" + TestCommon.SERVER_LIST_FILENAME);

    final Object obj = new JSONParser().parse(new FileReader(url.getPath()));

    final JSONArray servers = (JSONArray) obj;

    for (int i = 0; i < servers.size(); i++) {

        final JSONObject serverObj = (JSONObject) servers.get(i);

        if (serverObj.containsKey("host")) {

            final String host = serverObj.get("host").toString();

            if (serverObj.containsKey("download")) {

                final JSONArray downloadEndpoints = (JSONArray) serverObj.get("download");

                for (int j = 0; j < downloadEndpoints.size(); j++) {

                    final JSONObject downloadEndpoint = (JSONObject) downloadEndpoints.get(j);

                    if (downloadEndpoint.containsKey("protocol")) {

                        final String protocol = downloadEndpoint.get("protocol").toString();

                        if (downloadEndpoint.containsKey("uri")) {

                            final String uri = downloadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[download] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startDownload(host, uri);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":

                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (downloadEndpoint.containsKey("username")) {
                                    username = downloadEndpoint.get("username").toString();
                                }
                                if (downloadEndpoint.containsKey("password")) {
                                    password = downloadEndpoint.get("password").toString();
                                }
                                System.out.println("[download] FTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startFtpDownload(host, SpeedTestConst.FTP_DEFAULT_PORT, uri, username,
                                        password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("download for host " + host + " has no uri");
                        }
                    } else {
                        Assert.fail("download for host " + host + " has no protocol");
                    }
                }
            }
            if (serverObj.containsKey("upload")) {

                final JSONArray uploadEndpoints = (JSONArray) serverObj.get("upload");

                for (int j = 0; j < uploadEndpoints.size(); j++) {

                    final JSONObject uploadEndpoint = (JSONObject) uploadEndpoints.get(j);

                    if (uploadEndpoint.containsKey("protocol")) {

                        final String protocol = uploadEndpoint.get("protocol").toString();

                        if (uploadEndpoint.containsKey("uri")) {

                            final String uri = uploadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[upload] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startUpload(host, uri, TestCommon.FILE_SIZE_LARGE);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":
                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (uploadEndpoint.containsKey("username")) {
                                    username = uploadEndpoint.get("username").toString();
                                }
                                if (uploadEndpoint.containsKey("password")) {
                                    password = uploadEndpoint.get("password").toString();
                                }
                                System.out.println("[upload] FTP - testing " + host + " with uri " + uri);
                                final String fileName = generateFileName() + ".txt";
                                mWaiter = new Waiter();
                                mSocket.startFtpUpload(host, SpeedTestConst.FTP_DEFAULT_PORT,
                                        uri + "/" + fileName, TestCommon.FILE_SIZE_LARGE, username, password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("upload for host " + host + " has no uri");
                        }

                    } else {
                        Assert.fail("upload for host " + host + " has no protocol");
                    }
                }
            }
        }
    }

    mSocket.clearListeners();
}

From source file:com.dagobert_engine.trading.service.MtGoxTradeService.java

public List<Order> getOpenOrders() {

    ArrayList<Order> orders = new ArrayList<Order>();

    CurrencyType currency = config.getDefaultCurrency();

    try {//from   ww  w .j a  v a  2  s.  c o  m
        String resultJson = adapter.query(MtGoxQueryUtil.create(currency, API_MONEY_ORDERS));

        JSONObject root = (JSONObject) parser.parse(resultJson);
        String result = (String) root.get("result");

        if (!"success".equals(result)) {
            throw new MtGoxException(result);
        }

        JSONArray data = (JSONArray) root.get("data");

        for (int i = 0; i < data.size(); i++) {
            JSONObject orderJson = (JSONObject) data.get(i);

            Order order = new Order();
            order.setOrderId((String) orderJson.get("oid"));
            order.setItem(CurrencyType.valueOf((String) orderJson.get("item")));
            order.setType(Order.OrderType.valueOf(((String) orderJson.get("type")).toUpperCase()));
            order.setAmount(getCurrencyForJsonObj((JSONObject) orderJson.get("amount")));
            order.setEffectiveAmount(getCurrencyForJsonObj((JSONObject) orderJson.get("effective_amount")));
            order.setInvalidAmount(getCurrencyForJsonObj((JSONObject) orderJson.get("invalid_amount")));
            order.setPrice(getCurrencyForJsonObj((JSONObject) orderJson.get("price")));
            order.setStatus(StatusType.valueOf(((String) orderJson.get("status")).toUpperCase()));
            order.setDate(new Date((long) orderJson.get("date") * 1000));
            order.setPriority(Long.parseLong((String) orderJson.get("priority")));

            orders.add(order);

        }
    } catch (Exception exc) {
        throw new MtGoxException(exc);
    }

    return orders;
}