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.facebook.tsdb.tsdash.server.DataEndpoint.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {/*from   ww  w.  j a va2  s. c om*/
        long ts = System.currentTimeMillis();
        // decode parameters
        String jsonParams = request.getParameter("params");
        if (jsonParams == null) {
            throw new Exception("Parameters not specified");
        }
        JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams);
        long tsFrom = (Long) jsonParamsObj.get("tsFrom");
        long tsTo = (Long) jsonParamsObj.get("tsTo");
        JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics");
        if (metricsArray.size() == 0) {
            throw new Exception("No metrics to fetch");
        }
        MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()];
        for (int i = 0; i < metricsArray.size(); i++) {
            metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i));
        }

        TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
        Metric[] metrics = new Metric[metricQueries.length];
        for (int i = 0; i < metrics.length; i++) {
            MetricQuery q = metricQueries[i];
            metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders);
            metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator);
            if (q.rate) {
                metrics[i].computeRate();
            }
        }
        long loadTime = System.currentTimeMillis() - ts;
        JSONObject responseObj = new JSONObject();
        JSONArray encodedMetrics = new JSONArray();
        for (Metric metric : metrics) {
            encodedMetrics.add(metric.toJSONObject());
        }
        responseObj.put("metrics", encodedMetrics);
        responseObj.put("loadtime", loadTime);
        DataTable dataTable = new DataTable(metrics);
        responseObj.put("datatable", dataTable.toJSONObject());
        out.println(responseObj.toJSONString());
        long encodingTime = System.currentTimeMillis() - ts - loadTime;
        logger.info("[Data] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, "
                + "encoding time: " + encodingTime + "ms");
    } catch (Exception e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}

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

@Test
public void testTransformRollupDataForCoarserGran() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeRollupPoints(), "unknown",
            MetricData.Type.NUMBER);
    Set<MetricStat> filters = new HashSet<MetricStat>();
    filters.add(MetricStat.AVERAGE);/*  w w w.jav a 2 s .  c  om*/
    filters.add(MetricStat.MIN);
    filters.add(MetricStat.MAX);
    filters.add(MetricStat.NUM_POINTS);

    JSONObject metricDataJSON = serializer.transformRollupData(metricData, filters);
    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"));

        long numPoints = ((BasicRollup) point.getData()).getCount();
        Assert.assertEquals(numPoints, dataJSON.get("numPoints"));

        if (numPoints == 0) {
            Assert.assertNull(dataJSON.get("average"));
            Assert.assertNull(dataJSON.get("min"));
            Assert.assertNull(dataJSON.get("max"));
        } else {
            Assert.assertEquals(((BasicRollup) point.getData()).getAverage(), dataJSON.get("average"));
            Assert.assertEquals(((BasicRollup) point.getData()).getMaxValue(), dataJSON.get("max"));
            Assert.assertEquals(((BasicRollup) point.getData()).getMinValue(), dataJSON.get("min"));
        }

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

From source file:com.gmail.bleedobsidian.areaprotect.Updater.java

/**
 * Query ServerMods API for project variables.
 * //from  www. j av a2 s  .co m
 * @return If successful or not.
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

/**
 * Replaces any variables in the templates using the mapping specified in
 * the config./* www  .  ja  v  a 2s . c  o  m*/
 * 
 * @param solrDoc
 * @param vars
 * @param config
 * @param context
 */
private void initVars(SolrDoc solrDoc, List<String> vars, JsonSimple config, VelocityContext context) {
    for (String var : vars) {
        String varField = config.getString("", "mapping", var);
        String replacement = getCollectionValues(config, solrDoc, varField);
        if (StringUtils.isBlank(replacement)) {
            if (isVariableNameHiddenIfEmpty) {
                replacement = solrDoc.getString("", varField);
            } else {
                replacement = solrDoc.getString(var, varField);
            }
        }
        if (replacement == null || "".equals(replacement)) {
            JSONArray arr = solrDoc.getArray(varField);
            if (arr != null) {
                replacement = (String) arr.get(0);
                if (replacement == null) {
                    // giving up, setting back to source value so caller can
                    // evaluate
                    if (isVariableNameHiddenIfEmpty) {
                        replacement = "";
                    } else {
                        replacement = var;
                    }
                }
            } else {
                // giving up, setting back to source value so caller can
                // evaluate
                if (isVariableNameHiddenIfEmpty) {
                    replacement = "";
                } else {
                    replacement = var;
                }
            }
        }
        log.debug("Getting variable value '" + var + "' using field '" + varField + "', value:" + replacement);
        context.put(var.replace("$", ""), replacement);
    }
}

