List of usage examples for org.json.simple.parser ParseException toString
public String toString()
From source file:JavaCloud.Utils.java
public static Object request(String address, String function, final JSONObject params) throws CoreException { try {/*from w w w . j a va2 s .c o m*/ GenericUrl url = new GenericUrl(address + "/" + function); NetHttpTransport transport = new NetHttpTransport(); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new HttpContent() { @Override public long getLength() throws IOException { return params.toString().length(); } @Override public String getType() { return "text/json"; } @Override public boolean retrySupported() { return false; } @Override public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(params.toString().getBytes()); } }); HttpResponse response = request.execute(); JSONParser parser = new JSONParser(); JSONObject object = (JSONObject) parser.parse(response.parseAsString()); if (!object.get("status").equals("ok")) { throw new CoreException(object.get("status").toString()); } if (object.containsKey("data") && object.get("data") != null) return parser.parse(object.get("data").toString()); else return null; } catch (ParseException e) { System.out.println("Error parsing response: " + e.toString()); throw new CoreException("json_malformed"); } catch (IOException e) { System.out.println("Error connecting to server: " + e.toString()); throw new CoreException("connection_failed"); } }
From source file:me.prokopyl.commandtools.migration.UUIDFetcher.java
static public Map<String, UUID> fetch(List<String> names) throws IOException { Map<String, UUID> uuidMap = new HashMap<String, UUID>(); HttpURLConnection connection = createConnection(); writeBody(connection, names);//from ww w. j ava2 s . c o m JSONArray array; try { array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); } catch (ParseException ex) { throw new IOException("Invalid response from server, unable to parse received JSON : " + ex.toString()); } for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); uuidMap.put(name, fromMojangUUID(id)); } return uuidMap; }
From source file:com.nubits.nubot.trading.wrappers.TradeUtilsCCEDK.java
public static String getCCDKEvalidNonce(String htmlString) { //used by ccedkqueryservice JSONParser parser = new JSONParser(); try {// w w w .j a va 2s. c o m //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"} JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONObject errors = (JSONObject) httpAnswerJson.get("errors"); String nonceError = (String) errors.get("nonce"); //String startStr = " must be from"; //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2; //String from = nonceError.substring(indexStart, indexStart + 10); String startStr2 = " till"; int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2; String to = nonceError.substring(indexStart2, indexStart2 + 10); //if (to.equals(from)) { // LOG.info("Detected ! " + to + " = " + from); // return "retry"; //} return to; } catch (ParseException ex) { LOG.error(htmlString + " " + ex.toString()); return "1234567891"; } }
From source file:com.nubits.nubot.trading.TradeUtils.java
public static String getCCDKEvalidNonce(String htmlString) { JSONParser parser = new JSONParser(); try {//from ww w .j a v a 2 s . c o m //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"} JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONObject errors = (JSONObject) httpAnswerJson.get("errors"); String nonceError = (String) errors.get("nonce"); //String startStr = " must be from"; //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2; //String from = nonceError.substring(indexStart, indexStart + 10); String startStr2 = " till"; int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2; String to = nonceError.substring(indexStart2, indexStart2 + 10); //if (to.equals(from)) { // LOG.info("Detected ! " + to + " = " + from); // return "retry"; //} return to; } catch (ParseException ex) { LOG.severe(htmlString + " " + ex.toString()); return "1234567891"; } }
From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java
/** * Fetches the original UUID of the given name. * * As example, let's say we have a Foo account with the UUID {@code 00000} renamed to Bar, and * another account with UUID {@code 11111} was renamed later to Foo. Calling this method with * {@code "Foo"} will return {@code 00000}. * * @param name The player's name.//from ww w.j a v a 2s. com * * @return An internal object containing the current player name and his UUID. * @throws IOException If an exception occurs while contacting the Mojang API. */ static private User fetchOriginalUUID(String name) throws IOException { HttpURLConnection connection = getGETConnection(TIMED_PROFILE_URL + name + "?at=" + NAME_CHANGE_TIMESTAMP); JSONObject object; try { object = (JSONObject) readResponse(connection); } catch (ParseException ex) { throw new IOException("Invalid response from server, unable to parse received JSON : " + ex.toString()); } if (object == null) return null; User user = new User(); user.name = name; user.uuid = fromMojangUUID((String) object.get("id")); return user; }
From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java
/** * Fetches the UUIDs of the given list of player names from the Mojang API with one request for * them all./*from w w w . j av a 2s.com*/ * * <p><b>WARNING: this method needs to be called from a dedicated thread, as the requests to * Mojang are executed directly in the current thread and, due to the Mojang API rate limit, the * thread may be frozen to wait a bit between requests if a lot of UUID are requested.</b></p> * * This method may not be able to retrieve UUIDs for some players with old accounts. For them, * use {@link #fetchRemaining(Collection, Map)}. * * @param names A list of player names. * * @return A map linking a player name to his Mojang {@link UUID}. * @throws IOException If an exception occurs while contacting the Mojang API. */ static private Map<String, UUID> rawFetch(List<String> names) throws IOException { Map<String, UUID> uuidMap = new HashMap<>(); HttpURLConnection connection = getPOSTConnection(PROFILE_URL); writeBody(connection, names); JSONArray array; try { array = (JSONArray) readResponse(connection); } catch (ParseException ex) { throw new IOException("Invalid response from server, unable to parse received JSON : " + ex.toString()); } if (array == null) return uuidMap; List<String> remainingNames = new ArrayList<String>(); remainingNames.addAll(names); for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; String foundName = (String) jsonProfile.get("name"); String name = null; for (String requestedName : remainingNames) { if (requestedName.equalsIgnoreCase(foundName)) { name = requestedName; break; } } if (name == null) { name = foundName; } else { remainingNames.remove(name); } String id = (String) jsonProfile.get("id"); uuidMap.put(name, fromMojangUUID(id)); } return uuidMap; }
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 ww w . j a v a2 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; }
From source file:com.nubits.nubot.options.OptionsJSON.java
public static JSONObject parseFiles(ArrayList<String> filePaths) { JSONObject optionsObject = new JSONObject(); Map setMap = new HashMap(); for (int i = 0; i < filePaths.size(); i++) { try {/*w ww . j a va2 s . com*/ JSONParser parser = new JSONParser(); JSONObject fileJSON = (JSONObject) (parser.parse(FileSystem.readFromFile(filePaths.get(i)))); JSONObject tempOptions = (JSONObject) fileJSON.get("options"); Set tempSet = tempOptions.entrySet(); for (Object o : tempSet) { Map.Entry entry = (Map.Entry) o; setMap.put(entry.getKey(), entry.getValue()); } } catch (ParseException ex) { LOG.severe("Parse exception \n" + ex.toString()); System.exit(0); } } JSONObject content = new JSONObject(setMap); optionsObject.put("options", content); return optionsObject; }
From source file:com.nubits.nubot.tests.TestAggregateOptions.java
private void aggregate() { Map setMap = new HashMap(); for (int i = 0; i < fileNames.size(); i++) { try {/*from www . j a va 2 s . c om*/ JSONParser parser = new JSONParser(); JSONObject fileJSON = (JSONObject) (parser.parse(FileSystem.readFromFile(fileNames.get(i)))); JSONObject tempOptions = (JSONObject) fileJSON.get("options"); Set tempSet = tempOptions.entrySet(); for (Object o : tempSet) { Entry entry = (Entry) o; setMap.put(entry.getKey(), entry.getValue()); } } catch (ParseException ex) { LOG.severe("Parse exception \n" + ex.toString()); System.exit(0); } } JSONObject optionsObject = new JSONObject(); optionsObject.put("options", setMap); }
From source file:edu.anu.spice.SpiceScorer.java
public void scoreBatch(SpiceArguments args) throws IOException, ScriptException { Stopwatch timer = Stopwatch.createStarted(); SpiceParser parser = new SpiceParser(args.cache, args.numThreads, args.synsets); // Build filters for tuple categories Map<String, TupleFilter> filters = new HashMap<String, TupleFilter>(); if (args.tupleSubsets) { filters.put("Object", TupleFilter.objectFilter); filters.put("Attribute", TupleFilter.attributeFilter); filters.put("Relation", TupleFilter.relationFilter); filters.put("Cardinality", TupleFilter.cardinalityFilter); filters.put("Color", TupleFilter.colorFilter); filters.put("Size", TupleFilter.sizeFilter); }//from ww w.j a v a 2s. co m // Parse test and refs from input file ArrayList<Object> image_ids = new ArrayList<Object>(); ArrayList<String> testCaptions = new ArrayList<String>(); ArrayList<String> refCaptions = new ArrayList<String>(); ArrayList<Integer> refChunks = new ArrayList<Integer>(); JSONParser json = new JSONParser(); JSONArray input; try { input = (JSONArray) json.parse(new FileReader(args.inputPath)); for (Object o : input) { JSONObject item = (JSONObject) o; image_ids.add(item.get("image_id")); testCaptions.add((String) item.get("test")); JSONArray refs = (JSONArray) item.get("refs"); refChunks.add(refs.size()); for (Object ref : refs) { refCaptions.add((String) ref); } } } catch (ParseException e) { System.err.println("Could not read input: " + args.inputPath); System.err.println(e.toString()); e.printStackTrace(); } System.err.println("Parsing reference captions"); List<SceneGraph> refSgs = parser.parseCaptions(refCaptions, refChunks); System.err.println("Parsing test captions"); List<SceneGraph> testSgs = parser.parseCaptions(testCaptions); this.stats = new SpiceStats(filters, args.detailed); for (int i = 0; i < testSgs.size(); ++i) { this.stats.score(image_ids.get(i), testSgs.get(i), refSgs.get(i), args.synsets); } if (!args.silent) { System.out.println(this.stats.toString()); } if (args.outputPath != null) { BufferedWriter outputWriter = new BufferedWriter(new FileWriter(args.outputPath)); // Pretty print output using javascript String jsonStringNoWhitespace = this.stats.toJSONString(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine scriptEngine = manager.getEngineByName("JavaScript"); scriptEngine.put("jsonString", jsonStringNoWhitespace); scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)"); String prettyPrintedJson = (String) scriptEngine.get("result"); outputWriter.write(prettyPrintedJson); outputWriter.close(); } System.out.println("SPICE evaluation took: " + timer.stop()); }