List of usage examples for org.json.simple JSONObject toJSONString
public String toJSONString()
From source file:it.polimi.logging.LogMessageUtils.java
/** * //from w w w . ja v a 2s.c o m * Costruisce un messaggio di log rappresentante un evento scatenato in seguito ad un * messaggio ricevuto * * @param id * @param sender * @param type * @param logType * @param eventType * @param status * @param timestamp * @return */ public static String buildEventLog(String id, String sender, Type type, String eventType, JSONObject status, long timestamp) { JSONObject msg = new JSONObject(); msg.put(JsonStrings.LOG_ID, id); msg.put(JsonStrings.SENDER, sender); msg.put(JsonStrings.ENTITY_TYPE, type.name()); msg.put(JsonStrings.LOG_TYPE, LogType.EVENT.name()); msg.put(JsonStrings.EVENT_TYPE, eventType); msg.put(JsonStrings.STATUS, status); msg.put(JsonStrings.TIMESTAMP, timestamp); return msg.toJSONString(); }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Parses the json, extracts the rules and deploy those rules into modsecurity. It takes the rule * string from the json and creates a rule file then copy it to modsecurity rule file folder. It alsp * restarts the modsecurity after deploying the rule * @param json reponses whether the rule is successfully deployed or not. *///from w w w . j av a 2s . c om @SuppressWarnings("unchecked") public static void onDeployMSRules(JSONObject json) { log.info("onDeployMSRules called.. : " + json.toJSONString()); MSConfig serviceCfg = MSConfig.getInstance(); JSONObject jsonResp = new JSONObject(); String ruleDirPath = serviceCfg.getConfigMap().get("RuleFileDir"); String ruleFileString = (String) json.get("ruleString"); String ruleFileName = ""; InputStream ins = null; FileOutputStream out = null; BufferedReader br = null; if (json.containsKey("groupName")) { ruleFileName += ((String) json.get("groupName")).toLowerCase() + ".conf"; } else { UUID randomName = UUID.randomUUID(); ruleFileName += randomName.toString() + ".conf"; } try { //modified string writing to modsecurity configurations log.info("Writing a rule to File :" + ruleFileName); File file = new File(ruleDirPath + "/" + ruleFileName); file.createNewFile(); out = new FileOutputStream(file); out.write(ruleFileString.getBytes()); out.close(); log.info("ModSecurity Rules Written ... "); //For Restarting modsecurity so that modified configuration can be applied JSONObject restartJson = new JSONObject(); restartJson.put("action", "restart"); String cmd = serviceCfg.getConfigMap().get("MSRestart"); String status = (String) executeShScript(cmd, restartJson).get("status"); //if rule file is giving syntax error while deploying rules on server end if (status.equals("1")) { if (file.delete()) { log.info("Successfully deleted conflicting file : " + file.getName()); executeShScript(cmd, restartJson); } else { log.info("unable to delete file : " + file.getName()); } jsonResp.put("action", "deployRules"); jsonResp.put("status", "1"); jsonResp.put("message", "Unable to deploy specified Rules. They either" + "conflicting to the already deployed rules"); } else { jsonResp.put("action", "deployRules"); jsonResp.put("status", "0"); jsonResp.put("message", "Rules Deployed!"); } } catch (FileNotFoundException e1) { jsonResp.put("action", "deployRules"); jsonResp.put("status", "1"); jsonResp.put("message", "Internal Service is down!"); e1.printStackTrace(); } catch (IOException | NullPointerException e) { jsonResp.put("action", "deployRules"); jsonResp.put("status", "0"); jsonResp.put("message", "Unable to create rule file on Server."); e.printStackTrace(); } log.info("Sending Json :" + jsonResp.toJSONString()); ConnectorService.getConnectorProducer().send(jsonResp.toJSONString()); jsonResp.clear(); }
From source file:io.github.casnix.spawnerdropper.SpawnerStack.java
public static boolean PutSpawnerIntoService(String spawnerType) { // Read ./SpawnerDropper.SpawnerStack.json into a string // get the value of JSON->{spawnerType} and add 1 to it. // Write file back to disk try {//from w ww. j a v a 2 s .co m // Read entire ./SpawnerDropper.SpawnerStack.json into a string String spawnerStack = new String( Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json"))); // get the value of JSON->{spawnerType} JSONParser parser = new JSONParser(); Object obj = parser.parse(spawnerStack); JSONObject jsonObj = (JSONObject) obj; long numberInService = (Long) jsonObj.get(spawnerType); if (numberInService < 0) { numberInService = 0; } // System.out.println("[SD DBG MSG] PSIS numberInServer("+numberInService+")"); numberInService += 1; jsonObj.put(spawnerType, new Long(numberInService)); FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json"); file.write(jsonObj.toJSONString()); file.flush(); file.close(); return true; } catch (ParseException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in PutSpawnerIntoService(String)"); e.printStackTrace(); return false; } catch (FileNotFoundException e) { Bukkit.getLogger() .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json"); e.printStackTrace(); return false; } catch (IOException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in PutSpawnerIntoService(String)"); e.printStackTrace(); return false; } }
From source file:model.Post_store.java
public static void add_post(String title, String content) { JSONObject obj = new JSONObject(); obj.put("title", title); obj.put("content", content); JSONArray comments = new JSONArray(); obj.put("comments", comments); JSONArray UA_comments = new JSONArray(); obj.put("UA_comments", UA_comments); int lastid = getlastid(); obj.put("id", lastid); try (FileWriter file = new FileWriter(root + "posts/" + lastid + ".json");) { file.write(obj.toJSONString()); file.flush();//from w w w . j a v a 2 s . c o m file.close(); } catch (IOException e) { System.out.println(e); } lastid++; setlastid(lastid); //System.out.print(obj); }
From source file:io.personium.test.jersey.box.odatacol.schema.property.PropertyUtils.java
/** * Property?./* w w w .j a v a 2 s .c o m*/ * @param token * @param cell ?? * @param box ?? * @param collection ?? * @param srcPropertyName ?Property?? * @param srcEntityTypeName ?EntityType?? * @param body * @return ? */ public static PersoniumResponse update(String token, String cell, String box, String collection, String srcPropertyName, String srcEntityTypeName, JSONObject body) { // PersoniumRequest req = PersoniumRequest .put(UrlUtils.property(cell, box, collection, srcPropertyName, srcEntityTypeName)); req.header(HttpHeaders.AUTHORIZATION, OAuth2Helper.Scheme.BEARER + " " + token); req.header(HttpHeaders.IF_MATCH, "*"); req.addStringBody(body.toJSONString()); // return AbstractCase.request(req); }
From source file:io.github.casnix.spawnerdropper.SpawnerStack.java
public static boolean TakeSpawnerOutOfService(String spawnerType) { // Read ./SpawnerDropper.SpawnerStack.json into a string // get the value of JSON->{spawnerType} and subtract 1 to it unless it is 0. // If it's zero, return false // Write file back to disk try {/*from w ww.j a va 2 s. co m*/ // Read entire ./SpawnerDropper.SpawnerStack.json into a string String spawnerStack = new String( Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json"))); // get the value of JSON->{spawnerType} JSONParser parser = new JSONParser(); Object obj = parser.parse(spawnerStack); JSONObject jsonObj = (JSONObject) obj; long numberInService = (Long) jsonObj.get(spawnerType); if (numberInService <= 0) { return false; } else { // System.out.println("[SD DBG MSG] TSOOS numberInServer("+numberInService+")"); numberInService -= 1; jsonObj.put(spawnerType, new Long(numberInService)); FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json"); file.write(jsonObj.toJSONString()); file.flush(); file.close(); return true; } } catch (ParseException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in TakeSpawnerOutOfService(String)"); e.printStackTrace(); return false; } catch (FileNotFoundException e) { Bukkit.getLogger() .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json"); e.printStackTrace(); return false; } catch (IOException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in TakeSpawnerOutOfService(String)"); e.printStackTrace(); return false; } }
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. *///from w ww .jav a 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:gessi.ossecos.graph.GraphModel.java
public static void IStarJsonToGraphFile(String iStarModel, String layout, String typeGraph) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(iStarModel); JSONArray jsonArrayNodes = (JSONArray) jsonObject.get("nodes"); JSONArray jsonArrayEdges = (JSONArray) jsonObject.get("edges"); String modelType = jsonObject.get("modelType").toString(); // System.out.println(modelType); // System.out.println(jsonArrayNodes.toJSONString()); // System.out.println(jsonArrayEdges.toJSONString()); System.out.println(jsonObject.toJSONString()); Hashtable<String, String> nodesHash = new Hashtable<String, String>(); Hashtable<String, String> boundaryHash = new Hashtable<String, String>(); Hashtable<String, Integer> countNodes = new Hashtable<String, Integer>(); ArrayList<String> boundaryItems = new ArrayList<String>(); ArrayList<String> actorItems = new ArrayList<String>(); GraphViz gv = new GraphViz(); gv.addln(gv.start_graph());/* ww w . ja v a2 s . c om*/ String nodeType; String nodeName; String nodeBoundary; for (int i = 0; i < jsonArrayNodes.size(); i++) { jsonObject = (JSONObject) jsonArrayNodes.get(i); nodeName = jsonObject.get("name").toString().replace(" ", "_"); // .replace("(", "").replace(")", ""); nodeName = nodeName.replaceAll("[\\W]|`[_]", ""); nodeType = jsonObject.get("elemenType").toString(); nodeBoundary = jsonObject.get("boundary").toString(); // TODO: Verify type of diagram // if (!nodeType.equals("actor") & !nodeBoundary.equals("boundary")) // { if (countNodes.get(nodeName) == null) { countNodes.put(nodeName, 0); } else { countNodes.put(nodeName, countNodes.get(nodeName) + 1); nodeName += "_" + countNodes.put(nodeName, 0); } gv.addln(renderNode(nodeName, nodeType)); // } nodesHash.put(jsonObject.get("id").toString(), nodeName); boundaryHash.put(jsonObject.get("id").toString(), nodeBoundary); if (nodeType.equals("actor")) { actorItems.add(nodeName); } } String edgeType = ""; String source = ""; String target = ""; String edgeSubType = ""; int subgraphCount = 0; boolean hasCluster = false; nodeBoundary = "na"; String idSource; String idTarget; for (int i = 0; i < jsonArrayEdges.size(); i++) { jsonObject = (JSONObject) jsonArrayEdges.get(i); edgeSubType = jsonObject.get("linksubtype").toString(); edgeType = renderEdge(edgeSubType, jsonObject.get("linktype").toString()); idSource = jsonObject.get("source").toString(); idTarget = jsonObject.get("target").toString(); source = nodesHash.get(idSource); target = nodesHash.get(idTarget); if (!boundaryHash.get(idSource).toString().equals("boundary") && !boundaryHash.get(idTarget).toString().equals("boundary")) { if (!boundaryHash.get(idSource).toString().equals(nodeBoundary)) { nodeBoundary = boundaryHash.get(idSource).toString(); if (hasCluster) { gv.addln(gv.end_subgraph()); hasCluster = false; } else { hasCluster = true; } gv.addln(gv.start_subgraph(subgraphCount)); gv.addln(actorItems.get(subgraphCount++)); gv.addln("style=filled;"); gv.addln("color=lightgrey;"); } gv.addln(source + "->" + target + edgeType); } else { boundaryItems.add(source + "->" + target + edgeType); } } if (subgraphCount > 0) { gv.addln(gv.end_subgraph()); } for (String boundaryE : boundaryItems) { gv.addln(boundaryE); } gv.addln(gv.end_graph()); String type = typeGraph; // String type = "dot"; // String type = "fig"; // open with xfig // String type = "pdf"; // String type = "ps"; // String type = "svg"; // open with inkscape // String type = "png"; // String type = "plain"; String repesentationType = layout; // String repesentationType= "neato"; // String repesentationType= "fdp"; // String repesentationType= "sfdp"; // String repesentationType= "twopi"; // String repesentationType= "circo"; // //File out = new File("/tmp/out"+gv.getImageDpi()+"."+ type); // // Linux File out = new File("Examples/out." + type); // Windows gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type, repesentationType), out); }
From source file:com.nubits.nubot.launch.NuBot.java
private static void createShutDownHook() { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override//w ww . j av a2 s . c om public void run() { LOG.info("Bot shutting down.."); if (Global.options != null) { //Try to cancel all orders, if any if (Global.exchange.getTrade() != null && Global.options.getPair() != null) { LOG.info("Clearing out active orders ... "); ApiResponse deleteOrdersResponse = Global.exchange.getTrade() .clearOrders(Global.options.getPair()); if (deleteOrdersResponse.isPositive()) { boolean deleted = (boolean) deleteOrdersResponse.getResponseObject(); if (deleted) { LOG.info("Order clear request succesfully"); } else { LOG.severe("Could not submit request to clear orders"); } } else { LOG.severe(deleteOrdersResponse.getError().toString()); } } //reset liquidity info if (Global.rpcClient.isConnected() && Global.options.isSendRPC()) { //tier 1 LOG.info("Resetting Liquidity Info before quit"); JSONObject responseObject1 = Global.rpcClient.submitLiquidityInfo(Global.rpcClient.USDchar, 0, 0, 1); if (null == responseObject1) { LOG.severe("Something went wrong while sending liquidityinfo"); } else { LOG.fine(responseObject1.toJSONString()); } JSONObject responseObject2 = Global.rpcClient.submitLiquidityInfo(Global.rpcClient.USDchar, 0, 0, 2); if (null == responseObject2) { LOG.severe("Something went wrong while sending liquidityinfo"); } else { LOG.fine(responseObject2.toJSONString()); } } LOG.info("Exit. "); NuBot.mainThread.interrupt(); if (Global.taskManager != null) { if (Global.taskManager.isInitialized()) { Global.taskManager.stopAll(); } } } Thread.currentThread().interrupt(); return; } })); }
From source file:com.aerospike.load.Parser.java
/** * Process column definitions in JSON formated file and create two lists for metadata and bindata and one list for metadataLoader * @param file Config file name//from w w w . ja va 2 s . c o m * @param metadataLoader Map of metadata for loader to use, given in config file * @param metadataColumnDefs List of column definitions for metadata of bins like key,set * @param binColumnDefs List of column definitions for bins * @param params User given parameters * @throws ParseException * @throws IOException */ public static boolean processJSONColumnDefinitions(File file, HashMap<String, String> metadataConfigs, List<ColumnDefinition> metadataColumnDefs, List<ColumnDefinition> binColumnDefs, Parameters params) { boolean processConfig = false; if (params.verbose) { log.setLevel(Level.DEBUG); } try { // Create parser object JSONParser jsonParser = new JSONParser(); // Read the json config file Object obj; obj = jsonParser.parse(new FileReader(file)); JSONObject jobj; // Check config file contains metadata for datafile if (obj == null) { log.error("Empty config File"); return processConfig; } else { jobj = (JSONObject) obj; log.debug("Config file contents:" + jobj.toJSONString()); } // Get meta data of loader // Search for input_type if ((obj = getJsonObject(jobj, Constants.VERSION)) != null) { metadataConfigs.put(Constants.VERSION, obj.toString()); } else { log.error("\"" + Constants.VERSION + "\" Key is missing in config file"); return processConfig; } if ((obj = getJsonObject(jobj, Constants.INPUT_TYPE)) != null) { // Found input_type, check for csv if (obj instanceof String && obj.toString().equals(Constants.CSV_FILE)) { // Found csv format metadataConfigs.put(Constants.INPUT_TYPE, obj.toString()); // Search for csv_style if ((obj = getJsonObject(jobj, Constants.CSV_STYLE)) != null) { // Found csv_style JSONObject cobj = (JSONObject) obj; // Number_Of_Columns in data file if ((obj = getJsonObject(cobj, Constants.COLUMNS)) != null) { metadataConfigs.put(Constants.COLUMNS, obj.toString()); } else { log.error("\"" + Constants.COLUMNS + "\" Key is missing in config file"); return processConfig; } // Delimiter for parsing data file if ((obj = getJsonObject(cobj, Constants.DELIMITER)) != null) metadataConfigs.put(Constants.DELIMITER, obj.toString()); // Skip first row of data file if it contains column names if ((obj = getJsonObject(cobj, Constants.IGNORE_FIRST_LINE)) != null) metadataConfigs.put(Constants.IGNORE_FIRST_LINE, obj.toString()); } else { log.error("\"" + Constants.CSV_STYLE + "\" Key is missing in config file"); return processConfig; } } else { log.error("\"" + obj.toString() + "\" file format is not supported in config file"); return processConfig; } } else { log.error("\"" + Constants.INPUT_TYPE + "\" Key is missing in config file"); return processConfig; } // Get metadata of records // Get key definition of records if ((obj = getJsonObject(jobj, Constants.KEY)) != null) { metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.KEY)); } else { log.error("\"" + Constants.KEY + "\" Key is missing in config file"); return processConfig; } // Get set definition of records. Optional because we can get "set" name from user. if ((obj = getJsonObject(jobj, Constants.SET)) != null) { if (obj instanceof String) { metadataColumnDefs.add(new ColumnDefinition(Constants.SET, obj.toString(), true, true, "string", "string", null, -1, -1, null, null)); } else { metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.SET)); } } // Get bin column definitions JSONArray binList; if ((obj = getJsonObject(jobj, Constants.BINLIST)) != null) { // iterator for bins binList = (JSONArray) obj; Iterator<?> i = binList.iterator(); // take each bin from the JSON array separately while (i.hasNext()) { JSONObject binObj = (JSONObject) i.next(); binColumnDefs.add(getColumnDefs(binObj, Constants.BINLIST)); } } else { return processConfig; } log.info(String.format("Number of columns: %d(metadata) + %d(bins)", (metadataColumnDefs.size()), binColumnDefs.size())); processConfig = true; } catch (IOException ie) { log.error("File:" + Utils.getFileName(file.getName()) + " Config i/o Error: " + ie.toString()); if (log.isDebugEnabled()) { ie.printStackTrace(); } } catch (ParseException pe) { log.error("File:" + Utils.getFileName(file.getName()) + " Config parsing Error: " + pe.toString()); if (log.isDebugEnabled()) { pe.printStackTrace(); } } catch (Exception e) { log.error("File:" + Utils.getFileName(file.getName()) + " Config unknown Error: " + e.toString()); if (log.isDebugEnabled()) { e.printStackTrace(); } } return processConfig; }