From source file:connectivity.connection.java

public void sortLikes() throws SQLException, ParseException {
    PreparedStatement ps = con.prepareStatement("Select tip_id,likes_content from tips; ");

    ResultSet rs = ps.executeQuery();
    ArrayList likes = new ArrayList();
    while (rs.next()) {
        String[] arr = new String[2];
        arr[0] = rs.getString("tip_id");
        arr[1] = rs.getString("likes_content");
        likes.add(arr);/*  ww  w . j a  va  2s .c  o m*/
    }
    //System.out.println(likes);
    for (Object like : likes) {
        try {
            String[] arr = (String[]) like;
            JSONObject json = (JSONObject) new JSONParser().parse(arr[1]);
            //System.out.print(json.get("groups").toString());
            JSONArray groups = (JSONArray) new JSONParser().parse((json.get("groups").toString()));
            //Object [] a=(Object[]) user.get(0);
            JSONObject groups0 = (JSONObject) new JSONParser().parse((groups.get(0).toString()));
            JSONArray items = (JSONArray) new JSONParser().parse((groups0.get("items").toString()));
            for (Object item : items) {
                String ret = addUser((JSONObject) item);
                ps = con.prepareStatement("INSERT INTO `user_likes_tips` VALUES (?, ?);");
                ps.setString(1, ret);
                ps.setString(2, arr[0]);
                ps.addBatch();
            }
            ps.executeBatch();
            //System.out.print('a');
        } catch (Exception e) {
            System.out.println("exception e=" + e);
        }
    }
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

public boolean update(final double LATITUDE, final double LONGITUDE) {
    // Update only if lastUpdate is older than 10 min
    if (Instant.now().minusSeconds(600).isBefore(lastUpdate))
        return true;

    StringBuilder response = new StringBuilder();
    try {//from ww w .  j av a  2s  . co  m
        forecast.clear();
        alerts.clear();

        final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY,
                Exclude.MINUTELY, Exclude.FLAGS);
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString());
        longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString());
        timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString());

        // Update today data
        JSONObject currently = (JSONObject) jsonObj.get("currently");
        setDataPoint(today, currently);

        // Update forecast data
        JSONObject daily = (JSONObject) jsonObj.get("daily");
        JSONArray days = (JSONArray) daily.get("data");

        // Update today with more data
        JSONObject day0 = (JSONObject) days.get(0);
        today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString()));
        today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString()));
        today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString()));
        today.setPrecipType(PrecipType
                .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));

        for (int i = 1; i < days.size(); i++) {
            JSONObject day = (JSONObject) days.get(i);
            DataPoint dataPoint = new DataPoint();
            setDataPoint(dataPoint, day);
            forecast.add(dataPoint);
        }

        // Update alert data
        if (jsonObj.containsKey("alerts")) {
            JSONArray alerts = (JSONArray) jsonObj.get("alerts");
            for (Object alertObj : alerts) {
                JSONObject alertJson = (JSONObject) alertObj;
                Alert alert = new Alert();
                alert.setTitle(alertJson.get("title").toString());
                alert.setDescription(alertJson.get("description").toString());
                alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString()));
                alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString()));
                alerts.add(alert);
            }
        }

        lastUpdate = Instant.now();

        return true;
    } catch (IOException ex) {
        System.out.println(ex);
        return false;
    }
}

From source file:com.wcmc.Software.screens.RegistrationScreen.java

