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:com.opensoc.tagging.TelemetryTaggerBolt.java

@SuppressWarnings("unchecked")
public void execute(Tuple tuple) {

    LOG.trace("[OpenSOC] Starting to process message for alerts");
    JSONObject original_message = null;// w  w  w.ja v  a2 s .  c  om

    try {

        original_message = (JSONObject) tuple.getValue(0);

        if (original_message == null || original_message.isEmpty())
            throw new Exception("Could not parse message from byte stream");

        LOG.trace("[OpenSOC] Received tuple: " + original_message);

        JSONObject alerts_tag = new JSONObject();
        JSONArray alerts_list = _adapter.tag(original_message);

        LOG.trace("[OpenSOC] Tagged message: " + alerts_list);

        if (alerts_list.size() != 0) {
            if (original_message.containsKey("alerts")) {
                JSONObject tag = (JSONObject) original_message.get("alerts");
                JSONArray already_triggered = (JSONArray) tag.get("triggered");
                alerts_list.addAll(already_triggered);
                LOG.trace("[OpenSOC] Created a new string of alerts");
            }

            alerts_tag.put("identifier", _identifier);
            alerts_tag.put("triggered", alerts_list);
            original_message.put("alerts", alerts_tag);

            LOG.debug("[OpenSOC] Detected alerts: " + alerts_tag);
        } else {
            LOG.debug("[OpenSOC] The following messages did not contain alerts: " + original_message);
        }

        _collector.ack(tuple);
        _collector.emit(new Values(original_message));

        /*if (metricConfiguration != null) {
           emitCounter.inc();
           ackCounter.inc();
        }*/

    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Failed to tag message :" + original_message);
        e.printStackTrace();
        _collector.fail(tuple);

        /*
        if (metricConfiguration != null) {
           failCounter.inc();
        }*/
    }
}

From source file:librarysystem.JSONHandlerElsiever.java

public List<Journal> parseJson() {
    //  String elsevier = "http://api.elsevier.com/content/search/scidir?apiKey=" + KEY + "&query=ttl(neural)";
    try {//from  ww  w. j  a  va 2s .  co  m
        //URL uri = new URL(elsevier);

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(readUrl(url));
        JSONObject jsonObject = (JSONObject) obj;
        JSONObject searchObj = (JSONObject) jsonObject.get("search-results");

        if (searchObj.containsKey("entry")) {
            JSONArray entryarray = (JSONArray) searchObj.get("entry");
            Journal j = null;// new Journal();
            blist = new ArrayList<Journal>();
            //JSONArray autharray = null;

            for (int i = 0; i < entryarray.size(); i++) {
                j = new Journal();
                JSONObject jnext = (JSONObject) entryarray.get(i);

                j.setID(0);
                j.setAbstract(jnext.get("prism:teaser").toString());
                j.setPublication(jnext.get("prism:publicationName").toString());
                j.settitle(jnext.get("dc:title").toString());
                j.setisbn(jnext.get("prism:issn").toString());
                j.setYear(jnext.get("prism:coverDisplayDate").toString());
                String auths = "";

                if (jnext.containsKey("authors")) {
                    JSONObject jauthors = (JSONObject) jnext.get("authors");
                    JSONArray autharray = (JSONArray) jauthors.get("author");

                    for (int x = 0; x < autharray.size(); x++) {
                        JSONObject anext = (JSONObject) autharray.get(x);
                        auths = auths + " " + anext.get("given-name") + " " + anext.get("surname");
                    }
                    j.setauthors(auths);
                } else
                    j.setauthors("");

                blist.add(j);
            }
        }

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

    return blist;
}

From source file:control.ParametrizacionServlets.InsertarAsociacionContratos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w w w.java2 s  . c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        objectErrores = new JSONObject();
        arrayErrores = new JSONArray();

        //Obtenemos el numero de contrato
        Double contratoPadre = Double.parseDouble(request.getParameter("contrato"));

        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String puntos = request.getParameter("contratosAsignados");
        Object obj = JSONValue.parse(puntos);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < jsonArray.size(); i++) {

            //Obtenemos el contrato hijo
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            Double contratoHijo = Double.parseDouble((String) jsonObject.get("contratoAsignado"));

            //Creamos el manager y guardamos la informacion.
            AsociacionContratos manager = new AsociacionContratos();
            int error = manager.insertar(contratoPadre, contratoHijo);

            /*
            Obtenemos la respuesta del procedimiento y Validamos si el contrato padre 
            es valido, si no lo es no registramos nada y enviamos el error.
            */
            if (error == 2) {

                guardarErrores(error, contratoPadre);
                escribirJSON(response);

                break;

            } else if (error == 4) { //Si el hijo no es valido, registramos el error y 
                                     //enviamos el listado a la vista al finalizar el for.

                guardarErrores(error, contratoHijo);

            }

        }

        escribirJSON(response);

    } catch (Exception ex) {
        JSONObject respError = new JSONObject();
        respError.put("error", 0);
        arrayErrores.add(respError);
        escribirJSON(response);
    }

}

