Example usage for org.json.simple JSONArray size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:net.phyloviz.nj.json.NJItemFactory.java

private Map<Integer, NJLeafNode> createLeafs(TypingData<? extends AbstractProfile> td, JSONArray leafsArr) {

    Map<Integer, NJLeafNode> leafs = new HashMap(leafsArr.size());
    Map<String, Profile> profiles = new HashMap(td.size());

    for (Iterator<? extends AbstractProfile> it = td.iterator(); it.hasNext();) {
        Profile p = it.next();//from   www  . jav  a 2s  .  c o m
        profiles.put(p.getID(), p);
    }
    for (Iterator<JSONObject> it = leafsArr.iterator(); it.hasNext();) {
        JSONObject l = it.next();
        String p = (String) l.get("profile");
        Integer uid = (int) (long) l.get("id");
        leafs.put(uid, new NJLeafNode(profiles.get(p), td.size(), uid, null));
    }
    return leafs;
}

From source file:com.github.lgi2p.obirs.utils.IndexerJSON.java

public void indexItem(String json) throws IOException, ParseException {

    JSONParser parser = new JSONParser();

    Object obj;//from   ww w  .  ja v a  2  s  . co  m
    obj = parser.parse(json);
    JSONObject jsonObject = (JSONObject) obj;
    String uri = (String) jsonObject.get("uri").toString();
    String label = (String) jsonObject.get("label");
    String href = (String) jsonObject.get("href");

    URI itemUri = URIFactoryMemory.getSingleton().getURI(uri);
    Set<URI> itemAnnotations = new HashSet();

    ItemMetadata meta = new ItemMetadata(uri, label, href);

    JSONArray conceptIds = (JSONArray) jsonObject.get("annots");

    for (int i = 0; i < conceptIds.size(); i++) {
        String conceptURI = (String) conceptIds.get(i);
        URI uriConcept = URIFactory.getURI(conceptURI);
        itemAnnotations.add(uriConcept);
    }

    items.add(new Item(itemUri, itemAnnotations));
    metadata.put(itemUri, meta);
}

From source file:Json.JsonCodes.java

public void jsonRead(String patchName) throws IOException, ParseException {
    JSONParser parser = new JSONParser();

    JSONObject object = (JSONObject) parser.parse(new FileReader(patchName));
    JSONArray arr = new JSONArray();
    this.patch = (String) object.get("patch");
    arr = (JSONArray) object.get("page");
    for (int i = 0; i < arr.size(); i++) {
        this.pageList.add((String) arr.get(i));
    }// w  w w  . jav  a 2 s .  com

    System.out.println("Json.JsonWrite.jsonRead()");

}

From source file:com.github.itoshige.testrail.store.SectionStore.java

private void copyJsonArrayToMap(JSONArray from, ConcurrentHashMap<SectionStoreKey, String> to, String projectId,
        String runId, String key2, String value) {
    for (int i = 0; i < from.size(); i++) {
        JSONObject obj = (JSONObject) from.get(i);
        Object k2 = obj.get(key2);
        Object v = obj.get(value);
        if (projectId != null && k2 != null && v != null) {
            to.putIfAbsent(new SectionStoreKey(projectId, runId, k2.toString().trim()), v.toString().trim());
        }//from www .j a  v  a 2 s .  c o  m
    }
}

