List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:com.example.quadros_10084564.sunshine_v2.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./* w w w . jav a 2 s . c o m*/ */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } }
From source file:com.devsh.androidlogin.library.FacebookLoginUtil.java
private FacebookLoginUtil() { callbackManager = CallbackManager.Factory.create(); accessTokenTracker = new AccessTokenTracker() { @Override// w ww .j av a2 s . com protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if (oldAccessToken == null && currentAccessToken != null) { loginCallback.onCallback(currentAccessToken); } if (oldAccessToken != null && currentAccessToken == null) { SharedData.clearSharedPreference(sContext); logoutCallback.onCallback(currentAccessToken); } if (oldAccessToken != null && currentAccessToken != null) { updateTokenCallback.onCallback(currentAccessToken); } } }; // profileTracker = new ProfileTracker() { // @Override // protected void onCurrentProfileChanged( // Profile oldProfile, // Profile currentProfile) { // Log.i(TAG, "oldProfile" + oldProfile + "currentProfile" + currentProfile); // } // }; loginCallback = nullCallback; logoutCallback = nullCallback; updateTokenCallback = nullCallback; // LoginResultCallback LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Profile profile = Profile.getCurrentProfile(); final AccessToken accessToken = loginResult.getAccessToken(); if (profile != null) { SharedData.putAccountProvider(sContext, SharedData.PROVIDER_FACEBOOK); SharedData.putAccountIdToken(sContext, accessToken.getToken()); SharedData.putAccountId(sContext, profile.getId()); SharedData.putAccountUserName(sContext, profile.getName()); SharedData.putAccountUserPhoto(sContext, profile.getProfilePictureUri(200, 200).toString()); // No email loginResultCallback.onSuccess(loginResult); } else { final LoginResult loginResult2 = loginResult; GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { SharedData.putAccountProvider(sContext, SharedData.PROVIDER_FACEBOOK); SharedData.putAccountIdToken(sContext, accessToken.getToken()); SharedData.putAccountId(sContext, accessToken.getUserId()); try { String userName = response.getJSONObject().getString("name"); String userPhoto = object.getJSONObject("picture").getJSONObject("data") .getString("url"); String userEmail = object.getString("email"); SharedData.putAccountUserName(sContext, userName); SharedData.putAccountUserPhoto(sContext, userPhoto); SharedData.putAccountUserEmail(sContext, userEmail); } catch (JSONException e) { e.printStackTrace(); } loginResultCallback.onSuccess(loginResult2); } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,picture"); request.setParameters(parameters); request.executeAsync(); } } @Override public void onCancel() { SharedData.clearSharedPreference(sContext); loginResultCallback.onCancel(); } @Override public void onError(FacebookException error) { SharedData.clearSharedPreference(sContext); loginResultCallback.onError(error); } }); }
From source file:ja.ohac.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;/* w ww. j av a 2s . com*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Charsets.UTF_8); final StringBuilder content = new StringBuilder(); final long length = Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { final String rateStr = o.optString(field, null); if (rateStr != null) { try { final BigInteger rate = GenericUtils.parseCoin(rateStr, 0); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source)); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.aliyun.openservices.odps.console.commands.logview.GetTaskDetailsAction.java
private List<FuxiJob> loadJobsFromStream(InputStream in) throws ODPSConsoleException { JSONTokener tokener = new JSONTokener(new BufferedReader(new InputStreamReader(in))); try {/*from w w w .ja v a 2 s. co m*/ JSONObject obj = new JSONObject(tokener); ArrayList<FuxiJob> jobs = new ArrayList<FuxiJob>(); JSONObject mapReduceJson; try { mapReduceJson = obj.getJSONObject("mapReduce"); } catch (JSONException e) { return jobs; } JSONArray jobsJson = mapReduceJson.getJSONArray("jobs"); for (int i = 0; i < jobsJson.length(); i++) { jobs.add(getFuxiJobFromJson(jobsJson.getJSONObject(i))); } return jobs; } catch (JSONException e) { e.printStackTrace(); throw new ODPSConsoleException("Bad json format"); } }
From source file:com.soomla.store.domain.data.StaticPriceModel.java
/** * Creates a {@link StaticPriceModel} with the given JSONObject. * @param jsonObject is a JSONObject representation of the required {@link StaticPriceModel}. * @return an instance of {@link StaticPriceModel}. * @throws JSONException/*from www . j a va 2 s.c o m*/ */ public static StaticPriceModel fromJSONObject(JSONObject jsonObject) throws JSONException { JSONObject valuesJSONObject = jsonObject.getJSONObject(JSONConsts.GOOD_PRICE_MODEL_VALUES); Iterator<?> keys = valuesJSONObject.keys(); HashMap<String, Integer> values = new HashMap<String, Integer>(); while (keys.hasNext()) { String key = (String) keys.next(); values.put(key, valuesJSONObject.getInt(key)); } return new StaticPriceModel(values); }
From source file:org.stockchart.series.AbstractSeries.java
public void fromJSONObject(JSONObject j) throws JSONException { super.fromJSONObject(j); fAppearance.fromJSONObject(j.getJSONObject("appearance")); }
From source file:org.chromium.ChromeI18n.java
private JSONObject toLowerCaseMessage(JSONObject contents) throws JSONException { List<String> messages = toStringList(contents.names()); for (String message : messages) { JSONObject value = contents.getJSONObject(message); contents.remove(message);//from w w w .j av a 2 s.co m contents.put(message.toLowerCase(), value); } return contents; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitPushTest.java
@Test public void testPushNoBody() throws Exception { // clone a repo URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); IPath clonePath = getClonePath(workspaceId, project); clone(clonePath);/* w ww . ja va2 s . c o m*/ // get project metadata WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project = new JSONObject(response.getText()); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE); // get remote branch location JSONObject remoteBranch = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER); String remoteBranchLocation = remoteBranch.getString(ProtocolConstants.KEY_LOCATION); // push with no body request = getPostGitRemoteRequest(remoteBranchLocation, null, false, false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitPushTest.java
@Test public void testPushHead() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); // clone1/*from w w w. j a v a 2 s. c o m*/ JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null); IPath clonePath1 = getClonePath(workspaceId, project1); clone(clonePath1); // get project1 metadata WebRequest request = getGetRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project1 = new JSONObject(response.getText()); JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE); String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD); // clone2 JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null); IPath clonePath2 = getClonePath(workspaceId, project2); clone(clonePath2); // get project2 metadata request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project2 = new JSONObject(response.getText()); JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE); String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD); // clone1: list remotes request = GitRemoteTest.getGetGitRemoteRequest(gitRemoteUri1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject remotes = new JSONObject(response.getText()); JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(1, remotesArray.length()); JSONObject remote = remotesArray.getJSONObject(0); assertNotNull(remote); assertEquals(Constants.DEFAULT_REMOTE_NAME, remote.getString(ProtocolConstants.KEY_NAME)); // clone1: change JSONObject testTxt1 = getChild(project1, "test.txt"); modifyFile(testTxt1, "incoming change"); addFile(testTxt1); // clone1: commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming change commit", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: push ServerStatus pushStatus = push(gitRemoteUri1, 1, 0, Constants.MASTER, Constants.HEAD, false); assertEquals(true, pushStatus.isOK()); // clone2: get remote branch location JSONObject remoteBranch = getRemoteBranch(gitRemoteUri2, 1, 0, Constants.MASTER); String remoteBranchLocation2 = remoteBranch.getString(ProtocolConstants.KEY_LOCATION); // clone2: fetch fetch(remoteBranchLocation2); // clone2: get remote details JSONObject remoteBranch2 = getRemoteBranch(gitRemoteUri2, 1, 0, Constants.MASTER); String newRefId2 = remoteBranch2.getString(ProtocolConstants.KEY_ID); // clone2: merge into HEAD, "git merge origin/master" gitHeadUri2 = remoteBranch2.getString(GitConstants.KEY_HEAD); JSONObject merge = merge(gitHeadUri2, newRefId2); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD, mergeResult); // clone2: assert change from clone1 is in place JSONObject testTxt2 = getChild(project2, "test.txt"); request = getGetRequest(testTxt2.getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("incoming change", response.getText()); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitPushTest.java
@Test public void testPushHeadSshWithPrivateKeyPassphrase() throws Exception { Assume.assumeTrue(sshRepo2 != null); Assume.assumeTrue(knownHosts2 != null); Assume.assumeTrue(privateKey != null); Assume.assumeTrue(passphrase != null); URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); URIish uri = new URIish(sshRepo2); // clone1: create JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null); IPath clonePath = getClonePath(workspaceId, project1); WebRequest request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath) .setKnownHosts(knownHosts2).setPrivateKey(privateKey).setPublicKey(publicKey) .setPassphrase(passphrase).getWebRequest(); String cloneContentLocation1 = clone(request); // clone1: get project/folder metadata request = getGetRequest(cloneContentLocation1); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project1 = new JSONObject(response.getText()); // clone1: get git links JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri1 = gitSection1.optString(GitConstants.KEY_REMOTE); String gitIndexUri1 = gitSection1.optString(GitConstants.KEY_INDEX); String gitHeadUri1 = gitSection1.optString(GitConstants.KEY_HEAD); // clone2: create JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null); clonePath = getClonePath(workspaceId, project2); request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath).setKnownHosts(knownHosts2) .setPrivateKey(privateKey).setPublicKey(publicKey).setPassphrase(passphrase).getWebRequest(); String cloneContentLocation2 = clone(request); // clone2: get project/folder metadata request = getGetRequest(cloneContentLocation2); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project2 = new JSONObject(response.getText()); // clone2: get git links JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE); String gitCommitUri2 = gitSection2.getString(GitConstants.KEY_COMMIT); // clone1: list remotes request = GitRemoteTest.getGetGitRemoteRequest(gitRemoteUri1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject remotes = new JSONObject(response.getText()); JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(1, remotesArray.length()); JSONObject remote = remotesArray.getJSONObject(0); assertNotNull(remote);/* w w w. ja v a 2 s . c om*/ assertEquals(Constants.DEFAULT_REMOTE_NAME, remote.getString(ProtocolConstants.KEY_NAME)); // clone1: change JSONObject testTxt1 = getChild(project1, "test.txt"); modifyFile(testTxt1, "incoming change"); // clone1: add request = GitAddTest.getPutGitIndexRequest(gitIndexUri1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming change commit", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: push ServerStatus pushStatus = push(gitRemoteUri1, 1, 0, Constants.MASTER, Constants.HEAD, false, null, knownHosts2, privateKey, publicKey, passphrase, true); assertEquals(true, pushStatus.isOK()); // clone2: get remote branch location JSONObject remoteBranch = getRemoteBranch(gitRemoteUri2, 1, 0, Constants.MASTER); String remoteBranchLocation2 = remoteBranch.getString(ProtocolConstants.KEY_LOCATION); // clone2: fetch fetch(remoteBranchLocation2, null, knownHosts2, privateKey, publicKey, passphrase, true); // clone2: get remote details JSONObject remoteBranch2 = getRemoteBranch(gitRemoteUri2, 1, 0, Constants.MASTER); String newRefId2 = remoteBranch2.getString(ProtocolConstants.KEY_ID); // clone2: merge into HEAD, "git merge origin/master" gitCommitUri2 = remoteBranch2.getString(GitConstants.KEY_HEAD); JSONObject merge = merge(gitCommitUri2, newRefId2); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD, mergeResult); // clone2: assert change from clone1 is in place JSONObject testTxt2 = getChild(project2, "test.txt"); request = getGetRequest(testTxt2.getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("incoming change", response.getText()); }