List of usage examples for org.json.simple JSONArray iterator
public Iterator<E> iterator()
From source file:com.vizury.videocache.product.ProductDetail.java
public void jsonToProductDetail(String productData) { if (productData != null) { try {/*from w w w.jav a 2 s . c o m*/ JSONParser jsonParser = new JSONParser(); JSONArray jsonArray = (JSONArray) jsonParser.parse(productData); Iterator iterator = jsonArray.iterator(); int index = 0; while (iterator.hasNext()) { switch (index) { case 0: setProductName((String) iterator.next()); break; case 1: setLandingPageUrl((String) iterator.next()); break; case 2: setCdnUrl((String) iterator.next()); break; case 4: categoryId = ((String) iterator.next()).replace(" ", "+"); setCategoryId(categoryId.length() != 0 ? categoryId : null); break; case 9: subCategoryId = ((String) iterator.next()).replace(" ", "+"); setSubCategoryId(subCategoryId.length() != 0 ? subCategoryId : null); break; case 11: subSubCategoryId = ((String) iterator.next()).replace(" ", "+"); setSubSubCategoryId(subSubCategoryId.length() != 0 ? subSubCategoryId : null); break; default: iterator.next(); break; } index++; } } catch (ParseException ex) { Logger.getLogger(ProductDetail.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:net.nexxus.nntp.NntpArticleHeader.java
public void setPartsFromJSON(String json) { if (json == null || json.isEmpty()) { return;/* ww w .j av a 2 s . c om*/ } JSONParser parser = new JSONParser(); try { Object o = parser.parse(json); JSONArray array = (JSONArray) o; this.parts = new NntpArticlePartID[totalParts]; Iterator iter = array.iterator(); int x = 0; while (iter.hasNext()) { JSONArray part = (JSONArray) iter.next(); long partID = ((Long) part.get(0)).longValue(); String partMsgID = (String) part.get(1); NntpArticlePartID articlePart = new NntpArticlePartID(partID, partMsgID); this.parts[x++] = articlePart; } this.multipart = true; } catch (Exception e) { log.error("failed setting parts from JSON: " + e.getMessage()); log.debug("ID: " + this.id); } }
From source file:com.mythesis.userbehaviouranalysis.WebParser.java
/** * Get meta info for a Youtube link//from w w w. j a v a2 s.c o m * @param ventry the id of the Youtube video * @return a String with all the meta info about the youtube video */ public String GetYoutubeDetails(String ventry) { try { String apikey = "AIzaSyDa18Hdo8Fky9HuxVZZP2uDhvpAGckmxSY"; String output = ""; URL link_ur = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + ventry + "&key=" + apikey + "&part=snippet"); String line = ""; try { HttpURLConnection httpCon = (HttpURLConnection) link_ur.openConnection(); if (httpCon.getResponseCode() != 200) { line = "fail"; } else { try (BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()))) { StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } line = sb.toString(); } } } catch (IOException ex) { Logger.getLogger(WebParser.class.getName()).log(Level.SEVERE, null, ex); line = "fail"; return line; } JSONParser parser = new JSONParser(); //Create the map Map json = (Map) parser.parse(line); // Get a set of the entries Set set = json.entrySet(); Iterator iterator = set.iterator(); Map.Entry entry = null; boolean flagfound = false; while (iterator.hasNext() && !flagfound) { entry = (Map.Entry) iterator.next(); if (entry.getKey().toString().equalsIgnoreCase("items")) { flagfound = true; } } JSONArray jsonarray = (JSONArray) entry.getValue(); Iterator iteratorarray = jsonarray.iterator(); flagfound = false; JSONObject get = null; while (iteratorarray.hasNext() && !flagfound) { JSONObject next = (JSONObject) iteratorarray.next(); if (next.containsKey("snippet")) { get = (JSONObject) next.get("snippet"); flagfound = true; } } String description = ""; String title = ""; if (flagfound) { if (get.containsKey("description")) { description = get.get("description").toString(); } if (get.containsKey("title")) { title = get.get("title").toString(); } output = description + " " + title; } output = removeStopwords(output); return output; } catch (IOException | ArrayIndexOutOfBoundsException | ParseException ex) { Logger.getLogger(WebParser.class.getName()).log(Level.SEVERE, null, ex); String output = null; return output; } }
From source file:com.deem.zkui.utils.ZooKeeperUtil.java
public void setDefaultAcl(String jsonAcl) { if (jsonAcl == null || jsonAcl.trim().length() == 0) { logger.trace("Using UNSAFE ACL. Anyone on your LAN can change your Zookeeper data"); defaultAcl = ZooDefs.Ids.OPEN_ACL_UNSAFE; return;//w w w . ja va 2s . c o m } // Don't let things happen in a half-baked state, build the new ACL and then set it into // defaultAcl ArrayList<ACL> newDefault = new ArrayList<>(); try { JSONArray acls = (JSONArray) ((JSONObject) new JSONParser().parse(jsonAcl)).get("acls"); for (Iterator it = acls.iterator(); it.hasNext();) { JSONObject acl = (JSONObject) it.next(); String scheme = ((String) acl.get("scheme")).trim(); String id = ((String) acl.get("id")).trim(); int perms = 0; String permStr = ((String) acl.get("perms")).toLowerCase().trim(); for (char c : permStr.toCharArray()) { switch (c) { case 'a': perms += ZooDefs.Perms.ADMIN; break; case 'c': perms += ZooDefs.Perms.CREATE; break; case 'd': perms += ZooDefs.Perms.DELETE; break; case 'r': perms += ZooDefs.Perms.READ; break; case 'w': perms += ZooDefs.Perms.WRITE; break; case '*': perms += ZooDefs.Perms.ALL; break; default: throw new RuntimeException("Illegal permission character in ACL " + c); } } newDefault.add(new ACL(perms, new Id(scheme, id))); } } catch (ParseException e) { // Throw it all the way up to the error handlers throw new RuntimeException("Unable to parse default ACL " + jsonAcl, e); } defaultAcl = newDefault; }
From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java
private CloudHarmonyService getService(String serviceId, CloudTypes t) { /* computing the query string */ String getServiceQuery = "https://cloudharmony.com/api/service/" + serviceId + "?" + "api-key=" + API_KEY + "&"; JSONObject service = null;//w ww .j a v a 2 s . c o m try { service = (JSONObject) query(getServiceQuery); } catch (Exception ex) { // 'no content' possible. dunno why } if (service == null) return null; /* name */ String name = "unknown_name"; if (service.containsKey("name")) name = (String) service.get("name"); /* sla */ Double sla = null; if (service.containsKey("sla")) { Object slaValue = service.get("sla"); if (slaValue.getClass().equals(Long.class)) { sla = ((Long) slaValue).doubleValue(); } else { // Double sla = (Double) slaValue; } } /* locations */ JSONArray locations = null; if (service.containsKey("regions")) locations = (JSONArray) service.get("regions"); /* service features */ Object serviceFeatures; ArrayList<JSONObject> computeInstanceTypes = null; if (t == CloudTypes.IAAS) { serviceFeatures = iaas_getServiceFeatures(serviceId); /* in the service features we can find * all the instance types to use to retrieve * the compute instance types. */ if (serviceFeatures != null && ((JSONArray) (serviceFeatures)).size() != 0) { /* retrieving instance types * up to now only Amazon AWS:EC2 and Aruba ARUBA:COMPUTE * return more than one properties object */ JSONObject oneFeature = (JSONObject) ((JSONArray) (serviceFeatures)).get(0); /* It's actually returned a list of service features apparently equal * (except for id which is -> aws:ec2, aws:ec2-..-..) */ JSONArray instanceTypes = (JSONArray) oneFeature.get("instanceTypes"); Iterator<String> instanceTypesIDs = instanceTypes.iterator(); /* querying each instance type */ computeInstanceTypes = new ArrayList<JSONObject>(); while (instanceTypesIDs.hasNext()) { /* current instance id */ String instanceTypeID = instanceTypesIDs.next(); JSONObject cit = getComputeInstanceType(serviceId, instanceTypeID); computeInstanceTypes.add(cit); } } } else { // t == CloudTypes.PAAS serviceFeatures = paas_getServiceFeatures(serviceId); } /* returning everything */ return new CloudHarmonyService(t, // cloud type serviceId, // service id name, // cloud name sla, // availability locations, // geographics null, // bandwidth pricing (unused) serviceFeatures, // cloudharmony service features computeInstanceTypes); // compute instance types }
From source file:com.greatmancode.craftconomy3.utils.OldFormatConverter.java
public void step2() throws SQLException, IOException, ParseException { Common.getInstance().sendConsoleMessage(Level.INFO, "Converting step 2: Inserting the data back in all the new tables"); Common.getInstance().sendConsoleMessage(Level.INFO, "Creating the new tables"); String dbType = Common.getInstance().getMainConfig().getString("System.Database.Type"); if (dbType.equals("sqlite")) { Common.getInstance().sendConsoleMessage(Level.INFO, "You are using SQLite! This is now deprecated. Selecting H2 instead."); Common.getInstance().getMainConfig().setValue("System.Database.Type", "h2"); dbType = "h2"; }// w w w .j a v a2 s .c om StorageEngine engine = null; HikariConfig config = new HikariConfig(); if (dbType.equalsIgnoreCase("mysql")) { engine = new MySQLEngine(); } else if (dbType.equalsIgnoreCase("h2")) { engine = new H2Engine(); } else { throw new UnsupportedOperationException("Unknown database!"); } Common.getInstance().sendConsoleMessage(Level.INFO, "Loading backup json file"); File accountFile = new File(Common.getInstance().getServerCaller().getDataFolder(), "accounts.json"); System.out.println(accountFile.exists()); JSONObject jsonObject = (JSONObject) new JSONParser().parse(new FileReader(accountFile)); Map<Integer, String> currenciesMap = new HashMap<>(); Common.getInstance().sendConsoleMessage(Level.INFO, "Saving currencies"); //Create the currency table JSONArray currencyArray = (JSONArray) jsonObject.get("currencies"); Iterator<JSONObject> iterator = currencyArray.iterator(); while (iterator.hasNext()) { JSONObject obj = iterator.next(); currenciesMap.put(((Long) obj.get("id")).intValue(), (String) obj.get("name")); Currency currency = new Currency((String) obj.get("name"), (String) obj.get("plural"), (String) obj.get("minor"), (String) obj.get("minorPlural"), (String) obj.get("sign")); try { Class clazz = currency.getClass(); Method setDefault = clazz.getDeclaredMethod("setDefault", boolean.class); setDefault.setAccessible(true); setDefault.invoke(currency, (boolean) obj.get("status")); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } engine.saveCurrency("", currency); } Common.getInstance().sendConsoleMessage(Level.INFO, "Saving world groups..."); JSONArray worldgroup = (JSONArray) jsonObject.get("worldgroups"); iterator = worldgroup.iterator(); while (iterator.hasNext()) { JSONObject obj = iterator.next(); engine.saveWorldGroup((String) obj.get("groupName"), (String) obj.get("worldList")); } Common.getInstance().sendConsoleMessage(Level.INFO, "Saving Exchange rates"); JSONArray exchangeArray = (JSONArray) jsonObject.get("exchanges"); iterator = exchangeArray.iterator(); while (iterator.hasNext()) { JSONObject obj = iterator.next(); int id_from = ((Long) obj.get("from_currency_id")).intValue(); int id_to = ((Long) obj.get("to_currency_id")).intValue(); engine.setExchangeRate(engine.getCurrency(currenciesMap.get(id_from)), engine.getCurrency(currenciesMap.get(id_to)), (double) obj.get("amount")); } Common.getInstance().sendConsoleMessage(Level.INFO, "Saving configs"); JSONArray configArray = (JSONArray) jsonObject.get("configs"); iterator = configArray.iterator(); while (iterator.hasNext()) { JSONObject obj = iterator.next(); if (!obj.get("name").equals("dbVersion")) { engine.setConfigEntry((String) obj.get("name"), (String) obj.get("value")); } } Common.getInstance().sendConsoleMessage(Level.INFO, "Saving accounts. This may take a long time."); boolean log = false; if (Common.getInstance().getMainConfig().getBoolean("System.Logging.Enabled")) { Common.getInstance().getMainConfig().setValue("System.Logging.Enabled", false); log = true; } JSONArray accounts = (JSONArray) jsonObject.get("accounts"); iterator = accounts.iterator(); while (iterator.hasNext()) { JSONObject obj = iterator.next(); String name = (String) obj.get("name"); Account account = null; if (name.startsWith("bank:")) { account = engine.getAccount(name.split(":")[1], true, false); } else { account = engine.getAccount(name, false, false); } engine.setIgnoreACL(account, (Boolean) obj.get("ignoreACL")); engine.setInfiniteMoney(account, (Boolean) obj.get("infiniteMoney")); if (obj.get("uuid") != null) { engine.updateUUID(account.getAccountName(), UUID.fromString((String) obj.get("uuid"))); } JSONArray balances = (JSONArray) obj.get("balances"); Iterator<JSONObject> internalIterator = balances.iterator(); while (internalIterator.hasNext()) { JSONObject internalObj = internalIterator.next(); Currency currency = engine .getCurrency(currenciesMap.get(((Long) internalObj.get("currency_id")).intValue())); if (currency != null) { engine.setBalance(account, (double) internalObj.get("balance"), currency, (String) internalObj.get("worldName")); } } JSONArray logs = (JSONArray) obj.get("logs"); internalIterator = logs.iterator(); while (internalIterator.hasNext()) { JSONObject internalObj = internalIterator.next(); engine.saveLog(LogInfo.valueOf((String) internalObj.get("type")), Cause.valueOf((String) internalObj.get("cause")), (String) internalObj.get("causeReason"), account, (double) internalObj.get("amount"), engine.getCurrency((String) internalObj.get("currencyName")), (String) internalObj.get("worldName"), (Timestamp) internalObj.get("timestamp")); } JSONArray acls = (JSONArray) obj.get("acls"); internalIterator = acls.iterator(); while (internalIterator.hasNext()) { JSONObject internalObj = internalIterator.next(); //{"owner":true,"balance":true,"playerName":"khron_nexx","deposit":true,"acl":true,"withdraw":true} engine.saveACL(account, (String) internalObj.get("playerName"), (boolean) internalObj.get("deposit"), (boolean) internalObj.get("withdraw"), (boolean) internalObj.get("acl"), (boolean) internalObj.get("balance"), (boolean) internalObj.get("owner")); } } if (log) { Common.getInstance().getMainConfig().setValue("System.Logging.Enabled", true); } Common.getInstance().sendConsoleMessage(Level.INFO, "Converting done!"); }
From source file:com.nwn.NwnUpdater.java
/** * Parse json file containing files required for server * Convert those files into ServerFile objects and store them *//*w ww .j av a2 s.c o m*/ private boolean parseServerFileJson() { boolean success = true; String compressedFileName; currentGui.setTaskProgressBarValue(0); int currentProgress = 0; int statusIncrement; currentGui.appendOutputText("\n\nReading file list"); try { Thread.sleep(500); FileReader reader = new FileReader(serverFileJson.toString()); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); Set<String> folders = jsonObject.keySet(); if (folders.size() > 0) { statusIncrement = 100 / folders.size(); } else { statusIncrement = 100; } for (String folderName : folders) { if (!folderName.contains("..") && !folderName.contains(":")) { affectedFolders.add(folderName); JSONArray filesByFolder = (JSONArray) jsonObject.get(folderName); Iterator fileItr = filesByFolder.iterator(); while (fileItr.hasNext()) { currentGui.appendOutputText("."); JSONObject fileJson = (JSONObject) fileItr.next(); URL fileUrl = new URL(fileJson.get("url").toString()); if (folderName.equalsIgnoreCase(FolderByExt.COMPRESSED.toString())) { ArrayList<String> compressedFileList = new ArrayList<>(); JSONArray compressedFileArray = (JSONArray) fileJson.get("files"); Iterator cfItr = compressedFileArray.iterator(); while (cfItr.hasNext()) { compressedFileName = cfItr.next().toString(); affectedFolders.add(NwnFileHandler.getFileExtension(compressedFileName)); compressedFileList.add(compressedFileName); } serverFileList.add(new ServerFile(fileJson.get("name").toString(), fileUrl, folderName, compressedFileList)); } else { serverFileList .add(new ServerFile(fileJson.get("name").toString(), fileUrl, folderName)); } } } else { currentGui.appendOutputText("An unusual folder path was detected: " + folderName + "\nServer owner may be attempting to place files outside of NWN." + "\nThis folder has been excluded from the update."); } currentProgress = currentProgress + statusIncrement; currentGui.setTaskProgressBarValue(currentProgress); } currentGui.appendOutputText("done"); reader.close(); } catch (IOException ex) { // ex.printStackTrace(); currentGui.appendOutputText("...failed\nERROR: Cannot read server file list."); error[0] = true; success = false; } catch (ParseException ex) { // ex.printStackTrace(); currentGui.appendOutputText("...failed\nERROR: Cannot parse server file list."); error[0] = true; success = false; } catch (InterruptedException ex) { currentGui.appendOutputText("...canceled"); success = false; } return success; }
From source file:net.itransformers.toplogyviewer.gui.neo4j.Neo4jLoader.java
public void getNeighbourVertexes(String networkNodeId) { String query = "start network=node(" + networkNodeId + ") match network-->device-->interface-->neighbor where device.objectType='Node' and neighbor.objectType='DiscoveredNeighbor' return device.name, interface.name, neighbor.name, neighbor.Reachable?, neighbor.SNMPCommunity?,neighbor.DiscoveryMethod?,neighbor.LocalIPAddress?,neighbor.NeighborIPAddress?,neighbor.NeighborHostname?,neighbor.NeighborDeviceType?"; String params = ""; String output = executeCypherQuery(query, params); JSONObject json = null;/* www . ja va2 s. c o m*/ try { json = (JSONObject) new JSONParser().parse(output); } catch (ParseException e) { e.printStackTrace(); } JSONArray data = (JSONArray) json.get("data"); JSONArray columns = (JSONArray) json.get("columns"); HashMap<String, HashMap<String, String>> neighborMap = new HashMap<String, HashMap<String, String>>(); Iterator dataIter = data.iterator(); while (dataIter.hasNext()) { JSONArray temp = (JSONArray) dataIter.next(); Iterator tempIter = temp.iterator(); Iterator columnsIter = columns.iterator(); String neighborName = null; String deviceName = null; String interfaceName = null; String edgeName = null; // HashMap<String, GraphMLMetadata<String>> nodeMetaData = new HashMap<String, GraphMLMetadata<String>>(); HashMap<String, GraphMLMetadata<String>> nodePropertiesMap = new HashMap<String, GraphMLMetadata<String>>(); HashMap<String, GraphMLMetadata<String>> graphMLPropertiesMap = new HashMap<String, GraphMLMetadata<String>>(); while (tempIter.hasNext() & columnsIter.hasNext()) { String column = columnsIter.next().toString(); String keyNodeProperty = (String) tempIter.next(); String columnsValue = null; if (column.contains("neighbor.")) { columnsValue = StringUtils.replace(StringUtils.substringAfter(column, "neighbor."), "%20", " "); } else { columnsValue = column; } if (columnsValue.equals("device.name")) { deviceName = keyNodeProperty; } else if (columnsValue.equals("interface.name")) { interfaceName = keyNodeProperty; } else if (columnsValue.equals("name")) { neighborName = keyNodeProperty; nodePropertiesMap.put(neighborName, null); } else { if (keyNodeProperty == null) { keyNodeProperty = ""; } else if (keyNodeProperty.equals("emptyValue")) { keyNodeProperty = ""; } HashMap<String, String> transformerValue = new HashMap<String, String>(); transformerValue.put(neighborName, keyNodeProperty); MapSettableTransformer<String, String> transfrmer = new MapSettableTransformer<String, String>( transformerValue); GraphMLMetadata<String> t = new GraphMLMetadata<String>(null, null, transfrmer); nodePropertiesMap.put(columnsValue, t); } } String[] tempArray = { deviceName, neighborName }; Arrays.sort(tempArray); StringBuilder builder = new StringBuilder(); for (int i = 0; i < tempArray.length; i++) { builder.append(tempArray[i]); } edgeName = builder.toString(); Pair<String> endpoints = new Pair<String>(deviceName, neighborName); //Bogon filter if ((neighborName != null) && !entireGraph.containsVertex(neighborName) && (neighborName != "0.0.0.0") && !(StringUtils.contains(neighborName, "128.") || StringUtils.contains(neighborName, "127.") || StringUtils.contains(neighborName, "169.254.") || StringUtils.contains(neighborName, "0."))) { entireGraph.addVertex(neighborName); vertexMetadatas.put(neighborName, nodePropertiesMap); graphMetadatas.put(neighborName, graphMLPropertiesMap); } if (!entireGraph.containsEdge(edgeName)) { entireGraph.addEdge(edgeName, endpoints); } } }
From source file:com.yifanlu.Kindle.JSONMenu.java
/** * Recursively reads the JSON data and converts it to a {@link LauncherAction} which contains either a * {@link LauncherScript} which executes a shell command when called or a {@link LauncherMenu} which contains * other {@link LauncherAction} items.//from www . j a va2 s .co m * * @param json The JSON object to parse * @param parent The menu to add the items to * @return The {@link LauncherAction} that is defined by the JSON data * @throws IOException if there are problems reading the JSON file */ protected LauncherAction jsonToAction(JSONObject json, LauncherMenu parent) throws IOException { String name = (String) json.get("name"); Number priorityNum = (Number) json.get("priority"); int priority; String action = (String) json.get("action"); String params = (String) json.get("params"); JSONArray items = (JSONArray) json.get("items"); LauncherAction launcherAction; if (name == null) name = "No Text"; if (priorityNum == null) priority = 0; else priority = priorityNum.intValue(); if (items != null) { launcherAction = new LauncherMenu(name, priority, parent); KindleLauncher.LOG.debug(JSON_MENU_ITEM, new String[] { name, "submenu", "" }, ""); Iterator it = items.iterator(); while (it.hasNext()) { JSONObject itemObj = (JSONObject) it.next(); ((LauncherMenu) launcherAction).addMenuItem(jsonToAction(itemObj, (LauncherMenu) launcherAction)); } } else if (action != null) { if (params == null) params = ""; File script; if (action.startsWith("/")) script = new File(action); else script = new File(mJsonFile.getParentFile(), action); launcherAction = new LauncherScript(name, priority, script, params); KindleLauncher.LOG.debug(JSON_MENU_ITEM, new String[] { name, action, params }, ""); } else { throw new IOException("No valid action found for menu item: " + json.toJSONString()); } return launcherAction; }
From source file:net.phyloviz.project.action.LoadDataSetAction.java
private TreeFilter loadTreeFilter(File dir, String file) { TreeFilter tf = new TreeFilter(); TreeSet<String>[] filterSet = null; try (FileReader reader = new FileReader(new File(dir, file))) { JSONParser parser = new JSONParser(); JSONObject json;//from ww w. j av a 2 s . c om json = (JSONObject) parser.parse(reader); tf.datamodel = (String) json.get("datamodel"); JSONObject bounds = (JSONObject) json.get("bounds"); JSONArray filter = (JSONArray) json.get("filter"); int colSize = (int) (long) bounds.get("col-size"); filterSet = new TreeSet[colSize]; for (int i = 0; i < filterSet.length; i++) { filterSet[i] = new TreeSet<String>(); } for (Iterator<JSONObject> it = filter.iterator(); it.hasNext();) { JSONObject obj = it.next(); int c = (int) (long) obj.get("col"); String value = (String) obj.get("value"); filterSet[c].add(value); } } catch (IOException | ParseException ex) { Exceptions.printStackTrace(ex); } tf.filter = filterSet; return tf; }