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.p000ison.dev.simpleclans2.updater.bamboo.BambooBuild.java

@Override
public void fetchInformation() throws IOException, FailedBuildException {
    Reader reader;//from   w  w  w  .  j av  a 2s  .  c  om
    JSONObject content;

    String latestBuild = updateType == UpdateType.LATEST ? String.format(LATEST_BUILD, job)
            : String.format(LATEST_BUILD_BY_LABEL, job, updateType.toString());
    try {
        reader = connect(latestBuild);
    } catch (FileNotFoundException e) {
        Logging.debug("No build found in this channel!");
        return;
    }
    content = parseJSON(reader);
    JSONObject results = (JSONObject) content.get("results");
    JSONArray result = (JSONArray) results.get("result");
    if (result.isEmpty()) {
        Logging.debug("No build found in this channel!");
        return;
    }

    JSONObject firstResult = (JSONObject) result.get(0);
    int buildNumberToFetch = ((Long) firstResult.get("number")).intValue();
    String state = (String) firstResult.get("state");
    if (!state.equalsIgnoreCase("Successful")) {
        throw new FailedBuildException("The last build failed!");
    }

    reader.close();
    reader = connect(String.format(API_FILE, job, buildNumberToFetch));
    content = parseJSON(reader);

    try {
        this.started = DATE_FORMATTER.parse((String) content.get("buildStartedTime")).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    this.duration = (Long) content.get("buildDuration");

    this.buildNumber = ((Long) content.get("number")).intValue();
    this.commitId = (String) content.get("vcsRevisionKey");

    JSONArray changes = (JSONArray) ((JSONObject) content.get("changes")).get("change");

    if (!changes.isEmpty()) {
        JSONObject change = (JSONObject) changes.get(0);
        pusher = (String) change.get("userName");
    }

    reader.close();
}

From source file:ActualizadorLocal.Clientes.ClienteNodos.java

public void procesarDatos(String datos) throws SQLException {
    //Preprocesamos los datos, para darle un nombre al array:

    datos = "{\"nodos\":" + datos + "}";

    JSONParser parser = new JSONParser();

    try {//w ww.  j a v  a 2 s .  com
        JSONObject obj = (JSONObject) parser.parse(datos);
        JSONArray lista = (JSONArray) obj.get("nodos");

        for (int i = 0; i < lista.size(); i++) {
            long a0 = (long) ((JSONObject) lista.get(i)).get("idNodo");
            String a1 = (String) ((JSONObject) lista.get(i)).get("nombre");
            double a2 = (double) ((JSONObject) lista.get(i)).get("latitud");
            double a3 = (double) ((JSONObject) lista.get(i)).get("longitud");

            nodos.add(a0);

            //Tenemos que calcular el polgono para la visualizacin de los datos mediante GOOGLE FUSION TABLES:

            double lat = Math.toRadians(new Double(a2));
            double lon = Math.toRadians(new Double(a3));

            double radio = 50.0 / 6378137.0;

            String cadena_poligono = "<Polygon><outerBoundaryIs><LinearRing><coordinates>";

            for (int j = 0; j <= 360; j = j + 15) {
                double r = Math.toRadians(j);
                double lat_rad = Math
                        .asin(Math.sin(lat) * Math.cos(radio) + Math.cos(lat) * Math.sin(radio) * Math.cos(r));
                double lon_rad = Math.atan2(Math.sin(r) * Math.sin(radio) * Math.cos(lat),
                        Math.cos(radio) - Math.sin(lat) * Math.sin(lat_rad));
                double lon_rad_f = ((lon + lon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;

                cadena_poligono = cadena_poligono + Math.toDegrees(lon_rad_f) + "," + Math.toDegrees(lat_rad)
                        + ",0.0 ";
            }

            cadena_poligono = cadena_poligono + "</coordinates></LinearRing></outerBoundaryIs></Polygon>";

            this.InsertarDatos("\"" + (String) Long.toString(a0) + "\",\"" + a1 + "\",\"" + Double.toString(a2)
                    + "\",\"" + Double.toString(a3) + "\",\"" + cadena_poligono + "\"");

        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    syncDB();

}

From source file:gov.nasa.jpl.xdata.nba.impoexpo.manager.NBAManager.java

/** Parses a single log line in combined log format using StringTokenizers */
private GamePlayer parseGamePlayer(String gameId, JSONArray object) throws ParseException {
    // Construct and return GamePlayer object
    GamePlayer gameplayer = GamePlayer.newBuilder().build();
    gameplayer.setId(gameId + "_" + (String) object.get(0).toString());
    gameplayer.setPlayerId(((Long) object.get(0)).intValue());
    gameplayer.setPlayerName((String) object.get(1).toString());
    gameplayer.setTeamId(((Long) object.get(2)).intValue());
    gameplayer.setTeamCity((String) object.get(3).toString());

    return gameplayer;
}

From source file:com.documentgenerator.view.MainWindow.java

private ArrayList<JMenuItem> getMenuItem(JSONArray jsonMenuItems) {
    int count = jsonMenuItems.size(), i;
    menuItems = new ArrayList<>();
    for (i = 0; i < count; i++) {
        jsonMenuItem = (JSONObject) jsonMenuItems.get(i);
        String menuTitle = (String) jsonMenuItem.get("menuTitle");
        ImageIcon imageIcon = new ImageIcon(
                ClassLoader.getSystemResource((String) jsonMenuItem.get("imageIcon")));

        menuItem = new JMenuItem(menuTitle, imageIcon);
        String className = (String) jsonMenuItem.get("className");
        String shortcut = (String) jsonMenuItem.get("shortcut");
        Boolean hasSeparator = (Boolean) jsonMenuItem.get("separator");
        Boolean hasToolbar = (Boolean) jsonMenuItem.get("hasToolbar");

        if (!Strings.isNullOrEmpty(shortcut)) {
            menuItem.setAccelerator(utils.getKeyStroke(shortcut));
        }/*from w  ww.j  a  v a2s .  c om*/

        if (className.equals("string")) {
            menuItem.setActionCommand(menuTitle);
            menuItem.addActionListener(actionListener);
        } else {
            menuItem.setActionCommand(className);
            menuItem.addActionListener(new MenuItemActionListener(this, className));
        }
        menu.add(menuItem);

        if (hasToolbar) {
            JButton button = new JButton(imageIcon);
            button.setToolTipText(menuTitle);
            button.addActionListener(new MenuItemActionListener(this, className));
            toolBar.add(button);
        }
    }
    return menuItems;
}

From source file:amulet.resourceprofiler.JSONResourceReader.java

/**
 * Parse the input JSON file for energy data collected during our 
 * evaluation of the amulet hardware. JSON data content will be 
 * loaded into Plain Old Java Objects (POJOs) for easy handling 
 * in later parts of the AFT. //from w w w . j av  a  2s  .c  o  m
 * 
 * @param filename The JSON file with energy data. 
 */
public void read(String filename) {
    this.filename = filename;

    JSONParser parser = new JSONParser();
    try {
        // Top-level JSON object.
        JSONObject jsonRootObj = (JSONObject) parser.parse(new FileReader(this.filename));
        //         System.out.println("DEBUG:: jsonRootObj="+jsonRootObj);

        // Extract Device Information.
        JSONObject jsonDeviceInfo = (JSONObject) jsonRootObj.get("device_information");

        deviceInformation.jsonDeviceInfo = jsonDeviceInfo;
        deviceInformation.deviceName = (String) jsonDeviceInfo.get("device_name");
        deviceInformation.batterySize = (Long) jsonDeviceInfo.get("battery_size");
        deviceInformation.batterySizeUnits = (String) jsonDeviceInfo.get("battery_size_units");
        deviceInformation.memTypeVolatile = (String) jsonDeviceInfo.get("volatile_mem_type");
        deviceInformation.memSizeVolatile = (Long) jsonDeviceInfo.get("volatile_mem_size_bytes");
        deviceInformation.memTypeNonVolatile = (String) jsonDeviceInfo.get("non_volatile_mem_type");
        deviceInformation.memSizeNonVolatile = (Long) jsonDeviceInfo.get("non_volatile_mem_size_bytes");
        deviceInformation.memTypeSecondary = (String) jsonDeviceInfo.get("secondary_storage_type");
        deviceInformation.memSizeSecondary = (Double) jsonDeviceInfo.get("secondary_storage_size_bytes");
        deviceInformation.avgNumInstructionsPerLoC = (Double) jsonDeviceInfo.get("instructions_per_loc");
        deviceInformation.avgBasicInstructionPower = (Double) jsonDeviceInfo.get("basic_instruction_power");
        deviceInformation.avgBasicInstructionTime = (Double) jsonDeviceInfo.get("basic_instruction_time");
        deviceInformation.avgBasicInstructionUnit = (String) jsonDeviceInfo.get("basic_loc_time_unit");

        // Extract Steady-State Information.
        JSONObject jsonSteadyStateInfo = (JSONObject) jsonRootObj.get("steady_state_info");

        steadyStateInformation.jsonSteadyStateInfo = jsonSteadyStateInfo;
        steadyStateInformation.radioBoardSleepPower = (Double) jsonSteadyStateInfo
                .get("radio_board_sleep_power");
        steadyStateInformation.appBoardSleepPower = (Double) jsonSteadyStateInfo.get("app_board_sleep_power");
        steadyStateInformation.displayIdlePower = (Double) jsonSteadyStateInfo.get("display_idle_power");
        steadyStateInformation.sensorAccelerometer = (Double) jsonSteadyStateInfo.get("sensor_accelerometer");
        steadyStateInformation.sensorHeartRate = (Double) jsonSteadyStateInfo.get("sensor_heartrate");

        // Array of "parameters".
        JSONArray paramArray = (JSONArray) jsonRootObj.get("api_calls");
        apiInfo = paramArray;
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject jsonObj = (JSONObject) paramArray.get(i);

            /*
             * Build POJO based on energy parameter element from JSON data file.
             * 
             * NOTE: Extend this section of code to parse more parameters 
             * as needed. Also, see: `JSONEnergyParam` below.
             */
            EnergyParam param = new EnergyParam();
            param.name = jsonObj.get("resource_name").toString();
            param.type = jsonObj.get("resource_type").toString();
            param.avgPower = (Double) jsonObj.get("avg_power");
            param.avgTime = (Double) jsonObj.get("time");
            param.timeUnit = jsonObj.get("time_unit").toString();

            // Add the param to the collection of params read in. 
            addEnergyParam(param);
        }

        // DEBUG OUTPUT BLOCK /////////////////////////////////////
        if (debugEnabled) {
            System.out.println(this.toString());
        }
        ///////////////////////////////////////////////////////////

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

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"));
    }//w  ww . j  ava2  s. c om
}

From source file:hoot.services.controllers.job.JobResourceTest.java

/**
 * Tests the processChainJob failure by _execReflection
 *
 * @throws Exception/*from w  w w.  j  a  v a 2 s  .  c o  m*/
 */
@Test
@Category(UnitTest.class)
public void testProcessChainJobFailure() throws Exception {
    // Create Mock JobStatusManager Class
    JobStatusManager mockJobStatusManager = Mockito.mock(JobStatusManager.class);
    Mockito.doNothing().when(mockJobStatusManager).addJob(Matchers.anyString());
    Mockito.doNothing().when(mockJobStatusManager).updateJob(Matchers.anyString(), Matchers.anyString());
    Mockito.doNothing().when(mockJobStatusManager).setComplete(Matchers.anyString(), Matchers.anyString());
    Mockito.doNothing().when(mockJobStatusManager).setFailed(Matchers.anyString(), Matchers.anyString());

    // Mock child info
    JSONObject mockChild = new JSONObject();
    mockChild.put("id", "test_child_123_FAIL");
    mockChild.put("detail", "processing");
    mockChild.put("status", "running");

    JobResource real = new JobResource();
    JobResource spy = Mockito.spy(real);

    // so I use this to avoid actual call
    Mockito.doReturn(Response.ok().build()).when(spy).processJob(Matchers.anyString(), Matchers.anyString());
    Mockito.doReturn(mockJobStatusManager).when(spy).createJobStatusMananger(Matchers.any(Connection.class));

    // failure point
    Mockito.doThrow(new Exception("Mock failure for testing Process Chain Job failure. (Not real failure!!!)"))
            .when(spy).execReflection(Matchers.anyString(), Matchers.any(JSONObject.class),
                    Matchers.any(JobStatusManager.class));

    try {
        String jobStr = "[{\"caller\":\"FileUploadResource\",\"exec\":\"makeetl\","
                + "\"params\":[{\"INPUT\":\"upload\\/81898818-2ca3-4a15-9421-50eb91952586\\/GroundPhotos.shp\"},"
                + "{\"INPUT_TYPE\":\"OGR\"},{\"TRANSLATION\":\"translations\\/UTP.js\"},{\"INPUT_NAME\":\"GroundPhotos\"}],"
                + "\"exectype\":\"make\"},{\"class\":\"hoot.services.controllers.ingest.RasterToTilesService\","
                + "\"method\":\"ingestOSMResource\",\"params\":[{\"isprimitivetype\":\"false\",\"value\":\"GroundPhotos\","
                + "\"paramtype\":\"java.lang.String\"}],\"exectype\":\"reflection\"}]";

        spy.processChainJob("test_job_id_1234_FAIL", jobStr);

        // sleep for a couple of secs to make sure that all threads spawned by the the call to spy.processChainJob() finish
        Thread.sleep(2000);
    } catch (WebApplicationException wex) {
        Response res = wex.getResponse();
        Assert.assertEquals(500, res.getStatus());
    }

    // There should be one success for first part being completed. Second
    // would be setFailed which updates db directly so update is not called.
    ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);

    Mockito.verify(mockJobStatusManager, Mockito.times(2)).updateJob(Matchers.anyString(), argCaptor.capture());

    JSONParser parser = new JSONParser();

    List<String> args = argCaptor.getAllValues();
    JSONObject status = (JSONObject) parser.parse(args.get(0));
    JSONArray children = (JSONArray) status.get("children");
    JSONObject child = (JSONObject) children.get(0);

    Assert.assertEquals("processing", child.get("detail").toString());
    Assert.assertEquals("running", child.get("status").toString());

    status = (JSONObject) parser.parse(args.get(1));
    children = (JSONArray) status.get("children");
    Assert.assertEquals(1, children.size());

    child = (JSONObject) children.get(0);
    Assert.assertEquals("success", child.get("detail").toString());
    Assert.assertEquals("complete", child.get("status").toString());

    // Check for setFailed invocation
    ArgumentCaptor<String> setFailedArgCaptor = ArgumentCaptor.forClass(String.class);

    Mockito.verify(mockJobStatusManager, Mockito.times(1)).setFailed(Matchers.anyString(),
            setFailedArgCaptor.capture());

    args = setFailedArgCaptor.getAllValues();
    status = (JSONObject) parser.parse(args.get(0));
    children = (JSONArray) status.get("children");

    Assert.assertEquals(1, children.size());

    child = (JSONObject) children.get(0);
    Assert.assertEquals("Mock failure for testing Process Chain Job failure. (Not real failure!!!)",
            child.get("detail").toString());
    Assert.assertEquals("failed", child.get("status").toString());
}

From source file:com.nubits.nubot.pricefeeds.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  w  w  .  jav  a  2s.c  o m*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.severe(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.warning("Cannot find currency " + lookingfor + " on feed " + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (Exception ex) {
            LOG.severe(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.fine("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 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.
    }//from w  ww.j a  v a 2 s .c  o  m
}

From source file:edu.emory.library.spotlight.SpotlightClient.java

public List<SpotlightAnnotation> annotate(String txt) throws Exception {
    List<SpotlightAnnotation> annotations = new ArrayList<SpotlightAnnotation>();

    try {/*from  w  w  w.jav  a  2  s  .  c  om*/
        String uri = String.format("%s/annotate", this.baseUrl);

        HashMap headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");
        // content-type required when using POST
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        HashMap params = new HashMap<String, String>();
        params.put("text", txt);
        // restrict to supported types (TODO: don't hard-code here; configurable?)
        params.put("types", "Person,Place,Organisation");
        // include confidence & support parameters if set
        if (this.confidence != null) {
            params.put("confidence", String.format("%s", this.confidence));
        }
        if (this.support != null) {
            params.put("support", String.format("%d", this.support));
        }

        // always use POST to support text larger than that allowed in
        // an HTTP GET request URI
        String response = EULHttpUtils.postUrlContents(uri, headers, params);

        // load the result as json
        JSONObject json = (JSONObject) new JSONParser().parse(response);
        // information about identified names are listed under 'Resources'
        JSONArray jsonArray = (JSONArray) json.get("Resources");
        // if no names are identified, resources will not be set
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.size(); i++) {
                SpotlightAnnotation sa = new SpotlightAnnotation((JSONObject) jsonArray.get(i));
                annotations.add(sa);
            }
        }

    } catch (java.io.UnsupportedEncodingException e) {
        // TODO:  log error instead of just printing
        System.out.println("Error encoding text");
    } // TODO: also need to catch json decoding error

    return annotations;
}