List of usage examples for org.json.simple JSONObject put
V put(K key, V value);
From source file:anotadorderelacoes.model.UtilidadesPacotes.java
/** * Converte um arquivo de texto puro para o formato JSON aceito pela ARS. * O arquivo de texto deve conter uma sentena por linha. * * @param arquivoTexto Arquivo de texto puro * @param arquivoSaida Arquivo de texto convertido para o formato JSON */// w ww.ja v a2 s .c om public static void converterTextoJson(File arquivoTexto, File arquivoSaida) { BufferedReader br; BufferedWriter bw; String linha; int contadorSentencas = 1; try { //br = new BufferedReader( new FileReader( arquivoTexto ) ); br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivoTexto), "UTF-8")); //bw = new BufferedWriter( new FileWriter( arquivoSaida ) ); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(arquivoSaida), "UTF-8")); bw.write("# Arquivo \"" + arquivoTexto.getName() + "\" convertido para o formato JSON\n"); bw.write("===\n"); // Uma sentena por linha while ((linha = br.readLine()) != null) { JSONObject sentenca = new JSONObject(); JSONArray tokens = new JSONArray(); sentenca.put("id", contadorSentencas++); sentenca.put("texto", linha); sentenca.put("comentarios", ""); sentenca.put("termos", new JSONArray()); sentenca.put("relacoes", new JSONArray()); sentenca.put("anotadores", new JSONArray()); sentenca.put("anotada", false); sentenca.put("ignorada", false); // Separao simples de tokens for (String token : linha.split(" ")) tokens.add(novoToken(token, token, null, null)); sentenca.put("tokens", tokens); bw.write(sentenca.toString() + "\n"); } bw.close(); br.close(); Logger.getLogger("ARS logger").log(Level.INFO, "Arquivo JSON \"{0}\" gravado.", arquivoSaida.getAbsolutePath()); } catch (FileNotFoundException ex) { Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex); } }
From source file:com.codelanx.codelanxlib.logging.Debugger.java
/** * Returns a JSON payload containing as much relevant server information as * possible (barring anything identifiable) and the error itself * //w w w. jav a 2s. c o m * @since 0.1.0 * @version 0.1.0 * * @param opts The {@link DebugOpts} relevant to the current plugin context * @param error The {@link Throwable} to report * @param message The message relevant to the error * @return A new {@link JSONObject} payload */ private static JSONObject getPayload(DebugOpts opts, Throwable error, String message) { JSONObject back = new JSONObject(); back.put("project-type", "bukkit-plugin"); JSONObject plugin = new JSONObject(); PluginDescriptionFile pd = opts.getPlugin().getDescription(); plugin.put("name", pd.getName()); plugin.put("version", pd.getVersion()); plugin.put("main", pd.getMain()); plugin.put("prefix", opts.getPrefix()); back.put("plugin", plugin); JSONObject server = new JSONObject(); Server s = Bukkit.getServer(); server.put("allow-end", s.getAllowEnd()); server.put("allow-flight", s.getAllowFlight()); server.put("allow-nether", s.getAllowNether()); server.put("ambient-spawn-limit", s.getAmbientSpawnLimit()); server.put("animal-spawn-limit", s.getAnimalSpawnLimit()); server.put("binding-address", s.getIp()); server.put("bukkit-version", s.getBukkitVersion()); server.put("connection-throttle", s.getConnectionThrottle()); server.put("default-game-mode", s.getDefaultGameMode().name()); server.put("default-world-type", s.getWorldType()); server.put("generate-structures", s.getGenerateStructures()); server.put("idle-timeout", s.getIdleTimeout()); server.put("players-online", s.getOnlinePlayers().size()); server.put("max-players", s.getMaxPlayers()); server.put("monster-spawn-limit", s.getMonsterSpawnLimit()); server.put("motd", s.getMotd()); server.put("name", s.getName()); server.put("online-mode", s.getOnlineMode()); server.put("port", s.getPort()); server.put("server-id", s.getServerId()); server.put("server-name", s.getServerName()); server.put("spawn-radius", s.getSpawnRadius()); server.put("ticks-per-animal-spawns", s.getTicksPerAnimalSpawns()); server.put("ticks-per-monster-spawns", s.getTicksPerMonsterSpawns()); server.put("version", s.getVersion()); server.put("view-distance", s.getViewDistance()); server.put("warning-state", s.getWarningState()); server.put("water-animal-spawn-limit", s.getWaterAnimalSpawnLimit()); back.put("server", server); JSONObject system = new JSONObject(); system.put("name", System.getProperty("os.name")); system.put("version", System.getProperty("os.version")); system.put("arch", System.getProperty("os.arch")); back.put("system", system); JSONObject java = new JSONObject(); java.put("version", System.getProperty("java.version")); java.put("vendor", System.getProperty("java.vendor")); java.put("vendor-url", System.getProperty("java.vendor.url")); java.put("bit", System.getProperty("sun.arch.data.model")); back.put("java", java); back.put("message", message); back.put("error", Exceptions.readableStackTrace(error)); return back; }
From source file:hoot.services.controllers.job.JobResource.java
private static JSONObject createChildInfo(String id, String stat) { JSONObject child = new JSONObject(); child.put("id", id); child.put("status", stat); return child; }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Starts the modsecurity instance if not running. * @param json //from ww w . j av a2 s . co m */ @SuppressWarnings("unchecked") public static void onStartRequest(JSONObject json) { log.info("onStartRequest called.. : " + json.toJSONString()); MSConfig config = MSConfig.getInstance(); String cmd = config.getConfigMap().get("MSStart"); JSONObject resp = executeShScript(cmd, json); if (((String) resp.get("status")).equals("0")) { resp.put("message", "Modsecuity Sucessfully Started"); } log.info("Sending Json :" + resp.toJSONString()); ConnectorService.getConnectorProducer().send(resp.toJSONString()); resp.clear(); }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Stops the modsecurity instance if not stopped before. * @param json/* w w w .j a v a 2 s . c o m*/ */ @SuppressWarnings("unchecked") public static void onStopRequest(JSONObject json) { log.info("onStopRequest called.. : " + json.toJSONString()); MSConfig config = MSConfig.getInstance(); String cmd = config.getConfigMap().get("MSStop"); JSONObject resp = executeShScript(cmd, json); if (((String) resp.get("status")).equals("0")) { resp.put("message", "Modsecuity Sucessfully Stoped"); } log.info("Sending Json :" + resp.toJSONString()); ConnectorService.getConnectorProducer().send(resp.toJSONString()); resp.clear(); }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Restarts the instance.//from www.j av a2 s .c o m * @param json */ @SuppressWarnings("unchecked") public static void onRestartRequest(JSONObject json) { log.info("onRestartRequest called.. : " + json.toJSONString()); MSConfig config = MSConfig.getInstance(); String cmd = config.getConfigMap().get("MSRestart"); JSONObject resp = executeShScript(cmd, json); if (((String) resp.get("status")).equals("0")) { resp.put("message", "Modsecuity Sucessfully Restarted"); } log.info("Sending Json :" + resp.toJSONString()); ConnectorService.getConnectorProducer().send(resp.toJSONString()); resp.clear(); }
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 a v a2 s. 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:net.sourceforge.fenixedu.webServices.jersey.services.JerseyServices.java
protected static String getRegistrationsAsJSON(Set<Registration> registrations) { JSONArray infos = new JSONArray(); int i = 0;/*from w w w .j av a 2s .c om*/ for (Registration registration : registrations) { JSONObject studentInfoForJobBank = new JSONObject(); studentInfoForJobBank.put("username", registration.getPerson().getUsername()); studentInfoForJobBank.put("hasPersonalDataAuthorization", registration.getStudent().hasPersonalDataAuthorizationForProfessionalPurposesAt().toString()); Person person = registration.getStudent().getPerson(); studentInfoForJobBank.put("dateOfBirth", person.getDateOfBirthYearMonthDay() == null ? null : person.getDateOfBirthYearMonthDay().toString()); studentInfoForJobBank.put("nationality", person.getCountry() == null ? null : person.getCountry().getName()); PhysicalAddress defaultPhysicalAddress = person.getDefaultPhysicalAddress(); studentInfoForJobBank.put("address", defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getAddress()); studentInfoForJobBank.put("area", defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getArea()); studentInfoForJobBank.put("areaCode", defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getAreaCode()); studentInfoForJobBank.put("districtSubdivisionOfResidence", defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getDistrictSubdivisionOfResidence()); studentInfoForJobBank.put("mobilePhone", person.getDefaultMobilePhoneNumber()); studentInfoForJobBank.put("phone", person.getDefaultPhoneNumber()); studentInfoForJobBank.put("email", person.getEmailForSendingEmails()); studentInfoForJobBank.put("remoteRegistrationOID", registration.getExternalId()); studentInfoForJobBank.put("number", registration.getNumber().toString()); studentInfoForJobBank.put("degreeOID", registration.getDegree().getExternalId()); studentInfoForJobBank.put("isConcluded", String.valueOf(registration.isRegistrationConclusionProcessed())); studentInfoForJobBank.put("curricularYear", String.valueOf(registration.getCurricularYear())); for (CycleCurriculumGroup cycleCurriculumGroup : registration.getLastStudentCurricularPlan() .getCycleCurriculumGroups()) { studentInfoForJobBank.put(cycleCurriculumGroup.getCycleType().name(), cycleCurriculumGroup.getAverage().toString()); } infos.add(studentInfoForJobBank); } return infos.toJSONString(); }
From source file:net.sourceforge.fenixedu.webServices.jersey.services.JerseyServices.java
@SuppressWarnings("unchecked") protected static JSONObject getStudentInfoForJobBank(Registration registration) { try {/*from www .j a v a2 s . com*/ JSONObject studentInfoForJobBank = new JSONObject(); studentInfoForJobBank.put("username", registration.getPerson().getUsername()); studentInfoForJobBank.put("hasPersonalDataAuthorization", registration.getStudent().hasPersonalDataAuthorizationForProfessionalPurposesAt().toString()); Person person = registration.getStudent().getPerson(); studentInfoForJobBank.put("dateOfBirth", person.getDateOfBirthYearMonthDay() == null ? null : person.getDateOfBirthYearMonthDay().toString()); studentInfoForJobBank.put("nationality", person.getCountry() == null ? null : person.getCountry().getName()); studentInfoForJobBank.put("address", person.getDefaultPhysicalAddress() == null ? null : person.getDefaultPhysicalAddress().getAddress()); studentInfoForJobBank.put("area", person.getDefaultPhysicalAddress() == null ? null : person.getDefaultPhysicalAddress().getArea()); studentInfoForJobBank.put("areaCode", person.getDefaultPhysicalAddress() == null ? null : person.getDefaultPhysicalAddress().getAreaCode()); studentInfoForJobBank.put("districtSubdivisionOfResidence", person.getDefaultPhysicalAddress() == null ? null : person.getDefaultPhysicalAddress().getDistrictSubdivisionOfResidence()); studentInfoForJobBank.put("mobilePhone", person.getDefaultMobilePhoneNumber()); studentInfoForJobBank.put("phone", person.getDefaultPhoneNumber()); studentInfoForJobBank.put("email", person.getEmailForSendingEmails()); studentInfoForJobBank.put("remoteRegistrationOID", registration.getExternalId()); studentInfoForJobBank.put("number", registration.getNumber().toString()); studentInfoForJobBank.put("degreeOID", registration.getDegree().getExternalId()); studentInfoForJobBank.put("isConcluded", String.valueOf(registration.isRegistrationConclusionProcessed())); studentInfoForJobBank.put("curricularYear", String.valueOf(registration.getCurricularYear())); for (CycleType cycleType : registration.getDegreeType().getCycleTypes()) { CycleCurriculumGroup cycle = registration.getLastStudentCurricularPlan().getCycle(cycleType); if (cycle != null) { studentInfoForJobBank.put(cycle.getCycleType().name(), cycle.getAverage().toString()); } } return studentInfoForJobBank; } catch (Throwable e) { throw new Error(e); } }
From source file:com.fujitsu.dc.test.utils.CellUtils.java
/** * event?POST?.// w w w . j a v a2 s. c o m * @param authorization Authorization?(auth-shema?) * @param code ? * @param cellName ?? * @param level * @param action ? * @param object ? * @param result ?? * @return ? */ @SuppressWarnings("unchecked") public static TResponse eventWithAnyAuthSchema(String authorization, int code, String cellName, String level, String action, String object, String result) { JSONObject body = new JSONObject(); body.put("level", level); body.put("action", action); body.put("object", object); body.put("result", result); return Http.request("cell/cell-event-anyAuthSchema.txt").with("METHOD", HttpMethod.POST) .with("authorization", authorization).with("cellPath", cellName).with("requestKey", "") .with("json", body.toJSONString()).returns().statusCode(code); }