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:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to get the specified 0th property from the response array of
 * a previous REST call//from w  w  w .  j  a  va  2  s. c  o  m
 *
 * @param property
 * @return the value if it's found (else it'll be null)
 * @throws ParseException
 */
public String getFirstPropertyFromResponseArray(@NonNull String property) throws ParseException {
    final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
    if (jsonArray != null && !jsonArray.isEmpty())
        return JSONHelper.getValue((JSONObject) jsonArray.get(0), property);
    return null;
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to get the specified property randomly from the response array of
 * a previous REST call/*from ww  w.jav  a2s.c om*/
 *
 * @param property
 * @return the value if it's found (else it'll be null)
 * @throws ParseException
 */
public String getRandomlyPropertyFromResponseArray(@NonNull String property) throws ParseException {
    final JSONArray jsonArray = JSONHelper.toJSONArray(response.getResponseString());
    if (jsonArray != null && !jsonArray.isEmpty())
        return JSONHelper.getValue((JSONObject) jsonArray.get(new Random().nextInt(jsonArray.size())),
                property);
    return null;
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * The function receives the revisions as a JSON string and obtains the
 * details for the revisions in a list of strings.
 * //from  w  w w  . jav a  2  s .co m
 * @param revisionStr
 *            the string containing the revisions.
 * 
 * @return a vector with JSON strings describing the updated data sets.
 */
public static Vector<String> getUpdatedDatasets(String revisionStr) {

    // check the parameters
    if (revisionStr == null) {
        return null;
    }

    // the vector to return
    Vector<String> toreturnVector = new Vector<String>();

    // parse the JSON string and obtain an array of JSON objects
    Object obj = JSONValue.parse(revisionStr);
    JSONArray array = (JSONArray) obj;

    // prepare the URL string
    String CKANurl = url + "/api/rest/revision/";

    // iterate over the JSON objects
    for (int i = 0; i < array.size(); i++) {
        String revisionUrl = CKANurl + array.get(i).toString();

        // read the information for the revision from the CKAN API
        URL RevisionUrlInstance;
        String revisionDescriptionStr = "";
        try {

            // open a connection to the CKAN API
            RevisionUrlInstance = new URL(revisionUrl);
            URLConnection RevisionUrlInstanceConnection = RevisionUrlInstance.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(RevisionUrlInstanceConnection.getInputStream()));

            // read the output from the API
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                revisionDescriptionStr += inputLine;
            }
            in.close();

            // the description
            toreturnVector.add(revisionDescriptionStr);

        }
        // process exceptions
        catch (MalformedURLException e) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + CKANurl + "\" !!!");
            toreturnVector.add(null);
            continue;
        } catch (IOException e) {
            toreturnVector.add(null);
            continue;
        }
    }

    return toreturnVector;
}

From source file:ActualizadorLocal.Clientes.ClientePasos.java

