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:formatter.handler.post.FormatterPostHandler.java

/**
 * Process a field we recognise/* ww  w  .j a va2  s . c o  m*/
 * @param fieldName the field's name
 * @param contents its contents
 */
void processField(String fieldName, String contents) {
    //System.out.println("Received field "+fieldName);
    if (fieldName.equals(Params.DOCID))
        docid = contents;
    if (fieldName.equals(Params.VERSION1))
        version1 = contents;
    else if (fieldName.equals(Params.USERDATA)) {
        String key = "I tell a settlers tale of the old times";
        int klen = key.length();
        char[] data = Base64.decode(contents);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i++)
            sb.append((char) (data[i] ^ key.charAt(i % klen)));
        String json = sb.toString();
        //            System.out.println( "USERDATA: decoded json data="+json);
        userdata = (JSONObject) JSONValue.parse(json);
        //            System.out.println("json="+json);
        //            System.out.println( "user was "+userdata.get(JSONKeys.NAME));
        JSONArray roles = (JSONArray) userdata.get(JSONKeys.ROLES);
        //            if ( roles.size()>0 )
        //                System.out.println("role was "+roles.get(0));
        if (roles != null)
            for (int i = 0; i < roles.size(); i++)
                if (((String) roles.get(i)).equals("editor"))
                    isEditor = true;
    }
}

From source file:control.ProcesoVertimientosServlets.InsertarProgramacionMonitoreo.java

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

    JSONObject respError = new JSONObject();

    try {

        //Obtenemos el numero de contrato
        String consultorMonitoreo = request.getParameter("consultorMonitoreo");
        String fechaMonitoreo = request.getParameter("fechaMonitoreo");
        String horaInicioMonitoreo = request.getParameter("horaInicioMonitoreo");
        String horaFinMonitoreo = request.getParameter("horaFinMonitoreo");
        int laboratorioMonitoreo = Integer.parseInt(request.getParameter("laboratorioMonitoreo"));
        int codigoProceso = Integer.parseInt(request.getParameter("codigoProceso"));
        String observacion = request.getParameter("observacionesReprogramacion");
        String duracionMonitoreo = request.getParameter("duracionMonitoreo");

        //Insertamos el programacion del monitoreo y obtenemos el codigo
        ProgramarMonitoreo manager = new ProgramarMonitoreo();
        int codigoMonitoreo = manager.insertar(consultorMonitoreo, fechaMonitoreo, horaInicioMonitoreo,
                horaFinMonitoreo, laboratorioMonitoreo, codigoProceso, observacion, duracionMonitoreo);

        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String puntos = request.getParameter("puntosVertimiento");
        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 la info de los puntos
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            int codigoPunto = Integer.parseInt((String) jsonObject.get("codigo"));
            int codigoActividad = Integer.parseInt((String) jsonObject.get("actividad"));

            //Creamos el manager y guardamos la informacion.
            manager.insertarPuntoMonitoreo(codigoPunto, codigoActividad, codigoMonitoreo);

        }

        respError.put("error", "1");
        response.getWriter().write(respError.toString());

    } catch (Exception ex) {

        respError.put("error", "0");
        response.getWriter().write(respError.toString());

    }

}

From source file:geo.controller.GeoCodeServlet.java

private String geoCodeTransactions2(Transaction t) {
    String[] address = t.address.split("#");
    try {/* w ww .j  ava2 s. c om*/
        String url = "http://maps.googleapis.com/maps/api/geocode/json?address="
                + URLEncoder.encode(("Singapore, " + address[0].trim()), "UTF-8") + "&sensor=true";
        URL googleMapGeoCode = new URL(url);

        URLConnection yc = googleMapGeoCode.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        StringBuilder sb = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            sb.append(line).append("\n");
        }

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(sb.toString());
        JSONObject jsonObject = (JSONObject) obj;

        if (jsonObject.get("status").equals("OK")) {
            JSONArray jsonArray = (JSONArray) jsonObject.get("results");
            jsonObject = (JSONObject) jsonArray.get(0);
            jsonObject = (JSONObject) jsonObject.get("geometry");
            jsonObject = (JSONObject) jsonObject.get("location");

            return jsonObject.get("lng").toString() + "," + jsonObject.get("lat").toString();

        }

        //converts SVY21 (OneMap) to WSG84 (Google Map)
        //return convertCoordinates(xCoordinate,yCoordinate);

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

    return "";

}

