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:control.ParametrizacionServlets.ActualizarPuntoVertimiento.java

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

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

        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String puntos = request.getParameter("puntos");
        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++) {

            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            String ubicacion = (String) jsonObject.get("ubicacion");
            String latitud = (String) jsonObject.get("latitud");
            String longitud = (String) jsonObject.get("longitud");
            String observacion = (String) jsonObject.get("observacion");
            int estado = Integer.parseInt((String) jsonObject.get("estado"));
            String codigo = (String) jsonObject.get("codigo");
            String tipoEstructura = (String) jsonObject.get("tipoEstructura");

            //Creamos el manager y guardamos la informacion.
            PuntosVertimiento manager = new PuntosVertimiento();
            manager.actualizar(codigo, ubicacion, latitud, longitud, observacion, estado, contrato,
                    tipoEstructura);

        }

        resError.put("error", 1);
    } catch (Exception ex) {
        resError.put("error", 0);

    }

}

From source file:logistify.core.ModuloGoogleApiMatrix.java

public Object[] getDistanciaTiempo(Punto origen, Punto destino) {

    Object enCache[] = this.buscarEnCache(origen, destino);
    if (enCache != null)
        return enCache;
    if (origen.equals(destino)) {
        Object result[] = { origen, destino, 0, 0 };
        cache.add(result);/*from w w  w  . j av  a 2  s . c  o m*/
        return result;
    }

    //ARMA URL EN FORMATO VALIDO
    String url = this.armarURL(origen.getDireccion(), destino.getDireccion());

    //OBTIENE EL JSON EN TEXTO PLANO
    String jsonPlano = this.readUrl(url);
    this.contador++;
    //System.out.println("CANT CONSULTAS: "+contador);
    //SE CREA EL PARSER DE JSON Y EMPIEZA A OBTENER DATOS
    JSONParser parser = new JSONParser();

    try {
        //PARSEA EL CODIGO PLANO
        Object obj = parser.parse(jsonPlano);

        //OBTIENE UN OBJETO JSON 
        JSONObject jsonObject = (JSONObject) obj;

        //OBTIENE EL ARRAY DENTRO DEL OBJETO jsonObject, CONTENIDO EN LA VAR DE NOMBRE ROWS DEL JSON jsonObject
        JSONArray rows = (JSONArray) jsonObject.get("rows");

        //OBTIENE EL 1ER ELEMENTO DEL ARRAY rows, UN OBJETO JSON
        JSONObject jsonElemObj = (JSONObject) rows.get(0);

        //OBTIENE EL ARRAY DENTRO DEL OBJETO jsonElemObj, CONTENIDO EN LA VAR DE NOMBRE ELEMENTS DEL JSON
        JSONArray elements = (JSONArray) jsonElemObj.get("elements");

        //OBTIENE EL 1ER ELEMENTO DEL ARRAY elements, UN OBJETO JSON
        JSONObject dataJson = (JSONObject) elements.get(0);

        //OBTIENE EL OBJETO DENTRO DEL OBJETO dataJson, CONTENIDO EN LA VAR DE NOMBRE DISTANCE DEL JSON
        JSONObject distanceObj = (JSONObject) dataJson.get("distance");

        //OBTIENE EL VALOR DENTRO DEL OBJETO distanceObj, CONTENIDO EN LA VAR DE VALUE DEL JSON
        long valueDI = (long) distanceObj.get("value");

        //OBTIENE EL OBJETO DENTRO DEL OBJETO dataJson, CONTENIDO EN LA VAR DE NOMBRE DURATION DEL JSON
        JSONObject durationObj = (JSONObject) dataJson.get("duration");

        //OBTIENE EL VALOR DENTRO DEL OBJETO durationObj, CONTENIDO EN LA VAR DE VALUE DEL JSON
        long valueDU = (long) durationObj.get("value");

        //ASIGNACION DE VALORES OBTENIDOS A VARIABLES
        int distance = (int) valueDI;
        int duration = (int) valueDU;

        //ARMA SEGMENTO CON LOS DATOS OBTENIDOS Y LO DEVUELVE
        Object result[] = { origen, destino, distance, duration };
        cache.add(result);
        return result;

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

    //return new Segmento(origen, destino, 15000, 1520);
}

From source file:NetworkController.java

public Network networkResponse(String hostid, PutMethod putMethod, String name) {
    JSONParser parser = new JSONParser();

    String loginResponse = "";
    HttpClient client = new HttpClient();

    try {/*  w  ww  . ja  v  a2 s.co m*/
        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);
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (comparision(name, "loOut", tobj, LOOUT))
                return getNetwork(tobj, hostid, LOOUT);
            else if (comparision(name, "loIn", tobj, LOIN))
                return getNetwork(tobj, hostid, LOIN);
            else if (comparision(name, "eth1Out", tobj, ETH1OUT))
                return getNetwork(tobj, hostid, ETH1OUT);
            else if (comparision(name, "eth0Out", tobj, ETH0OUT))
                return getNetwork(tobj, hostid, ETH0OUT);
            else if (comparision(name, "eth0In", tobj, ETH0IN))
                return getNetwork(tobj, hostid, ETH0IN);
            else if (comparision(name, "eth1In", tobj, ETH1IN))
                return getNetwork(tobj, hostid, ETH1IN);
            else if (comparision(name, "latency", tobj, LATENCY))
                return getNetwork(tobj, hostid, LATENCY);
            else if (comparision(name, "packetloss", tobj, PACKETLOSS))
                return getNetwork(tobj, hostid, PACKETLOSS);
            else
                continue;
        }
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    return new Network(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:com.blogspot.jadecalyx.webtools.jcPageObjectHelper.java

private void loadIndexFromJson(String site, String pageHandle) throws Exception {

    String s = System.getProperty("file.separator");
    String runPath = System.getProperty("user.dir");
    String fileToRead = pageHandle + ".json";
    String fullPath = String.join(s, runPath, "SiteInfo", site, "PageInfo", fileToRead);
    File f = new File(fullPath);
    if (!f.isFile()) {
        throw new Exception(
                String.format("loadIndex unable to find file for site: %s and file %s", site, fullPath));
    }//from   ww w .  ja  va2  s.  c o  m

    //load json file
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(fullPath));
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray objectList = (JSONArray) jsonObject.get("object-list");

    try {
        if (objectList.size() > 0) {
            for (int i = 0; i < objectList.size(); i++) {
                JSONObject theObject = (JSONObject) objectList.get(i);
                JSONArray lookups = (JSONArray) theObject.get("lookup");
                List<jcPageObjectSet> currList = new ArrayList<jcPageObjectSet>();
                for (int j = (lookups.size() - 1); j > -1; j--) {
                    JSONObject currLookup = (JSONObject) lookups.get(j);
                    currList.add(new jcPageObjectSet(currLookup.get("type").toString(),
                            currLookup.get("detail").toString()));
                }
                _objectIndex.put(theObject.get("handle").toString(), currList);
            }
        }
    } catch (Exception e) {
        int x = 1;
    }

    //load include list
    JSONArray includeList = (JSONArray) jsonObject.get("include-list");
    if (includeList.size() > 0) {
        for (int i = 0; i < includeList.size(); i++) {
            loadIndexFromJson(site, includeList.get(i).toString());
        }
    }

}

From source file:com.p000ison.dev.simpleclans2.updater.jenkins.JenkinsBuild.java

@Override
public void fetchInformation() throws IOException {
    URL buildAPIURL = new URL("http", JENKINS_HOST, 80, "/job/" + job + "/" + updateType + "/" + API_FILE);

    URLConnection connection = buildAPIURL.openConnection();
    Reader reader = new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8"));

    JSONObject content = parseJSON(reader);

    this.buildNumber = content.get("number").hashCode();
    this.started = (Long) content.get("timestamp");
    this.duration = (Long) content.get("duration");

    try {//from  ww  w . j av a2 s . c o m
        JSONArray artifactsInfo = (JSONArray) content.get("artifacts");
        if (artifactsInfo == null || artifactsInfo.isEmpty()) {
            return;
        }

        final String artifactURL = content.get("url").toString().substring(httpLength + JENKINS_HOST.length())
                + "artifact/";

        for (Object rawArtifact : artifactsInfo) {
            JSONObject artifactInfo = (JSONObject) rawArtifact;
            String path = (String) artifactInfo.get("relativePath");

            for (JenkinsArtifact artifact : artifacts) {
                if (path.contains(artifact.getName())) {
                    artifact.setURL(new URL("http", JENKINS_HOST, 80, artifactURL + path));
                }
            }
        }

        JSONObject changes = (JSONObject) content.get("changeSet");
        JSONArray items = (JSONArray) changes.get("items");
        if (!items.isEmpty()) {
            JSONObject buildInfo = (JSONObject) items.get(0);

            this.commitId = buildInfo.get("commitId").toString();
            this.pusher = ((JSONObject) buildInfo.get("author")).get("fullName").toString();
            this.comment = buildInfo.get("msg").toString();

            for (Object element : (JSONArray) buildInfo.get("paths")) {
                JSONObject entry = (JSONObject) element;

                if (entry.get("editType").equals("edit")) {
                    modifiedFiles.add(entry.get("file").toString());
                } else if (entry.get("editType").equals("delete")) {
                    deletedFiles.add(entry.get("file").toString());
                } else if (entry.get("editType").equals("add")) {
                    createdFiles.add(entry.get("file").toString());
                }
            }
        }
    } catch (ClassCastException e) {
        Logging.debug(e, true, "The format of the api changed! Could not fetch the cause!");
    }
}

From source file:interfaceTisseoWS.ST4.java

public final void init() throws ParseException, IOException, URISyntaxException {
    RequestJCDecaux r = new RequestJCDecaux();
    JSONParser parser = new JSONParser();

    r.setPathURIB("/vls/v1/stations");

    Object obj = parser.parse(r.request());
    JSONArray array = (JSONArray) obj;

    int nbStations = array.size();
    DefaultListModel lm = new DefaultListModel();
    for (int i = 0; i < nbStations; i++) {
        stations.add(new Station((JSONObject) array.get(i)));
        lm.addElement(stations.get(i).getName());
    }/*w ww  .ja v  a 2s  .  c o m*/
    listeStations.setModel(lm);
}

From source file:JavaCloud.Api.java

public ArrayList<Image> imageList(String type, String access, String[] prohibited_states) throws CoreException {
    JSONObject object = new JSONObject();
    object.put("token", token);
    if (type != null)
        object.put("type", type);
    if (access != null)
        object.put("access", access);
    if (prohibited_states.length > 0)
        object.put("prohibited_states", prohibited_states);

    JSONArray jsonimages = (JSONArray) Utils.request(address, "/api/image/get_list/", object);
    ArrayList<Image> images = new ArrayList<Image>();
    for (int i = 0; i < jsonimages.size(); i++) {
        images.add(new Image(address, token, (JSONObject) jsonimages.get(i)));
    }//from  ww w . j  a v a 2  s .  c o m

    return images;
}

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

public List<AbstractBackupPath> get(final AbstractBackupPath meta) {
    List<AbstractBackupPath> files = Lists.newArrayList();
    try {//  w  w w .  ja  va2s .c  om
        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.optimizely.ab.config.parser.JsonSimpleConfigParser.java

private Condition parseConditions(JSONArray conditionJson) {
    List<Condition> conditions = new ArrayList<Condition>();
    String operand = (String) conditionJson.get(0);

    for (int i = 1; i < conditionJson.size(); i++) {
        Object obj = conditionJson.get(i);
        if (obj instanceof JSONArray) {
            conditions.add(parseConditions((JSONArray) conditionJson.get(i)));
        } else {//from w w w.  ja  va 2s  .  c  o  m
            JSONObject conditionMap = (JSONObject) obj;
            conditions.add(new UserAttribute((String) conditionMap.get("name"),
                    (String) conditionMap.get("type"), (String) conditionMap.get("value")));
        }
    }

    Condition condition;
    if (operand.equals("and")) {
        condition = new AndCondition(conditions);
    } else if (operand.equals("or")) {
        condition = new OrCondition(conditions);
    } else {
        condition = new NotCondition(conditions.get(0));
    }

    return condition;
}

From source file:graphvk.Search.java

public ArrayList<String> zaprosSearch() throws IOException {
    String strUrl = "";
    String resultSeachJson;//  ww w .  ja  v  a  2 s  .c o  m
    strUrl = urlApi + methodUusersSearch + paramsSearch + "&count=1000" + "&access_token=" + accessToken;
    File file = new File(pathOne);
    //?    ??.
    if (!file.exists()) {
        // .
        file.createNewFile();
    }
    URL url = new URL(strUrl); // ?  API VK UserSearch
    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
    resultSeachJson = reader.readLine();
    reader.close();
    JSONParser parser = new JSONParser(); // ?  Json 
    try {
        Object objS = parser.parse(resultSeachJson);
        JSONObject jsonSObject = (JSONObject) objS;
        JSONArray listResult = (JSONArray) jsonSObject.get("response");
        JSONObject jsonSObj;
        for (int i = 1; i < listResult.size() - 1; i++) {
            jsonSObj = (JSONObject) listResult.get(i);
            userListSearch1.add("" + jsonSObj.get("uid"));
        }
    } catch (Exception e) {
        System.out.println(" Search ");
    }
    return userListSearch1;
}