List of usage examples for org.json.simple JSONArray clear
public void clear()
From source file:dependencies.DependencyResolving.java
/** * @param args the command line arguments *//* ww w . ja v a 2 s. c o m*/ public static void main(String[] args) { // TODO code application logic here JSONParser parser = new JSONParser(); //we use JSONParser in order to be able to read from JSON file try { //here we declare the file reader and define the path to the file dependencies.json Object obj = parser.parse(new FileReader( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\dependencies.json")); JSONObject project = (JSONObject) obj; //a JSON object containing all the data in the .json file JSONArray dependencies = (JSONArray) project.get("dependencies"); //get array of objects with key "dependencies" System.out.print("We need to install the following dependencies: "); Iterator<String> iterator = dependencies.iterator(); //define an iterator over the array "dependencies" while (iterator.hasNext()) { System.out.println(iterator.next()); } //on the next line we declare another object, which parses a Parser object and reads from all_packages.json Object obj2 = parser.parse(new FileReader( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\all_packages.json")); JSONObject tools = (JSONObject) obj2; //a JSON object containing all thr data in the file all_packages.json for (int i = 0; i < dependencies.size(); i++) { if (tools.containsKey(dependencies.get(i))) { System.out.println( "In order to install " + dependencies.get(i) + ", we need the following programs:"); JSONArray temporaryArray = (JSONArray) tools.get(dependencies.get(i)); //a temporary JSON array in which we store the keys and values of the dependencies for (i = 0; i < temporaryArray.size(); i++) { System.out.println(temporaryArray.get(i)); } ArrayList<Object> arraysOfJsonData = new ArrayList<Object>(); //an array in which we will store the keys of the objects, after we use the values and won't need them anymore for (i = 0; i < temporaryArray.size(); i++) { System.out.println("Installing " + temporaryArray.get(i)); } while (!temporaryArray.isEmpty()) { for (Object element : temporaryArray) { if (tools.containsKey(element)) { JSONArray secondaryArray = (JSONArray) tools.get(element); //a temporary array within the scope of the if-statement if (secondaryArray.size() != 0) { System.out.println("In order to install " + element + ", we need "); } for (i = 0; i < secondaryArray.size(); i++) { System.out.println(secondaryArray.get(i)); } for (Object o : secondaryArray) { arraysOfJsonData.add(o); //here we create a file with the installed dependency File file = new File( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\" + o); if (file.createNewFile()) { System.out.println(file.getName() + " is installed!"); } else { } } secondaryArray.clear(); } } temporaryArray.clear(); for (i = 0; i < arraysOfJsonData.size(); i++) { temporaryArray.add(arraysOfJsonData.get(i)); } arraysOfJsonData.clear(); } } } Set<String> keys = tools.keySet(); // here we define a set of keys of the objects in all_packages.json for (String s : keys) { File file = new File( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\" + s); if (file.createNewFile()) { System.out.println(file.getName() + " is installed."); } else { } } } catch (IOException ex) { Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:modelo.ApiManager.java
public static void limpiarJSONArray(JSONArray jsonArray) { if (!jsonArray.isEmpty()) { jsonArray.clear(); } }
From source file:cloudclient.Client.java
@SuppressWarnings("unchecked") public static void batchSendTask(PrintWriter out, String workload) throws FileNotFoundException, MalformedURLException { FileInputStream input = new FileInputStream(workload); BufferedReader bin = new BufferedReader(new InputStreamReader(input)); // Get task from workload file String line;//from ww w. j a v a 2s. c o m // String sleepLength; String id; int count = 0; final int batchSize = 10; try { //Get client public IP String ip = getIP(); //System.out.println(ip); //JSON object Array JSONArray taskList = new JSONArray(); while ((line = bin.readLine()) != null) { //sleepLength = line.replaceAll("[^0-9]", ""); //System.out.println(sleepLength); count++; id = ip + ":" + count; JSONObject task = new JSONObject(); task.put("task_id", id); task.put("task", line); taskList.add(task); if (taskList.size() == batchSize) { out.println(taskList.toString()); taskList.clear(); } } //System.out.println(taskList.toString()); if (!taskList.isEmpty()) { out.println(taskList.toString()); taskList.clear(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.itmanwuiso.checksums.dao.ResultJSONWriter.java
@SuppressWarnings("unchecked") public boolean write(List<HashResult> resuls, OutputStream outputStream) { if (null == resuls || outputStream == null) { throw new InvalidArgumentException("Resuls or OutputStream is " + "null."); }//from ww w. j a v a 2s .c o m JSONArray jsons = new JSONArray(); for (HashResult hr : resuls) { jsons.add(converter.resultToJson(hr)); } try { outputStream.write(jsons.toString().getBytes()); outputStream.flush(); outputStream.close(); jsons.clear(); return true; } catch (IOException io) { logger.error("", io); } return false; }
From source file:com.valygard.aohruthless.utils.inventory.InventoryHandler.java
/** * Store the player's inventory in the directory. Doesn't avoid overrides * because we are only saving the most recent inventory. This method stores * the inventory in memory and on disk for convenience. * /*from ww w. ja va 2 s .c o m*/ * @param p */ @SuppressWarnings("unchecked") public void storeInventory(Player p) { ItemStack[] items = p.getInventory().getContents(); ItemStack[] armor = p.getInventory().getArmorContents(); UUID uuid = p.getUniqueId(); String name = p.getName(); this.items.put(name, items); this.armor.put(name, armor); JsonConfiguration json = new JsonConfiguration(dir, uuid.toString()); json.writeString("last-known-username", name).writeString("uuid", uuid.toString()); JSONArray contents = new JSONArray(); JSONArray armorContents = new JSONArray(); contents.addAll(Arrays.asList(items)); armorContents.addAll(Arrays.asList(armor)); json.writeArray("items", contents).writeArray("armor", armorContents); contents.clear(); armorContents.clear(); // And clear the inventory InventoryUtils.clearInventory(p); }
From source file:com.googlecode.fascinator.portal.process.RecordProcessor.java
/** * 'post' - processing method.//from w w w .j av a2 s. c o m * * he 'inputKey' entry in the dataMap contains ids queued for resending. * This is merged with the 'includeList' and persisted on the config file. * The 'lastRun' is updated and persisted as well. * * @param id * @param inputKey * @param configFilePath * @param dataMap * @return * @throws Exception */ private boolean postProcess(String id, String inputKey, String configFilePath, HashMap<String, Object> dataMap) throws Exception { File configFile = new File(configFilePath); SimpleDateFormat dtFormat = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss'Z'"); JsonSimple config = new JsonSimple(configFile); config.getJsonObject().put("lastrun", dtFormat.format(new Date())); Collection<String> oids = (Collection<String>) dataMap.get(inputKey); JSONArray includedArr = config.getArray("includeList"); if (oids != null && oids.size() > 0) { // some oids failed, writing it to inclusion list so it can be sent // next time... if (includedArr == null) { includedArr = config.writeArray("includeList"); } includedArr.clear(); for (String oid : oids) { includedArr.add(oid); } } else { // no oids failed, all good, clearing the list... if (includedArr != null && includedArr.size() > 0) { includedArr.clear(); } } FileWriter writer = new FileWriter(configFile); writer.write(config.toString(true)); writer.close(); return true; }
From source file:com.tresys.jalop.utils.jnltest.Config.ConfigTest.java
@Test public void updateKnownHostsWorks() throws Exception { Config cfg = new Config("/path/to/nothing"); assertTrue(cfg.getPeerConfigs().isEmpty()); JSONObject peer0 = new JSONObject(); JSONArray hosts = new JSONArray(); JSONArray pubAllow = new JSONArray(); JSONArray subAllow = new JSONArray(); peer0.put("hosts", hosts); peer0.put("publishAllow", pubAllow); peer0.put("subscribeAllow", subAllow); assertTrue(cfg.getPeerConfigs().isEmpty()); cfg.updateKnownHosts(peer0);/*w w w. j a v a2 s. co m*/ JSONObject peer1 = new JSONObject(); hosts.add("192.168.1.1"); peer1.put("hosts", hosts); pubAllow.add("audit"); peer1.put("publishAllow", pubAllow); subAllow.add("log"); peer1.put("subscribeAllow", subAllow); cfg.updateKnownHosts(peer1); JSONObject peer2 = new JSONObject(); hosts.clear(); hosts.add("192.168.1.2"); peer2.put("hosts", hosts); pubAllow.clear(); pubAllow.add("log"); peer2.put("publishAllow", pubAllow); subAllow.clear(); subAllow.add("audit"); peer2.put("subscribeAllow", subAllow); Map<InetAddress, PeerConfig> peerCfgs = cfg.getPeerConfigs(); InetAddress addr1 = InetAddresses.forString("192.168.1.1"); assertTrue(peerCfgs.containsKey(addr1)); assertTrue( peerCfgs.get(InetAddresses.forString("192.168.1.1")).getPublishAllow().contains(RecordType.Audit)); assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.1")).getPublishAllow() .contains(RecordType.Journal)); assertFalse( peerCfgs.get(InetAddresses.forString("192.168.1.1")).getPublishAllow().contains(RecordType.Log)); assertTrue( peerCfgs.get(InetAddresses.forString("192.168.1.1")).getSubscribeAllow().contains(RecordType.Log)); assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.1")).getSubscribeAllow() .contains(RecordType.Audit)); assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.1")).getSubscribeAllow() .contains(RecordType.Journal)); cfg.updateKnownHosts(peer2); peerCfgs = cfg.getPeerConfigs(); assertTrue(peerCfgs.containsKey(InetAddresses.forString("192.168.1.2"))); assertFalse( peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Audit)); assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow() .contains(RecordType.Journal)); assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Log)); assertFalse( peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow().contains(RecordType.Log)); assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow() .contains(RecordType.Journal)); assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow() .contains(RecordType.Audit)); peer2.remove("subscribeAllow"); JSONArray subAllows = new JSONArray(); subAllows.add("journal"); peer2.put("subscribeAllow", subAllows); cfg.updateKnownHosts(peer2); peerCfgs = cfg.getPeerConfigs(); assertTrue(peerCfgs.containsKey(InetAddresses.forString("192.168.1.2"))); assertFalse( peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Audit)); assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow() .contains(RecordType.Journal)); assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Log)); assertFalse( peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow().contains(RecordType.Log)); assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow() .contains(RecordType.Journal)); assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow() .contains(RecordType.Audit)); }
From source file:modelo.AutenticacionManager.PermisosAcceso.java
public JSONArray SeleccionarPermisos(String rol) throws SQLException { JSONArray permisos = new JSONArray(); JSONArray ArrayPantallas = new JSONArray(); JSONObject modulos = new JSONObject(); JSONObject pantallas = new JSONObject(); Boolean flag = true;/*from w w w.j a v a 2s. c om*/ String modulo = ""; String codigo_modulo = ""; SeleccionarPermisos select = new SeleccionarPermisos(); ResultSet result = select.getModulos(); while (result.next()) { modulo = result.getString("VAR_MODULO"); codigo_modulo = result.getString("PK_CODIGO"); modulos.put("modulo", modulo); ResultSet rstPantallas = select.getPantallas(rol, codigo_modulo); while (rstPantallas.next()) { pantallas.put("codigo", rstPantallas.getString("PK_CODIGO")); pantallas.put("jsp", rstPantallas.getString("VAR_PANTALLA")); pantallas.put("pantalla", rstPantallas.getString("VAR_DESCRIPCION")); pantallas.put("existe", rstPantallas.getString("EXISTE")); ArrayPantallas.add(pantallas.clone()); pantallas.clear(); } modulos.put("pantallas", ArrayPantallas.clone()); ArrayPantallas.clear(); permisos.add(modulos.clone()); } select.desconectar(); return permisos; }
From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java
public boolean update(final double LATITUDE, final double LONGITUDE) { // Update only if lastUpdate is older than 10 min if (Instant.now().minusSeconds(600).isBefore(lastUpdate)) return true; StringBuilder response = new StringBuilder(); try {/*from ww w .ja va 2s . com*/ forecast.clear(); alerts.clear(); final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY, Exclude.MINUTELY, Exclude.FLAGS); final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection(); final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream())); String inputLine; while ((inputLine = IN.readLine()) != null) { response.append(inputLine).append("\n"); } IN.close(); Object obj = JSONValue.parse(response.toString()); JSONObject jsonObj = (JSONObject) obj; latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString()); longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString()); timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString()); // Update today data JSONObject currently = (JSONObject) jsonObj.get("currently"); setDataPoint(today, currently); // Update forecast data JSONObject daily = (JSONObject) jsonObj.get("daily"); JSONArray days = (JSONArray) daily.get("data"); // Update today with more data JSONObject day0 = (JSONObject) days.get(0); today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString())); today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString())); today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString())); today.setPrecipType(PrecipType .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_"))); for (int i = 1; i < days.size(); i++) { JSONObject day = (JSONObject) days.get(i); DataPoint dataPoint = new DataPoint(); setDataPoint(dataPoint, day); forecast.add(dataPoint); } // Update alert data if (jsonObj.containsKey("alerts")) { JSONArray alerts = (JSONArray) jsonObj.get("alerts"); for (Object alertObj : alerts) { JSONObject alertJson = (JSONObject) alertObj; Alert alert = new Alert(); alert.setTitle(alertJson.get("title").toString()); alert.setDescription(alertJson.get("description").toString()); alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString())); alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString())); alerts.add(alert); } } lastUpdate = Instant.now(); return true; } catch (IOException ex) { System.out.println(ex); return false; } }
From source file:org.openlegacy.ide.eclipse.actions.DeployToServerAction.java
@SuppressWarnings("unchecked") private static JSONArray loadServersList(IProject project) { JSONArray serversList = new JSONArray(); // get servers list String jsonServersList = EclipseDesignTimeExecuter.instance().getPreference(project, "SERVERS_LIST"); if (!StringUtils.isEmpty(jsonServersList)) { Object obj = JSONValue.parse(jsonServersList); serversList.clear(); serversList.addAll((JSONArray) obj); } else {//from w w w. j a v a 2 s . c o m serversList.clear(); } return serversList; }