List of usage examples for org.json.simple JSONObject toJSONString
public String toJSONString()
From source file:com.example.networkPacketFormats.ServeFunction.java
public String traverseAndMakeJSON(String path) { System.out.println("DIRECTORY PATH IS :" + path); JSONObject obj = new JSONObject(); File f = new File(path); String dirPath = f.getAbsolutePath(); if (f.isDirectory()) { String[] subNote = f.list(); for (String filename : subNote) { String completePath = dirPath + "/" + filename; obj.put(filename, completePath); }/*from w w w . ja va 2s . c om*/ } else { System.out.println("Its not a directory!"); obj.put("Error fetching", "Error"); } return obj.toJSONString(); }
From source file:com.tresys.jalop.utils.jnltest.SubscriberImpl.java
/** * Write status information about a record out to disk. * @param file The {@link File} object to write to * @param toWrite The {@link JSONObject} that will be written to the file * @return <code>true</code> If the data was successfully written out. * <code>false</code> otherwise. *//*from ww w . j a v a 2s . c om*/ final boolean dumpStatus(final File file, final JSONObject toWrite) { BufferedOutputStream w; try { w = new BufferedOutputStream(new FileOutputStream(file)); w.write(toWrite.toJSONString().getBytes("utf-8")); w.close(); } catch (final FileNotFoundException e) { LOGGER.error("Failed to open file (" + file.getPath() + ") for writing:" + e.getMessage()); return false; } catch (final UnsupportedEncodingException e) { SubscriberImpl.LOGGER.error("cannot find UTF-8 encoder?"); return false; } catch (final IOException e) { LOGGER.error("failed to write to the file (" + file.getPath() + "), aborting"); return false; } return true; }
From source file:lv.semti.morphology.webservice.InflectPhraseResource.java
@Get public String retrieve() { String query = (String) getRequest().getAttributes().get("phrase"); try {//from w w w .ja v a 2 s. c o m query = URLDecoder.decode(query, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String category = getQuery().getValues("category"); MorphoServer.analyzer.enableGuessing = true; MorphoServer.analyzer.enableVocative = true; MorphoServer.analyzer.guessVerbs = false; MorphoServer.analyzer.guessParticiples = false; MorphoServer.analyzer.guessAdjectives = true; MorphoServer.analyzer.guessInflexibleNouns = true; MorphoServer.analyzer.enableAllGuesses = true; //MorphoServer.analyzer.describe(new PrintWriter(System.err)); JSONObject oInflections = new JSONObject(); Expression e = new Expression(query, category, true); // Pieemam, ka klients padod pamatformu //e.describe(new PrintWriter(System.err)); // ko tad tageris im ir sadom?jis Map<String, String> inflections = e.getInflections(); for (String i_case : inflections.keySet()) { oInflections.put(i_case, inflections.get(i_case).replaceAll("'", "''")); } if (e.category == Category.hum) { if (e.gender == Gender.masculine) oInflections.put(AttributeNames.i_Gender, AttributeNames.v_Masculine); if (e.gender == Gender.feminine) oInflections.put(AttributeNames.i_Gender, AttributeNames.v_Feminine); } MorphoServer.analyzer.defaultSettings(); return oInflections.toJSONString(); }
From source file:me.uni.sushilkumar.geodine.util.WhatsCooking.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request//from w ww .jav a2s . com * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); try { JSONObject obj = new JSONObject(); JSONArray array = new JSONArray(); DBConnection con = new DBConnection(); ArrayList<String> cuisineList = con.getCuisineList(); Random generator = new Random(); int size = cuisineList.size(); for (int i = 0; i < 10; i++) { JSONObject temp = new JSONObject(); String title = cuisineList.get(generator.nextInt(size)); //title=WordUtils.capitalize(title); temp.put("title", title); title = title.replaceAll("\\s+", "-"); String link = "cuisine/" + title; temp.put("link", link); array.add(temp); } obj.put("links", array); out.println(obj.toJSONString()); } catch (SQLException ex) { Logger.getLogger(WhatsCooking.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:be.iminds.aiolos.ui.ComponentServlet.java
@SuppressWarnings("unchecked") @Override/* w ww .java 2s .co m*/ protected void writeJSON(Writer w, Locale locale) throws IOException { Collection<ComponentDescription> components = getComponentsInfo(); final Object[] status = getStatusLine(components); final JSONObject obj = new JSONObject(); JSONArray stat = new JSONArray(); for (int i = 0; i < status.length; i++) stat.add(status[i]); obj.put("status", stat); final JSONArray list = new JSONArray(); for (ComponentDescription component : components) { JSONObject jsonComponent = new JSONObject(); jsonComponent.put("id", component.componentId); jsonComponent.put("version", component.version); JSONArray jsonNodes = new JSONArray(); jsonNodes.addAll(component.nodes); jsonComponent.put("nodes", jsonNodes); list.add(jsonComponent); } obj.put("components", list); w.write(obj.toJSONString()); }
From source file:importer.handler.post.stages.StageThreeXML.java
/** * Convert the corcode using the filter corresponding to its docid * @param pair the stil and its corresponding text - return result here * @param docID the docid of the document * @param enc the encoding/*from w w w.ja v a2s . co m*/ */ void convertCorcode(StandoffPair pair) { String[] parts = this.docid.split("/"); StringBuilder sb = new StringBuilder("mml.filters"); for (String part : parts) { if (part.length() > 0) { sb.append("."); sb.append(part); } } sb.append(".Filter"); String className = sb.toString(); Filter f = null; while (className.length() > "mml.filters".length()) { try { Class fClass = Class.forName(className); f = (Filter) fClass.newInstance(); break; } catch (Exception e) { System.out.println("no filter for " + className + " popping..."); className = popClassName(className); } } if (f != null) { System.out.println("Applying filter " + className + " to " + pair.vid); // woo hoo! we have a filter baby! try { JSONObject cc = (JSONObject) JSONValue.parse(pair.stil); // if ( pair.vid.equals("A") ) // { // printFile(pair.stil,"/tmp/A-stil.json"); // printFile(pair.text,"/tmp/A.txt"); // } cc = f.translate(cc, pair.text); pair.stil = cc.toJSONString(); pair.text = f.getText(); } catch (Exception e) { //OK it didn't work System.out.println("It failed for " + pair.vid + e.getMessage()); e.printStackTrace(System.out); } } else System.out.println("Couldn't find filter " + className + " for " + this.docid); }
From source file:com.nubits.nubot.RPC.NuRPCClient.java
private JSONObject invokeRPC(String id, String method, List params) { DefaultHttpClient httpclient = new DefaultHttpClient(); JSONObject json = new JSONObject(); json.put("id", id); json.put("method", method); if (null != params) { JSONArray array = new JSONArray(); array.addAll(params);/*ww w . j a v a2 s . co m*/ json.put("params", params); } JSONObject responseJsonObj = null; try { httpclient.getCredentialsProvider().setCredentials(new AuthScope(this.ip, this.port), new UsernamePasswordCredentials(this.rpcUsername, this.rpcPassword)); StringEntity myEntity = new StringEntity(json.toJSONString()); if (Global.options.verbose) { LOG.info("RPC : " + json.toString()); } HttpPost httppost = new HttpPost("http://" + this.ip + ":" + this.port); httppost.setEntity(myEntity); if (Global.options.verbose) { LOG.info("RPC executing request :" + httppost.getRequestLine()); } HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (Global.options.verbose) { LOG.info("RPC----------------------------------------"); LOG.info("" + response.getStatusLine()); if (entity != null) { LOG.info("RPC : Response content length: " + entity.getContentLength()); } } JSONParser parser = new JSONParser(); String entityString = EntityUtils.toString(entity); LOG.debug("Entity = " + entityString); /* TODO In case of wrong username/pass the response would be the following .Consider parsing it. Entity = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"> <HTML> <HEAD> <TITLE>Error</TITLE> <META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'> </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML> */ responseJsonObj = (JSONObject) parser.parse(entityString); } catch (ClientProtocolException e) { LOG.error("Nud RPC Connection problem:" + e.toString()); this.connected = false; } catch (IOException e) { LOG.error("Nud RPC Connection problem:" + e.toString()); this.connected = false; } catch (ParseException ex) { LOG.error("Nud RPC Connection problem:" + ex.toString()); this.connected = false; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return responseJsonObj; }
From source file:org.kitodo.data.index.elasticsearch.type.TaskType.java
@SuppressWarnings("unchecked") @Override//from ww w . j a v a2 s .c om public HttpEntity createDocument(Task task) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); LinkedHashMap<String, String> orderedTaskMap = new LinkedHashMap<>(); orderedTaskMap.put("title", task.getTitle()); String priority = task.getPriority() != null ? task.getPriority().toString() : "null"; orderedTaskMap.put("priority", priority); String ordering = task.getOrdering() != null ? task.getOrdering().toString() : "null"; orderedTaskMap.put("ordering", ordering); String processingStatus = task.getProcessingStatusEnum() != null ? task.getProcessingStatusEnum().toString() : "null"; orderedTaskMap.put("processingStatus", processingStatus); String processingTime = task.getProcessingTime() != null ? dateFormat.format(task.getProcessingTime()) : null; orderedTaskMap.put("processingTime", processingTime); String processingBegin = task.getProcessingBegin() != null ? dateFormat.format(task.getProcessingBegin()) : null; orderedTaskMap.put("processingBegin", processingBegin); String processingEnd = task.getProcessingEnd() != null ? dateFormat.format(task.getProcessingEnd()) : null; orderedTaskMap.put("processingEnd", processingEnd); orderedTaskMap.put("homeDirectory", String.valueOf(task.getHomeDirectory())); orderedTaskMap.put("typeMetadata", String.valueOf(task.isTypeMetadata())); orderedTaskMap.put("typeAutomatic", String.valueOf(task.isTypeAutomatic())); orderedTaskMap.put("typeImportFileUpload", String.valueOf(task.isTypeImportFileUpload())); orderedTaskMap.put("typeExportRussian", String.valueOf(task.isTypeExportRussian())); orderedTaskMap.put("typeImagesRead", String.valueOf(task.isTypeImagesRead())); orderedTaskMap.put("typeImagesWrite", String.valueOf(task.isTypeImagesWrite())); orderedTaskMap.put("batchStep", String.valueOf(task.isBatchStep())); String processingUser = task.getProcessingUser() != null ? task.getProcessingUser().getId().toString() : "null"; orderedTaskMap.put("processingUser", processingUser); String process = task.getProcess() != null ? task.getProcess().getId().toString() : "null"; orderedTaskMap.put("process", process); JSONObject taskObject = new JSONObject(orderedTaskMap); JSONArray users = new JSONArray(); List<User> taskUsers = task.getUsers(); for (User user : taskUsers) { JSONObject propertyObject = new JSONObject(); propertyObject.put("id", user.getId()); users.add(propertyObject); } taskObject.put("users", users); JSONArray userGroups = new JSONArray(); List<UserGroup> taskUserGroups = task.getUserGroups(); for (UserGroup userGroup : taskUserGroups) { JSONObject userGroupObject = new JSONObject(); userGroupObject.put("id", userGroup.getId().toString()); userGroups.add(userGroupObject); } taskObject.put("userGroups", userGroups); return new NStringEntity(taskObject.toJSONString(), ContentType.APPLICATION_JSON); }
From source file:edu.vt.vbi.patric.portlets.GenomeFinder.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String sraction = request.getParameter("sraction"); if (sraction != null) { if (sraction.equals("save_params")) { Map<String, String> key = new HashMap<>(); String genomeId = request.getParameter("genomeId"); String taxonId = request.getParameter("taxonId"); String cType = request.getParameter("cType"); String cId = request.getParameter("cId"); if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) { taxonId = cId;/* w w w . j a va2s . c o m*/ } String keyword = request.getParameter("keyword"); String state = request.getParameter("state"); String exact_search_term = request.getParameter("exact_search_term"); String search_on = request.getParameter("search_on"); if (genomeId != null && !genomeId.equals("")) { key.put("genomeId", genomeId); } if (taxonId != null && !taxonId.equals("")) { key.put("taxonId", taxonId); } if (keyword != null) { key.put("keyword", keyword.trim()); } if (state != null) { key.put("state", state); } if (exact_search_term != null) { key.put("exact_search_term", exact_search_term); } if (search_on != null) { key.put("search_on", search_on); } if (!key.containsKey("genomeId") && cType != null && cType.equals("genome") && cId != null && !cId.equals("")) { key.put("genomeId", cId); } if (!key.containsKey("taxonId") && cType != null && cType.equals("taxon") && cId != null && !cId.equals("")) { key.put("taxonId", cId); } long pk = (new Random()).nextLong(); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); PrintWriter writer = response.getWriter(); writer.write("" + pk); writer.close(); } else if (sraction.equals("get_params")) { String ret = ""; String pk = request.getParameter("pk"); String json = SessionHandler.getInstance().get(SessionHandler.PREFIX + pk); if (json != null) { Map<String, String> key = jsonReader.readValue(json); ret = key.get("keyword"); } PrintWriter writer = response.getWriter(); writer.write("" + ret); writer.close(); } } else { String need = request.getParameter("need"); JSONObject jsonResult = new JSONObject(); switch (need) { case "0": { // Getting Genome List String pk = request.getParameter("pk"); Map data = processGenomeTab(request); Map<String, String> key = (Map) data.get("key"); int numFound = (Integer) data.get("numFound"); List<Genome> records = (List<Genome>) data.get("genomes"); JSONArray docs = new JSONArray(); for (Genome item : records) { docs.add(item.toJSONObject()); } if (data.containsKey("facets")) { JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets")); key.put("facets", facets.toJSONString()); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); } jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "1": { // getting Genome Sequence List Map data = processSequenceTab(request); int numFound = (Integer) data.get("numFound"); List<GenomeSequence> sequences = (List<GenomeSequence>) data.get("sequences"); JSONArray docs = new JSONArray(); for (GenomeSequence item : sequences) { docs.add(item.toJSONObject()); } jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "tree": { String pk = request.getParameter("pk"); String state; Map<String, String> key = jsonReader .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); if (key.containsKey("state")) { state = key.get("state"); } else { state = request.getParameter("state"); } key.put("state", state); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); JSONArray tree = new JSONArray(); try { if (key.containsKey("facets") && !key.get("facets").isEmpty()) { JSONObject facet_fields = (JSONObject) (new JSONParser()).parse(key.get("facets")); DataApiHandler dataApi = new DataApiHandler(request); tree = FacetHelper.processStateAndTree(dataApi, SolrCore.GENOME, key, need, facet_fields, key.get("facet"), state, key.get("join"), 4); } } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } response.setContentType("application/json"); PrintWriter writer = response.getWriter(); tree.writeJSONString(writer); writer.close(); break; } case "tree_for_taxon": { // This is called by Taxon Overview page to faceted summary of genome under a specific taxa. String facet = request.getParameter("facet"); String keyword = request.getParameter("keyword"); Map<String, String> key = new HashMap<>(); key.put("keyword", keyword); DataApiHandler dataApi = new DataApiHandler(request); SolrQuery query = dataApi.buildSolrQuery(key, null, facet, 0, 0, false); // build solr query LOGGER.debug("tree_for_taxon: [{}] {}", SolrCore.GENOME.getSolrCoreName(), query.toString()); String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query); Map resp = jsonReader.readValue(apiResponse); JSONObject facet_fields = FacetHelper.formatFacetTree((Map) resp.get("facet_counts")); JSONArray tree = FacetHelper.processStateAndTree(dataApi, SolrCore.GENOME, key, need, facet_fields, facet, "", null, 4); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); tree.writeJSONString(writer); writer.close(); break; } case "getGenome": { // This is called by Genome Overview page to display genome metadata. DataApiHandler dataApi = new DataApiHandler(request); Genome genome = dataApi.getGenome(request.getParameter("id")); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); if (genome != null) { genome.toJSONObject().writeJSONString(writer); } writer.close(); break; } case "download": { List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); JSONArray tableSource = new JSONArray(); String fileName = "GenomeFinder"; String fileFormat = request.getParameter("fileformat"); // String _tablesource = request.getParameter("tablesource"); String aT = request.getParameter("aT"); switch (aT) { case "0": { // genome Map data = processGenomeTab(request); List<Genome> genomes = (List<Genome>) data.get("genomes"); for (Genome genome : genomes) { tableSource.add(genome.toJSONObject()); } tableHeader.addAll(DownloadHelper.getHeaderForGenomes()); tableField.addAll(DownloadHelper.getFieldsForGenomes()); break; } case "1": { // sequence Map data = processSequenceTab(request); List<GenomeSequence> sequences = (List<GenomeSequence>) data.get("sequences"); for (GenomeSequence sequence : sequences) { tableSource.add(sequence.toJSONObject()); } tableHeader.addAll(DownloadHelper.getHeaderForGenomeSequence()); tableField.addAll(DownloadHelper.getFieldsForGenomeSequence()); break; } } ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource); excel.buildSpreadsheet(); if (fileFormat.equalsIgnoreCase("xlsx")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); excel.writeSpreadsheettoBrowser(response.getPortletOutputStream()); } else if (fileFormat.equalsIgnoreCase("txt")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); response.getPortletOutputStream().write(excel.writeToTextFile().getBytes()); } } } } }
From source file:net.matthewauld.racetrack.server.WrSQL.java
@SuppressWarnings("unchecked") public String getJSONString(String query, String[] args) throws SQLException { connect();/* w w w . j av a 2s. c om*/ ps = con.prepareStatement(query); for (int i = 0; i < args.length; i++) { ps.setString(i + 1, args[i]); } rs = ps.executeQuery(); JSONObject json = new JSONObject(); JSONArray riders = new JSONArray(); while (rs.next()) { JSONObject riderJSON = new JSONObject(); riderJSON.put("id", rs.getInt("id")); riderJSON.put("first_name", rs.getString("first_name")); riderJSON.put("last_name", rs.getString("last_name")); riders.add(riderJSON); } if (riders.size() == 0) { json.put("riders", null); } else { json.put("riders", riders); } return json.toJSONString(); }