List of usage examples for org.json.simple JSONObject remove
V remove(Object key);
From source file:compare.handler.get.MetadataHandler.java
/** * Save the version1 metadata item to the METADATA database * @param jObj1 the object retrieved from the metadata database or null * @param conn the database connection//from w w w .j a va 2 s .co m * @throws CompareException if database save failed */ protected void saveToMetadata(JSONObject jObj1, Connection conn) throws CompareException { try { if (!saved && metadataValue != null && metadataValue.length() > 0) { if (jObj1 == null) jObj1 = new JSONObject(); // update metadata for next time jObj1.put(metadataKey, metadataValue); if (jObj1.containsKey(JSONKeys._ID)) jObj1.remove(JSONKeys._ID); conn.putToDb(Database.METADATA, docid, jObj1.toJSONString()); } } catch (Exception e) { throw new CompareException(e); } }
From source file:forumbox.PostingnewpostServlet.java
public void filewrite(String url, String username, String title, String description, HttpServletResponse response, String id) throws IOException { count++;/*ww w . java 2 s . com*/ /* BufferedWriter out ; out = new BufferedWriter(new FileWriter(url,true)); out.write(count+"/"+array[0]+"/"+array[1]+"/"+array[2]+";"); out.close(); }catch (Exception e) { System.out.println("Error: " + e.getMessage()); } */ JSONObject post = new JSONObject(); JSONArray comments = new JSONArray(); JSONArray toapprove = new JSONArray(); JSONParser parser = new JSONParser(); JSONObject list = null; post.put("title", title); post.put("description", description); post.put("id", id); post.put("username", username); // post.put("comments",comments); // post.put("toapprove",toapprove); try { Object obj = parser.parse(new FileReader(url + "list.json")); list = (JSONObject) obj; JSONArray msg = (JSONArray) list.get("list"); msg.add(id); list.remove("list"); list.put("list", msg); } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Adding new ID is unsuccessful"); out.println(e); out.println("......................"); } try { File file = new File(url + id + ".json"); file.createNewFile(); BufferedWriter out; out = new BufferedWriter(new FileWriter(file)); out.write(post.toJSONString()); out.close(); File fileList = new File(url + "list.json"); // fileList.createNewFile(); // BufferedWriter outin ; // outin = new BufferedWriter(new FileWriter(fileList)); // outin.write(post.toJSONString()); FileWriter listwrite = new FileWriter(fileList); listwrite.write(list.toJSONString()); listwrite.flush(); listwrite.close(); //outin.close(); } catch (IOException e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("adding new post is unsuccessful"); out.println(e); out.println("......................"); } }
From source file:com.opensoc.parsing.parsers.BasicLancopeParser.java
@SuppressWarnings("unchecked") @Override//ww w .j av a2 s .c om public JSONObject parse(byte[] msg) { JSONObject payload = null; try { String raw_message = new String(msg, "UTF-8"); payload = (JSONObject) JSONValue.parse(raw_message); String message = payload.get("message").toString(); String[] parts = message.split(" "); payload.put("ip_src_addr", parts[6]); payload.put("ip_dst_addr", parts[7]); String fixed_date = parts[5].replace('T', ' '); fixed_date = fixed_date.replace('Z', ' ').trim(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date; date = formatter.parse(fixed_date); payload.put("timestamp", date.getTime()); payload.remove("@timestamp"); payload.remove("message"); payload.put("original_string", message); return payload; } catch (Exception e) { _LOG.error("Unable to parse message: " + payload.toJSONString()); return null; } }
From source file:com.opensoc.parsing.parsers.BasicBroParser.java
@SuppressWarnings("unchecked") public JSONObject parse(byte[] msg) { _LOG.trace("[OpenSOC] Starting to parse incoming message"); String raw_message = null;//w w w. j a v a 2 s. c o m try { raw_message = new String(msg, "UTF-8"); _LOG.trace("[OpenSOC] Received message: " + raw_message); JSONObject cleaned_message = cleaner.Clean(raw_message); _LOG.debug("[OpenSOC] Cleaned message: " + raw_message); if (cleaned_message == null || cleaned_message.isEmpty()) throw new Exception("Unable to clean message: " + raw_message); String key = cleaned_message.keySet().iterator().next().toString(); if (key == null) throw new Exception("Unable to retrieve key for message: " + raw_message); JSONObject payload = (JSONObject) cleaned_message.get(key); String originalString = " |"; for (Object k : payload.keySet()) { originalString = originalString + " " + k.toString() + ":" + payload.get(k).toString(); } originalString = key.toUpperCase() + originalString; payload.put("original_string", originalString); if (payload == null) throw new Exception("Unable to retrieve payload for message: " + raw_message); if (payload.containsKey("ts")) { String ts = payload.remove("ts").toString(); payload.put("timestamp", ts); _LOG.trace("[OpenSOC] Added ts to: " + payload); } if (payload.containsKey("id.orig_h")) { String source_ip = payload.remove("id.orig_h").toString(); payload.put("ip_src_addr", source_ip); _LOG.trace("[OpenSOC] Added ip_src_addr to: " + payload); } else if (payload.containsKey("tx_hosts")) { JSONArray txHosts = (JSONArray) payload.remove("tx_hosts"); if (txHosts != null && !txHosts.isEmpty()) { payload.put("ip_src_addr", txHosts.get(0)); _LOG.trace("[OpenSOC] Added ip_src_addr to: " + payload); } } if (payload.containsKey("id.resp_h")) { String source_ip = payload.remove("id.resp_h").toString(); payload.put("ip_dst_addr", source_ip); _LOG.trace("[OpenSOC] Added ip_dst_addr to: " + payload); } else if (payload.containsKey("rx_hosts")) { JSONArray rxHosts = (JSONArray) payload.remove("rx_hosts"); if (rxHosts != null && !rxHosts.isEmpty()) { payload.put("ip_dst_addr", rxHosts.get(0)); _LOG.trace("[OpenSOC] Added ip_dst_addr to: " + payload); } } if (payload.containsKey("id.orig_p")) { String source_port = payload.remove("id.orig_p").toString(); payload.put("ip_src_port", source_port); _LOG.trace("[OpenSOC] Added ip_src_port to: " + payload); } if (payload.containsKey("id.resp_p")) { String dest_port = payload.remove("id.resp_p").toString(); payload.put("ip_dst_port", dest_port); _LOG.trace("[OpenSOC] Added ip_dst_port to: " + payload); } // if (payload.containsKey("host")) { // // String host = payload.get("host").toString().trim(); // String tld = tldex.extractTLD(host); // // payload.put("tld", tld); // _LOG.trace("[OpenSOC] Added tld to: " + payload); // // } // if (payload.containsKey("query")) { // String host = payload.get("query").toString(); // String[] parts = host.split("\\."); // int length = parts.length; // if (length >= 2) { // payload.put("tld", parts[length - 2] + "." // + parts[length - 1]); // _LOG.trace("[OpenSOC] Added tld to: " + payload); // } // } _LOG.trace("[OpenSOC] Inner message: " + payload); payload.put("protocol", key); _LOG.debug("[OpenSOC] Returning parsed message: " + payload); return payload; } catch (Exception e) { _LOG.error("Unable to Parse Message: " + raw_message); e.printStackTrace(); return null; } }
From source file:com.photon.phresco.util.Utility.java
public static void killProcess(String baseDir, String actionType) throws PhrescoException { File do_not_checkin = new File(baseDir + File.separator + DO_NOT_CHECKIN_DIRY); File jsonFile = new File(do_not_checkin.getPath() + File.separator + "process.json"); if (!jsonFile.exists()) { return;/*from w w w.j a va 2 s.co m*/ } try { JSONObject jsonObject = new JSONObject(); JSONParser parser = new JSONParser(); FileReader reader = new FileReader(jsonFile); jsonObject = (JSONObject) parser.parse(reader); Object processId = jsonObject.get(actionType); if (processId == null) { return; } if (System.getProperty(Constants.OS_NAME).startsWith(Constants.WINDOWS_PLATFORM)) { Runtime.getRuntime().exec("cmd /X /C taskkill /F /T /PID " + processId.toString()); } else { Runtime.getRuntime().exec(Constants.JAVA_UNIX_PROCESS_KILL_CMD + processId.toString()); } jsonObject.remove(actionType); FileWriter writer = new FileWriter(jsonFile); writer.write(jsonObject.toString()); writer.close(); reader.close(); if (jsonObject.size() <= 0) { FileUtil.delete(jsonFile); } } catch (IOException e) { throw new PhrescoException(e); } catch (ParseException e) { throw new PhrescoException(e); } }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops repBuy(String shopName, String cost, String index, Player player) { if (!shops.containsKey(shopName)) { player.sendMessage("\u00a7eThat shop does not exist!"); return this; }//from ww w.j av a2 s . com try { String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONObject shopObj = (JSONObject) jsonObj.get(shopName); JSONArray shopItems = (JSONArray) shopObj.get("ShopItems"); if (shopItems.size() <= Integer.parseInt(index)) { player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!"); return this; } String itemName = (String) shopItems.get(Integer.parseInt(index)); shopObj.remove(itemName); shopItems.remove(Integer.parseInt(index)); String newItem = player.getItemInHand().getType().name(); Bukkit.getLogger() .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName); shopItems.add(Integer.parseInt(index), newItem + ":buy:" + player.getItemInHand().getDurability()); shopObj.put("ShopItems", shopItems); JSONObject itemStub = new JSONObject(); itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount())); itemStub.put("price", cost); itemStub.put("type", "buy"); itemStub.put("durability", "" + player.getItemInHand().getDurability()); shopObj.put(newItem + ":buy:" + player.getItemInHand().getDurability(), itemStub); shopObj.put("ShopItems", shopItems); jsonObj.put(shopName, shopObj); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop updated!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in repBuy()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in repBuy()"); e.printStackTrace(); } return this; }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops repSell(String shopName, String cost, String index, Player player) { if (!shops.containsKey(shopName)) { player.sendMessage("\u00a7eThat shop does not exist!"); return this; }//from w ww . j a v a2 s . c o m try { String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONObject shopObj = (JSONObject) jsonObj.get(shopName); JSONArray shopItems = (JSONArray) shopObj.get("ShopItems"); if (shopItems.size() <= Integer.parseInt(index)) { player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!"); return this; } String itemName = (String) shopItems.get(Integer.parseInt(index)); shopObj.remove(itemName); shopItems.remove(Integer.parseInt(index)); String newItem = player.getItemInHand().getType().name(); Bukkit.getLogger() .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName); shopItems.add(Integer.parseInt(index), newItem + ":sell:" + player.getItemInHand().getDurability()); shopObj.put("ShopItems", shopItems); JSONObject itemStub = new JSONObject(); itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount())); itemStub.put("price", cost); itemStub.put("type", "sell"); itemStub.put("durability", "" + player.getItemInHand().getDurability()); shopObj.put(newItem + ":sell:" + player.getItemInHand().getDurability(), itemStub); shopObj.put("ShopItems", shopItems); jsonObj.put(shopName, shopObj); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop updated!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in repBuy()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in repBuy()"); e.printStackTrace(); } return this; }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops delIndex(String shopName, String index, Player player) { if (!shops.containsKey(shopName)) { player.sendMessage("\u00a7eThat shop does not exist!"); return this; }/*from w w w . ja v a 2s . com*/ try { String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONObject shopObj = (JSONObject) jsonObj.get(shopName); JSONArray shopItems = (JSONArray) shopObj.get("ShopItems"); if (shopItems.size() <= Integer.parseInt(index)) { player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!"); return this; } String itemName = (String) shopItems.get(Integer.parseInt(index)); shopItems.remove(Integer.parseInt(index)); shopObj.put("ShopItems", shopItems); shopObj.remove(itemName); jsonObj.put(shopName, shopObj); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop updated!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in delIndex()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in delIndex()"); e.printStackTrace(); } return this; }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Writes the modified modsecurity configurations to configuration file. * @param json contains modsecurity configurations as json object. *//* ww w. j a va 2 s . co m*/ @SuppressWarnings("unchecked") public static void onWriteMSConfig(JSONObject json) { log.info("onWriteMSConfig called.. : " + json.toJSONString()); MSConfig serviceCfg = MSConfig.getInstance(); JSONObject jsonResp = new JSONObject(); String fileName = serviceCfg.getConfigMap().get("MSConfigFile"); String modifiedStr = ""; InputStream ins = null; FileOutputStream out = null; BufferedReader br = null; try { File file = new File(fileName); DataInputStream in; @SuppressWarnings("resource") FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); FileLock lock = channel.lock(); try { ins = new FileInputStream(file); in = new DataInputStream(ins); br = new BufferedReader(new InputStreamReader(in)); String line = ""; boolean check; while ((line = br.readLine()) != null) { check = true; //log.info("Line :" + line); for (ModSecConfigFields field : ModSecConfigFields.values()) { if (line.startsWith(field.toString())) { if (line.trim().split(" ")[0].equals(field.toString())) { if (json.containsKey(field.toString())) { if (((String) json.get(field.toString())).equals("") || json.get(field.toString()) == null) { log.info("---------- Log Empty value ----:" + (String) json.get(field.toString())); json.remove(field.toString()); check = false; continue; } else { modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n"; check = false; } } } } } if (check) { modifiedStr += line + "\n"; } } for (ModSecConfigFields field : ModSecConfigFields.values()) { if (json.containsKey(field.toString())) { if (json.get(field.toString()) == null || ((String) json.get(field.toString())).equals("")) { log.info("---------- Log Empty value ----:" + (String) json.get(field.toString())); json.remove(field.toString()); check = false; continue; } else { modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n"; } } } //modified string writing to modsecurity configurations log.info("Writing File :" + modifiedStr); out = new FileOutputStream(fileName); out.write(modifiedStr.getBytes()); log.info("ModSecurity Configurations configurations Written ... "); } finally { lock.release(); } br.close(); in.close(); ins.close(); out.close(); //For Restarting modsecurity so that modified configuration can be applied JSONObject restartJson = new JSONObject(); restartJson.put("action", "restart"); String cmd = serviceCfg.getConfigMap().get("MSRestart"); executeShScript(cmd, restartJson); jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "0"); jsonResp.put("message", "Configurations updated!"); } catch (FileNotFoundException e1) { jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "1"); jsonResp.put("message", "Internal Service is down!"); e1.printStackTrace(); } catch (IOException | NullPointerException e) { jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "0"); jsonResp.put("message", "Unable to modify configurations. Sorry of inconvenience"); e.printStackTrace(); } log.info("Sending Json :" + jsonResp.toJSONString()); ConnectorService.getConnectorProducer().send(jsonResp.toJSONString()); jsonResp.clear(); }
From source file:com.tresys.jalop.utils.jnltest.SubscriberImpl.java
/** * Helper utility to run through all records that have been transferred, * but not yet synced. For log & audit records, this will remove all * records that are not synced (even if they are completely downloaded). * For journal records, this finds the record after the most recently * synced record record, and deletes all the other unsynced records. For * example, if the journal records 1, 2, 3, and 4 have been downloaded, and * record number 2 is marked as 'synced', then this will remove record * number 4, and try to resume the transfer for record number 3. * * @throws IOException If there is an error reading existing files, or an * error removing stale directories. * @throws org.json.simple.parser.ParseException * @throws ParseException If there is an error parsing status files. * @throws java.text.ParseException If there is an error parsing a * directory name.// w ww .ja v a 2s . c o m */ final void prepareForSubscribe() throws IOException, ParseException, java.text.ParseException { final File[] outputRecordDirs = this.outputRoot.listFiles(SubscriberImpl.FILE_FILTER); long lastSerial = 0; if (outputRecordDirs.length >= 1) { Arrays.sort(outputRecordDirs); final List<File> sortedOutputRecords = java.util.Arrays.asList(outputRecordDirs); final File lastRecord = sortedOutputRecords.get(sortedOutputRecords.size() - 1); lastSerial = Long.valueOf(lastRecord.getName()); } switch (this.recordType) { case Audit: this.jnlTest.setLatestAuditSID(lastSerial++); break; case Journal: this.jnlTest.setLatestJournalSID(lastSerial++); break; case Log: this.jnlTest.setLatestLogSID(lastSerial++); break; } this.lastSerialFromRemote = SubscribeRequest.EPOC; this.journalOffset = 0; final JSONParser p = new JSONParser(); final File[] recordDirs = this.outputIpRoot.listFiles(SubscriberImpl.FILE_FILTER); if (this.lastConfirmedFile.length() > 0) { final JSONObject lastConfirmedJson = (JSONObject) p.parse(new FileReader(this.lastConfirmedFile)); this.lastSerialFromRemote = (String) lastConfirmedJson.get(LAST_CONFIRMED_SID); } final Set<File> deleteDirs = new HashSet<File>(); if (this.recordType == RecordType.Journal && recordDirs.length > 0) { // Checking the first record to see if it can be resumed, the rest will be deleted Arrays.sort(recordDirs); final List<File> sortedRecords = new ArrayList<File>(java.util.Arrays.asList(recordDirs)); final File firstRecord = sortedRecords.remove(0); deleteDirs.addAll(sortedRecords); JSONObject status; try { status = (JSONObject) p.parse(new FileReader(new File(firstRecord, STATUS_FILENAME))); final Number progress = (Number) status.get(PAYLOAD_PROGRESS); if (!CONFIRMED.equals(status.get(DGST_CONF)) && progress != null) { // journal record can be resumed this.lastSerialFromRemote = (String) status.get(REMOTE_SID); this.journalOffset = progress.longValue(); FileUtils.forceDelete(new File(firstRecord, APP_META_FILENAME)); FileUtils.forceDelete(new File(firstRecord, SYS_META_FILENAME)); status.remove(APP_META_PROGRESS); status.remove(SYS_META_PROGRESS); this.sid = SID_FORMATER.parse(firstRecord.getName()).longValue(); this.journalInputStream = new FileInputStream(new File(firstRecord, PAYLOAD_FILENAME)); } else { deleteDirs.add(firstRecord); } } catch (final FileNotFoundException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deleting " + firstRecord + ", because it is missing the '" + STATUS_FILENAME + "' file"); } deleteDirs.add(firstRecord); } catch (final ParseException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Deleting " + firstRecord + ", because failed to parse '" + STATUS_FILENAME + "' file"); } deleteDirs.add(firstRecord); } } else { // Any confirmed record should have been moved so deleting all that are left deleteDirs.addAll(java.util.Arrays.asList(recordDirs)); } for (final File f : deleteDirs) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Removing directory for unsynced record: " + f.getAbsolutePath()); } FileUtils.forceDelete(f); } }