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.dagobert_engine.portfolio.service.MtGoxPortfolioService.java

/**
 * Get the transaction history with a given page. Result is always 50 as
 * maximum//from  ww w  . j  a va 2  s .  c  o m
 * 
 */
public List<Transaction> getTransactions(CurrencyType curr, int page) {

    // create url and params
    final String url = API_MONEY_WALLET_HISTORY;
    final HashMap<String, String> params = QueryArgBuilder.create().add("currency", curr.name())
            .add("page", "" + page).build();

    // Get json string
    final String jsonString = adapter.query(url, params);
    try {
        JSONObject root = (JSONObject) parser.parse(jsonString);
        String result = (String) root.get("result");

        if (!"success".equals(result)) {
            throw new MtGoxException(result);
        } else {
            JSONObject data = (JSONObject) root.get("data");
            JSONArray transactions = (JSONArray) data.get("result");

            final List<Transaction> resultList = new ArrayList<>();

            for (int i = 0; i < transactions.size(); i++) {
                JSONObject currentObj = (JSONObject) transactions.get(i);

                Transaction transaction = new Transaction();

                // int index = Integer.parseInt((String)
                // currentObj.get("Index"));
                Date time = new Date(((long) currentObj.get("Date")) * 1000);
                Transaction.RecordType type = Transaction.RecordType
                        .valueOf(((String) currentObj.get("Type")).toUpperCase());
                CurrencyData value = adapter.getCurrencyForJsonObj((JSONObject) currentObj.get("Value"));
                CurrencyData balance = adapter.getCurrencyForJsonObj((JSONObject) currentObj.get("Balance"));
                String info = (String) currentObj.get("Info");

                JSONArray link = (JSONArray) currentObj.get("Link");

                transaction.setCurrency(curr);

                if (info == null)
                    return null;

                String rateText = info.split("at ")[1].replace(",", "");
                Pattern pattern = Pattern.compile("[0-9]*\\.[0-9]{5}");
                Matcher matcher = pattern.matcher(rateText);

                if (matcher.find()) {

                    transaction.setRate(new CurrencyData(Double.parseDouble(matcher.group(0)),
                            config.getDefaultCurrency()));
                }

                transaction.setTime(time);
                transaction.setType(type);
                transaction.setValue(value);
                transaction.setBalance(balance);
                transaction.setInfo(info);

                if (link.size() > 0) {
                    transaction.setTransactionUuid((String) link.get(0));
                    transaction.setTransactionCategory(
                            Transaction.TransactionCategory.forLink((String) link.get(1)));
                    transaction.setIdentifier((String) link.get(2));
                }

                resultList.add(transaction);
            }
            return resultList;
        }

    } catch (ParseException e) {
        throw new MtGoxException(e);
    }

}

From source file:com.alvexcore.repo.masterdata.getConstraintWork.java

protected List<Map<String, String>> getRestJsonMasterData(NodeRef source) throws Exception {
    NodeService nodeService = serviceRegistry.getNodeService();
    String urlStr = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL);
    String rootPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_ROOT_QUERY);
    String labelField = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_LABEL_FIELD);
    String valueField = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_VALUE_FIELD);
    String caching = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE);

    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    InputStream inputStream = conn.getInputStream();
    String str = IOUtils.toString(inputStream);

    Object jsonObj = JSONValue.parse(str);

    List<Map<String, String>> res = new ArrayList<Map<String, String>>();
    if (jsonObj.getClass().equals(JSONArray.class)) {
        JSONArray arr = (JSONArray) jsonObj;
        for (int k = 0; k < arr.size(); k++) {
            JSONObject item = (JSONObject) arr.get(k);
            String value = item.get(valueField).toString();
            String label = item.get(labelField).toString();
            HashMap<String, String> resItem = new HashMap<String, String>();
            resItem.put("ref", "");
            resItem.put("value", value);
            resItem.put("label", label);
            res.add(resItem);//  w ww.  ja v  a 2  s.  c o  m
        }
    }

    return res;
}

From source file:com.mobicage.rogerthat.registration.RegistrationWizard2.java