From source file:fr.itldev.koya.webscript.content.ZipContent.java

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    Map<String, Object> jsonPostMap = KoyaWebscript.getJsonMap(req);

    ArrayList<String> nodeRefs = new ArrayList<>();
    JSONArray jsonArray = (JSONArray) jsonPostMap.get(ARG_NODEREFS);
    if (jsonArray != null) {
        int len = jsonArray.size();
        for (int i = 0; i < len; i++) {
            nodeRefs.add(jsonArray.get(i).toString());
        }//w  w  w  .  j  a v a2  s . co m
    }

    try {
        res.setContentType(MIMETYPE_ZIP);
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition", "attachment");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

        File tmpZipFile = koyaContentService.zip(nodeRefs);

        OutputStream outputStream = res.getOutputStream();
        if (nodeRefs.size() > 0) {
            InputStream in = new FileInputStream(tmpZipFile);
            try {
                byte[] buffer = new byte[8192];
                int len;

                while ((len = in.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (KoyaServiceException ex) {
        throw new WebScriptException("KoyaError : " + ex.getErrorCode().toString());
    } catch (RuntimeException e) {
        /**
         * TODO koya specific exception
         */
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                "Erreur lors de la gnration de l'archive.", e);
    }

}

From source file:com.mcapanel.utils.ErrorHandler.java

private ObfuscatedString v(Object rb) {
    JSONArray qg = (JSONArray) rb;

    long[] nc = new long[qg.size()];

    for (int i = 0; i < qg.size(); i++) {
        nc[i] = (Long) qg.get(i);
    }//from w w w  .j  ava2s . c o  m

    return new ObfuscatedString(nc);
}

From source file:HostController.java

@RequestMapping("/hosts")
public @ResponseBody Host host(
        @RequestParam(value = "authentication", required = false, defaultValue = "") String authentication)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);// w  ww.ja  v  a2s.  c  om

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    // content-type is controlled in api_jsonrpc.php, so set it like this
    putMethod.setRequestHeader("Content-Type", "application/json-rpc");
    // create json object for apiinfo.version 
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = new JSONObject();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "host.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response

        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            JSONObject objret = new JSONObject();

            objret.put("hostid", tobj.get("hostid"));
            objret.put("hostName", tobj.get("host"));

            list.add(objret);
        }
        return new Host(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Host(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:c3.ops.priam.backup.MetaData.java

public List<AbstractBackupPath> get(final AbstractBackupPath meta) {
    List<AbstractBackupPath> files = Lists.newArrayList();
    try {//from w  w w  .  j  a va  2 s  .com
        new RetryableCallable<Void>() {
            @Override
            public Void retriableCall() throws Exception {
                fs.download(meta, new FileOutputStream(meta.newRestoreFile()));
                return null;
            }
        }.call();

        File file = meta.newRestoreFile();
        JSONArray jsonObj = (JSONArray) new JSONParser().parse(new FileReader(file));
        for (int i = 0; i < jsonObj.size(); i++) {
            AbstractBackupPath p = pathFactory.get();
            p.parseRemote((String) jsonObj.get(i));
            files.add(p);
        }
    } catch (Exception ex) {
        logger.error("Error downloading the Meta data try with a diffrent date...", ex);
    }
    return files;
}

From source file:com.facebook.tsdb.tsdash.server.PlotEndpoint.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {//w w  w . j a va 2 s  .  c  o m
        // 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");
        long width = (Long) jsonParamsObj.get("width");
        long height = (Long) jsonParamsObj.get("height");
        boolean surface = (Boolean) jsonParamsObj.get("surface");
        boolean palette = false;
        if (jsonParams.contains("palette")) {
            palette = (Boolean) jsonParamsObj.get("palette");
        }
        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();
        long ts = System.currentTimeMillis();
        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;
        // check to see if we have data
        boolean hasData = false;
        for (Metric metric : metrics) {
            if (metric.hasData()) {
                hasData = true;
                break;
            }
        }
        if (!hasData) {
            throw new Exception("No data");
        }
        JSONObject responseObj = new JSONObject();
        JSONArray encodedMetrics = new JSONArray();
        for (Metric metric : metrics) {
            encodedMetrics.add(metric.toJSONObject());
        }
        // plot just the first metric for now
        GnuplotProcess gnuplot = GnuplotProcess.create(surface);
        GnuplotOptions options = new GnuplotOptions(surface);
        options.enablePalette(palette);
        options.setDimensions((int) width, (int) height).setTimeRange(tsFrom, tsTo);
        String plotFilename = gnuplot.plot(metrics, options);
        gnuplot.close();

        responseObj.put("metrics", encodedMetrics);
        responseObj.put("loadtime", loadTime);
        responseObj.put("ploturl", generatePlotURL(plotFilename));
        out.println(responseObj.toJSONString());
        long renderTime = System.currentTimeMillis() - ts - loadTime;
        logger.info("[Plot] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, "
                + "render time: " + renderTime + "ms");
    } catch (Throwable e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}

From source file:com.sourav.apps.PiMessageFetcher.java

@Override
public void run() {
    while (running) {
        try {/*from   www . ja va2s .com*/
            String rawJSON = client.get().getText();
            JSONArray messages = (JSONArray) JSONValue.parse(rawJSON);
            PiChatterWindow window = PiChatterWindow.getWindow();

            for (int i = 0; i < messages.size(); i++) {
                JSONObject message = (JSONObject) messages.get(i);
                String from = (String) message.get("from");
                String time = (String) message.get("time");
                String body = (String) message.get("data");
                body = PiCodec.decode(body);

                String str = String.format(" %s: %s\t (sent at: %s)", from, body, time);
                window.appendChat(str);
            }

            if (messages.size() > 0) {
                menuref.setNotification();
            }

        } catch (IOException iox) {
            iox.printStackTrace();
        }
        try {
            Thread.sleep(600);
        } catch (InterruptedException iox) {
            iox.printStackTrace();
        }
    }
}