public void setRidersData(String data) {
    try {/*from   w  ww. j a va 2  s  .co  m*/
        JSONObject json = (JSONObject) jsonParser.parse(data);
        JSONObject classInfo = (JSONObject) json.get("class");
        if (classInfo != null) {
            classRiders.setTitle(classInfo.get("title").toString());
        }

        classRiders.clear();

        JSONArray riders = (JSONArray) json.get("riders");

        if (riders != null) {
            for (int i = 0; i < riders.size(); i++) {
                JSONObject rider_info = (JSONObject) riders.get(i);
                ClassItem riderItem = new ClassItem();
                riderItem.setText(rider_info.get("name").toString());
                riderItem.setID(Integer.parseInt(rider_info.get("id").toString()));

                riderItem.setY(i * 15);
                riderItem.setWidth(classRiders.getWidth());

                classRiders.add(riderItem);
            }
        }

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

From source file:com.wcmc.Software.screens.RegistrationScreen.java

public void setAutocompleteData(String data) {
    try {/*from   w  ww  . j a v a 2s.  co m*/
        riders.clear();
        JSONObject json = (JSONObject) jsonParser.parse(data);
        JSONArray json_riders = (JSONArray) json.get("riders");
        if (json_riders != null) {
            for (int i = 0; i < json_riders.size(); i++) {
                JSONObject rider = (JSONObject) json_riders.get(i);
                System.out.println(rider);
                AutoCompleteItem item = new AutoCompleteItem();
                item.setWidth(400);
                item.setHeight(15);
                item.setText(rider.get("first_name").toString() + " " + rider.get("last_name").toString());
                item.setID(Integer.parseInt(rider.get("id").toString()));
                item.setY((i * 15) + 1);
                riders.add(item);
            }
        }
        showAutocomplete = true;
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.capitalone.dashboard.client.project.ProjectDataClientImpl.java

/**
 * Updates the MongoDB with a JSONArray received from the source system
 * back-end with story-based data./*from w ww .ja  va2 s  .  c  o m*/
 *
 * @param tmpMongoDetailArray
 *            A JSON response in JSONArray format from the source system
 * @param featureCollector
 * @return
 * @return
 */
@SuppressWarnings("unchecked")
protected void updateMongoInfo(JSONArray tmpMongoDetailArray) {
    try {
        JSONObject dataMainObj = new JSONObject();
        for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
            if (dataMainObj != null) {
                dataMainObj.clear();
            }
            dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
            Scope scope = new Scope();

            @SuppressWarnings("unused") // ?
            boolean deleted = this
                    .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            // collectorId
            scope.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId());

            // ID;
            scope.setpId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            // name;
            scope.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name")));

            // beginDate;
            scope.setBeginDate(
                    TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("BeginDate"))));

            // endDate;
            scope.setEndDate(
                    TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("EndDate"))));

            // changeDate;
            scope.setChangeDate(
                    TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate"))));

            // assetState;
            scope.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")));

            // isDeleted;
            scope.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted")));

            // path;
            String projPath = new String(scope.getName());
            List<String> projList = (List<String>) dataMainObj.get("ParentAndUp.Name");
            if (projList != null) {
                for (String proj : projList) {
                    projPath = proj + "-->" + projPath;
                }
                projPath = "All-->" + projPath;
            } else {
                projPath = "All-->" + projPath;
            }
            scope.setProjectPath(TOOLS.sanitizeResponse(projPath));

            try {
                projectRepo.save(scope);
            } catch (Exception e) {
                LOGGER.error("Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(),
                        e);
            }
        }
    } catch (Exception e) {
        LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass());
    }
}

From source file:com.ge.research.semtk.sparqlX.parallel.SparqlParallelQueries.java

@SuppressWarnings("unchecked")
public SparqlParallelQueries(String subqueriesJson, String subqueryType, boolean isSubqueryOptional,
        String columnsToFuseOn, String columnsToReturn) throws Exception {
    // parse the json array and build the subquery objects as we go
    gResultTable = null;//from w ww  . j a v  a2 s  . co  m

    JSONArray subqueries = (JSONArray) (new JSONParser()).parse(subqueriesJson);
    this.subqueries = new ArrayList<>(subqueries.size());
    for (int i = 0; i < subqueries.size(); i++) {
        JSONObject subquery = (JSONObject) subqueries.get(i);
        // let the constructor do the heavy lifting here
        this.subqueries.add(new SparqlSubquery(subquery));
    }

    this.subqueryType = subqueryType;
    this.isSubqueryOptional = isSubqueryOptional;
    this.columnsToFuseOn = new LinkedHashSet<>(Arrays.asList(columnsToFuseOn.split(",")));
    this.columnsToReturn = new LinkedHashSet<>(Arrays.asList(columnsToReturn.split(",")));

    if (this.subqueries.size() == 0) {
        // this was completely invalid a call as we have no subqueries to process
        throw new Exception("subqueries json does not contain any subqueries.");
    }
}