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:gui.EventAllReader.java

@Override
public void run() {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    //HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet("https://api.guildwars2.com/v1/event_names.json?lang=" + this.language);

    HttpResponse response;/*from  w w w. j av  a  2 s. com*/

    String line = "";
    String out = "";

    while (!this.isInterrupted()) {

        try {

            response = client.execute(request);

            if (response.getStatusLine().toString().contains("200")) {

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));

                line = "";
                out = "";

                while ((line = rd.readLine()) != null) {

                    out = out + line;
                }

                JSONParser parser = new JSONParser();

                Object obj;

                this.result.clear();

                try {

                    obj = parser.parse(out);

                    JSONArray array = (JSONArray) obj;

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

                        JSONObject obj2 = (JSONObject) array.get(i);

                        if (obj2.get("name") != null) {

                            this.result.put(obj2.get("id"), obj2.get("name"));
                        }
                    }

                    this.apimanager.updateToolTips();

                    request.releaseConnection();
                    this.interrupt();
                } catch (ParseException ex) {
                    try {
                        Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex);

                        request.releaseConnection();
                        Thread.sleep(5000);
                    } catch (InterruptedException ex1) {
                        Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex1);
                    }
                }
            } else {
                try {
                    request.releaseConnection();
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (IOException | IllegalStateException ex) {
            try {
                Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);

                request.releaseConnection();
                Thread.sleep(5000);
            } catch (InterruptedException ex1) {
                Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex1);

                this.interrupt();
            }
        }
    }
}

From source file:me.timothy.ddd.entities.EntityManager.java

public void loadEntities(File file) throws IOException, ParseException {
    logger.printf(Level.INFO, "Loading entities from %s (exists: %b)", file.getCanonicalPath(), file.exists());
    JSONArray jsonArray;
    try (FileReader fr = new FileReader(file)) {
        JSONParser parser = new JSONParser();
        jsonArray = (JSONArray) parser.parse(fr);
    }/*from  ww  w.  j  a  v a2  s  .c om*/

    for (int i = 0; i < jsonArray.size(); i++) {
        EntityInfo ei = new EntityInfo();
        ei.loadFrom((JSONObject) jsonArray.get(i));
        logger.trace(ei.toString());
        entities.add(new Entity(ei));
    }
    logger.printf(Level.INFO, "Successfully loaded %d entities", entities.size());
}

From source file:com.opensoc.json.serialization.JSONKafkaSerializer.java

public void putArray(DataOutputStream data, JSONArray array) throws IOException {

    data.writeByte(JSONKafkaSerializer.JSONArrayID);

    data.writeInt(array.size());

    for (Object o : array)
        putObject(data, o);//from   w ww  .  j a  v  a2s  . com

}

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  a  2 s  .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:com.rackspacecloud.blueflood.outputs.serializers.JSONBasicRollupsOutputSerializer.java

@Override
public JSONObject transformRollupData(MetricData metricData, Set<MetricStat> filterStats)
        throws SerializationException {
    final JSONObject globalJSON = new JSONObject();
    final JSONObject metaObject = new JSONObject();
    filterStats = fixFilterStats(metricData, filterStats);

    final JSONArray valuesArray = transformDataToJSONArray(metricData, filterStats);

    metaObject.put("count", valuesArray.size());
    metaObject.put("limit", null);
    metaObject.put("marker", null);
    metaObject.put("next_href", null);
    globalJSON.put("values", valuesArray);
    globalJSON.put("metadata", metaObject);
    globalJSON.put("unit", metricData.getUnit() == null ? Util.UNKNOWN : metricData.getUnit());

    return globalJSON;
}

From source file:control.ParametrizacionServlets.InsertarLaboratorios.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w ww. j a  va2s  . 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 {
    JSONObject salida = new JSONObject();
    try {

        String nombre = request.getParameter("nombre");
        String direccion = request.getParameter("direccion");
        String telefono = request.getParameter("telefono1");
        String telefono2 = request.getParameter("telefono2");
        String correo = request.getParameter("correo");
        String resolucion = request.getParameter("resolucion");
        String vigencia = request.getParameter("vigencia");
        String contactos = request.getParameter("contactos");
        String paramAcreditados = request.getParameter("paramAcreditados");

        Laboratorios manager = new Laboratorios();
        manager.insertar(nombre, contactos, direccion, telefono, telefono2, correo, resolucion, vigencia);

        AcreditacionParametros managerAcreditacion = new AcreditacionParametros();

        int codigoLaboratorio = manager.getCodigoLaboratorio();
        // la informacion se converte en unJSONArray

        Object obj = JSONValue.parse(paramAcreditados);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

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

            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            int codParametro = Integer.parseInt((String) jsonObject.get("codigoParam"));

            managerAcreditacion.insertar(codParametro, codigoLaboratorio);

        }

    } catch (Exception e) {
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        salida.put("error", 0);
        response.getWriter().write(salida.toString());
    }

}