public void procesarDatos(String datos) throws SQLException {

    datos = "{\"pasos\":" + datos + "}";

    JSONParser parser = new JSONParser();

    try {/*from  w w w.  ja va  2  s .c om*/

        JSONObject obj = (JSONObject) parser.parse(datos);
        JSONArray lista = (JSONArray) obj.get("pasos");
        procesados = lista.size();

        int conta = 1;
        int lotes = procesados / MAX_CACHE_SIZE + 1;

        for (int i = 0; i < lista.size(); i++) {
            if (i % MAX_CACHE_SIZE == 0) {
                _d.primeOUT(label, "Procesado Lote " + conta + " de " + lotes);
                conta++;
            }
            Long a0 = (Long) ((JSONObject) lista.get(i)).get("idNodo");
            String a1 = (String) ((JSONObject) lista.get(i)).get("idDispositivo");
            Long a2 = (Long) ((JSONObject) lista.get(i)).get("tfin");
            Long a3 = (Long) ((JSONObject) lista.get(i)).get("tinicio");

            this.InsertarDatos("\"" + (String) Long.toString(a0) + "\",\"" + a1 + "\",\"" + Long.toString(a2)
                    + "\",\"" + Long.toString(a3) + "\"");

        }

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    syncDB();

}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * Returns a list of the most popular tags.
 * //  ww  w .  ja v a 2 s .c o  m
 * @param numberOfTags
 *            the number of popular tags to return.
 * @return the most popular tags or null if an error occurred.
 */
@Deprecated
@SuppressWarnings("unchecked")
public static JSONArray getMostPopularTagsOld(int numberOfTags) {

    // check the parameters
    if (numberOfTags <= 0) {
        return null;
    }

    // the json array to return
    JSONArray toreturn = new JSONArray();

    // the array to store rating values
    double[] ratingValues = new double[numberOfTags];
    // even tough Java does it automatically, we set the values to zero
    for (int i = 0; i < ratingValues.length; i++) {
        ratingValues[i] = 0.0;
    }

    // a help array for the package ratings
    HashMap<String, Double> packageRatings = new HashMap<String, Double>();

    // prepare the REST API call
    String RESTcall = "api/rest/tag";

    try {
        // run the REST call to obtain all tags
        String tagListString = connectorInstance.restCallWithAuthorization(RESTcall, null);
        if (tagListString == null) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
            return null;
        }

        // parse the JSON string and obtain an array of JSON objects
        Object obj = JSONValue.parse(tagListString);
        JSONArray array = (JSONArray) obj;

        // move over the tags in the array
        for (int i = 0; i < array.size(); i++) {

            // pick the tag name
            String tagName = (String) array.get(i);

            // run the REST call to obtain all packages for the tag in
            // question
            String tRESTcall = RESTcall + "/" + tagName;
            String pListString = connectorInstance.restCallWithAuthorization(tRESTcall, null);

            if (pListString == null) {
                log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
                return null;
            }

            // parse the JSON string
            Object pObj = JSONValue.parse(pListString);
            JSONArray pArray = (JSONArray) pObj;

            // iterate over the JSON array
            double tagRating = 0.0;
            for (int j = 0; j < pArray.size(); j++) {
                // pick the name of the package
                String pName = (String) (pArray.get(j));

                // check whether the average rating value has already been
                // obtained
                Double aRatingValueD = packageRatings.get(pName);

                if (aRatingValueD == null) {
                    // in case it was not obtained until now --> get it and
                    // store it locally
                    double aRatingValue = CKANGatewayUtil.getDataSetRatingsAverage(pName);
                    aRatingValueD = new Double(aRatingValue);
                    packageRatings.put(pName, aRatingValueD);
                }

                // update the tag rating
                tagRating += aRatingValueD.doubleValue();
            }

            // update the toreturn array
            if (toreturn.size() < numberOfTags) {
                toreturn.add(tagName);
                ratingValues[toreturn.size() - 1] = tagRating;

            } else {
                // get the smallest value in the rating values
                int minIndex = minDoubleArray(ratingValues);
                if (ratingValues[minIndex] < tagRating) {
                    ratingValues[minIndex] = tagRating;
                    toreturn.set(minIndex, tagName);
                }
            }
        }
    }
    // catch potential exceptions
    catch (MalformedURLException e) {
        log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
        return null;
    } catch (IOException e) {
        return null;
    }

    return toreturn;
}

From source file:de.ingrid.external.gemet.GEMETService.java

/**
 * Determine parents of passed TreeTerm and set them in TreeTerm. Only first
 * parent can be set./*from  w w w  . j  a  v  a 2  s. c  o  m*/
 * 
 * @param termToProcess
 *            TreeTerm without parents but id
 * @param language
 *            fetch parents in this language
 * @param onlyFirstParent
 *            pass true if only the first parent should be added to the
 *            parents list of the TreeTerm to get only one path to top !
 * @return the passed TreeTerm with parents !
 */