From source file:de.instantouch.model.io.SnakeJSONReader.java

public void readList(SnakeList<SnakeType> myList, Object value) throws SnakeModelException, IOException,
        ClassNotFoundException, InstantiationException, IllegalAccessException {

    if (!(value instanceof JSONArray)) {
        throw new SnakeWrongTypeException(
                "couldn't extract list: " + myList.getName() + " from json object:" + value);
    }//from   ww w  .j  ava2 s .  c o m

    JSONArray jsonArray = (JSONArray) value;

    myList.clear();
    for (int i = 0; i < jsonArray.size(); i++) {
        Object object = jsonArray.get(i);

        SnakeType child = myList.newElement();
        if (child == null) {
            SnakeLog.error(
                    "couldn't read list data: " + object + "for: " + myList.getClass().getCanonicalName());
            break;
        }

        child.setParent(myList);
        read(child, object);

        myList.add(child);
    }

}

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;//from  w ww .  java  2 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:control.ParametrizacionServlets.ActualizarAsociacionContratos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w w. j a va  2  s . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        //Obtenemos el numero de contrato
        Double contratoPadre = Double.parseDouble(request.getParameter("contrato"));

        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String puntos = request.getParameter("contratosAsignados");
        Object obj = JSONValue.parse(puntos);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < jsonArray.size(); i++) {

            //Obtenemos el contrato hijo
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            Double contratoHijo = Double.parseDouble((String) jsonObject.get("contratoAsignado"));
            String codigo = (String) jsonObject.get("codigo");

            //Creamos el manager y guardamos la informacion.
            AsociacionContratos manager = new AsociacionContratos();
            int error = manager.actualizar(contratoPadre, contratoHijo, codigo);

            /*
            Obtenemos la respuesta del procedimiento y Validamos si el contrato padre 
            es valido, si no lo es no registramos nada y enviamos el error.
            */
            if (error == 2) {

                guardarErrores(error, contratoPadre);
                escribirJSON(response);

                break;

            } else if (error == 4) { //Si el hijo no es valido, registramos el error y 
                                     //enviamos el listado a la vista al finalizar el for.

                guardarErrores(error, contratoHijo);

            }

        }

        escribirJSON(response);

    } catch (Exception ex) {

        JSONObject respError = new JSONObject();
        respError.put("error", 0);
        arrayErrores.add(respError);
        escribirJSON(response);

    }

}

From source file:matrix.CreateUrlMatrix.java

public void urlMatrix()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException {

    CosSim cossim = new CosSim();
    JSONParser jParser = new JSONParser();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweetsUrls.json"), "ISO-8859-9"));
    JSONArray a = (JSONArray) jParser.parse(in);
    File fout = new File("/Users/nSabri/Desktop/urlMatris.csv");
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

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

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

            JSONObject tweet1 = (JSONObject) a.get(i);
            JSONObject tweet2 = (JSONObject) a.get(j);
            String tweetUrl1 = tweet1.get("title").toString() + tweet1.get("meta").toString();
            System.out.println(tweetUrl1);
            String tweetUrl2 = tweet2.get("title").toString() + tweet1.get("meta").toString();
            System.out.println(tweetUrl2);

            double CosSimValue = cossim.Cosine_Similarity_Score(tweetUrl1, tweetUrl2);
            CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue));
            bw.write(Double.toString(CosSimValue) + ", ");

        }//  w  ww  .  ja  va  2 s.  co  m
        bw.newLine();
    }
    bw.close();

}