From source file:net.bashtech.geobot.JSONUtil.java

public static String getRace(String channel) {
    String raceID = "";

    Set<String> entrantSet = new HashSet<String>();
    try {//from  w  ww. ja  v a2  s. c  o  m
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager.getRemoteContent("http://api.speedrunslive.com:81/races"));

        JSONObject jsonObject = (JSONObject) obj;
        int count = Integer.parseInt((String) jsonObject.get("count"));
        JSONArray raceList = (JSONArray) jsonObject.get("races");

        for (int i = 0; i < count; i++) {
            JSONObject races = (JSONObject) raceList.get(i);
            String id = (String) races.get("id");

            JSONObject entrants = (JSONObject) races.get("entrants");
            Set<String> entrantNames = entrants.keySet();
            String entrantsString = entrants.toJSONString();
            if (entrantsString.contains(channel)) {
                raceID = id;
                entrantSet.add(channel);
                for (String s : entrantNames) {

                    JSONObject entrant = (JSONObject) entrants.get(s);
                    String entranttwitch = (String) entrant.get("twitch");
                    if (entrantSet.size() < 5) {
                        entrantSet.add(entranttwitch);
                    }

                }
            }

        }
        if (entrantSet.size() > 0) {
            String raceLink = "http://speedrun.tv/race:" + raceID;
            for (String s : entrantSet) {
                raceLink = raceLink + "/" + s;
            }
            return raceLink;
        } else {
            return null;
        }

    } catch (Exception ex) {
        System.out.println("Failed to get races.");
        return null;
    }
}

From source file:com.googlecode.fascinator.portal.process.HomeInstitutionNotifier.java

@Override
public boolean process(String id, String inputKey, String outputKey, String stage, String configFilePath,
        HashMap<String, Object> dataMap) throws Exception {
    Indexer indexer = (Indexer) dataMap.get("indexer");

    HashSet<String> failedOids = (HashSet<String>) dataMap.get(outputKey);
    if (failedOids == null) {
        failedOids = new HashSet<String>();
    }/*from  w ww  . j a  v a 2 s  . c o  m*/

    Collection<String> oids = (Collection<String>) dataMap.get(inputKey);

    // load up the list of institutions...
    JsonSimple config = new JsonSimple(new File(configFilePath));
    HashMap<String, JsonObject> homes = new HashMap<String, JsonObject>();
    for (Object homeObj : config.getArray("institutions")) {
        JsonObject home = (JsonObject) homeObj;
        homes.put((String) home.get("name"), home);
    }

    File sysFile = JsonSimpleConfig.getSystemFile();
    Storage storage = PluginManager.getStorage("file-system");
    storage.init(sysFile);
    ByteArrayOutputStream out;
    String targetPayload = "arms.xml";
    String targetProperty = "dataprovider:organization";

    for (String oid : oids) {
        log.debug("Processing oid:" + oid);
        out = null;
        // get the solr doc
        SearchRequest searchRequest = new SearchRequest("id:" + oid);
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        indexer.search(searchRequest, result);
        SolrResult resultObject = new SolrResult(result.toString());
        List<SolrDoc> results = resultObject.getResults();
        SolrDoc solrDoc = results.get(0);

        // get the target property
        String targetProp = solrDoc.getString("", targetProperty);
        if (targetProp == null) {
            JSONArray array = solrDoc.getArray(targetProperty);
            if (array.size() > 0) {
                targetProp = (String) array.get(0);
            }
        }
        log.debug("Target property value: " + targetProp);
        if (targetProp != null && targetProp.length() > 0) {
            String channel = (String) homes.get(targetProp).get("channel");
            if (channel != null) {
                log.debug("Using channel:" + channel);
                if (channel.endsWith("email")) {
                    sendEmail(dataMap, failedOids, config, storage, out, targetPayload, oid, solrDoc, channel);
                } else {
                    log.debug("Sending message through the queue...");
                    // defaults to queue
                    MessageqNotifierService notifierService = ApplicationContextProvider.getApplicationContext()
                            .getBean(channel + "_service", MessageqNotifierService.class);

                    out = extractPayload(storage, out, targetPayload, oid);
                    if (out != null) {
                        notifierService.sendMessage(out.toString("UTF-8"));
                    } else {
                        log.error("Payload not found: " + targetPayload + ", for oid:" + oid);
                    }
                }
            } else {
                log.debug("Channel configuration not found, ignoring.");
            }
        } else {
            log.debug("Target property has no value, ignoring.");
        }
    }
    return true;
}

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