private TreeTerm processParentsOfTerm(TreeTerm termToProcess, String language, boolean onlyFirstParent) {
    // get parents
    List<JSONArray> parentsList = gemetClient.getParentConcepts(termToProcess.getId(), language);
    for (JSONArray parents : parentsList) {
        if (onlyFirstParent) {
            // only first parent should be set
            if (parents.size() > 0) {
                gemetMapper.addParentToTreeTerm(termToProcess, (JSONObject) parents.get(0));
                break;
            }
        } else {
            gemetMapper.addParentsToTreeTerm(termToProcess, parents);
        }
    }

    return termToProcess;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Build a quick lookup ltable for lineformats
 *///from w  w  w .jav a2  s .  co  m
void buildLineFormats() {
    JSONArray lfs = (JSONArray) this.dialect.get("lineformats");
    this.lineFormats = new HashSet<String>();
    for (int i = 0; i < lfs.size(); i++) {
        JSONObject lf = (JSONObject) lfs.get(i);
        String lfProp = (String) lf.get("prop");
        lineFormats.add(lfProp);
    }
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * Sets this.colsUsed to number of times each column is used.  Skipping ZEROS.
 *///w w  w.j av a  2 s . com
private void setupColsUsed() {
    // clear cols used
    colsUsed = new HashMap<String, Integer>();

    JSONArray nodes = (JSONArray) importspec.get("nodes");

    for (int i = 0; i < nodes.size(); i++) {
        JSONObject node = (JSONObject) nodes.get(i);

        // check mappings in nodes
        if (node.containsKey("mapping")) {
            JSONArray mapItems = (JSONArray) node.get("mapping");
            for (int j = 0; j < mapItems.size(); j++) {
                JSONObject item = (JSONObject) mapItems.get(j);
                if (item.containsKey("colId")) {
                    String colId = (String) item.get("colId");
                    if (colsUsed.containsKey(colId)) {
                        colsUsed.put(colId, colsUsed.get(colId) + 1);
                    } else {
                        colsUsed.put(colId, 1);
                    }
                }
            }
        }
        if (node.containsKey("props")) {
            JSONArray propItems = (JSONArray) node.get("props");
            for (int p = 0; p < propItems.size(); p++) {
                JSONObject prop = (JSONObject) propItems.get(p);

                // check mappings in props
                if (prop.containsKey("mapping")) {
                    JSONArray mapItems = (JSONArray) prop.get("mapping");
                    for (int j = 0; j < mapItems.size(); j++) {
                        JSONObject item = (JSONObject) mapItems.get(j);
                        if (item.containsKey("colId")) {
                            String colId = (String) item.get("colId");
                            if (colsUsed.containsKey(colId)) {
                                colsUsed.put(colId, colsUsed.get(colId) + 1);
                            } else {
                                colsUsed.put(colId, 1);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * If a column has transforms in the mapping, apply them to the input raw text
 * @param raw - untransformed string/*from  w  ww  . j av a  2 s .c om*/
 * @param mappingJson - single mapping entry
 * @return
 */
private String applyTransforms(String raw, JSONObject mappingJson) {
    if (mappingJson.containsKey("transformList")) {
        String ret = raw;
        JSONArray transforms = (JSONArray) mappingJson.get("transformList");
        for (int i = 0; i < transforms.size(); i += 1) {
            ret = transformsAvailable.get((String) transforms.get(i)).applyTransform(ret);
        }
        return ret;

    } else {
        return raw;
    }
}

From source file:com.titankingdoms.nodinchan.mobjockeys.MobJockeys.java

/**
 * Checks for update of the library//w w  w . j ava2 s .com
 */
private void updateLib() {
    PluginManager pm = getServer().getPluginManager();

    NCBL libPlugin = (NCBL) pm.getPlugin("NC-BukkitLib");

    File destination = new File(getDataFolder().getParentFile().getParentFile(), "lib");
    destination.mkdirs();

    File lib = new File(destination, "NC-BukkitLib.jar");
    File pluginLib = new File(getDataFolder().getParentFile(), "NC-BukkitLib.jar");

    boolean inPlugins = false;
    boolean download = false;

    try {
        URL url = new URL("http://bukget.org/api/plugin/nc-bukkitlib");

        JSONObject jsonPlugin = (JSONObject) new JSONParser().parse(new InputStreamReader(url.openStream()));
        JSONArray versions = (JSONArray) jsonPlugin.get("versions");

        if (libPlugin == null) {
            getLogger().log(Level.INFO, "Missing NC-Bukkit lib");
            inPlugins = true;
            download = true;

        } else {
            double currentVer = Double.parseDouble(libPlugin.getDescription().getVersion());
            double newVer = currentVer;

            for (int ver = 0; ver < versions.size(); ver++) {
                JSONObject version = (JSONObject) versions.get(ver);

                if (version.get("type").equals("Release")) {
                    newVer = Double
                            .parseDouble(((String) version.get("name")).split(" ")[1].trim().substring(1));
                    break;
                }
            }

            if (newVer > currentVer) {
                getLogger().log(Level.INFO, "NC-Bukkit lib outdated");
                download = true;
            }
        }

        if (download) {
            System.out.println("Downloading NC-Bukkit lib...");

            String dl_link = "";

            for (int ver = 0; ver < versions.size(); ver++) {
                JSONObject version = (JSONObject) versions.get(ver);

                if (version.get("type").equals("Release")) {
                    dl_link = (String) version.get("dl_link");
                    break;
                }
            }

            if (dl_link == null)
                throw new Exception();

            URL link = new URL(dl_link);
            ReadableByteChannel rbc = Channels.newChannel(link.openStream());

            if (inPlugins) {
                FileOutputStream output = new FileOutputStream(pluginLib);
                output.getChannel().transferFrom(rbc, 0, 1 << 24);
                pm.loadPlugin(pluginLib);

            } else {
                FileOutputStream output = new FileOutputStream(lib);
                output.getChannel().transferFrom(rbc, 0, 1 << 24);
            }

            getLogger().log(Level.INFO, "Downloaded NC-Bukkit lib");
        }

    } catch (Exception e) {
        System.out.println("Failed to check for library update");
    }
}