List of usage examples for org.json.simple JSONArray iterator
public Iterator<E> iterator()
From source file:com.nubits.nubot.trading.wrappers.BittrexWrapper.java
@Override public ApiResponse getAvailableBalances(CurrencyPair pair) { ApiResponse apiResponse = new ApiResponse(); String url = API_BASE_URL; HashMap<String, String> args = new HashMap<>(); String method = API_BALANCES; boolean isGet = true; boolean needAuth = true; ApiResponse response = getQuery(url, method, args, needAuth, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); if (httpAnswerJson.get("result") == null) { ApiError error = errors.nullReturnError; error.setDescription("No Wallets Enabled"); apiResponse.setError(error); } else {//from w w w .j ava2 s. co m Amount NBTOnOrder = new Amount(0, pair.getOrderCurrency()); Amount NBTAvailable = new Amount(0, pair.getOrderCurrency()); Amount PegOnOrder = new Amount(0, pair.getPaymentCurrency()); Amount PegAvailable = new Amount(0, pair.getPaymentCurrency()); JSONArray result = (JSONArray) httpAnswerJson.get("result"); for (Iterator<JSONObject> wallet = result.iterator(); wallet.hasNext();) { JSONObject thisWallet = wallet.next(); if (thisWallet.get("Currency").equals(pair.getPaymentCurrency().getCode().toUpperCase())) { PegAvailable.setQuantity(Utils.getDouble(thisWallet.get("Available"))); PegOnOrder.setQuantity( Utils.getDouble(thisWallet.get("Balance")) - PegAvailable.getQuantity()); } if (thisWallet.get("Currency").equals(pair.getOrderCurrency().getCode().toUpperCase())) { NBTAvailable.setQuantity(Utils.getDouble(thisWallet.get("Available"))); NBTOnOrder.setQuantity( Utils.getDouble(thisWallet.get("Balance")) - NBTAvailable.getQuantity()); } } PairBalance balance = new PairBalance(PegAvailable, NBTAvailable, PegOnOrder, NBTOnOrder); apiResponse.setResponseObject(balance); } } else { apiResponse = response; } return apiResponse; }
From source file:de.ingrid.external.gemet.GEMETService.java
private TreeTerm[] getHierarchyTopLevel(Locale locale) { String language = getGEMETLanguageFilter(locale); // get top supergroups JSONArray children = gemetClient.getTopmostConcepts(ConceptType.SOUPERGROUP, language); // get children (next hierarchy level) and create TreeTerms List<TreeTerm> resultList = new ArrayList<TreeTerm>(); Iterator<JSONObject> childrenIterator = children.iterator(); while (childrenIterator.hasNext()) { // map basic TreeTerm TreeTerm resultTreeTerm = gemetMapper.mapToTreeTerm(childrenIterator.next(), null, null); // NOTICE: Do not set parents in TreeTerm, stays null cause is top // term//from w w w.j a v a 2s.c om // get next hierarchy level (subchildren) and add to TreeTerm ! // For GROUPS OR SOUPERGROUPS we just add DUMMY CHILD to indicate // children, so we reduce requests ! resultTreeTerm.addChild(new TreeTermImpl()); // @formatter:off /* // get children and add to TreeTerm List<JSONArray> subChildrenList = gemetClient.getChildConcepts( resultTreeTerm.getId(), language ); for (JSONArray subChildren : subChildrenList) { gemetMapper.addChildrenToTreeTerm( resultTreeTerm, subChildren ); } */ // @formatter:on resultList.add(resultTreeTerm); } return resultList.toArray(new TreeTerm[resultList.size()]); }
From source file:literarytermsquestionbank.AChristmasCarol.java
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // Set window icon this.setIconImage(Toolkit.getDefaultToolkit() .getImage(getClass().getResource("/Resources/Images/book-icon_acc.png"))); // Set custom fonts try {//from w w w. j av a 2 s . c om GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // Load Gill Sans from resources Font gillSansFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/GILLSANS.TTF")); ge.registerFont(gillSansFontFace); tabbedPane.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f)); questionLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f)); checkButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f)); youAreViewingLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f)); quoteIndexTextField.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 24f)); totalNumberLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 36f)); goButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 20f)); randomButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 20f)); backButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f)); clueLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f)); passageLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f)); exampleLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f)); commentsLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f)); realAnswerLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f)); realAnswerTitleLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f)); // Load the FreeStyle Script font from resources Font freeStyleFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/FREESCPT.TTF")); ge.registerFont(freeStyleFontFace); salutationLabel.setFont(freeStyleFontFace.deriveFont(Font.PLAIN, 30f)); signatureLabel.setFont(freeStyleFontFace.deriveFont(Font.PLAIN, 30f)); } catch (FontFormatException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } JSONParser parser = new JSONParser(); try { // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package. Object quoteObj = parser .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json"))); // This casts the object to a JSONObject for future manipulation JSONObject jsonObject = (JSONObject) quoteObj; // This array holds all the quotes JSONArray quotesArray = (JSONArray) jsonObject.get("A Christmas Carol"); Iterator<JSONObject> iterator = quotesArray.iterator(); // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList while (iterator.hasNext()) { Collections.addAll(quotesList, iterator.next()); totalNumberOfQuotes++; } // Init randomizer Random rand = new Random(); // Generate a random integer between 1 and size of the ArrayList quoteIndex = rand.nextInt(quotesList.size()) + 1; generateQuote(quoteIndex); // This calls a method to generate a quote and display it } catch (Exception e) { // This means something went very wrong when starting the program System.out.println("Uh oh, something bad happened. Possible database corruption."); JOptionPane.showMessageDialog(null, "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } }
From source file:literarytermsquestionbank.ShortStories.java
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // Set window icon this.setIconImage( Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/Images/book-icon_ss.png"))); // Set custom fonts try {//from ww w .j av a 2 s. c o m GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // Load Great Vibes from resources Font bradleyFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/BRADHITC.TTF")); ge.registerFont(bradleyFontFace); questionLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f)); checkButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 36f)); stuckLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 24f)); rescueButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); answerLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); youAreViewingLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); quoteIndexTextField.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); totalNumberLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 36f)); goButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); randomButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); previousButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); nextButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); backButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 24f)); clueTitleLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 24f)); clueLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f)); passageLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f)); examplesLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f)); commentsLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f)); storyLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 20f)); tabbedPane.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); menuTitleLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f)); // Load and set Imprint font face Font imprintFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/IMPRISHA.TTF")); ge.registerFont(imprintFontFace); quoteTopLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f)); quoteBottomLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f)); } catch (FontFormatException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } JSONParser parser = new JSONParser(); try { // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package. Object quoteObj = parser .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json"))); // This casts the object to a JSONObject for future manipulation JSONObject jsonObject = (JSONObject) quoteObj; // This array holds all the quotes JSONArray quotesArray = (JSONArray) jsonObject.get("Short Stories"); Iterator<JSONObject> iterator = quotesArray.iterator(); // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList while (iterator.hasNext()) { Collections.addAll(quotesList, iterator.next()); totalNumberOfQuotes++; } // Init randomizer Random rand = new Random(); // Generate a random integer between 1 and size of the ArrayList quoteIndex = rand.nextInt(quotesList.size()) + 1; generateQuote(quoteIndex); // This calls a method to generate a quote and display it } catch (Exception e) { // This means something went very wrong when starting the program System.out.println("Uh oh, something bad happened. Possible database corruption."); JOptionPane.showMessageDialog(null, "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } }
From source file:literarytermsquestionbank.RomeoAndJuliet.java
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // Set custom icon this.setIconImage( Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/Images/book-icon_rj.png"))); // Set custom fonts try {/*from www . ja v a 2 s . c o m*/ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // Load Old English from resources Font englishFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/OLDENGL.TTF")); ge.registerFont(englishFontFace); actLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 30f)); sceneLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 16f)); lineNumberLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 16f)); // Load Matura Script font from resources Font maturaFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/MATURASC.TTF")); ge.registerFont(maturaFontFace); tabbedPane.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); questionLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); checkButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); stuckLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); rescueButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); answerLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); youAreViewingLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); quoteIndexTextField.setFont(maturaFontFace.deriveFont(Font.PLAIN, 24f)); totalNumberLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 36f)); goButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 24f)); randomButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f)); previousButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); nextButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); backButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f)); // Load Corsova font from resources Font corsovaFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/MTCORSVA.TTF")); ge.registerFont(corsovaFontFace); clueLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f)); passageLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f)); examplesLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f)); commentsLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 14f)); // Load Imprint font from resources Font imprintFontFace = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Resources/Fonts/IMPRISHA.TTF")); ge.registerFont(imprintFontFace); quoteTopLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f)); quoteBottomLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f)); } catch (FontFormatException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex); } JSONParser parser = new JSONParser(); try { // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package. Object quoteObj = parser .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json"))); // This casts the object to a JSONObject for future manipulation JSONObject jsonObject = (JSONObject) quoteObj; // This array holds all the quotes JSONArray quotesArray = (JSONArray) jsonObject.get("Romeo and Juliet"); Iterator<JSONObject> iterator = quotesArray.iterator(); // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList while (iterator.hasNext()) { Collections.addAll(quotesList, iterator.next()); totalNumberOfQuotes++; } // Init randomizer Random rand = new Random(); // Generate a random integer between 1 and size of the ArrayList quoteIndex = rand.nextInt(quotesList.size()) + 1; generateQuote(quoteIndex); // This calls a method to generate a quote and display it } catch (Exception e) { // This means something went very wrong when starting the program System.out.println("Uh oh, something bad happened. Possible database corruption."); JOptionPane.showMessageDialog(null, "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } }
From source file:com.unilever.audit.services2.SyncUp.java
@POST @Path("Data") @Produces("application/json") @Consumes("text/plain") public SyncUpReply SyncUp(String json) { SyncUpReply syncReply = new SyncUpReply(); String id = null;/*from ww w . j a v a2 s . co m*/ try { JSONObject result = (JSONObject) new JSONParser().parse(json); JSONArray visitArray = (JSONArray) result.get("visit"); id = ((JSONObject) visitArray.get(0)).get("merchandiserId").toString(); System.out.println("--------------" + visitArray); /*****************save Json***********************/ Visitsjson visitsjson = new Visitsjson(); visitsjson.setSyncdate(new Date()); visitsjson.setMerchandiserid(new BigInteger(id)); visitsjson.setJson(json); visitsjsonFacadeREST.create(visitsjson); for (Iterator<JSONObject> it = visitArray.iterator(); it.hasNext();) { try { // save every visit with its results by calling one method that works in a single transaction JSONObject visitData = it.next(); context.getBusinessObject(SyncUp.class).saveVisit(visitData); syncReply.getVisits().add(visitData.get("visitId").toString()); syncReply.setMsg("successfully added"); } catch (Exception e) // if any error/exception occured this will not affect the other visits { e.printStackTrace(); syncLog.setAuditLog(0, Integer.parseInt(id), new Date(), Utils.getRootCause(e).getMessage(), "syncUp"); // log the exception } } if (syncReply.getVisits().size() > 0) { Merchandisers m = em.getReference(Merchandisers.class, new BigDecimal(id)); m.setLast_sync_up(new Date()); merchandisersFacadeREST.edit(new BigDecimal(id), m); } } catch (Exception ex) { // TODO: log this in DB Logger.getLogger(SyncUp.class.getName()).log(Level.SEVERE, null, ex); syncLog.setAuditLog(0, Integer.parseInt(id), new Date(), Utils.getRootCause(ex).getMessage(), "syncUp"); } return syncReply; }
From source file:myClass_Main.java
/** * * @param request//from ww w. ja v a 2 s . c o m * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int option = Integer.parseInt(request.getParameter("optionValue")); String url; // do some processing here... // get response writer switch (option) { case 1: { int userValue = Integer.parseInt(request.getParameter("userValue")); String htmlres = ""; // build HTML code for (int i = 0; i < userValue; i++) { htmlres = htmlres + "<input type=\"text\" id=\"inputValue\" name=\"inputValue\" class=\"form-group form-control\" placeholder=\"Nombre de Pais " + (i + 1) + "\" required autofocus>"; } request.setAttribute("htmlres", htmlres); url = "/myPage_core.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; case 2: { String[] input = request.getParameterValues("inputValue"); String sourceURL = "http://api.myjson.com/bins/vcv1"; //just a string // Connect to the URL using java's native library URL urlobject = new URL(sourceURL); HttpURLConnection conection = (HttpURLConnection) urlobject.openConnection(); conection.connect(); // Convert to a JSON object to print data String[][] contry_values = new String[10][input.length]; String zipcode = null; JSONParser jp = new JSONParser(); //from gson JSONObject root = null; JSONArray root_array = null; try { root = (JSONObject) jp.parse(new InputStreamReader(conection.getInputStream())); //Convert the input stream to a json element } catch (ParseException ex) { Logger.getLogger(myClass_Main.class.getName()).log(Level.SEVERE, null, ex); } boolean firstName = (boolean) root.containsKey("countries"); root = (JSONObject) root.get("countries"); root_array = (JSONArray) root.get("country"); //Iterator j = root_array.iterator(); for (int i = 0; i < input.length; i++) { Iterator j = root_array.iterator(); while (j.hasNext()) { JSONObject inner = (JSONObject) j.next(); if (inner.containsValue(input[i])) { contry_values[0][i] = (String) inner.get("isoNumeric"); contry_values[1][i] = (String) inner.get("countryName"); contry_values[2][i] = (String) inner.get("continentName"); contry_values[3][i] = (String) inner.get("capital"); contry_values[4][i] = (String) inner.get("languages"); if (contry_values[4][i].length() > 11) { String strOut = contry_values[4][i]; String trimedstring = strOut.substring(0, 10) + "...";// count start in 0 and 8 is excluded contry_values[4][i] = trimedstring; } contry_values[5][i] = (String) inner.get("population"); contry_values[6][i] = (String) inner.get("areaInSqKm"); contry_values[7][i] = (String) inner.get("countryCode"); contry_values[8][i] = "https://es.wikipedia.org/wiki/" + ((String) inner.get("countryName")); } } } System.out.println("The first name is: " + zipcode); request.setAttribute("firstname", zipcode); String htmlres = "<table class=\"table\">\n" + "<caption>Datos de Paises</caption>\n" + "<thead>\n" + "<tr>\n" + "<th>COD INT.</th>\n" + "<th>AVB.</th>\n" + "<th>Nombre</th>\n" + "<th>Continente</th>\n" + "<th>Capital</th>\n" + "<th>Idioma</th>\n" + "<th>Poblacion</th>\n" + "<th>Area km2</th>\n" + "<th>Wiki URL</th>\n" + "</tr>\n" + "</thead>\n" + "<tbody>"; // build HTML code for (int h = 0; h < input.length; h++) { if ((contry_values[0][h]) != null) { htmlres = htmlres + "<tr><th scope=\"row\">" + contry_values[0][h] + "</th>"; for (int g = 0; g < 9; g++) { if (g != 8) { htmlres = htmlres + "<td>" + contry_values[g][h] + "</td>"; } else { htmlres = htmlres + "<td>" + "<a href=\"" + contry_values[g][h] + "\" class=\"btn btn-info\" role=\"button\">" + contry_values[7][h] + "</a>" + "</td>"; } } htmlres = htmlres + "</tr>"; } else { htmlres = htmlres + "<tr><th scope=\"row\">" + "#Er." + h + "</th>"; htmlres = htmlres + "<td colspan=\"9\">" + "El pais \"" + input[h] + "\" no esta en la BD, verifique que el nombre esta en ingls, e intente de nuevo" + "</td>"; } } htmlres = htmlres + "<tr>"; htmlres = htmlres + "</tbody>\n" + "</table>"; request.setAttribute("htmlres", htmlres); url = "/myPage_res.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; case 3: { url = "/index.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; default: { url = "/index.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; } }
From source file:com.nubits.nubot.trading.wrappers.ExcoinWrapper.java
public ApiResponse getLastTradesImpl(CurrencyPair pair, long startTime) { ApiResponse apiResponse = new ApiResponse(); ArrayList<Trade> tradeList = new ArrayList<Trade>(); String url;/* ww w . j ava 2 s .c om*/ if (startTime == 0) { //https://api.exco.in/v1/account/trades(/{COUNT}) LOG.info("A maximum of " + API_MAX_TRADES + " trades can be returned from the API"); url = API_BASE_URL + "/" + API_ACCOUNT + "/" + API_TRADES + "/" + API_MAX_TRADES; } else { //https://api.exco.in/v1/account/timestamp/{TIMESTAMP} url = API_BASE_URL + "/" + API_ACCOUNT + "/" + API_TRADES + "/" + API_TIMESTAMP + "/" + startTime; } ApiResponse response = getQuery(url); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); JSONArray trades = (JSONArray) httpAnswerJson.get("trades"); for (Iterator<JSONObject> trade = trades.iterator(); trade.hasNext();) { tradeList.add(parseTrade(trade.next())); } apiResponse.setResponseObject(tradeList); } else { apiResponse = response; } return apiResponse; }
From source file:es.tid.fiware.fiwareconnectors.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.j a v a 2s . c o 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 = null; // 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-connectors/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.AltsTradeWrapper.java
private ApiResponse getBalancesImpl(CurrencyPair pair, Currency currency) { ApiResponse apiResponse = new ApiResponse(); String url = API_BASE_URL + "/" + API_BALANCE; HashMap<String, String> args = new HashMap<>(); boolean isGet = false; ApiResponse response = getQuery(url, args, true, isGet); if (response.isPositive()) { JSONArray httpAnswerJson = (JSONArray) response.getResponseObject(); if (currency != null) { //get just one currency balance Amount balance = new Amount(0, currency); for (Iterator<JSONObject> wallet = httpAnswerJson.iterator(); wallet.hasNext();) { JSONObject thisWallet = wallet.next(); if (thisWallet.get("code").equals(currency.getCode().toUpperCase())) { balance.setQuantity(Utils.getDouble(thisWallet.get("balance"))); }/*from w w w. j ava 2 s . c o m*/ } apiResponse.setResponseObject(balance); } else { // get the full pair balances Amount PEGAvail = new Amount(0, pair.getPaymentCurrency()); Amount NBTAvail = new Amount(0, pair.getOrderCurrency()); Amount PEGonOrder = new Amount(0, pair.getPaymentCurrency()); Amount NBTonOrder = new Amount(0, pair.getOrderCurrency()); for (Iterator<JSONObject> wallet = httpAnswerJson.iterator(); wallet.hasNext();) { JSONObject thisWallet = wallet.next(); if (thisWallet.get("code").equals(pair.getOrderCurrency().getCode().toUpperCase())) { NBTAvail.setQuantity(Utils.getDouble(thisWallet.get("balance"))); NBTonOrder.setQuantity(Utils.getDouble(thisWallet.get("held_for_orders"))); } if (thisWallet.get("code").equals(pair.getPaymentCurrency().getCode().toUpperCase())) { PEGAvail.setQuantity(Utils.getDouble(thisWallet.get("balance"))); PEGonOrder.setQuantity(Utils.getDouble(thisWallet.get("held_for_orders"))); } } PairBalance balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder); apiResponse.setResponseObject(balance); } } else { apiResponse = response; } return apiResponse; }