@POST
@Consumes(MediaType.APPLICATION_JSON)/*from  w ww.ja v a2 s .c o m*/
@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.piusvelte.hydra.HydraRequest.java

private String[] parseArray(JSONParser parser, String obj) {
    try {//from  w w  w  .  j a va2  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];
}

From source file:io.gomint.server.network.packet.PacketLogin.java

@Override
public void deserialize(PacketBuffer buffer) {
    this.protocol = buffer.readInt();

    // Decompress inner data (i don't know why you compress inside of a Batched Packet but hey)
    byte[] compressed = new byte[buffer.readInt()];
    buffer.readBytes(compressed);//ww w . j av  a 2 s  .  c  o m

    Inflater inflater = new Inflater();
    inflater.setInput(compressed);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {
        byte[] comBuffer = new byte[1024];
        while (!inflater.finished()) {
            int read = inflater.inflate(comBuffer);
            bout.write(comBuffer, 0, read);
        }
    } catch (DataFormatException e) {
        System.out.println("Failed to decompress batch packet" + e);
        return;
    }

    // More data please
    ByteBuffer byteBuffer = ByteBuffer.wrap(bout.toByteArray());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] stringBuffer = new byte[byteBuffer.getInt()];
    byteBuffer.get(stringBuffer);

    // Decode the json stuff
    try {
        JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(stringBuffer));
        JSONArray chainArray = (JSONArray) jsonObject.get("chain");
        if (chainArray != null) {
            this.validationKey = parseBae64JSON((String) chainArray.get(chainArray.size() - 1)); // First key in chain is last response in chain #brainfuck :D
            for (Object chainObj : chainArray) {
                decodeBase64JSON((String) chainObj);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Skin comes next
    this.skin = new byte[byteBuffer.getInt()];
    byteBuffer.get(this.skin);
}

From source file:CPUController.java

@RequestMapping("/cpu")
public @ResponseBody CPU cpu(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);//from  ww  w  .  j  ava2  s.co m

    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

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "cpu");
    params.put("search", search);
    params.put("sortfield", "name");
    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 = "";
    String cpu = "";
    String clock = "";
    String metricType = "";

    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");

        //         System.out.println(array);

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);
            String key = (String) tobj.get("key_");
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("idle") && key.contains("idle")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu idle time";
            } else if (name.equals("iowait") && key.contains("iowait")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu iowait time";
            } else if (name.equals("nice") && key.contains("nice")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu nice time";
            } else if (name.equals("system") && key.contains("system")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu system time";
            } else if (name.equals("user") && key.contains("user")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu user time";
            } else if (name.equals("load") && key.contains("load")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "processor load";
            } else if (name.equals("usage") && key.contains("usage")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "system cpu usage average";
            }
        }
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    if (cpu.equals("")) {
        return new CPU(
                "Error: Please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
    }

    return new CPU(hostid, metricType, cpu, clock);
}

From source file:com.capitalone.dashboard.util.ClientUtil.java

/**
 * Converts JSONArray to list artifact//  www.  ja  v  a2 s . co  m
 * 
 * @param array
 *            JSONArray artifact
 * @return A List artifact representing JSONArray information
 * @throws JSONException
 */
protected List<Object> toList(JSONArray array) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for (int i = 0; i < array.size(); i++) {
        Object value = array.get(i);
        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        }

        else if (value instanceof JSONObject) {
            value = this.toCanonicalSprintPOJO(value.toString());
        }
        list.add(value);
    }
    return list;
}