List of usage examples for org.json JSONTokener JSONTokener
public JSONTokener(String s)
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTaskTest.java
@Test public void testJSONRuleConstruction() throws Exception { ICalTaskProvider provider = new ICalTaskProvider("pluginId", null, null); provider.setScheduleExecutor(new MockScheduledTaskExecutor()); // validate we start with a non-existent temp file File calendarFile = File.createTempFile("schedule", ".ics"); assertTrue(calendarFile.delete());/*from w ww .j a v a 2s .com*/ assertFalse(calendarFile.exists()); try { provider.setScheduleFile(calendarFile); provider.reloadScheduleFile(); JSONObject json = new JSONObject(new JSONTokener( "{'name':'My Task','conditions':[{'start':'20140701T100000','recurrence':'FREQ=MINUTELY;INTERVAL=1'}],'actions':[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Action','properties':{'message':'logentry'}}]}")); provider.addTask(json); // make sure the provider updated the rule file assertTrue(calendarFile.exists()); Calendar cal = new CalendarBuilder().build(new FileReader(calendarFile)); assertEquals(2, cal.getComponents().size()); assertTrue(cal.getComponents().get(0) instanceof VJournal); assertTrue(cal.getComponents().get(1) instanceof VEvent); VEvent event = (VEvent) cal.getComponents().get(1); assertNotNull(event.getUid().getValue()); assertEquals("My Task", event.getSummary().getValue()); assertEquals("20140701T100000", event.getProperties().getProperty("DTSTART").getValue()); assertEquals("FREQ=MINUTELY;INTERVAL=1", event.getProperties().getProperty("RRULE").getValue()); assertNotNull(event.getProperties().getProperty("COMMENT")); JSONArray jarray = new JSONArray( new JSONTokener(event.getProperties().getProperty("COMMENT").getValue())); assertEquals(1, jarray.length()); JSONObject ajson = jarray.getJSONObject(0); assertEquals("com.whizzosoftware.hobson.server-api", ajson.getString("pluginId")); assertEquals("log", ajson.getString("actionId")); assertTrue(ajson.has("properties")); JSONObject props = ajson.getJSONObject("properties"); assertEquals("logentry", props.getString("message")); } finally { assertTrue(calendarFile.delete()); } }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTaskTest.java
@Test public void testJSONRuleConstructionWithSunOffset() throws Exception { ICalTaskProvider provider = new ICalTaskProvider("pluginId", null, null); provider.setScheduleExecutor(new MockScheduledTaskExecutor()); // validate we start with a non-existent temp file File calendarFile = File.createTempFile("schedule", ".ics"); assertTrue(calendarFile.delete());/*from w w w . ja v a2s .c om*/ assertFalse(calendarFile.exists()); try { provider.setScheduleFile(calendarFile); provider.reloadScheduleFile(); JSONObject json = new JSONObject(new JSONTokener( "{'name':'My Task','conditions':[{'start':'20140701T100000','recurrence':'FREQ=MINUTELY;INTERVAL=1','sunOffset':'SR'}],'actions':[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Action','properties':{'message':'logentry'}}]}")); provider.addTask(json); // make sure the provider updated the rule file assertTrue(calendarFile.exists()); Calendar cal = new CalendarBuilder().build(new FileReader(calendarFile)); assertEquals(2, cal.getComponents().size()); assertTrue(cal.getComponents().get(0) instanceof VJournal); assertTrue(cal.getComponents().get(1) instanceof VEvent); VEvent event = (VEvent) cal.getComponents().get(1); assertNotNull(event.getUid().getValue()); assertEquals("My Task", event.getSummary().getValue()); assertEquals("20140701T100000", event.getProperties().getProperty("DTSTART").getValue()); assertEquals("FREQ=MINUTELY;INTERVAL=1", event.getProperties().getProperty("RRULE").getValue()); assertEquals("SR", event.getProperties().getProperty(ICalTask.PROP_SUN_OFFSET).getValue()); assertNotNull(event.getProperties().getProperty("COMMENT")); JSONArray jarray = new JSONArray( new JSONTokener(event.getProperties().getProperty("COMMENT").getValue())); assertEquals(1, jarray.length()); JSONObject ajson = jarray.getJSONObject(0); assertEquals("com.whizzosoftware.hobson.server-api", ajson.getString("pluginId")); assertEquals("log", ajson.getString("actionId")); assertTrue(ajson.has("properties")); JSONObject props = ajson.getJSONObject("properties"); assertEquals("logentry", props.getString("message")); } finally { assertTrue(calendarFile.delete()); } }
From source file:com.nttdata.depend.util.OAuthUtil.java
private void createSession(String code) { try {/* w w w . ja v a 2 s . co m*/ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); nameValuePairs.add(new BasicNameValuePair("client_id", clientId)); nameValuePairs.add(new BasicNameValuePair("client_secret", clientSecret)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", requestURI)); HttpPost httppost = new HttpPost(OAUTH_TOKEN_URL); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); // Execute HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); String json = EntityUtils.toString(entity); session = new JSONObject(new JSONTokener(json)); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error in IO", e); } catch (ParseException e) { LOGGER.log(Level.SEVERE, "Error in JSON Parser", e); } catch (JSONException e) { LOGGER.log(Level.SEVERE, "Error in JSON", e); } }
From source file:com.ponysdk.generator.PropertiesDictionnaryGenerator.java
@SuppressWarnings("unchecked") private void generateDictionnary() throws FileNotFoundException, JSONException { log.info("Generating " + fileName); final String pathToFile = srcGeneratedDirectory + "/" + GeneratorHelper.getDirectoryFromPackage(packageName) + "/"; final TokenGenerator tokenGenerator = new TokenGenerator(); final FileReader fileReader = new FileReader("src-core/main/resources/spec/propertiesDictionnary.json"); final JSONTokener tokener = new JSONTokener(fileReader); final CodeWriter writer = new CodeWriter(); writer.addLine("package " + packageName + ";"); writer.addNewLine();/*from w w w . j ava 2s . c o m*/ writer.addLine("public interface " + fileName + " {"); writer.indentBlock(); final JSONObject dico = new JSONObject(tokener); final Iterator<String> domainKeys = dico.sortedKeys(); while (domainKeys.hasNext()) { // Domain final String domainKey = domainKeys.next(); writer.addLine("public interface " + domainKey.toUpperCase() + " {"); writer.indentBlock(); final JSONObject domain = dico.getJSONObject(domainKey); final Iterator<String> keys = domain.sortedKeys(); while (keys.hasNext()) { final String key = keys.next(); final String keyUpper = GeneratorHelper.toUpperUnderscore(key); final JSONArray values = domain.getJSONArray(key); if (verbose) writer.addLine("public static final String " + keyUpper + " = \"" + key + "\";"); else writer.addLine("public static final String " + keyUpper + " = \"" + tokenGenerator.nextToken() + "\";"); if (values.length() > 0) { writer.addLine("public interface " + keyUpper + "_" + " {"); writer.indentBlock(); for (int i = 0; i < values.length(); i++) { if (verbose) writer.addLine("public static final String " + GeneratorHelper.toUpperUnderscore(values.getString(i)) + " = \"" + values.getString(i) + "\";"); else writer.addLine("public static final String " + GeneratorHelper.toUpperUnderscore(values.getString(i)) + " = \"" + tokenGenerator.nextToken() + "\";"); } writer.unindentBlock(); writer.addLine("}"); } } writer.unindentBlock(); writer.addLine("}"); writer.addNewLine(); } writer.unindentBlock(); writer.addLine("}"); final File file = new File(pathToFile); if (!file.exists()) file.mkdirs(); writer.saveToFile(pathToFile + fileName + ".java"); }
From source file:org.jkan997.slingbeans.slingfs.FileSystemServer.java
public FileObject getFileObject(String path, int childDepth) { FileObject res = null;//from ww w . j ava 2 s . c o m path = StringHelper.normalizePath(path); try { final String jcrPath = String.format("%s.%s.json", path, childDepth); byte[] jsonBytes = getData(jcrPath); String jsonStr = new String(jsonBytes); JSONTokener jsonTokener = new JSONTokener(jsonStr); JSONObject json = new JSONObject(jsonTokener); res = loadFileObject(path, json); } catch (Exception ex) { LogHelper.logError(ex); } if (res == null) { LogHelper.logInfo(this, "Null file returned for path %s", path); } return res; }
From source file:org.jkan997.slingbeans.slingfs.FileSystemServer.java
public List<String> executeQuery(String query) { List<String> res = new ArrayList<String>(); Map<String, String> params = new HashMap<String, String>(); params.put("_charset_", "utf-8"); params.put("_dc", "" + System.currentTimeMillis()); params.put("showResults", "true"); params.put("type", "JCR-SQL2"); params.put("stmt", query); byte[] data = sendGet("/crx/de/query.jsp", params); if (data != null) { String jsonStr = new String(data); JSONTokener jsonTokener = new JSONTokener(jsonStr); JSONObject json = new JSONObject(jsonTokener); JSONArray jsonArr = json.getJSONArray("results"); for (int i = 0; i < jsonArr.length(); i++) { JSONObject result = jsonArr.getJSONObject(i); String path = result.getString("path"); res.add(path);/*from w w w.java2 s . c om*/ } } return res; }
From source file:org.lafs.hdfs.LAFS.java
private JSONArray getJSONForPath(Path path) throws IOException { URL url = new URL(httpURI.toString() + "/uri/" + getLAFSPath(path) + "?t=json"); URLConnection uc = url.openConnection(); uc.setDoInput(true);//from w w w. ja v a 2 s . c om BufferedReader br; try { br = new BufferedReader(new InputStreamReader(uc.getInputStream())); } catch (ConnectException e1) { logger.severe(url.toString()); throw new IOException(e1); } StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } br.close(); //logger.info(sb.toString()); JSONArray ja; try { ja = new JSONArray(new JSONTokener(sb.toString())); } catch (JSONException e) { throw new IOException(e.getMessage()); } return ja; }
From source file:de.hscoburg.etif.vbis.lagerix.android.barcode.result.supplement.BookResultInfoRetriever.java
@Override void retrieveSupplementalInfo() throws IOException { CharSequence contents = HttpHelper.downloadViaHttp( "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON); if (contents.length() == 0) { return;//from ww w .j ava 2s . co m } String title; String pages; Collection<String> authors = null; try { JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue(); JSONArray items = topLevel.optJSONArray("items"); if (items == null || items.isNull(0)) { return; } JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo"); if (volumeInfo == null) { return; } title = volumeInfo.optString("title"); pages = volumeInfo.optString("pageCount"); JSONArray authorsArray = volumeInfo.optJSONArray("authors"); if (authorsArray != null && !authorsArray.isNull(0)) { authors = new ArrayList<String>(authorsArray.length()); for (int i = 0; i < authorsArray.length(); i++) { authors.add(authorsArray.getString(i)); } } } catch (JSONException e) { throw new IOException(e.toString()); } Collection<String> newTexts = new ArrayList<String>(); maybeAddText(title, newTexts); maybeAddTextSeries(authors, newTexts); maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts); String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context) + "/search?tbm=bks&source=zxing&q="; append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn); }
From source file:com.tnc.android.graphite.utils.GraphiteConnection.java
private static void getTargetsRecursive(ArrayList<Target> targets, String serverUrl, String targetFilter, int levels) throws Exception { BufferedReader reader = getReader(serverUrl + TARGETS_PARAM_STRING + targetFilter); String line;//from ww w. j ava2 s. c om if ((line = reader.readLine()) != null) { JSONTokener jTok = new JSONTokener(line); if (jTok.more()) { JSONArray array = (JSONArray) jTok.nextValue(); for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); String id = obj.getString("id"); int exp = obj.getInt("expandable"); Target t = new Target(); t.setHash(hash); t.setName(id); if (1 == exp) { t.setExpandable(true); } targets.add(t); if (1 == exp && 1 < levels) { // Recursively parse the branch getTargetsRecursive(targets, serverUrl, id + ".*", levels - 1); } } } } }
From source file:com.grameenfoundation.ictchallenge.controllers.ConnectedAppREST.java
private JSONObject showFarmers(String instanceUrl, String accessToken) throws ServletException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); //add key and value httpGet.addHeader("Authorization", "OAuth " + accessToken); try {//from w w w . j a va 2s.c o m URIBuilder builder = new URIBuilder(instanceUrl + "/services/data/v30.0/query"); //builder.setParameter("q", "SELECT Name, Id from Account LIMIT 100"); builder.setParameter("q", "SELECT Name__c,Date_Of_Birth__c,Land_size__c,Farmer_I_D__c,Picture__c from Farmer__c LIMIT 100"); httpGet.setURI(builder.build()); log.log(Level.INFO, "URl to salesforce {0}", builder.build().getPath()); CloseableHttpResponse closeableresponse = httpclient.execute(httpGet); System.out.println("Response Status line :" + closeableresponse.getStatusLine()); if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Now lets use the standard java json classes to work with the // results try { // Do the needful with entity. HttpEntity entity = closeableresponse.getEntity(); InputStream rstream = entity.getContent(); JSONObject authResponse = new JSONObject(new JSONTokener(rstream)); log.log(Level.INFO, "Query response: {0}", authResponse.toString(2)); log.log(Level.INFO, "{0} record(s) returned\n\n", authResponse.getInt("totalSize")); return authResponse; } catch (JSONException e) { e.printStackTrace(); throw new ServletException(e); } } } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { httpclient.close(); } return null; }