@SuppressWarnings("unchecked")
@Override// w  w w  . ja  v  a2  s .  c  om
public void readFromPickle(int version, DataInput in) throws IOException, PickleException {
    T.UI();
    super.readFromPickle(version, in);
    boolean set = in.readBoolean();
    if (set)
        mCredentials = new Credentials(new Pickle(in.readInt(), in));
    set = in.readBoolean();
    mEmail = set ? in.readUTF() : null;
    mTimestamp = in.readLong();
    mRegistrationId = in.readUTF();
    mInGoogleAuthenticationProcess = in.readBoolean();
    mInstallationId = in.readUTF();
    // A version bump was forgotten when serializing mDeviceId, so we need a try/catch
    try {
        mDeviceId = in.readUTF();
    } catch (EOFException e) {
        mDeviceId = null;
    }
    if (version >= 2) {
        try {
            set = in.readBoolean();
            mBeaconRegions = set
                    ? new GetBeaconRegionsResponseTO((Map<String, Object>) JSONValue.parse(in.readUTF()))
                    : null;

            set = in.readBoolean();
            if (set) {
                String detectedBeacons = in.readUTF();
                JSONArray db1 = (JSONArray) JSONValue.parse(detectedBeacons);
                if (db1 != null) {
                    mDetectedBeacons = new HashSet<String>();
                    for (int i = 0; i < db1.size(); i++) {
                        mDetectedBeacons.add((String) db1.get(i));
                    }
                } else {
                    mDetectedBeacons = null;
                }
            } else {
                mDetectedBeacons = null;
            }
        } catch (IncompleteMessageException e) {
            L.bug(e);
        }
    }
}

From source file:matrix.TextUrlMatrix.java

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

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

    for (int i = 0; i < 100; i++) {

        for (int j = 0; j < 100; j++) {

            JSONObject tweet1text = (JSONObject) jArray.get(i);
            JSONObject tweet2text = (JSONObject) jArray.get(j);
            JSONObject tweet1url = (JSONObject) jArray2.get(i);
            JSONObject tweet2url = (JSONObject) jArray2.get(j);
            String tweetText1 = tweet1text.get("tweets").toString();
            String tweetText2 = tweet2text.get("tweets").toString();
            String tweetUrl1 = tweet1url.get("title").toString() + tweet1url.get("meta").toString();
            String tweetUrl2 = tweet2url.get("title").toString() + tweet1url.get("meta").toString();

            double CosSimValueText = cossim.Cosine_Similarity_Score(tweetText1, tweetText2);

            double CosSimValueUrl = cossim.Cosine_Similarity_Score(tweetUrl1, tweetUrl2);

            double TextUrlSimValue = (a * CosSimValueText) + ((1 - a) * CosSimValueUrl);

            TextUrlSimValue = Double.parseDouble(new DecimalFormat("##.###").format(TextUrlSimValue));

            bw.write(Double.toString(TextUrlSimValue) + ", ");

        }/*w ww.j a  v a2  s  .  c om*/
        bw.newLine();
    }
    bw.close();

}

From source file:au.edu.jcu.fascinator.portal.sso.shibboleth.roles.simple.SimpleShibbolethRoleManager.java

