List of usage examples for org.json.simple JSONArray iterator
public Iterator<E> iterator()
From source file:analysers.ExportValidated.java
/** * Write the validated lineages as CSV files * //from w ww. j a v a2s . c o m * @param f the file name */ private void writeCSV(File f) { HashMap<String, Integer> lineagesDone = new HashMap<String, Integer>(); int nlin = 1; int linsWritten = 0; int cellsWritten = 0; String sep = ", "; double dt = exp.getFrameInterval(); try { FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); int maxframe = 1; for (Cell c : cells) { if (c.getFrame() > maxframe) { maxframe = c.getFrame(); } } // 1. write time axis bw.write("Lineage" + sep + "Cell" + sep + "First Frame" + sep + "Last Frame" + sep + "FirstX" + sep + "FirstY" + sep + "Area" + sep + "Start Time" + sep + "End Time" + sep); bw.write("Time"); for (int fr = 1; fr <= maxframe; ++fr) { bw.write(sep + ((fr - 1) * dt)); } bw.write("\n"); FilterValidatedDialog fvd = new FilterValidatedDialog(); fvd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); fvd.setCells(cells); boolean doExportPositions = Prefs.get("TrackApp.FilterValidatedDialog.exportPositions", false); for (Cell c : cells) { if (c.isValidated()) { Cell a = findFirstAncestor(c); if (lineagesDone.get("" + a.getCellID()) == null) { lineagesDone.put("" + a.getCellID(), new Integer(nlin++)); if (fvd.accepts(a)) { JSONObject lino = makeLineageJSON(a, nlin); JSONArray cells = (JSONArray) lino.get("cells"); for (@SuppressWarnings("rawtypes") Iterator cit = cells.iterator(); cit.hasNext();) { JSONObject co = (JSONObject) cit.next(); String name = co.get("name").toString(); String firstx = co.get("first_x").toString(); String firsty = co.get("first_y").toString(); String carea = co.get("area").toString(); int start = ((Integer) co.get("start_index")).intValue(); String prefix = ""; for (int i = 1; i < start; ++i) { prefix += sep + "0"; } JSONArray ad = (JSONArray) co.get("data"); int i = 1; for (@SuppressWarnings("rawtypes") Iterator itad = ad.iterator(); itad.hasNext();) { JSONArray da = (JSONArray) itad.next(); int end = start + da.size() - 1; bw.write("" + nlin); bw.write(sep + name); bw.write(sep + start); bw.write(sep + end); bw.write(sep + firstx); bw.write(sep + firsty); bw.write(sep + carea); bw.write(sep + ((start - 1) * dt)); bw.write(sep + ((end - 1) * dt)); bw.write(sep + "Channel " + i + prefix); i++; for (@SuppressWarnings("rawtypes") Iterator itda = da.iterator(); itda.hasNext();) { bw.write(sep + itda.next().toString()); } for (int k = end + 1; k <= maxframe; ++k) { bw.write(sep + "0"); } bw.write("\n"); } if (doExportPositions) { ad = (JSONArray) co.get("frame_position"); i = 1; for (@SuppressWarnings("rawtypes") Iterator itad = ad.iterator(); itad.hasNext();) { JSONArray da = (JSONArray) itad.next(); int end = start + da.size() - 1; bw.write("" + nlin); bw.write(sep + name); bw.write(sep + start); bw.write(sep + end); bw.write(sep + firstx); bw.write(sep + firsty); bw.write(sep + carea); bw.write(sep + ((start - 1) * dt)); bw.write(sep + ((end - 1) * dt)); bw.write(sep + "Position " + i + prefix); i++; for (@SuppressWarnings("rawtypes") Iterator itda = da.iterator(); itda.hasNext();) { bw.write(sep + itda.next().toString()); } for (int k = end + 1; k <= maxframe; ++k) { bw.write(sep + "0"); } bw.write("\n"); } /** write areas too */ JSONArray da = (JSONArray) co.get("frame_area"); int end = start + da.size() - 1; bw.write("" + nlin); bw.write(sep + name); bw.write(sep + start); bw.write(sep + end); bw.write(sep + firstx); bw.write(sep + firsty); bw.write(sep + carea); bw.write(sep + ((start - 1) * dt)); bw.write(sep + ((end - 1) * dt)); bw.write(sep + "Area" + prefix); i++; for (@SuppressWarnings("rawtypes") Iterator itda = da.iterator(); itda.hasNext();) { bw.write(sep + itda.next().toString()); } for (int k = end + 1; k <= maxframe; ++k) { bw.write(sep + "0"); } bw.write("\n"); } ++cellsWritten; } ++linsWritten; } } } } fvd.dispose(); bw.close(); fw.close(); IJ.log("Done, " + linsWritten + " lineages, and " + cellsWritten + " cells were exported."); } catch (IOException e) { IJ.log("Failed to write file!"); e.printStackTrace(); } }
From source file:com.telefonica.iot.cygnus.backends.ckan.CKANCache.java
/** * Populates the package map of a given orgName with the package information from the CKAN response. * @param packages JSON vector from the CKAN response containing package information * @param orgName Organization name/* w w w . ja v a 2 s.co m*/ * @throws Exception */ private void populatePackagesMap(JSONArray packages, String orgName) throws Exception { // this check is for debuging purposes if (packages.size() == 0) { LOGGER.debug("The pacakges list is empty, nothing to cache"); return; } // if LOGGER.debug("Packages to be populated: " + packages.toJSONString() + "(orgName=" + orgName + ")"); // iterate on the packages Iterator<JSONObject> iterator = packages.iterator(); while (iterator.hasNext()) { // get the package name JSONObject pkg = (JSONObject) iterator.next(); String pkgName = (String) pkg.get("name"); // check if the package is in "deleted" state String pkgState = pkg.get("state").toString(); if (pkgState.equals("deleted")) { throw new CygnusBadConfiguration("The package exists but it is in a deleted state (orgName=" + orgName + ", pkgName=" + pkgName + ")"); } // if // put the package in the tree and in the packages map String pkgId = pkg.get("id").toString(); tree.get(orgName).put(pkgName, new ArrayList<String>()); pkgMap.put(pkgName, pkgId); LOGGER.debug("Package found in CKAN, now cached (orgName=" + orgName + " -> pkgName/pkgId=" + pkgName + "/" + pkgId + ")"); // get the resources JSONArray resources; // this piece of code tries to make the code compatible with CKAN 2.0, whose "organization_show" // method returns no resource lists for its packages! (not in CKAN 2.2) // more info --> https://github.com/telefonicaid/fiware-cygnus/issues/153 // if the resources list is null we must try to get it package by package if (ckanVersion.equals("2.0")) { LOGGER.debug("CKAN version is 2.0, try to discover the resources for this package (pkgName=" + pkgName + ")"); resources = discoverResources(pkgName); } else { // 2.2 or higher LOGGER.debug("CKAN version is 2.2 (or higher), the resources list can be obtained from the " + "organization information (pkgName=" + pkgName + ")"); resources = (JSONArray) pkg.get("resources"); } // if else // populate the resources map LOGGER.debug( "Going to populate the resources cache (orgName=" + orgName + ", pkgName=" + pkgName + ")"); populateResourcesMap(resources, orgName, pkgName, false); } // while }
From source file:com.nubits.nubot.trading.wrappers.PeatioWrapper.java
public ApiResponse getLastTradesImpl(CurrencyPair pair, long startTime) { ApiResponse apiResponse = new ApiResponse(); String url = apiBaseUrl;/*w w w .j a v a2s .c o m*/ String method = API_GET_TRADES; boolean isGet = true; TreeMap<String, String> query_args = new TreeMap<>(); ArrayList<Trade> tradeList = new ArrayList<Trade>(); query_args.put("canonical_verb", "GET"); query_args.put("canonical_uri", method); query_args.put("market", pair.toString()); query_args.put("limit", "1000"); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { LOG.info("A maximum of 1000 trades can be returned from the Peatio API"); JSONArray httpAnswerJson = (JSONArray) response.getResponseObject(); for (Iterator<JSONObject> trade = httpAnswerJson.iterator(); trade.hasNext();) { Trade thisTrade = parseTrade(trade.next()); if (thisTrade.getDate().getTime() < startTime) { continue; } tradeList.add(thisTrade); } apiResponse.setResponseObject(tradeList); } else { apiResponse = response; } return apiResponse; }
From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java
public ApiResponse getLastTradesImpl(CurrencyPair pair, long startTime) { ApiResponse apiResponse = new ApiResponse(); String url = API_BASE_URL; String method = API_GET_TRADES; boolean isGet = true; TreeMap<String, String> query_args = new TreeMap<>(); ArrayList<Trade> tradeList = new ArrayList<>(); query_args.put("canonical_verb", "GET"); query_args.put("canonical_uri", method); query_args.put("market", pair.toString()); query_args.put("limit", "1000"); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { LOG.debug("A maximum of 1000 trades can be returned from the BitSpark API"); JSONArray httpAnswerJson = (JSONArray) response.getResponseObject(); for (Iterator<JSONObject> trade = httpAnswerJson.iterator(); trade.hasNext();) { Trade thisTrade = parseTrade(trade.next()); if (thisTrade.getDate().getTime() < (startTime * 1000L)) { continue; }/*w ww . j a va 2s .c om*/ tradeList.add(thisTrade); } apiResponse.setResponseObject(tradeList); } else { apiResponse = response; } return apiResponse; }
From source file:com.nubits.nubot.trading.wrappers.CcedkWrapper.java
private ApiResponse getActiveOrdersImpl(CurrencyPair pair) { ApiResponse apiResponse = new ApiResponse(); ArrayList<Order> orderList = new ArrayList<Order>(); String url = API_BASE_URL; String method = API_ACTIVE_ORDERS; boolean isGet = false; ;//w ww. j av a 2s . co m HashMap<String, String> query_args = new HashMap<>(); if (pair != null) { String pair_id = Integer.toString(TradeUtilsCCEDK.getCCDKECurrencyPairId(pair)); query_args.put("pair_id", pair_id); } ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); JSONObject dataJson = (JSONObject) httpAnswerJson.get("response"); JSONArray entities = (JSONArray) dataJson.get("entities"); for (Iterator<JSONObject> entity = entities.iterator(); entity.hasNext();) { JSONObject orderObject = entity.next(); Order tempOrder = parseOrder(orderObject); if (!tempOrder.isCompleted()) //Do not add executed orders { orderList.add(tempOrder); } } apiResponse.setResponseObject(orderList); } else { apiResponse = response; } return apiResponse; }
From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANCache.java
/** * Populates the resourceName-resource map of a given orgName with the package information from the CKAN response. * @param resources JSON vector from the CKAN response containing resource information * @param orgName Organization name//from www. j a v a2 s. c o m * @param pkgName Package name * @param checkExistence If true, checks if the queried resource already exists in the cache */ private void populateResourcesMap(JSONArray resources, String orgName, String pkgName, boolean checkExistence) { // this check is for debuging purposes if (resources.size() == 0) { logger.debug("The resources list is empty, nothing to cache"); return; } // if logger.debug("Resources to be populated: " + resources.toJSONString() + "(orgName=" + orgName + ", pkgName=" + pkgName + ")"); // iterate on the resources Iterator<JSONObject> iterator = resources.iterator(); while (iterator.hasNext()) { // get the resource name and id (resources cannot be in deleted state) JSONObject factObj = (JSONObject) iterator.next(); String resourceName = (String) factObj.get("name"); String resourceId = (String) factObj.get("id"); // put the resource in the tree and in the resource map if (checkExistence) { if (tree.get(orgName).get(pkgName).contains(resourceName)) { continue; } // if } // if tree.get(orgName).get(pkgName).add(resourceName); resMap.put(resourceName, resourceId); logger.debug("Resource found in CKAN, now cached (orgName=" + orgName + " -> pkgName=" + pkgName + " -> " + "resourceName/resourceId=" + resourceName + "/" + resourceId + ")"); } // while }
From source file:com.nubits.nubot.trading.wrappers.ExcoinWrapper.java
public ApiResponse getActiveOrdersImpl(CurrencyPair pair) { ApiResponse apiResponse = new ApiResponse(); //https://api.exco.in/v1/account/orders(/{CURRENCY}/{COMMODITY}(/{TYPE})) String url = API_BASE_URL + "/" + API_ACCOUNT + "/" + API_ORDERS; String commodity;//from ww w. jav a 2 s . c o m String currency; CurrencyPair returnedPair; String type; ArrayList<Order> orderList = new ArrayList<Order>(); ApiResponse response = getQuery(url); /* [ { "currency": "NBT", "commodity": "BTC", "orders": [ { "count": "23", "type": "BID", "orders": [ { "id": "BLK-DRK-BID-Qjclkj34GKmc4gDXKc", "timestamp": "2014-12-06T07:03:53.584Z", "price": "0.00000023", "commodity_amount": "22446985.14519785", "currency_amount": "5.16280655", "status": "OPEN" }, ... ] }, { "count": "23", "type": "ASK", "orders": [ { "id": "BLK-DRK-ASK-Qjc03d5dlKmc4gDXKc", "timestamp": "2014-12-06T07:03:53.584Z", "price": "0.00000023", "commodity_amount": "22446985.14519785", "currency_amount": "5.16280655", "status": "OPEN" }, ... ] } ] } */ if (response.isPositive()) { JSONArray httpAnswerJson = (JSONArray) response.getResponseObject(); for (Iterator<JSONObject> exchange = httpAnswerJson.iterator(); exchange.hasNext();) { JSONObject thisExchange = exchange.next(); commodity = thisExchange.get("commodity").toString(); currency = thisExchange.get("currency").toString(); //only valid pair if a pair is specified if ((pair != null) && (!currency.equals(pair.getPaymentCurrency().getCode().toUpperCase()) && !commodity.equals(pair.getOrderCurrency().getCode().toUpperCase()))) { continue; } JSONArray _orders = (JSONArray) thisExchange.get("orders"); for (Iterator<JSONObject> _order = _orders.iterator(); _order.hasNext();) { JSONObject thisTyp = _order.next(); type = thisTyp.get("type").toString(); JSONArray orders = (JSONArray) thisTyp.get("orders"); for (Iterator<JSONObject> order = orders.iterator(); order.hasNext();) { JSONObject orderJson = order.next(); returnedPair = CurrencyPair.getCurrencyPairFromString(commodity + "_" + currency, "_"); Order out = parseOrder(orderJson, returnedPair, type); orderList.add(out); } } } apiResponse.setResponseObject(orderList); } else { apiResponse = response; } return apiResponse; }
From source file:com.telefonica.iot.cygnus.backends.ckan.CKANCache.java
/** * Populates the resourceName-resource map of a given orgName with the package information from the CKAN response. * @param resources JSON vector from the CKAN response containing resource information * @param orgName Organization name/* w w w.j av a 2s. c o m*/ * @param pkgName Package name * @param checkExistence If true, checks if the queried resource already exists in the cache */ private void populateResourcesMap(JSONArray resources, String orgName, String pkgName, boolean checkExistence) { // this check is for debuging purposes if (resources.size() == 0) { LOGGER.debug("The resources list is empty, nothing to cache"); return; } // if LOGGER.debug("Resources to be populated: " + resources.toJSONString() + "(orgName=" + orgName + ", pkgName=" + pkgName + ")"); // iterate on the resources Iterator<JSONObject> iterator = resources.iterator(); while (iterator.hasNext()) { // get the resource name and id (resources cannot be in deleted state) JSONObject factObj = (JSONObject) iterator.next(); String resourceName = (String) factObj.get("name"); String resourceId = (String) factObj.get("id"); // put the resource in the tree and in the resource map if (checkExistence) { if (tree.get(orgName).get(pkgName).contains(resourceName)) { continue; } // if } // if tree.get(orgName).get(pkgName).add(resourceName); resMap.put(resourceName, resourceId); LOGGER.debug("Resource found in CKAN, now cached (orgName=" + orgName + " -> pkgName=" + pkgName + " -> " + "resourceName/resourceId=" + resourceName + "/" + resourceId + ")"); } // while }
From source file:es.upm.dit.gsi.seas.EurosentimenAnalysis.java
/** * @param eurosentiment/*from ww w . j a v a 2s . c o m*/ * @param annotation */ public void sentimentAnnotation(String eurosentiment, Annotation annotation) { try { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(eurosentiment); //Parse SEAS response. JSONObject jsonObject = (JSONObject) obj; //Cast into JSON. JSONObject jsonObject2 = (JSONObject) jsonObject.get("results"); JSONArray entries; if (jsonObject2 == null) { entries = (JSONArray) jsonObject.get("entries"); } else { entries = (JSONArray) jsonObject2.get("entries"); } Iterator<JSONObject> iterator = entries.iterator(); while (iterator.hasNext()) { // For each entry JSONObject entrie = iterator.next(); // We take the text //String context = (String) entrie.get("nif:isString"); //docContent = context; // We parse the opinions of the text JSONArray opinions = (JSONArray) entrie.get("opinions"); Iterator<JSONObject> iteratorOpinions = opinions.iterator(); while (iteratorOpinions.hasNext()) { JSONObject opinion = iteratorOpinions.next(); // We take the polarity and the value of the text Long textPolarityValue = (Long) opinion.get("marl:polarityValue"); String textHasPolarity = (String) opinion.get("marl:hasPolarity"); // We create the features for the processed input. FeatureMap sentimentFeatures = Factory.newFeatureMap(); sentimentFeatures.put(this.getSentimentPolarityName(), textHasPolarity); sentimentFeatures.put(this.getSentimentValueName(), textPolarityValue); // We put the features in the annotation or in the document. if (annotation != null) { annotation.setFeatures(sentimentFeatures); } else { document.setFeatures(sentimentFeatures); } } // We take the words in the text with a sentiment value and polarity // JSONArray strings = (JSONArray) entrie.get("strings"); // Iterator<JSONObject> iteratorStrings = strings.iterator(); // while (iteratorStrings.hasNext()) { // For each word we take its values. // JSONObject string = iteratorStrings.next(); // // String word= (String) string.get("nif:anchorOf"); // Long beginIndex = (Long) string.get("nif:beginIndex"); // Long endIndex = (Long) string.get("nif:endIndex"); // JSONObject stringOpinion = (JSONObject) string.get("opinions"); // Double stringPolarityValue= (Double) stringOpinion.get("marl:polarityValue"); // String stringHasPolarity = (String) stringOpinion.get("marl:hasPolarity"); // } } } catch (Exception e) { e.printStackTrace(); // System.out.println("The JSON is not parsed."); // System.out.println("The response of the service has been: " + eurosentiment); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.nubits.nubot.trading.wrappers.AllCoinWrapper.java
public ApiResponse getLastTradesImpl(CurrencyPair pair, long startTime) { ApiResponse apiResponse = new ApiResponse(); String url = API_AUTH_URL; String method = API_TRADES;/*from w w w. j ava2 s .c o m*/ boolean isGet = false; ArrayList<Trade> tradeList = new ArrayList<Trade>(); TreeMap<String, String> query_args = new TreeMap<>(); query_args.put("page", "1"); query_args.put("page_size", "20"); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); JSONArray trades = (JSONArray) httpAnswerJson.get("data"); if (trades != null) { //LOG.info(trades.toJSONString()); for (Iterator<JSONObject> trade = trades.iterator(); trade.hasNext();) { Trade thisTrade = parseTrade(trade.next()); if (!thisTrade.getPair().equals(pair)) { continue; } if (thisTrade.getDate().getTime() < startTime) { continue; } tradeList.add(thisTrade); } } apiResponse.setResponseObject(tradeList); } else { apiResponse = response; } return apiResponse; }