List of usage examples for org.json.simple JSONObject entrySet
Set<Map.Entry<K, V>> entrySet();
From source file:br.com.blackhubos.eventozero.updater.assets.Asset.java
@SuppressWarnings("unchecked") public static Optional<Asset> parseJsonObject(JSONObject jsonObject, MultiTypeFormatter formatter) { String url = null;/*from w ww . j a v a2 s . co m*/ String name = null; String downloadUrl = null; Date createdDate = null; Date updatedDate = null; long id = Long.MIN_VALUE; long size = Long.MIN_VALUE; long downloads = Long.MIN_VALUE; AssetState state = null; Optional<String> label = Optional.empty(); Optional<Uploader> uploader = Optional.empty(); // Obtem todos valores do JSON for (Map.Entry entries : (Set<Map.Entry>) jsonObject.entrySet()) { Object key = entries.getKey(); Object value = entries.getValue(); String valueString = String.valueOf(value); switch (AssetInput.parseObject(key)) { case URL: { // URL do Asset url = valueString; break; } case ID: { // Id do Asset id = Long.parseLong(valueString); break; } case BROWSER_DOWNLOAD_URL: { // Link de download downloadUrl = valueString; break; } case CREATED_AT: { // Data de criao if (formatter.canFormat(Date.class)) { Optional<Date> dateResult = formatter.format(valueString, Date.class); if (dateResult.isPresent()) { createdDate = dateResult.get(); } } break; } case UPDATED_AT: { // Data de atualizao if (formatter.canFormat(Date.class)) { Optional<Date> dateResult = formatter.format(valueString, Date.class); if (dateResult.isPresent()) { updatedDate = dateResult.get(); } } break; } case NAME: { // Nome name = valueString; break; } case DOWNLOAD_COUNT: { // Quantidade de downloads downloads = Long.parseLong(valueString); break; } case LABEL: { /** Rtulo (se houver, caso contrrio, {@link Optional#absent()} **/ if (value == null) { label = Optional.empty(); } else { label = Optional.of(valueString); } break; } case STATE: { // Estado state = AssetState.parseString(valueString); break; } case SIZE: { // Tamanho do arquivo (em bytes) size = Long.parseLong(valueString); break; } case UPLOADER: { // Quem envou (traduzido externalmente) uploader = Uploader.parseJsonObject((JSONObject) value, formatter); break; } default: { } } } if (id == Long.MIN_VALUE) { // Retorna um optional de valor ausente se no for encontrado o Asset. return Optional.empty(); } // Cria um novo Asset return Optional.of(new Asset(url, name, downloadUrl, createdDate, updatedDate, id, size, downloads, state, label, uploader)); }
From source file:model.Config.java
@Override public void load(JSONObject item) { Iterator it = item.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it.next(); String key = pair.getKey(); Object value = pair.getValue(); if (value == null) { continue; }/*from ww w .j a va2 s. c o m*/ if ("queries".equals(key)) { JSONArray queries = (JSONArray) value; this.loadQueries(queries); continue; } this.setAttribute(key, value.toString()); } }
From source file:com.nubits.nubot.options.OptionsJSON.java
/** * * @param paths/* w w w .j ava 2s .com*/ * @return */ public static OptionsJSON parseOptions(String[] paths) { OptionsJSON options = null; ArrayList<String> filePaths = new ArrayList(); filePaths.addAll(Arrays.asList(paths)); try { JSONObject inputJSON = parseFiles(filePaths); JSONObject optionsJSON = (JSONObject) inputJSON.get("options"); //First try to parse compulsory parameters String exchangeName = (String) optionsJSON.get("exchangename"); String apiKey = ""; if (!exchangeName.equalsIgnoreCase(Constant.CCEX)) { //for ccex this parameter can be omitted if (!optionsJSON.containsKey("apikey")) { Utils.exitWithMessage("The apikey parameter is compulsory."); } else { apiKey = (String) optionsJSON.get("apikey"); } } String apiSecret = (String) optionsJSON.get("apisecret"); String mailRecipient = (String) optionsJSON.get("mail-recipient"); String pairStr = (String) optionsJSON.get("pair"); CurrencyPair pair = CurrencyPair.getCurrencyPairFromString(pairStr, "_"); boolean aggregate = true; //true only for USD if (!pair.getPaymentCurrency().getCode().equalsIgnoreCase("USD")) { aggregate = false; //default to false } boolean dualside = (boolean) optionsJSON.get("dualside"); //Based on the pair, set a parameter do define whether setting SecondaryPegOptionsJSON i necessary or not boolean requireCryptoOptions = Utils.requiresSecondaryPegStrategy(pair); org.json.JSONObject pegOptionsJSON; SecondaryPegOptionsJSON cpo = null; if (requireCryptoOptions) { if (optionsJSON.containsKey("secondary-peg-options")) { Map setMap = new HashMap(); //convert from simple JSON to org.json.JSONObject JSONObject oldObject = (JSONObject) optionsJSON.get("secondary-peg-options"); Set tempSet = oldObject.entrySet(); for (Object o : tempSet) { Map.Entry entry = (Map.Entry) o; setMap.put(entry.getKey(), entry.getValue()); } pegOptionsJSON = new org.json.JSONObject(setMap); cpo = SecondaryPegOptionsJSON.create(pegOptionsJSON, pair); } else { LOG.severe("secondary-peg-options are required in the options"); System.exit(0); } /* org.json.JSONObject jsonString = new org.json.JSONObject(optionsString); org.json.JSONObject optionsJSON2 = (org.json.JSONObject) jsonString.get("options"); pegOptionsJSON = (org.json.JSONObject) optionsJSON2.get("secondary-peg-options"); cpo = SecondaryPegOptionsJSON.create(pegOptionsJSON, pair);*/ } //Then parse optional settings. If not use the default value declared here String nudIp = "127.0.0.1"; boolean sendMails = true; boolean submitLiquidity = true; boolean executeOrders = true; boolean verbose = false; boolean sendHipchat = true; boolean multipleCustodians = false; int executeStrategyInterval = 41; int sendLiquidityInterval = Integer.parseInt(Global.settings.getProperty("submit_liquidity_seconds")); double txFee = 0.2; double priceIncrement = 0.0003; double keepProceeds = 0; double maxSellVolume = 0; double maxBuyVolume = 0; int emergencyTimeout = 60; if (optionsJSON.containsKey("nudip")) { nudIp = (String) optionsJSON.get("nudip"); } if (optionsJSON.containsKey("priceincrement")) { priceIncrement = Utils.getDouble(optionsJSON.get("priceincrement")); } if (optionsJSON.containsKey("txfee")) { txFee = Utils.getDouble(optionsJSON.get("txfee")); } if (optionsJSON.containsKey("submit-liquidity")) { submitLiquidity = (boolean) optionsJSON.get("submit-liquidity"); } if (optionsJSON.containsKey("max-sell-order-volume")) { maxSellVolume = Utils.getDouble(optionsJSON.get("max-sell-order-volume")); } if (optionsJSON.containsKey("max-buy-order-volume")) { maxBuyVolume = Utils.getDouble(optionsJSON.get("max-buy-order-volume")); } //Now require the parameters only if submitLiquidity is true, otherwise can use the default value String nubitAddress = "", rpcPass = "", rpcUser = ""; int nudPort = 9091; if (submitLiquidity) { if (optionsJSON.containsKey("nubitaddress")) { nubitAddress = (String) optionsJSON.get("nubitaddress"); } else { Utils.exitWithMessage("When submit-liquidity is set to true " + "you need to declare a value for \"nubitaddress\" "); } if (optionsJSON.containsKey("rpcpass")) { rpcPass = (String) optionsJSON.get("rpcpass"); } else { Utils.exitWithMessage("When submit-liquidity is set to true " + "you need to declare a value for \"rpcpass\" "); } if (optionsJSON.containsKey("rpcuser")) { rpcUser = (String) optionsJSON.get("rpcuser"); } else { Utils.exitWithMessage("When submit-liquidity is set to true " + "you need to declare a value for \"rpcuser\" "); } if (optionsJSON.containsKey("nudport")) { long nudPortlong = (long) optionsJSON.get("nudport"); nudPort = (int) nudPortlong; } else { Utils.exitWithMessage("When submit-liquidity is set to true " + "you need to declare a value for \"nudport\" "); } } if (optionsJSON.containsKey("executeorders")) { executeOrders = (boolean) optionsJSON.get("executeorders"); } if (optionsJSON.containsKey("verbose")) { verbose = (boolean) optionsJSON.get("verbose"); } if (optionsJSON.containsKey("hipchat")) { sendHipchat = (boolean) optionsJSON.get("hipchat"); } if (optionsJSON.containsKey("mail-notifications")) { sendMails = (boolean) optionsJSON.get("mail-notifications"); } /*Ignore this parameter to prevent one custodian to execute faster than others (walls collapsing) if (optionsJSON.containsKey("check-balance-interval")) { long checkBalanceIntervallong = (long) optionsJSON.get("check-balance-interval"); checkBalanceInterval = (int) checkBalanceIntervallong; } if (optionsJSON.containsKey("check-orders-interval")) { long checkOrdersIntevallong = (long) optionsJSON.get("check-orders-interval"); checkOrdersInteval = (int) checkOrdersIntevallong; } */ if (optionsJSON.containsKey("emergency-timeout")) { long emergencyTimeoutLong = (long) optionsJSON.get("emergency-timeout"); emergencyTimeout = (int) emergencyTimeoutLong; } if (optionsJSON.containsKey("keep-proceeds")) { keepProceeds = Utils.getDouble((optionsJSON.get("keep-proceeds"))); } if (optionsJSON.containsKey("multiple-custodians")) { multipleCustodians = (boolean) optionsJSON.get("multiple-custodians"); } //Create a new Instance options = new OptionsJSON(dualside, apiKey, apiSecret, nubitAddress, rpcUser, rpcPass, nudIp, nudPort, priceIncrement, txFee, submitLiquidity, exchangeName, executeOrders, verbose, pair, executeStrategyInterval, sendLiquidityInterval, sendHipchat, sendMails, mailRecipient, emergencyTimeout, keepProceeds, aggregate, multipleCustodians, maxSellVolume, maxBuyVolume, cpo); } catch (NumberFormatException e) { LOG.severe("Error while parsing the options file : " + e); } return options; }
From source file:com.nubits.nubot.tests.TestAggregateOptions.java
private void aggregate() { Map setMap = new HashMap(); for (int i = 0; i < fileNames.size(); i++) { try {// w w w . j a v a 2 s . c o m JSONParser parser = new JSONParser(); JSONObject fileJSON = (JSONObject) (parser.parse(FileSystem.readFromFile(fileNames.get(i)))); JSONObject tempOptions = (JSONObject) fileJSON.get("options"); Set tempSet = tempOptions.entrySet(); for (Object o : tempSet) { Entry entry = (Entry) o; setMap.put(entry.getKey(), entry.getValue()); } } catch (ParseException ex) { LOG.severe("Parse exception \n" + ex.toString()); System.exit(0); } } JSONObject optionsObject = new JSONObject(); optionsObject.put("options", setMap); }
From source file:com.intel.genomicsdb.GenomicsDBImporter.java
/** * Utility function that returns a list of ChromosomeInterval objects for * the column partition specified by the loader JSON file and rank/partition index * @param loaderJSONFile path to loader JSON file * @param partitionIdx rank/partition index * @return list of ChromosomeInterval objects for the specified partition * @throws ParseException when there is a bug in the JNI interface and a faulty JSON is returned *//* w ww . ja va 2 s . c o m*/ public static ArrayList<ChromosomeInterval> getChromosomeIntervalsForColumnPartition( final String loaderJSONFile, final int partitionIdx) throws ParseException { final String chromosomeIntervalsJSONString = jniGetChromosomeIntervalsForColumnPartition(loaderJSONFile, partitionIdx); /* JSON format { "contigs": [ { "chr1": [ 100, 200] }, { "chr2": [ 500, 600] } ] } */ ArrayList<ChromosomeInterval> chromosomeIntervals = new ArrayList<ChromosomeInterval>(); JSONParser parser = new JSONParser(); JSONObject topObj = (JSONObject) (parser.parse(chromosomeIntervalsJSONString)); assert topObj.containsKey("contigs"); JSONArray listOfDictionaries = (JSONArray) (topObj.get("contigs")); for (Object currDictObj : listOfDictionaries) { JSONObject currDict = (JSONObject) currDictObj; assert currDict.size() == 1; //1 entry for (Object currEntryObj : currDict.entrySet()) { Map.Entry<String, JSONArray> currEntry = (Map.Entry<String, JSONArray>) currEntryObj; JSONArray currValue = currEntry.getValue(); assert currValue.size() == 2; chromosomeIntervals.add(new ChromosomeInterval(currEntry.getKey(), (Long) (currValue.get(0)), (Long) (currValue.get(1)))); } } return chromosomeIntervals; }
From source file:edu.anu.spice.SpiceScoreTest.java
@SuppressWarnings("unchecked") protected void compare(JSONArray expected, JSONArray actual) { assertEquals("Output wrong number of results", expected.size(), actual.size()); for (int i = 0; i < expectedOutput.size(); i++) { JSONObject expectedItem = (JSONObject) expected.get(i); JSONObject actualItem = (JSONObject) actual.get(i); // Image id assertEquals("Incorrect image id", expectedItem.get("image_id"), actualItem.get("image_id")); // Scores JSONObject testScores = (JSONObject) actualItem.get("scores"); JSONObject refScores = (JSONObject) expectedItem.get("scores"); Set<Map.Entry<String, JSONObject>> entrySet = refScores.entrySet(); for (Map.Entry<String, JSONObject> e : entrySet) { assertEquals(String.format("Incorrect score for image id %s", expectedItem.get("image_id")), e.getValue(), testScores.get(e.getKey())); }/* w w w .ja va 2s. c om*/ } }
From source file:model.SearchResponse.java
@Override public void load(JSONObject object) { Iterator it = object.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it.next(); String key = pair.getKey(); Object value = pair.getValue(); if (value == null) { continue; }//from w w w .j ava 2 s . c om switch (key) { case "used_indices": this.used_indices = new Index(); JSONArray usedIndices = (JSONArray) value; if (usedIndices.size() == 1) { this.used_indices.load((JSONObject) usedIndices.get(0)); } break; case "messages": this.loadMessage((JSONArray) value); break; default: this.setAttribute(key, value.toString()); } } System.out.println(this); }
From source file:com.juniform.JUniformPackerJSON.java
@Override public JUniformObject toUniformObjectFromObject(Object object) { if (object == null) { return JUniformObject.OBJECT_NIL; } else if (object instanceof JSONObject) { JSONObject jsonMap = (JSONObject) object; Map<Object, Object> map = new HashMap<>(); Iterator it = jsonMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); map.put(pair.getKey(), this.toUniformObjectFromObject(pair.getValue())); }//from www . j a v a2s. c om return new JUniformObject(map); } else if (object instanceof JSONArray) { JSONArray jsonArray = (JSONArray) object; ArrayList<Object> array = new ArrayList<>(); @SuppressWarnings("unchecked") Iterator<Object> it = jsonArray.iterator(); while (it.hasNext()) { array.add(this.toUniformObjectFromObject(it.next())); } return new JUniformObject(array); } else { return new JUniformObject(object); } }
From source file:net.amigocraft.mpt.command.AddRepositoryCommand.java
@Override public void handle() { if (!checkPerms()) return;//from www. j a v a2 s .c o m if (args.length == 2) { final String path = args[1]; // get the main array from the JSON object JSONObject repos = (JSONObject) Main.repoStore.get("repositories"); // verify the repo hasn't already been added Set<Map.Entry> entries = repos.entrySet(); for (Map.Entry e : entries) { // iterate repos in local store JSONObject o = (JSONObject) e.getValue(); // check URL if (o.containsKey("url") && o.get("url").toString().equalsIgnoreCase(path)) { sender.sendMessage(ERROR_COLOR + "[MPT] The repository at that URL has already been added!"); return; } } // no way we're making the main thread wait for us to open and read the stream Bukkit.getScheduler().runTaskAsynchronously(Main.plugin, new Runnable() { public void run() { try { threadSafeSendMessage(sender, INFO_COLOR + "[MPT] Attempting connection to repository..."); String id = addRepository(path); threadSafeSendMessage(sender, INFO_COLOR + "[MPT] Successfully added " + "repository under ID " + ID_COLOR + id + INFO_COLOR + " to local store! You may now use " + COMMAND_COLOR + "/mpt update" + INFO_COLOR + " to fetch available packages."); } catch (MPTException ex) { threadSafeSendMessage(sender, ERROR_COLOR + "[MPT] " + ex.getMessage()); } } }); } else if (args.length < 2) sender.sendMessage(ERROR_COLOR + "[MPT] Too few arguments! Type " + COMMAND_COLOR + "/mpt help " + ERROR_COLOR + "for help"); else sender.sendMessage(ERROR_COLOR + "[MPT] Too many arguments! Type " + COMMAND_COLOR + "/mpt help " + ERROR_COLOR + "for help"); }
From source file:actions.ScanFileAction.java
@Override public void actionPerformed(ActionEvent e) { new SwingWorker() { @Override/* w w w . j a v a 2 s.com*/ protected Object doInBackground() throws Exception { if (pmFileNode.pmFile.isIsScanned()) { JOptionPane.showMessageDialog(null, "The file has been already scanned."); } if (VirusTotalAPIHelper.apiKey.equals("")) { VirusTotalAPIHelper.apiKey = JOptionPane.showInputDialog("Enter valid API key"); } if (VirusTotalAPIHelper.apiKey.equals("")) { return null; } else { // scan file and get the report. CloseableHttpResponse scanFileResponse = VirusTotalAPIHelper .scanFile(pmFileNode.pmFile.getFile()); try { JSONObject obj = (JSONObject) parser .parse(getStringFromClosableHttpResponse(scanFileResponse)); pmFileNode.pmFile.isScanned = true; pmFileNode.pmFile.md5 = (String) obj.get("md5"); pmFileNode.pmFile.sha1 = (String) obj.get("sha1"); pmFileNode.pmFile.sha2 = (String) obj.get("sha256"); pmFileNode.pmFile.scan_id = (String) obj.get("scan_id"); } catch (ParseException ex) { Exceptions.printStackTrace(ex); } } CloseableHttpResponse reportResponse = VirusTotalAPIHelper.getReport(pmFileNode.pmFile.getSha2()); try { JSONObject obj = (JSONObject) parser.parse(getStringFromClosableHttpResponse(reportResponse)); pmFileNode.pmFile.scanDate = (String) obj.get("scan_date"); pmFileNode.pmFile.positives = (Long) obj.get("positives"); pmFileNode.pmFile.totals = (Long) obj.get("total"); JSONObject scans = (JSONObject) obj.get("scans"); if (scans != null && !scans.isEmpty()) { Iterator iterator = scans.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry pair = (Map.Entry) iterator.next(); JSONObject scan = (JSONObject) pair.getValue(); pmFileNode.pmFile.listOfScans.add(new Scan((String) pair.getKey(), true, scan.get("result") == null ? "" : (String) scan.get("result"), scan.get("version") == null ? "" : (String) scan.get("version"), scan.get("update") == null ? "" : (String) scan.get("update"))); iterator.remove(); // avoids a ConcurrentModificationException pmFileNode.pmFile.numberOfScans++; } } } catch (ParseException ex) { Exceptions.printStackTrace(ex); } MainWindowTopComponent.getInstance().writeOutput(pmFileNode.pmFile.toString()); pmFileNode.pmfcf.refresh(pmFileNode.pmFile); return null; } }.run(); }