List of usage examples for org.json JSONObject optString
public String optString(String key, String defaultValue)
From source file:com.cdd.bao.importer.ImportControlledVocab.java
public void exec() throws IOException, JSONException { File f = new File(srcFN); if (!f.exists()) throw new IOException("Source file not found: " + f.getCanonicalPath()); Reader rdr = new FileReader(srcFN); JSONObject json = new JSONObject(new JSONTokener(rdr)); rdr.close();/*from w w w .ja v a2 s . co m*/ if (!json.has("columns") || !json.has("rows")) throw new IOException("Source JSON must have 'columns' and 'rows'."); srcColumns = json.getJSONArray("columns"); srcRows = json.getJSONArray("rows"); map = new KeywordMapping(mapFN); Util.writeln("Mapping file:"); Util.writeln(" # identifiers = " + map.identifiers.size()); Util.writeln(" # textblocks = " + map.textBlocks.size()); Util.writeln(" # properties = " + map.properties.size()); Util.writeln(" # values = " + map.values.size()); Util.writeln(" # literals = " + map.literals.size()); Util.writeln(" # references = " + map.references.size()); Util.writeln(" # assertions = " + map.assertions.size()); schema = ModelSchema.deserialise(new File(schemaFN)); assignments = schema.getRoot().flattenedAssignments(); InputStream istr = new FileInputStream(vocabFN); schvoc = SchemaVocab.deserialise(istr, new Schema[] { schema }); istr.close(); for (SchemaVocab.StoredTree stored : schvoc.getTrees()) treeCache.put(stored.assignment, stored.tree); if (hintFN != null) { rdr = new FileReader(hintFN); JSONObject jsonHints = new JSONObject(new JSONTokener(rdr)); rdr.close(); for (String key : jsonHints.keySet()) { String uri = ModelSchema.expandPrefix(jsonHints.getString(key)); hints.put(key, uri); invHints.put(uri, ArrayUtils.add(invHints.get(uri), key)); } Util.writeln(" # hints = " + hints.size()); } checkMappingProperties(); for (int n = 0; n < srcColumns.length(); n++) matchColumn(srcColumns.getString(n)); for (int n = 0; n < srcRows.length(); n++) { Util.writeln("---- Row#" + (n + 1) + " ----"); JSONObject row = srcRows.getJSONObject(n); for (String key : row.keySet()) { if (map.findIdentifier(key) != null) continue; Property prop = map.findProperty(key); if (prop == null || Util.isBlank(prop.propURI)) continue; // passed on the opportunity to map String val = row.optString(key, ""); if (map.findValue(key, val) != null || map.findLiteral(key, val) != null || map.findReference(key, val) != null) continue; // already mapped matchValue(prop, key, val); } } Util.writeln("Saving mapping file..."); map.save(); writeMappedAssays(); Util.writeln("Done."); }
From source file:com.ammobyte.radioreddit.api.GetSongInfo.java
@Override protected Boolean doInBackground(String... params) { final String cookie = params[0]; // This will be null if not logged in // Prepare GET with cookie, execute it, parse response as JSON JSONObject response = null;// ww w .j a va 2 s . co m try { final HttpClient httpClient = new DefaultHttpClient(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url)); final HttpGet httpGet = new HttpGet( "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8")); if (cookie != null) { // Using HttpContext, CookieStore, and friends didn't work httpGet.setHeader("Cookie", "reddit_session=" + cookie); } httpGet.setHeader("User-Agent", RedditApi.USER_AGENT); final HttpResponse httpResponse = httpClient.execute(httpGet); response = new JSONObject(EntityUtils.toString(httpResponse.getEntity())); } catch (UnsupportedEncodingException e) { Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e); } catch (ClientProtocolException e) { Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e); } catch (IOException e) { Log.i(RedditApi.TAG, "IOException while getting song info", e); } catch (ParseException e) { Log.i(RedditApi.TAG, "ParseException while getting song info", e); } catch (JSONException e) { Log.i(RedditApi.TAG, "JSONException while getting song info", e); } // Check for failure if (response == null) { Log.i(RedditApi.TAG, "Response is null"); return false; } // Get the info we want final JSONObject data1 = response.optJSONObject("data"); if (data1 == null) { Log.i(RedditApi.TAG, "First data is null"); return false; } final String modhash = data1.optString("modhash", ""); if (modhash.length() > 0) { mService.setModhash(modhash); } final JSONArray children = data1.optJSONArray("children"); if (children == null) { Log.i(RedditApi.TAG, "Children is null"); return false; } final JSONObject child = children.optJSONObject(0); if (child == null) { // This is common if the song hasn't been submitted to reddit yet // so we intentionally don't log this case return false; } final String kind = child.optString("kind"); if (kind == null) { Log.i(RedditApi.TAG, "Kind is null"); return false; } final JSONObject data2 = child.optJSONObject("data"); if (data2 == null) { Log.i(RedditApi.TAG, "Second data is null"); return false; } final String id = data2.optString("id"); if (id == null) { Log.i(RedditApi.TAG, "Id is null"); return false; } final int score = data2.optInt("score"); Boolean likes = null; if (!data2.isNull("likes")) { likes = data2.optBoolean("likes"); } final boolean saved = data2.optBoolean("saved"); // Modify song with collected info if (kind != null && id != null) { mSong.reddit_id = kind + "_" + id; } else { mSong.reddit_id = null; } mSong.upvoted = (likes != null && likes == true); mSong.downvoted = (likes != null && likes == false); mSong.votes = score; mSong.saved = saved; return true; }
From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java
private void step1GetOAuthToken() { if (mOAuthCode == null) { setState(State.AUTH_ERROR); showRetryForOAuth();//from ww w . j a v a 2 s . co m return; } Activity activity = getActivity(); if (activity == null) { return; } final String gistText = GithubResource.generate(activity, mFingerprint); new AsyncTask<Void, Void, JSONObject>() { Exception mException; @Override protected JSONObject doInBackground(Void... dummy) { try { JSONObject params = new JSONObject(); params.put("client_id", BuildConfig.GITHUB_CLIENT_ID); params.put("client_secret", BuildConfig.GITHUB_CLIENT_SECRET); params.put("code", mOAuthCode); params.put("state", mOAuthState); return jsonHttpRequest("https://github.com/login/oauth/access_token", params, null); } catch (IOException | HttpResultException e) { mException = e; } catch (JSONException e) { throw new AssertionError("json error, this is a bug!"); } return null; } @Override protected void onPostExecute(JSONObject result) { super.onPostExecute(result); Activity activity = getActivity(); if (activity == null) { // we couldn't show an error anyways return; } Log.d(Constants.TAG, "response: " + result); if (result == null || result.optString("access_token", null) == null) { setState(State.AUTH_ERROR); showRetryForOAuth(); if (result != null) { Notify.create(activity, R.string.linked_error_auth_failed, Style.ERROR).show(); return; } if (mException instanceof SocketTimeoutException) { Notify.create(activity, R.string.linked_error_timeout, Style.ERROR).show(); } else if (mException instanceof HttpResultException) { Notify.create(activity, activity.getString(R.string.linked_error_http, ((HttpResultException) mException).mResponse), Style.ERROR).show(); } else if (mException instanceof IOException) { Notify.create(activity, R.string.linked_error_network, Style.ERROR).show(); } return; } step2PostGist(result.optString("access_token"), gistText); } }.execute(); }
From source file:com.facebook.internal.Utility.java
private static FetchedAppSettings parseAppSettingsFromJSON(String applicationId, JSONObject settingsJSON) { FetchedAppSettings result = new FetchedAppSettings( settingsJSON.optBoolean(APP_SETTING_SUPPORTS_IMPLICIT_SDK_LOGGING, false), settingsJSON.optString(APP_SETTING_NUX_CONTENT, ""), settingsJSON.optBoolean(APP_SETTING_NUX_ENABLED, false), parseDialogConfigurations(settingsJSON.optJSONObject(APP_SETTING_DIALOG_CONFIGS))); fetchedAppSettings.put(applicationId, result); return result; }
From source file:org.brickred.socialauth.provider.StackExchangeImpl.java
private Profile getProfile() throws Exception { String presp;//w w w.ja v a2 s. c o m String profileURL = PROFILE_URL; String site = "stackoverflow"; if (config.getCustomProperties() != null) { if (config.getCustomProperties().get("site") != null) { site = config.getCustomProperties().get("site"); } profileURL += "?key=" + config.getCustomProperties().get("key") + "&site=" + site; } else { throw new SocialAuthException( "Please set 'stackapps.com.custom.key' property in oauth_consumer.properties "); } try { Response response = authenticationStrategy.executeFeed(profileURL); presp = response.getResponseBodyAsString(Constants.ENCODING); } catch (Exception e) { throw new SocialAuthException("Error while getting profile from " + profileURL, e); } try { LOG.debug("User Profile : " + presp); JSONObject jsonResp = new JSONObject(presp); Profile p = new Profile(); if (jsonResp.has("items")) { JSONArray items = jsonResp.getJSONArray("items"); if (items.length() > 0) { JSONObject resp = items.getJSONObject(0); p.setDisplayName(resp.optString("display_name", null)); p.setFullName(resp.optString("display_name", null)); p.setProfileImageURL(resp.optString("profile_image", null)); p.setValidatedId(resp.optString("user_id", null)); p.setLocation(resp.optString("location", null)); if (config.isSaveRawResponse()) { p.setRawResponse(presp); } p.setProviderId(getProviderId()); if (config.isSaveRawResponse()) { p.setRawResponse(presp); } } } userProfile = p; return p; } catch (Exception ex) { throw new ServerDataException("Failed to parse the user profile json : " + presp, ex); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitUriTest.java
@Test public void testGitUrisInContentLocation() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); // http://<host>/workspace/<workspaceId>/ JSONObject newProject = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); String contentLocation = newProject.optString(ProtocolConstants.KEY_CONTENT_LOCATION, null); assertNotNull(contentLocation);//w w w .ja v a 2 s . co m // http://<host>/file/<projectId>/ WebRequest request = getGetRequest(contentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject project = new JSONObject(response.getText()); assertGitSectionExists(project); // TODO: it's a linked repo, see bug 346114 // assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null)); String childrenLocation = project.getString(ProtocolConstants.KEY_CHILDREN_LOCATION); assertNotNull(childrenLocation); // http://<host>/file/<projectId>/?depth=1 request = getGetRequest(childrenLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText())); String[] expectedChildren = new String[] { Constants.DOT_GIT, "folder", "test.txt" }; assertEquals("Wrong number of directory children", expectedChildren.length, children.size()); for (JSONObject child : children) { assertGitSectionExists(child); // TODO: it's a linked repo, see bug 346114 // assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null)); } childrenLocation = getChildByName(children, "folder").getString(ProtocolConstants.KEY_CHILDREN_LOCATION); // http://<host>/file/<projectId>/folder/?depth=1 request = getGetRequest(childrenLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); children = getDirectoryChildren(new JSONObject(response.getText())); expectedChildren = new String[] { "folder.txt" }; assertEquals("Wrong number of directory children", expectedChildren.length, children.size()); for (JSONObject child : children) { assertGitSectionExists(child); // TODO: it's a linked repo, see bug 346114 // assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null)); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitUriTest.java
@Test public void testGitUrisForEmptyDir() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); File emptyDir = AllGitTests.getRandomLocation().toFile(); emptyDir.mkdir();/*from ww w .j a v a 2s . c om*/ ServletTestingSupport.allowedPrefixes = emptyDir.toString(); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), emptyDir.toString()); project.getString(ProtocolConstants.KEY_ID); String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION); WebRequest request = getGetRequest(location); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject files = new JSONObject(response.getText()); // FIXME: these assertions do nothing useful assertNull(files.optString(GitConstants.KEY_STATUS, null)); assertNull(files.optString(GitConstants.KEY_DIFF, null)); assertNull(files.optString(GitConstants.KEY_DIFF, null)); assertNull(files.optString(GitConstants.KEY_COMMIT, null)); assertNull(files.optString(GitConstants.KEY_REMOTE, null)); assertNull(files.optString(GitConstants.KEY_TAG, null)); assertNull(files.optString(GitConstants.KEY_CLONE, null)); assertTrue(emptyDir.delete()); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitUriTest.java
@Test public void testGitUrisForFile() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); File dir = AllGitTests.getRandomLocation().toFile(); dir.mkdir();//from ww w. j a va2 s .c o m File file = new File(dir, "test.txt"); file.createNewFile(); ServletTestingSupport.allowedPrefixes = dir.toString(); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, dir.toString()); String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION); WebRequest request = getGetRequest(location); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject files = new JSONObject(response.getText()); assertNull(files.optString(GitConstants.KEY_STATUS, null)); assertNull(files.optString(GitConstants.KEY_DIFF, null)); assertNull(files.optString(GitConstants.KEY_DIFF, null)); assertNull(files.optString(GitConstants.KEY_COMMIT, null)); assertNull(files.optString(GitConstants.KEY_REMOTE, null)); assertNull(files.optString(GitConstants.KEY_TAG, null)); assertNull(files.optString(GitConstants.KEY_CLONE, null)); FileUtils.delete(dir, FileUtils.RECURSIVE); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitUriTest.java
@Test public void testGitUrisForRepositoryClonedIntoSubfolder() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); String folderName = "subfolder"; WebRequest request = getPostFilesRequest("", getNewDirJSON(folderName).toString(), folderName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); IPath clonePath = getClonePath(workspaceId, project).append(folderName).makeAbsolute(); clone(clonePath);/*from w ww . j a v a 2 s. co m*/ String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION); request = getGetRequest(location); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject responseJSON = new JSONObject(response.getText()); // no Git section for /file/{projectId} assertNull(responseJSON.optString(GitConstants.KEY_STATUS, null)); assertNull(responseJSON.optString(GitConstants.KEY_DIFF, null)); assertNull(responseJSON.optString(GitConstants.KEY_DIFF, null)); assertNull(responseJSON.optString(GitConstants.KEY_COMMIT, null)); assertNull(responseJSON.optString(GitConstants.KEY_REMOTE, null)); assertNull(responseJSON.optString(GitConstants.KEY_TAG, null)); assertNull(responseJSON.optString(GitConstants.KEY_CLONE, null)); request = getGetRequest(responseJSON.getString(ProtocolConstants.KEY_CHILDREN_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText())); assertEquals(1, children.size()); // expected Git section for /file/{projectId}/?depth=1 assertGitSectionExists(children.get(0)); JSONObject gitSection = children.get(0).getJSONObject(GitConstants.KEY_GIT); assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null)); location = children.get(0).getString(ProtocolConstants.KEY_LOCATION); request = getGetRequest(location); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); responseJSON = new JSONObject(response.getText()); // expected Git section for /file/{projectId}/subfolder assertGitSectionExists(responseJSON); gitSection = responseJSON.getJSONObject(GitConstants.KEY_GIT); assertCloneUri(gitSection.optString(GitConstants.KEY_CLONE, null)); }
From source file:com.mikecorrigan.trainscorekeeper.MainActivity.java
private void createActionBar(final JSONArray jsonTabs) { Log.vc(VERBOSE, TAG, "createActionBar: jsonTabs=" + jsonTabs); final ActionBar actionBar = getSupportActionBar(); actionBar.removeAllTabs();/*from ww w.j a v a2 s . co m*/ actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); ActionBar.TabListener tabListener = new XTabListener(viewPager); // Add the button tabs to the ActionBar. int i; for (i = 0; i < jsonTabs.length(); i++) { JSONObject jsonTab = jsonTabs.optJSONObject(i); if (jsonTab == null) { continue; } final String name = jsonTab.optString(JsonSpec.TAB_NAME, JsonSpec.DEFAULT_TAB_NAME); actionBar.addTab(actionBar.newTab().setText(name).setTabListener(tabListener)); } // Add the special tabs to the ActionBar. actionBar.addTab(actionBar.newTab().setText(getString(R.string.summary)).setTabListener(tabListener)); i++; actionBar.addTab(actionBar.newTab().setText(getString(R.string.history)).setTabListener(tabListener)); i++; }