List of usage examples for org.json.simple.parser ParseException printStackTrace
public void printStackTrace()
From source file:com.turt2live.xmail.api.Attachments.java
/** * Attempts to get an attachment from a JSON string. This will throw an IllegalArgumentException if * the json string is null or invalid.//from w ww . j av a 2 s. co m * * @param json the JSON string * * @return the attachment, or an UnknownAttachment if no match */ @SuppressWarnings("unchecked") public static Attachment getAttachment(String json) { if (json == null) { throw new IllegalArgumentException(); } JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { @Override public List<Object> creatArrayContainer() { return new LinkedList<Object>(); } @Override public Map<String, Object> createObjectContainer() { return new LinkedHashMap<String, Object>(); } }; Map<String, Object> map = new HashMap<String, Object>(); try { Map<?, ?> json1 = (Map<?, ?>) parser.parse(json, containerFactory); Iterator<?> iter = json1.entrySet().iterator(); // Type check while (iter.hasNext()) { Entry<?, ?> entry = (Entry<?, ?>) iter.next(); if (!(entry.getKey() instanceof String)) { throw new IllegalArgumentException("Not in <String, Object> format"); } } map = (Map<String, Object>) json1; } catch (ParseException e) { e.printStackTrace(); return null; } catch (IllegalArgumentException e) { e.printStackTrace(); return null; } XMail plugin = XMail.getInstance(); Attachment a = plugin.getMailServer().attemptAttachmentDecode(map); if (a != null) { return a; } a = plugin.getAttachmentHandlerRegistry().getAttachmentFromHandler(json); return a == null ? new UnknownAttachment(json) : a; }
From source file:models.Snack.java
public static ArrayList getsnackList() throws IOException { ArrayList<Snack> snackList = new ArrayList(); try {// ww w .j a v a 2s.c o m InputStream input = new URL(url).openStream(); String genreJson = IOUtils.toString(input); JSONParser parser = new JSONParser(); JSONArray tileJson = (JSONArray) parser.parse(genreJson); for (Object object : tileJson) { JSONObject aJson = (JSONObject) object; long id = (Long) aJson.get("id"); String name = (String) aJson.get("name"); boolean opt = (Boolean) aJson.get("optional"); String loc = (String) aJson.get("purchaseLocations"); long count = (Long) aJson.get("purchaseCount"); String date = (String) aJson.get("lastPurchaseDate"); JSONArray imgSize = (JSONArray) aJson.get("size"); snackList.add(new Snack(id, name, opt, loc, count, date)); } } catch (ParseException e) { e.printStackTrace(); } return snackList; }
From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsLocalSchemaExtractor.java
/**** * This function counts the total occurrences of keys, in the json records files * // w w w. j a va 2s.c om * @param input_filename path to a json file * @return a HashMap with the keys / total counts pairs */ private static KeyValueCounter countKeysInJsonRecordsFile(String input_filename) { InputStream fis; BufferedReader bufferedReader; String line; JSONParser jsonParser = new JSONParser(); KeyValueCounter keyValueCounter = new KeyValueCounter(); String jsonValue = ""; try { fis = new FileInputStream(input_filename); bufferedReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8"))); while ((line = bufferedReader.readLine()) != null) { JSONObject jsonObject = (JSONObject) jsonParser.parse(line); Set<String> keyset = jsonObject.keySet(); for (String jsonkey : keyset) { if (jsonObject.get(jsonkey) != null) { jsonValue = (String) jsonObject.get(jsonkey).toString(); if (jsonValue == null || jsonValue == "") { jsonValue = ""; } int lenValue = jsonValue.length(); keyValueCounter.incrementKeyCounter(jsonkey); keyValueCounter.putValueLength(jsonkey, lenValue); } else { if (jsonkey.compareTo("user_agent") != 0) { logger.error("Errot typing to get jsonkey " + jsonkey); } } } } bufferedReader.close(); } catch (ParseException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } //System.out.println(keyCounter.toString()); //System.out.println(sortHashByKey(keyCounter)); return keyValueCounter; }
From source file:eu.riscoss.rdc.GithubAPI_Test.java
/** * GIT API Test method // ww w .j a v a 2s . com * @param req * @return */ static JSONArray gitJSONGetter() { String json = ""; //String repository = values.get("repository"); String owner = "RISCOSS/"; //String repo = "riscoss-analyser/"; String repo = "riscoss-data-collector/"; String r = owner + repo; String req; req = r + "commits"; //NST: needs some time to be calculated. 1st time it returns Status 202! req = r + "stats/contributors"; //NST single contributors with weekly efforts: w:week, a:add, d:del, c:#commits //https://developer.github.com/v3/repos/statistics/#commit-activity req = r + "stats/commit_activity";//NST data per week (1y): The days array is a group of commits per day, starting on Sunday. req = r + "collaborators"; //needs authorization! Error 401 req = r + "events"; //committs and other events. Attention: max 10x30 events, max 90days! req = r + "issues?state=all"; //all issues. Of interest: state=open, closed, // req = r + "stats/participation";//NST weekly commit count //req = r + "stats/code_frequency"; //NST: week, number of additions, number of deletions per week //HttpGet( "https://api.github.com/rate_limit"); //rate limit is 60 requests per hour!! /** * TODO: * participation: week list, analysis value * issues open, issues closed today status * */ HttpGet get = new HttpGet("https://api.github.com/repos/" + req); //get = new HttpGet( "https://api.github.com/rate_limit"); //only for getting the License //get.setHeader("Accept", "application/vnd.github.drax-preview+json"); HttpResponse response; try { response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); json = EntityUtils.toString(entity); } else if (response.getStatusLine().getStatusCode() == 202) { System.err.println("WARNING 202 Accept: Computing....try again in some seconds."); return null; } else { // something has gone wrong... System.err.println(response.getStatusLine().getStatusCode()); System.err.println(response.getStatusLine().toString()); return null; } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("****JSON****\n" + json + "\n************"); try { JSONAware jv = (JSONAware) new JSONParser().parse(json); if (jv instanceof JSONObject) { JSONObject jo = (JSONObject) jv; System.out.println("JO: "); for (Object o : jo.entrySet()) { System.out.println("\t" + o); } } if (jv instanceof JSONArray) { JSONArray ja = (JSONArray) jv; int size = ja.size(); System.out.println("JA Size = " + size); for (Object o : ja) { if (o instanceof JSONObject) { JSONObject jo = (JSONObject) o; System.out.println("JA Object:"); for (Object o2 : jo.entrySet()) { System.out.println("\t" + o2); } } else { System.out.println("JA Array: " + (JSONArray) o); } } return ja; } } catch (ParseException e) { e.printStackTrace(); } return null; }
From source file:it.polimi.geinterface.filter.PropertiesFilter.java
/** * Method that parse a JSON {@link String} representing a filter into the corresponding {@link PropertiesFilter} * @param jsonPropFilter - the JSON {@link String} representing the filter * @return the corresponding {@link PropertiesFilter} *//*from w w w.j a v a 2s .co m*/ public static PropertiesFilter parseFromString(String jsonPropFilter) throws Exception { JSONParser p = new JSONParser(); try { JSONObject obj = (JSONObject) p.parse(jsonPropFilter); PropertiesFilter ret = new PropertiesFilter(); for (Object key : obj.keySet()) ret.put(key, obj.get(key)); return ret; } catch (ParseException e) { e.printStackTrace(); throw new Exception("Error parsing filter " + jsonPropFilter); } }
From source file:io.github.casnix.spawnerdropper.Config.java
public static int GetTNTChance() { try {//from w w w. j a va2 s . c o m // Read entire ./SpawnerDropper/SpawnerDropperConfig.json into a string // System.out.println("[SD DEBUG] 1"); String configTable = new String( Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerDropperConfig.json"))); // get the value of JSON->{spawnerType} // System.out.println("[SD DEBUG] 2"); JSONParser parser = new JSONParser(); // System.out.println("[SD DEBUG] 3"); Object obj = parser.parse(configTable); //System.out.println("[SD DEBUG] 4"); JSONObject jsonObj = (JSONObject) obj; // System.out.println("[SD DEBUG] 5"); String chance = (String) jsonObj.get("tntpercent"); // System.out.println("[SD DEBUG] 6"); // if(chance != null) // System.out.println("[SD DBG MSG] "+chance); // else // System.out.println("[SD DBG MSG] chance is null"); // System.out.println("[SD DEBUG] 7"); return Integer.valueOf(chance); //System.out.println("[SD DEBUG] 6"); //return chance; } catch (ParseException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in GetTNTChance(void)"); e.printStackTrace(); return -1; } catch (FileNotFoundException e) { Bukkit.getLogger() .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerDropperConfig.json"); e.printStackTrace(); return -1; } catch (IOException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in GetTNTChance(void)"); e.printStackTrace(); return -1; } }
From source file:io.github.casnix.spawnerdropper.Config.java
public static int GetCreeperChance() { try {//from ww w. j a v a 2 s. c om // Read entire ./SpawnerDropper/SpawnerDropperConfig.json into a string // System.out.println("[SD DEBUG] 7"); String configTable = new String( Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerDropperConfig.json"))); // get the value of JSON->{spawnerType} // System.out.println("[SD DEBUG] 8"); JSONParser parser = new JSONParser(); // System.out.println("[SD DEBUG] 9"); Object obj = parser.parse(configTable); //System.out.println("[SD DEBUG] 10"); JSONObject jsonObj = (JSONObject) obj; // System.out.println("[SD DEBUG] 11"); String chance = (String) jsonObj.get("creeperpercent"); // System.out.println("[SD DEBUG] 12"); return Integer.valueOf(chance); } catch (ParseException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in GetCreeperChance(void)"); e.printStackTrace(); return -1; } catch (FileNotFoundException e) { Bukkit.getLogger() .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerDropperConfig.json"); e.printStackTrace(); return -1; } catch (IOException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in GetCreeperChance(void)"); e.printStackTrace(); return -1; } catch (NumberFormatException e) { Bukkit.getLogger().warning("[SpawnerDropper] Caught NumberFormatException in GetCreeperChance(void)"); e.printStackTrace(); return -1; } }
From source file:com.google.api.services.samples.prediction.cmdline.PredictionSample.java
private static Insert2 responseToObject(String jsonString) { Insert2 res = new Insert2(); JSONParser parser = new JSONParser(); try {//from w w w . j a v a 2 s. c om JSONObject obj = (JSONObject) parser.parse(jsonString); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); res.setCreated(new DateTime((Date) formatter.parse((String) obj.get("created")))); res.setId((String) obj.get("id")); res.setKind((String) obj.get("kind")); res.setSelfLink((String) obj.get("selfLink")); res.setTrainingStatus((String) obj.get("trainingStatus")); if (obj.get("trainingComplete") != null) { res.setTrainingComplete(new DateTime((Date) formatter.parse((String) obj.get("trainingComplete")))); JSONObject ml = (JSONObject) obj.get("modelInfo"); Insert2.ModelInfo modelInfo = new ModelInfo(); modelInfo.setNumberInstances(Long.parseLong((String) ml.get("numberInstances"))); modelInfo.setModelType((String) ml.get("modelType")); modelInfo.setNumberLabels(Long.parseLong((String) ml.get("numberLabels"))); modelInfo.setClassificationAccuracy((String) ml.get("classificationAccuracy")); res.setModelInfo(modelInfo); } } catch (ParseException e) { e.printStackTrace(); res = null; } catch (java.text.ParseException e) { e.printStackTrace(); res = null; } return res; }
From source file:com.turt2live.xmail.mail.attachment.MailMessageAttachment.java
@SuppressWarnings("unchecked") public static MailMessageAttachment deserializeFromJson(String content) { JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { @Override/*from ww w . j a va 2s .c om*/ public List<Object> creatArrayContainer() { return new LinkedList<Object>(); } @Override public Map<String, Object> createObjectContainer() { return new LinkedHashMap<String, Object>(); } }; Map<String, Object> map = new HashMap<String, Object>(); try { Map<?, ?> json = (Map<?, ?>) parser.parse(content, containerFactory); Iterator<?> iter = json.entrySet().iterator(); // Type check while (iter.hasNext()) { Entry<?, ?> entry = (Entry<?, ?>) iter.next(); if (!(entry.getKey() instanceof String)) { throw new IllegalArgumentException("Not in <String, Object> format"); } } map = (Map<String, Object>) json; } catch (ParseException e) { e.printStackTrace(); return null; } catch (IllegalArgumentException e) { e.printStackTrace(); return null; } Mail mail = Mail.fromJSON(map); MessageAttachmentType type = MessageAttachmentType.OTHER; if (mail != null) { Object obj = map.get("message_type"); if (obj instanceof String) { String typestr = (String) obj; type = MessageAttachmentType.fromString(typestr); } } return new MailMessageAttachment(mail, type); }
From source file:com.mycompany.craftdemo.utility.java
public static JSONObject getAPIData(String apiURL) { try {/*w ww . j ava2s . com*/ URL url = new URL(apiURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder sb = new StringBuilder(); String output; while ((output = br.readLine()) != null) sb.append(output); String res = sb.toString(); JSONParser parser = new JSONParser(); JSONObject json = null; try { json = (JSONObject) parser.parse(res); } catch (ParseException ex) { ex.printStackTrace(); } //resturn api data in json format return json; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }