Java Code Examples for org.json.simple.parser.JSONParser#parse()
The following examples show how to use
org.json.simple.parser.JSONParser#parse() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UIComponents.java From BedrockConnect with GNU General Public License v3.0 | 6 votes |
public static ArrayList<String> getFormData(String data) { JSONParser parser = new JSONParser(); // If no server data if(data == null) return new ArrayList<>(); try { JSONArray obj = (JSONArray) parser.parse(data); ArrayList<String> strings = new ArrayList<>(); for(int i=0;i<obj.size();i++) { strings.add(obj.get(i).toString()); } return strings; } catch(ParseException e) { System.out.println(e.toString()); } return null; }
Example 2
Source File: LibraryProvider.java From netbeans with Apache License 2.0 | 6 votes |
/** * Update a library returned by {@link #findLibraries(java.lang.String)}. * The full library data is fetched and the {@code versions} property is * filled. * * @param library to be updated */ public void updateLibraryVersions(Library library) { Objects.nonNull(library); if(library.getVersions() != null && library.getVersions().length > 0) { return; } Library cachedLibrary = getCachedLibrary(library.getName()); if(cachedLibrary != null) { library.setVersions(cachedLibrary.getVersions()); return; } String data = readUrl(getLibraryDataUrl(library.getName())); if(data != null) { try { JSONParser parser = new JSONParser(); JSONObject libraryData = (JSONObject)parser.parse(data); updateLibrary(library, libraryData); entryCache.put(library.getName(), new WeakReference<>(library)); } catch (ParseException ex) { Logger.getLogger(LibraryProvider.class.getName()).log(Level.INFO, null, ex); } } }
Example 3
Source File: ServerConnection.java From netbeans with Apache License 2.0 | 6 votes |
private void received(Listener listener, String tools, String message) throws ParseException, IOException { //System.out.println("RECEIVED: tools: '"+tools+"', message: '"+message+"'"); fireReceived(message); LOG.log(Level.FINE, "RECEIVED: {0}, {1}", new Object[]{tools, message}); if (message.isEmpty()) { return ; } JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(message, containerFactory); V8Request request = JSONReader.getRequest(obj); ResponseProvider rp = listener.request(request); if (V8Command.Disconnect.equals(request.getCommand())) { try { closeCurrentConnection(); } catch (IOException ioex) {} } if (rp != null) { rp.sendTo(this); } }
Example 4
Source File: LibraryProvider.java From netbeans with Apache License 2.0 | 6 votes |
/** * Parses the given JSON result of the search. * * @param data search result. * * @return libraries returned in the search result. */ Library[] parse(String data) { Library[] libraries = null; try { JSONParser parser = new JSONParser(); JSONObject searchResult = (JSONObject) parser.parse(data); JSONArray libraryArray = (JSONArray) searchResult.get(PROPERTY_RESULT); libraries = new Library[libraryArray.size()]; for (int i = 0; i < libraries.length; i++) { JSONObject libraryData = (JSONObject) libraryArray.get(i); libraries[i] = createLibrary(libraryData); } } catch (ParseException pex) { Logger.getLogger(LibraryProvider.class.getName()).log(Level.INFO, null, pex); } return libraries; }
Example 5
Source File: LoadoutPanel.java From Explvs-AIO with MIT License | 6 votes |
private Optional<URL> getIcon(final int itemID) { try { URL url = new URL("http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=" + itemID); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(bufferedReader); JSONObject itemJSON = (JSONObject) json.get("item"); String iconURL = (String) itemJSON.get("icon"); return Optional.of(new URL(iconURL)); } } catch (Exception e) { e.printStackTrace(); System.out.println("Failed to get icon from RuneScape api"); } return Optional.empty(); }
Example 6
Source File: LibraryProvider.java From netbeans with Apache License 2.0 | 6 votes |
/** * Load the full data for the supplied library. All fields are populated, * including the {@code versions} property. * * @param libraryName * @return */ public Library loadLibrary(String libraryName) { Library cachedLibrary = getCachedLibrary(libraryName); if(cachedLibrary != null) { return cachedLibrary; } String data = readUrl(getLibraryDataUrl(libraryName)); if (data != null) { try { JSONParser parser = new JSONParser(); JSONObject libraryData = (JSONObject) parser.parse(data); Library library = createLibrary(libraryData); entryCache.put(library.getName(), new WeakReference<>(library)); return library; } catch (ParseException ex) { Logger.getLogger(LibraryProvider.class.getName()).log(Level.INFO, null, ex); } } return null; }
Example 7
Source File: ParserASTJSON.java From soltix with Apache License 2.0 | 6 votes |
public AST parse(InputStream input) throws Exception { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject)jsonParser.parse( new InputStreamReader(input, "UTF-8")); AST ast = new AST(); if (!Configuration.skipASTProcessing) { // Process JSON object to build AST JSONObjectToAST(ast, jsonObject, 0); } else { // For debugging: only print, don't interpret printJSONObject(jsonObject, 0); } return ast; }
Example 8
Source File: DOMTest.java From netbeans with Apache License 2.0 | 5 votes |
/** * Test of {@code handleAttributeRemoved} method. */ @Test public void testHandleAttributeRemoved() throws ParseException { TransportImplementation transport = new DummyTransportImplementation(); DOM dom = new DOM(new TransportHelper(transport), null); final Node root = dom.getDocument(); final String ATTR_NAME = "class"; // NOI18N final int[] eventsFired = new int[1]; DOM.Listener listener = new DOMAdapter() { @Override public void attributeRemoved(Node node, String attrName) { eventsFired[0]++; assertEquals(ATTR_NAME, attrName); assertEquals(root, node); Node.Attribute attr = node.getAttribute(attrName); assertNull(attr); } }; dom.addListener(listener); JSONParser parser = new JSONParser(); // Modification of a known node Object json = parser.parse("{\"nodeId\":" + ROOT_NODE_ID + ",\"name\":\"" + ATTR_NAME + "\"}"); // NOI18N dom.handleAttributeRemoved((JSONObject)json); assertEquals(1, eventsFired[0]); // Modification of an unknown node json = parser.parse("{\"nodeId\":" + (ROOT_NODE_ID+1) + ",\"name\":\"someName\"}"); // NOI18N dom.handleAttributeRemoved((JSONObject)json); assertEquals(1, eventsFired[0]); }
Example 9
Source File: ReferenceTests.java From teku with Apache License 2.0 | 5 votes |
@MustBeClosed static Stream<Arguments> hashG2TestCases() { final JSONParser parser = new JSONParser(); final ArrayList<Arguments> argumentsList = new ArrayList<>(); try { final Reader reader = new FileReader(pathToHashG2Tests.toFile(), US_ASCII); final JSONObject refTests = (JSONObject) parser.parse(reader); final Bytes dst = Bytes.wrap(((String) refTests.get("dst")).getBytes(US_ASCII)); final JSONArray tests = (JSONArray) refTests.get("vectors"); int idx = 0; for (Object o : tests) { JSONObject test = (JSONObject) o; Bytes message = Bytes.wrap(((String) test.get("msg")).getBytes(US_ASCII)); JacobianPoint p = getPoint((JSONObject) test.get("P")); JacobianPoint q0 = getPoint((JSONObject) test.get("Q0")); JacobianPoint q1 = getPoint((JSONObject) test.get("Q1")); JSONArray uArray = (JSONArray) test.get("u"); FP2Immutable[] u = { getFieldPoint((String) uArray.get(0)), getFieldPoint((String) uArray.get(1)) }; argumentsList.add( Arguments.of(pathToExpandMessageTests.toString(), idx++, dst, message, u, q0, q1, p)); } } catch (IOException | ParseException e) { throw new RuntimeException(e); } return argumentsList.stream(); }
Example 10
Source File: RecipeMerger.java From Path-of-Leveling with MIT License | 5 votes |
private JSONObject parseFileAtPath(String path) { JSONParser parser = new JSONParser(); try { return (JSONObject) parser.parse(new FileReader(path)); } catch (IOException | ParseException e) { e.printStackTrace(); } return null; }
Example 11
Source File: EPLiteConnection.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Handle error condition and returns the parsed content * * @param jsonString a valid JSON string * @return Object */ protected Object handleResponse(String jsonString) { try { JSONParser parser = new JSONParser(); Map response = (Map) parser.parse(jsonString); // Act on the response code if (response.get("code") != null) { int code = ((Long) response.get("code")).intValue(); switch ( code ) { // Valid code, parse the response case CODE_OK: return response.get("data"); // Invalid code, throw an exception with the message case CODE_INVALID_PARAMETERS: case CODE_INTERNAL_ERROR: case CODE_INVALID_METHOD: case CODE_INVALID_API_KEY: throw new EPLiteException((String)response.get("message")); default: throw new EPLiteException("An unknown error has occurred while handling the response: " + jsonString); } // No response code, something's really wrong } else { throw new EPLiteException("An unexpected response from the server: " + jsonString); } } catch (ParseException e) { throw new EPLiteException("Unable to parse JSON response (" + jsonString + ")", e); } }
Example 12
Source File: JSONUtil.java From Indra with MIT License | 5 votes |
public static Map<String, Object> loadJSONAsMap(File file) { if (file.exists()) { try { JSONParser jsonParser = new JSONParser(); return (JSONObject) jsonParser.parse(new FileReader(file)); } catch (ParseException | IOException e) { throw new RuntimeException(e); } } return Collections.EMPTY_MAP; }
Example 13
Source File: DOMTest.java From netbeans with Apache License 2.0 | 5 votes |
/** * Test of {@code handleSetChildNodes} method. */ @Test public void testHandleSetChildNodes1() throws ParseException { TransportImplementation transport = new DummyTransportImplementation(); DOM dom = new DOM(new TransportHelper(transport), null); final Node root = dom.getDocument(); final int[] eventsFired = new int[1]; DOM.Listener listener = new DOMAdapter() { @Override public void childNodesSet(Node parent) { eventsFired[0]++; assertEquals(root, parent); List<Node> children = parent.getChildren(); assertNotNull(children); assertEquals(0, children.size()); } }; dom.addListener(listener); JSONParser parser = new JSONParser(); // Modification of a known node Object json = parser.parse("{\"parentId\":" + ROOT_NODE_ID + ",\"nodes\":[]}"); // NOI18N assertNull(root.getChildren()); dom.handleSetChildNodes((JSONObject)json); assertEquals(1, eventsFired[0]); // Modification of an unknown node json = parser.parse("{\"parentId\":" + (ROOT_NODE_ID+1) + ",\"nodes\":[]}"); // NOI18N dom.handleSetChildNodes((JSONObject)json); assertEquals(1, eventsFired[0]); }
Example 14
Source File: ODataTestUtils.java From micro-integrator with Apache License 2.0 | 5 votes |
public static String getETag(String content) throws ParseException, JSONException { JSONParser parser = new JSONParser(); Object obj = parser.parse(content); if (((JSONObject) obj).get("@odata.etag") != null) { return ((JSONObject) obj).get("@odata.etag").toString(); } else { return ((JSONObject) ((JSONArray) ((JSONObject) obj).get("value")).get(0)).get("@odata.etag").toString(); } }
Example 15
Source File: GDBootstrap.java From GriefDefender with MIT License | 4 votes |
@Override public void onEnable() { // check if reload if (instance != null) { instance = this; GriefDefenderPlugin.getInstance().onEnable(true); return; } instance = this; final JSONParser parser = new JSONParser(); String bukkitJsonVersion = null; this.getLogger().info("Loading libraries..."); if (Bukkit.getVersion().contains("1.8.8")) { bukkitJsonVersion = "1.8.8"; } else if (Bukkit.getVersion().contains("1.12.2")) { bukkitJsonVersion = "1.12.2"; } else if (Bukkit.getVersion().contains("1.13.2")) { bukkitJsonVersion = "1.13.2"; } else if (Bukkit.getVersion().contains("1.14.2")) { bukkitJsonVersion = "1.14.2"; } else if (Bukkit.getVersion().contains("1.14.3")) { bukkitJsonVersion = "1.14.3"; } else if (Bukkit.getVersion().contains("1.14.4")) { bukkitJsonVersion = "1.14.4"; } else if (Bukkit.getVersion().contains("1.15.2")) { bukkitJsonVersion = "1.15.2"; } else if (Bukkit.getVersion().contains("1.15")) { bukkitJsonVersion = "1.15"; } else if (Bukkit.getVersion().contains("1.16.1")) { bukkitJsonVersion = "1.16.1"; } else { this.getLogger().severe("Detected unsupported version '" + Bukkit.getVersion() + "'. GriefDefender only supports 1.8.8, 1.12.2, 1.13.2, 1.14.x, 1.15.0-1.15.2, 1.16.1. GriefDefender will NOT load."); return; } try { final InputStream in = getClass().getResourceAsStream("/" + bukkitJsonVersion + ".json"); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); final JSONObject a = (JSONObject) parser.parse(reader); final JSONArray libraries = (JSONArray) a.get("libraries"); if (libraries == null) { this.getLogger().severe("Resource " + bukkitJsonVersion + ".json is corrupted!. Please contact author for assistance."); return; } final Iterator<JSONObject> iterator = libraries.iterator(); while (iterator.hasNext()) { JSONObject lib = iterator.next(); final String name = (String) lib.get("name"); final String sha1 = (String) lib.get("sha1"); final String path = (String) lib.get("path"); final String relocate = (String) lib.get("relocate"); final String url = (String) lib.get("url"); final Path libPath = Paths.get(LIB_ROOT_PATH).resolve(path); final File file = libPath.toFile(); downloadLibrary(name, relocate, sha1, url, libPath); } } catch (Throwable t) { t.printStackTrace(); } // Inject jar-relocator and asm debug injectRelocatorDeps(); // Relocate all GD dependencies and inject GDRelocator.getInstance().relocateJars(this.jarMap); // Boot GD GriefDefenderPlugin.getInstance().onEnable(); }
Example 16
Source File: GDBootstrap.java From GriefDefender with MIT License | 4 votes |
@Listener(order = Order.LAST) public void onPreInit(GamePreInitializationEvent event) { instance = this; final JSONParser parser = new JSONParser(); String bukkitJsonVersion = null; this.getLogger().info("Loading libraries..."); final MinecraftVersion version = Sponge.getPlatform().getMinecraftVersion(); if (Sponge.getPlatform().getMinecraftVersion().getName().contains("1.12.2")) { bukkitJsonVersion = "1.12.2"; } else { this.getLogger().error("Detected unsupported version '" + version.getName() + "'. GriefDefender only supports 1.12.2 on Sponge. GriefDefender will NOT load."); return; } try { final InputStream in = getClass().getResourceAsStream("/" + bukkitJsonVersion + ".json"); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); final JSONObject a = (JSONObject) parser.parse(reader); final JSONArray libraries = (JSONArray) a.get("libraries"); if (libraries == null) { this.getLogger().error("Resource " + bukkitJsonVersion + ".json is corrupted!. Please contact author for assistance."); return; } final Path LIB_ROOT_PATH = instance.configPath.resolve("lib"); final Iterator<JSONObject> iterator = libraries.iterator(); while (iterator.hasNext()) { JSONObject lib = iterator.next(); final String name = (String) lib.get("name"); final String sha1 = (String) lib.get("sha1"); final String path = (String) lib.get("path"); final String relocate = (String) lib.get("relocate"); final String url = (String) lib.get("url"); final Path libPath = LIB_ROOT_PATH.resolve(path); downloadLibrary(name, relocate, sha1, url, libPath); } } catch (Throwable t) { t.printStackTrace(); } // Inject jar-relocator and asm debug injectRelocatorDeps(); // Relocate all GD dependencies and inject GDRelocator.getInstance().relocateJars(this.jarMap); // Boot GD GriefDefenderPlugin.getInstance().onPreInit(event, this.logger, this.configPath, this.pluginContainer); //Sponge.getEventManager().registerListeners(GriefDefenderPlugin.getInstance(), GriefDefenderPlugin.getInstance()); }
Example 17
Source File: DatasetUtil.java From BPR with Apache License 2.0 | 4 votes |
/** * Convert the original Yelp Challenge datasets into votes file. * Input file format example: * yelp_datasets/yelp_reviews_220K.json * Output file format: * A list of quadruple of form (userID, itemID, rating, time), followed by #words of the review, * followed by the words themselves (lower-cased). * See example of amazon_datasets/arts.votes * @param inputfileDir * @param dataset * @throws IOException * @throws ParseException * @throws java.text.ParseException */ public void ConvertJsonToVotesFile(String inputfileDir, String dataset) throws IOException, ParseException, java.text.ParseException { String inputfileName = inputfileDir + dataset + ".json"; String outputfileName = inputfileDir + dataset + ".votes"; System.out.println("\nConverting to .votes file: " + inputfileName); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputfileName))); PrintWriter writer = new PrintWriter (new FileOutputStream(outputfileName)); String line; JSONParser parser=new JSONParser(); int count = 0; while ((line = reader.readLine()) != null) { JSONObject obj = (JSONObject) parser.parse(line); String user_id = (String) obj.get("user_id"); String business_id = (String) obj.get("business_id"); String score = (Long) obj.get("stars") + ".0"; // Parse time to unix time. String date = (String) obj.get("date"); String time = date.replace("-", "") + "0800"; DateFormat dfm = new SimpleDateFormat("yyyyMMddHHmm"); Long unixtime = dfm.parse(time).getTime() / 1000; String review_text = (String) obj.get("text"); review_text = review_text.replace("|", " ").replace("\n", " "); // Parse review words. String[] review_words = parseSentence((String) obj.get("text")); String parse_review_text = ""; for (String review_word : review_words) { parse_review_text = parse_review_text + review_word.toLowerCase() + " "; } // Output to the .votes file. writer.println(user_id + " " + business_id + " " + score + " " + unixtime + " " + review_words.length + " " + parse_review_text); //writer.println(user_id + "|" + business_id + "|" + score + "|" + //unixtime + "|" + review_text); if (count++ % 10000 == 0) System.out.print("."); } System.out.println("#reviews: " + count); reader.close(); writer.close(); }
Example 18
Source File: SlackMetaDataExtension.java From syndesis with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public Optional<MetaData> meta(Map<String, Object> parameters) { final String token = ConnectorOptions.extractOption(parameters, "token"); if (token != null) { LOG.debug("Retrieving channels for connection to slack with token {}", token); HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); HttpPost httpPost = new HttpPost("https://slack.com/api/channels.list"); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("token", token)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(httpPost); String jsonString = readResponse(response); JSONParser parser = new JSONParser(); JSONObject c = (JSONObject) parser.parse(jsonString); List<Object> list = (List<Object>) c.get("channels"); Set<String> setChannels = new HashSet<String>(); Iterator<Object> it = list.iterator(); while (it.hasNext()) { Object object = it.next(); JSONObject singleChannel = (JSONObject) object; if (singleChannel.get("name") != null) { setChannels.add((String) singleChannel.get("name")); } } return Optional .of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain") .withAttribute(MetaData.JAVA_TYPE, String.class).withPayload(setChannels).build()); } catch (Exception e) { throw new IllegalStateException( "Get information about channels failed with token has failed.", e); } } else { return Optional.empty(); } }
Example 19
Source File: SpoofedTextContentReader.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * @param url a URL describing the type of text to produce (see class comments) */ public SpoofedTextContentReader(String url) { super(url); if (url.length() > 255) { throw new IllegalArgumentException("A content URL is limited to 255 characters: " + url); } // Split out data part int index = url.indexOf(ContentStore.PROTOCOL_DELIMITER); if (index <= 0 || !url.startsWith(FileContentStore.SPOOF_PROTOCOL)) { throw new RuntimeException("URL not supported by this reader: " + url); } String urlData = url.substring(index + 3, url.length()); // Parse URL try { JSONParser parser = new JSONParser(); JSONObject mappedData = (JSONObject) parser.parse(urlData); String jsonLocale = mappedData.containsKey(KEY_LOCALE) ? (String) mappedData.get(KEY_LOCALE) : Locale.ENGLISH.toString(); String jsonSeed = mappedData.containsKey(KEY_SEED) ? (String) mappedData.get(KEY_SEED) : "0"; String jsonSize = mappedData.containsKey(KEY_SIZE) ? (String) mappedData.get(KEY_SIZE) : "1024"; JSONArray jsonWords = mappedData.containsKey(KEY_WORDS) ? (JSONArray) mappedData.get(KEY_WORDS) : new JSONArray(); // Get the text generator Locale locale = new Locale(jsonLocale); seed = Long.valueOf(jsonSeed); size = Long.valueOf(jsonSize); words = new String[jsonWords.size()]; for (int i = 0; i < words.length; i++) { words[i] = (String) jsonWords.get(i); } this.textGenerator = SpoofedTextContentReader.getTextGenerator(locale); // Set the base class storage for external information super.setLocale(locale); super.setEncoding("UTF-8"); super.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); } catch (Exception e) { throw new RuntimeException("Unable to interpret URL: " + url, e); } }
Example 20
Source File: UtilsClustering.java From apogen with Apache License 2.0 | 2 votes |
/** * Modifies the Crawljax output accordingly to cluster information * * @throws ParseException * @throws IOException * @throws FileNotFoundException */ @SuppressWarnings("unchecked") public static void modifyCrawljaxResultAccordingToClusters() throws FileNotFoundException, IOException, ParseException { // open file JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader("output/resultAfterMerging.json")); JSONObject jsonResults = (JSONObject) obj; obj = parser.parse(new FileReader("output/cluster.json")); JSONObject jsonClusters = (JSONObject) obj; /* * TODO: foreach read slaves states from cluster.json remove it from * resultAfterMerging.json and remove/modify the related edges */ JSONObject allStates = (JSONObject) jsonResults.get("states"); JSONArray allEdges = (JSONArray) jsonResults.get("edges"); JSONArray allClusters = (JSONArray) jsonClusters.get("clusters"); System.out.println("[INFO] #edges before merging: " + allEdges.size()); allEdges = removeIntraClusterEdges(allEdges, allClusters); allEdges = modifyInterClusterEdges(allEdges, allClusters); System.out.println("[INFO] #edges after merging: " + allEdges.size()); // System.out.println("[INFO] #states before merging: " + allStates.size()); // allStates = removeStatesFromResultFile(allStates, allClusters); // System.out.println("[INFO] #states after merging: " + allStates.size()); JSONObject resultAfterMerging = new JSONObject(); resultAfterMerging.put("states", allStates); resultAfterMerging.put("edges", allEdges); ObjectMapper mapper = new ObjectMapper(); FileUtils.writeStringToFile(new File("output/resultAfterMerging.json"), mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultAfterMerging)); }