From source file:com.optimizely.ab.config.parser.JsonSimpleConfigParser.java

private List<Group> parseGroups(JSONArray groupJson) {
    List<Group> groups = new ArrayList<Group>(groupJson.size());

    for (Object obj : groupJson) {
        JSONObject groupObject = (JSONObject) obj;
        String id = (String) groupObject.get("id");
        String policy = (String) groupObject.get("policy");
        List<Experiment> experiments = parseExperiments((JSONArray) groupObject.get("experiments"), id);
        List<TrafficAllocation> trafficAllocations = parseTrafficAllocation(
                (JSONArray) groupObject.get("trafficAllocation"));

        groups.add(new Group(id, policy, experiments, trafficAllocations));
    }/*from  w ww  .  j a  va2 s  .co m*/

    return groups;
}

From source file:com.wasteofplastic.acidisland.Update.java

/**
 * Query the API to find the latest approved file's details.
 * /*ww w. j  a  va  2  s  . c  o  m*/
 * @return true if successful
 */
public boolean query() {
    URL url = null;

    try {
        // Create the URL to query using the project's ID
        url = new URL(API_HOST + API_QUERY + projectID);
    } catch (MalformedURLException e) {
        // There was an error creating the URL

        e.printStackTrace();
        return false;
    }

    try {
        // Open a connection and query the project
        URLConnection conn = url.openConnection();

        if (apiKey != null) {
            // Add the API key to the request if present
            conn.addRequestProperty("X-API-Key", apiKey);
        }

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ASkyBlockAcidIsland Update Checker");

        // Read the response of the query
        // The response will be in a JSON format, so only reading one line
        // is necessary.
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();

        // Parse the array of files from the query's response
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            // Get the version's title
            versionName = (String) latest.get(API_NAME_VALUE);

            // Get the version's link
            versionLink = (String) latest.get(API_LINK_VALUE);

            // Get the version's release type
            versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);

            // Get the version's file name
            versionFileName = (String) latest.get(API_FILE_NAME_VALUE);

            // Get the version's game version
            versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);

            return true;
        } else {
            System.out.println("There are no files for this project");
            return false;
        }
    } catch (IOException e) {
        // There was an error reading the query

        e.printStackTrace();
        return false;
    }
}

From source file:control.ProcesoVertimientosServlets.RegistrarSuperviciones.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  ww . j  av a  2s .c  om*/
 * @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 {

    JSONArray resp = new JSONArray();

    try {
        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String monitoreos = request.getParameter("monitoreos");
        int tecnico = Integer.parseInt(request.getParameter("tecnico"));
        int resul;
        int codProceso;
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        Object obj = JSONValue.parse(monitoreos);
        JSONArray monitoreosArray = new JSONArray();
        monitoreosArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < monitoreosArray.size(); i++) {
            codProceso = Integer.parseInt(monitoreosArray.get(i).toString());

            ProgramarMonitoreo manager = new ProgramarMonitoreo();
            resul = manager.registrarSupervision(codProceso, tecnico);

            jsonObject.put("monitoreo", codProceso);
            jsonObject.put("resultado", resul);

            jsonArray.add(jsonObject.clone());

        }
        resp.add(jsonArray);
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");

        for (Object jsonObjectResp : resp) {

            response.getWriter().write(jsonObjectResp.toString());

        }
    } catch (Exception ex) {

    }
}

From source file:com.piusvelte.hydra.HydraRequest.java

private String[] parseArray(JSONParser parser, String obj) {
    try {/*  w  ww .  j a  va  2  s  . c  o  m*/
        JSONArray jsonArr = (JSONArray) parser.parse(obj);
        int s = jsonArr.size();
        String[] arr = new String[s];
        for (int i = 0; i < s; i++)
            arr[s] = (String) jsonArr.get(s);
        return arr;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return new String[0];
}