@Override
public List<String> getRolesList(JsonSessionState session) {
    List<String> toRet = new ArrayList<String>();
    if (cfg == null) {
        return toRet;
    }//  www  . j  a  v a2s. c o  m
    JSONArray tmp, _tmp;
    JSONArray rule;
    ArrayList _attr;
    String attr, op;
    ShibSimpleRoleOperator operation;
    for (Object role : cfg.keySet()) {
        _tmp = (JSONArray) cfg.get(role);
        for (Object o : _tmp) {
            tmp = (JSONArray) o;

            logger.info(String.format("%s Array: %s", role, tmp.toJSONString()));
            int entryCount = 0;
            for (Object _rule : tmp) {
                if (_rule instanceof JSONArray) {
                    rule = (JSONArray) _rule;
                    _attr = (ArrayList) session.get(rule.get(ATTR_POS).toString());
                    if (_attr != null) {
                        logger.trace("Found attr: " + rule.get(ATTR_POS) + " in session.");
                        operation = operations.get(op = rule.get(OP_POS).toString());
                        if (operation != null) {
                            for (Object s : _attr) {
                                attr = (String) s;
                                if (operation.doOperation(rule.get(VALUE_POS).toString(), attr)) {
                                    entryCount++;
                                }
                            }
                        } else {
                            logger.error(String.format("The operation: %s is unknown, skipping.", op));
                        }
                    }
                } else {
                    logger.error(
                            String.format("The %s role is not correctly configured fo the %s role manager.",
                                    role, SimpleShibbolethRoleManager.class.getName()));
                }
            }
            logger.trace(String.format("Entry Count: %d Size: %d", entryCount, tmp.size()));
            if (entryCount == tmp.size()) {
                toRet.add(role.toString());
            }
        }
    }
    return toRet;
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> readJson(ArrayList<String> elementsList, JSONObject jsonObject, PrintWriter writer,
        String TagName) throws FileNotFoundException, IOException, ParseException {
    String appId = "";
    if (jsonObject.get(TagName) == null) {
        elementsList.add("null");
    } else {/*from ww w  . ja v  a2  s .co m*/
        String Objectscontent = jsonObject.get(TagName).toString();
        if (Objectscontent.startsWith("[{") && Objectscontent.endsWith("}]")) {
            JSONArray jsonArray = (JSONArray) jsonObject.get(TagName);

            for (int temp = 0; temp < jsonArray.size(); temp++) {
                System.out.println("Array:" + jsonArray.toJSONString());
                JSONObject jsonObjectResult = (JSONObject) jsonArray.get(temp);
                System.out.println("Result:" + jsonObjectResult.toJSONString());

                Set<String> jsonObjectResultKeySet = jsonObjectResult.keySet();
                System.out.println("KeySet:" + jsonObjectResultKeySet.toString());

                for (String s : jsonObjectResultKeySet) {
                    System.out.println(s);
                    readJson(elementsList, jsonObjectResult, writer, s);
                }
            }
        } else {
            appId = jsonObject.get(TagName).toString();
            elementsList.add(appId);
        }
    }
    return elementsList;
}

From source file:net.phyloviz.goeburst.GoeBurstItemFactory.java

private void updateEdgeStats(JSONArray edgesStatsArray, Map<Integer, GOeBurstClusterWithStats> groups) {

    for (Iterator<JSONObject> esIt = edgesStatsArray.iterator(); esIt.hasNext();) {
        JSONObject edgeStat = esIt.next();
        Integer groupId = (int) (long) edgeStat.get("group");
        JSONArray ne = (JSONArray) edgeStat.get("ne");
        JSONArray fne = (JSONArray) edgeStat.get("fne");
        JSONArray xLV = (JSONArray) edgeStat.get("xLV");
        Integer withoutTies = (int) (long) edgeStat.get("withoutTies");

        GOeBurstClusterWithStats group = groups.get(groupId);
        group.setEdgeTieStatsWithoutTies(withoutTies);
        int i = 0;
        for (; i < ne.size(); i++) {

            group.setEdgeTieStatsNE(i, (int) (long) ne.get(i));
            group.setEdgeTieStatsFNE(i, (int) (long) fne.get(i));
            group.setEdgeTieStatsNE(i, (int) (long) xLV.get(i));

        }/*from  www . j  a v  a2  s.c  om*/
        for (; i < xLV.size(); i++)
            group.setEdgeTieStatsXlv(i, (int) (long) xLV.get(i));

    }

}

From source file:mml.handler.post.MMLPostHTMLHandler.java

boolean isLineFormat(String name) {
    JSONArray lfs = (JSONArray) dialect.get("lineformats");
    for (int i = 0; i < lfs.size(); i++) {
        JSONObject lf = (JSONObject) lfs.get(i);
        if (name.equals((String) lf.get("prop")))
            return true;
    }//from www  .j av a  2  s .c  om
    return false;
}

From source file:fr.bird.bloom.model.GeographicTreatment.java

/**
 * Get the polygon type : multipolygon or simple polygon
 * /*from   ww w  . j  a  va 2s  .com*/
 * @param File geoJsonFile
 * 
 * @return String
 */
public String getPolygoneType(File geoJsonFile) {
    String typePolygon = "";
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(new FileReader(geoJsonFile.getAbsoluteFile()));
        JSONObject jsonObjectFeatures = (JSONObject) obj;
        JSONArray features = (JSONArray) jsonObjectFeatures.get("features");
        JSONObject firstFeature = (JSONObject) features.get(0);
        JSONObject geometry = (JSONObject) firstFeature.get("geometry");
        typePolygon = (String) geometry.get("type");

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return typePolygon;
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * List the statuses of the files/directories in the given path if the path is
 * a directory.//from www .j ava  2 s. c  om
 *
 * @param f
 *          given path
 * @return the statuses of the files/directories in the given patch
 * @throws IOException
 */
@Override
public FileStatus[] listStatus(Path f) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("op", "list");
    HttpURLConnection conn = getConnection("GET", params, f);
    validateResponse(conn, HttpURLConnection.HTTP_OK);
    JSONArray json = (JSONArray) jsonParse(conn);
    FileStatus[] array = new FileStatus[json.size()];
    for (int i = 0; i < json.size(); i++) {
        array[i] = createFileStatus((JSONObject) json.get(i));
    }
    return array;
}