Search in sources :

Example 66 with JSONArray

use of org.json.simple.JSONArray in project Essentials by drtshock.

the class Metrics method submitData.

/**
     * Collects the data and sends it afterwards.
     */
private void submitData() {
    if (!enabled)
        return;
    final JSONObject data = getServerData();
    JSONArray pluginData = new JSONArray();
    // Search for all other bStats Metrics classes to get their plugin data
    for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
        try {
            // Our identifier :)
            service.getField("B_STATS_VERSION");
        } catch (NoSuchFieldException ignored) {
            // Continue "searching"
            continue;
        }
        // Found one!
        try {
            pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service)));
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
        }
    }
    data.put("plugins", pluginData);
    // Create a new thread for the connection to the bStats server
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                // Send the data
                sendData(data);
            } catch (Exception e) {
                // Something went wrong! :(
                if (logFailedRequests) {
                    plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
                }
            }
        }
    }).start();
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 67 with JSONArray

use of org.json.simple.JSONArray in project ddf by codice.

the class RrdMetricsRetrieverTest method testMetricsJsonDataWithCounter.

@Test
public void testMetricsJsonDataWithCounter() throws Exception {
    String rrdFilename = TEST_DIR + "queryCount_Counter" + RRD_FILE_EXTENSION;
    long endTime = new RrdFileBuilder().rrdFileName(rrdFilename).build();
    MetricsRetriever metricsRetriever = new RrdMetricsRetriever();
    String json = metricsRetriever.createJsonData("queryCount", rrdFilename, START_TIME, endTime);
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(json);
    // Verify the title, totalCount, and data (i.e., samples) are present
    assertThat(jsonObj.size(), equalTo(3));
    assertThat(jsonObj.get("title"), not(nullValue()));
    assertThat(jsonObj.get("totalCount"), not(nullValue()));
    // Verify 2 samples were retrieved from the RRD file and put in the JSON fetch results
    JSONArray samples = (JSONArray) jsonObj.get("data");
    // 6 because that's the max num rows configured for
    assertThat(samples.size(), equalTo(6));
    // Verify each retrieved sample has a timestamp and value
    for (int i = 0; i < samples.size(); i++) {
        JSONObject sample = (JSONObject) samples.get(i);
        LOGGER.debug("timestamp = {},   value= {}", (String) sample.get("timestamp"), sample.get("value"));
        assertThat(sample.get("timestamp"), not(nullValue()));
        assertThat(sample.get("value"), not(nullValue()));
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) MetricsRetriever(ddf.metrics.reporting.internal.MetricsRetriever) JSONParser(org.json.simple.parser.JSONParser) Test(org.junit.Test)

Example 68 with JSONArray

use of org.json.simple.JSONArray in project ddf by codice.

the class RrdMetricsRetriever method createJsonData.

@Override
public String createJsonData(String metricName, String rrdFilename, long startTime, long endTime) throws IOException, MetricsGraphException {
    LOGGER.trace("ENTERING: createJsonData");
    JSONObject obj = new JSONObject();
    String displayableMetricName = convertCamelCase(metricName);
    MetricData metricData = getMetricData(rrdFilename, startTime, endTime);
    String title = displayableMetricName + " for " + getCalendarTime(startTime) + " to " + getCalendarTime(endTime);
    obj.put("title", title);
    List<Long> timestamps = metricData.getTimestamps();
    List<Double> values = metricData.getValues();
    JSONArray samples = new JSONArray();
    for (int i = 0; i < timestamps.size(); i++) {
        String timestamp = getCalendarTime(timestamps.get(i));
        JSONObject sample = new JSONObject();
        sample.put("timestamp", timestamp);
        sample.put("value", new Double(values.get(i)));
        samples.add(sample);
    }
    obj.put("data", samples);
    if (metricData.hasTotalCount()) {
        obj.put("totalCount", metricData.getTotalCount());
    }
    JsonWriter writer = new JsonWriter();
    obj.writeJSONString(writer);
    String jsonText = writer.toString();
    LOGGER.trace("jsonText = {}", jsonText);
    LOGGER.trace("EXITING: createJsonData");
    return jsonText;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray)

Example 69 with JSONArray

use of org.json.simple.JSONArray in project processdash by dtuma.

the class SelectLabelFilter method getDefinedLabelsArray.

private JSONArray getDefinedLabelsArray(String projectRoot) {
    String dataName = DataRepository.createDataName(projectRoot, LABELS_DATA_NAME);
    SimpleData labelsValue = getDataRepository().getSimpleValue(dataName);
    ListData list = ListData.asListData(labelsValue);
    JSONArray result = new JSONArray();
    try {
        result.addAll(Globsearch.getTags(list));
        Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
    } catch (Throwable t) {
    // the Globsearch.getTags() method was added in PD 1.14.5.  In
    // earlier versions, this will throw an exception.  Gracefully
    // degrade and diable autocompletion support.
    }
    return result;
}
Also used : JSONArray(org.json.simple.JSONArray) SimpleData(net.sourceforge.processdash.data.SimpleData) ListData(net.sourceforge.processdash.data.ListData)

Example 70 with JSONArray

use of org.json.simple.JSONArray in project tika by apache.

the class GrobidNERecogniser method recognise.

/**
     * recognises names of entities in the text
     * @param text text which possibly contains names
     * @return map of entity type -> set of names
     */
public Map<String, Set<String>> recognise(String text) {
    Map<String, Set<String>> entities = new HashMap<String, Set<String>>();
    Set<String> measurementNumberSet = new HashSet<String>();
    Set<String> unitSet = new HashSet<String>();
    Set<String> measurementSet = new HashSet<String>();
    Set<String> normalizedMeasurementSet = new HashSet<String>();
    Set<String> measurementTypeSet = new HashSet<String>();
    try {
        String url = restHostUrlStr + readRestEndpoint();
        Response response = WebClient.create(url).accept(MediaType.APPLICATION_JSON).post("text=" + text);
        int responseCode = response.getStatus();
        if (responseCode == 200) {
            String result = response.readEntity(String.class);
            JSONObject jsonObject = convertToJSONObject(result);
            JSONArray measurements = convertToJSONArray(jsonObject, "measurements");
            for (int i = 0; i < measurements.size(); i++) {
                StringBuffer measurementString = new StringBuffer();
                StringBuffer normalizedMeasurementString = new StringBuffer();
                JSONObject quantity = (JSONObject) convertToJSONObject(measurements.get(i).toString()).get("quantity");
                if (quantity != null) {
                    if (quantity.containsKey("rawValue")) {
                        String measurementNumber = (String) convertToJSONObject(quantity.toString()).get("rawValue");
                        measurementString.append(measurementNumber);
                        measurementString.append(" ");
                        measurementNumberSet.add(measurementNumber);
                    }
                    if (quantity.containsKey("normalizedQuantity")) {
                        String normalizedMeasurementNumber = convertToJSONObject(quantity.toString()).get("normalizedQuantity").toString();
                        normalizedMeasurementString.append(normalizedMeasurementNumber);
                        normalizedMeasurementString.append(" ");
                    }
                    if (quantity.containsKey("type")) {
                        String measurementType = (String) convertToJSONObject(quantity.toString()).get("type");
                        measurementTypeSet.add(measurementType);
                    }
                    JSONObject jsonObj = (JSONObject) convertToJSONObject(quantity.toString());
                    if (jsonObj.containsKey("rawUnit")) {
                        JSONObject rawUnit = (JSONObject) jsonObj.get("rawUnit");
                        String unitName = (String) convertToJSONObject(rawUnit.toString()).get("name");
                        unitSet.add(unitName);
                        measurementString.append(unitName);
                    }
                    if (jsonObj.containsKey("normalizedUnit")) {
                        JSONObject normalizedUnit = (JSONObject) jsonObj.get("normalizedUnit");
                        String normalizedUnitName = (String) convertToJSONObject(normalizedUnit.toString()).get("name");
                        normalizedMeasurementString.append(normalizedUnitName);
                    }
                    if (!measurementString.toString().equals("")) {
                        measurementSet.add(measurementString.toString());
                    }
                    if (!normalizedMeasurementString.toString().equals("")) {
                        normalizedMeasurementSet.add(normalizedMeasurementString.toString());
                    }
                }
            }
            entities.put("MEASUREMENT_NUMBERS", measurementNumberSet);
            entities.put("MEASUREMENT_UNITS", unitSet);
            entities.put("MEASUREMENTS", measurementSet);
            entities.put("NORMALIZED_MEASUREMENTS", normalizedMeasurementSet);
            entities.put("MEASUREMENT_TYPES", measurementTypeSet);
        }
    } catch (Exception e) {
        LOG.info(e.getMessage(), e);
    }
    ENTITY_TYPES.clear();
    ENTITY_TYPES.addAll(entities.keySet());
    return entities;
}
Also used : Response(javax.ws.rs.core.Response) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) IOException(java.io.IOException)

Aggregations

JSONArray (org.json.simple.JSONArray)267 JSONObject (org.json.simple.JSONObject)238 JSONParser (org.json.simple.parser.JSONParser)73 Test (org.junit.Test)40 ParseException (org.json.simple.parser.ParseException)23 ArrayList (java.util.ArrayList)21 HttpClient (org.apache.commons.httpclient.HttpClient)21 IOException (java.io.IOException)17 HashMap (java.util.HashMap)17 GetMethod (org.apache.commons.httpclient.methods.GetMethod)17 Transaction (org.xel.Transaction)12 File (java.io.File)11 List (java.util.List)10 HttpResponse (org.apache.http.HttpResponse)10 BlockchainTest (org.xel.BlockchainTest)10 APICall (org.xel.http.APICall)10 Block (org.xel.Block)9 MapLayer (au.org.emii.portal.menu.MapLayer)8 Map (java.util.Map)8 FileReader (java.io.FileReader)6