From source file:ch.zhaw.icclab.tnova.expressionsolver.OTFlyEval.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*w w  w. j  a v a  2s .c om*/
@Produces(MediaType.APPLICATION_JSON)
public Response evalOnTheFly(String incomingMsg) {
    JSONObject incoming = (JSONObject) JSONValue.parse(incomingMsg);
    JSONObject outgoing = new JSONObject();
    String result = "";
    try {
        String expression = (String) incoming.get("exp");
        JSONArray vals = (JSONArray) incoming.get("values");
        Stack<Double> param = new Stack<Double>();
        for (int i = 0; i < vals.size(); i++) {
            Double val = new Double((String) vals.get(i));
            param.push(val);
        }
        double threshold = Double.parseDouble((String) incoming.get("threshold"));
        result = evaluateExpression(expression, param, threshold);
    } catch (Exception ex) {
        if (App.showExceptions)
            ex.printStackTrace();
    }
    logger.info("received expression: " + incoming.get("exp"));
    logger.info("expression evaluation result: " + result);
    //construct proper JSON response.
    outgoing.put("info", "t-nova expression evaluation service");
    if (result != null && result.length() != 0) {
        outgoing.put("result", result);
        outgoing.put("status", "ok");
        KPI.expressions_evaluated += 1;
        KPI.api_calls_success += 1;
        return Response.ok(outgoing.toJSONString(), MediaType.APPLICATION_JSON_TYPE).build();
    } else {
        outgoing.put("status", "execution failed");
        outgoing.put("msg",
                "malformed request parameters, check your expression or parameter list for correctness.");
        KPI.expressions_evaluated += 1;
        KPI.api_calls_failed += 1;
        return Response.status(Response.Status.BAD_REQUEST).entity(outgoing.toJSONString())
                .encoding(MediaType.APPLICATION_JSON).build();
    }
}

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

private void outputText() {
    JSONParser parser = new JSONParser();
    textArea.setEditable(false);/* w  ww  .  ja v a2 s. com*/
    String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output";
    try {
        Object obj = parser.parse(new FileReader(path + File.separator + "MovieInfo.json"));
        JSONArray parsedArr = (JSONArray) obj;

        if (parsedArr.size() == 0) {
            textArea.setEditable(false);
            textArea.clear();
            textArea.appendText("No Movies found from the provided Directory !!!");
        } else {
            textArea.clear();
            // Loop JSON Array

            for (int i = 0; i < parsedArr.size(); i++) {
                JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                textArea.setWrapText(true);
                textArea.appendText("Title: " + (String) parsedObj.get("Title") + "\n");
                textArea.appendText("Release Date: " + (String) parsedObj.get("Released") + "\n");
                textArea.appendText("Genre: " + (String) parsedObj.get("Genre") + "\n");

                textArea.appendText(
                        "IMDB Link: " + "http://www.imdb.com/title/" + (String) parsedObj.get("imdbID") + "\n");
                textArea.appendText("IMDB Rating: " + (String) parsedObj.get("imdbRating") + "\n");
                textArea.appendText("Actors: " + (String) parsedObj.get("Actors") + "\n");
                textArea.appendText("Plot: " + (String) parsedObj.get("Plot") + "\n");

                textArea.appendText("\n\n");
            }
            textArea.positionCaret(0);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:me.realized.tm.utilities.profile.UUIDFetcher.java

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 *
 * @param output   Whether or not to print output
 * @param log      The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of player names to their {@link UUID}s
 * @throws IOException          If there's a problem sending or receiving the request
 * @throws ParseException       If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 * @version 0.1.0// ww  w  .j  av  a  2  s.com
 * @since 0.0.1
 */
public Map<String, UUID> callWithProgressOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            String out = "[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...";
            if (log != null) {
                log.warning(out);
            } else {
                Bukkit.getLogger().warning(out);
            }
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }

        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();

        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }

        if (output) {
            int processed = completed + failed;
            if (doOutput.apply(processed) || processed == totalNames) {
                if (log != null) {
                    log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                            totalNames, ((double) processed / totalNames) * 100D, failed));
                }
            }
        }
    }
    return uuidMap;
}