List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
From source file:com.tune.reporting.base.endpoints.EndpointBase.java
/** * Helper function for fetching report document given provided job identifier. * * <p>// w w w. ja v a2 s.com * Requesting for report url is not the same for all report endpoints. * </p> * * @param exportController Controller for report export status. * @param exportAction Action for report export status. * @param jobId Job Identifier of report on queue. * * @return TuneServiceResponse * @throws TuneSdkException If error within SDK. * @throws TuneServiceException If service fails to handle post request. */ protected final TuneServiceResponse fetchRecords(final String exportController, final String exportAction, final String jobId) throws IllegalArgumentException, TuneServiceException, TuneSdkException { if ((null == exportController) || exportController.isEmpty()) { throw new IllegalArgumentException("Parameter 'exportController' is not defined."); } if ((null == exportAction) || exportAction.isEmpty()) { throw new IllegalArgumentException("Parameter 'exportAction' is not defined."); } if ((null == jobId) || jobId.isEmpty()) { throw new IllegalArgumentException("Parameter 'jobId' is not defined."); } Integer sleep = this.sdkConfig.getFetchSleep(); Integer timeout = this.sdkConfig.getFetchTimeout(); Boolean verbose = this.sdkConfig.getFetchVerbose(); ReportExportWorker exportWorker = new ReportExportWorker(exportController, exportAction, this.authKey, this.authType, jobId, verbose, sleep, timeout); if (verbose) { System.out.println("Starting worker..."); } if (exportWorker.run()) { if (verbose) { System.out.println("Completed worker..."); } } TuneServiceResponse response = exportWorker.getResponse(); if (null == response) { throw new TuneServiceException("Report export request no response."); } int httpCode = response.getHttpCode(); if (httpCode != HTTP_STATUS_OK) { throw new TuneServiceException(String.format("Report export request error: '%d'", httpCode)); } JSONObject jdata = (JSONObject) response.getData(); if (null == jdata) { throw new TuneServiceException("Report export response failed to get data."); } if (!jdata.has("status")) { throw new TuneSdkException(String.format("Export data does not contain report 'status', response: %s", response.toString())); } String status = null; try { status = jdata.getString("status"); } catch (JSONException ex) { throw new TuneSdkException(ex.getMessage(), ex); } catch (Exception ex) { throw new TuneSdkException(ex.getMessage(), ex); } if (status.equals("fail")) { throw new TuneSdkException( String.format("Report export status '%s':, response: %s", status, response.toString())); } return response; }
From source file:com.tune.reporting.base.endpoints.EndpointBase.java
/** * Parse response and gather report url. * * @param response @see TuneServiceResponse * * @return String Report URL download from Export queue. * @throws TuneSdkException If error within SDK. * @throws TuneServiceException If service fails to handle post request. *//* w w w. j a va 2 s . com*/ public static String parseResponseReportUrl(final TuneServiceResponse response) throws IllegalArgumentException, TuneSdkException, TuneServiceException { if (null == response) { throw new IllegalArgumentException("Parameter 'response' is not defined."); } JSONObject jdata = (JSONObject) response.getData(); if (null == jdata) { throw new TuneServiceException("Report export response failed to get data."); } if (!jdata.has("data")) { throw new TuneSdkException( String.format("Export data does not contain report 'data', response: %s", response.toString())); } JSONObject jdataInternal = null; try { jdataInternal = jdata.getJSONObject("data"); } catch (JSONException ex) { throw new TuneSdkException(ex.getMessage(), ex); } catch (Exception ex) { throw new TuneSdkException(ex.getMessage(), ex); } if (null == jdataInternal) { throw new TuneServiceException(String .format("Export data response does not contain 'data', response: %s", response.toString())); } if (!jdataInternal.has("url")) { throw new TuneSdkException(String.format("Export response 'data' does not contain 'url', response: %s", response.toString())); } String jdataInternalUrl = null; try { jdataInternalUrl = jdataInternal.getString("url"); } catch (JSONException ex) { throw new TuneSdkException(ex.getMessage(), ex); } catch (Exception ex) { throw new TuneSdkException(ex.getMessage(), ex); } if ((null == jdataInternalUrl) || jdataInternalUrl.isEmpty()) { throw new TuneSdkException( String.format("Export response 'url' is not defined, response: %s", response.toString())); } return jdataInternalUrl; }
From source file:com.endiansoftware.echo.remotewatch.MainActivity.java
public void callback(String response) { StringBuffer sb = new StringBuffer(); try {//from w ww.jav a 2 s . c om // "kkt_list" ? JSON ? JSONArray Array = new JSONArray(response); for (int i = 0; i < Array.length(); i++) { // bodylist ? JSON ? JSON ? ? JSONObject insideObject = Array.getJSONObject(i); sb.append(insideObject.getString("m_Key")).append(" : ").append(insideObject.getString("m_Value")) .append("\n"); } } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } mDisplay.setText(sb.toString()); }
From source file:com.geecko.QuickLyric.tasks.IdDecoder.java
@Override protected Lyrics doInBackground(String... strings) { String url = strings[0];/*from w w w. j av a 2 s. com*/ String artist; String track; if (url.contains("//www.soundhound.com/")) { try { // todo switch to Jsoup String html = getUrlAsString(url); int preceding = html.indexOf("root.App.trackDa") + 19; int following = html.substring(preceding).indexOf(";"); String data = html.substring(preceding, preceding + following); JSONObject jsonData = new JSONObject(data); artist = jsonData.getString("artist_display_name"); track = jsonData.getString("track_name"); } catch (IOException | JSONException e) { e.printStackTrace(); return new Lyrics(ERROR); } } else if (url.contains("//shz.am/")) { try { Document doc = Jsoup.connect(url.trim()).get(); track = doc.getElementsByAttribute("data-track-title").text(); artist = doc.getElementsByAttribute("data-track-artist").text(); } catch (IOException e) { e.printStackTrace(); return new Lyrics(ERROR); } } else if (url.contains("//play.google.com/store/music/")) { String docID = url.substring(url.indexOf("&tid=") + 5); try { Document doc = Jsoup.connect(url).get(); Element playCell = doc.getElementsByAttributeValue("data-track-docid", docID).get(0); artist = doc.getElementsByClass("primary").text(); track = playCell.parent().parent().child(1).getElementsByClass("title").text(); } catch (IOException e) { e.printStackTrace(); return new Lyrics(ERROR); } } else return new Lyrics(ERROR); Lyrics res = new Lyrics(Lyrics.SEARCH_ITEM); res.setArtist(artist); res.setTitle(track); return res; }
From source file:com.guipenedo.pokeradar.activities.settings.PokemonFilterSettingsActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory();//w w w. j a va2 s. c o m getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this); PreferenceCategory category = new PreferenceCategory(this); category.setTitle(R.string.filter_pokemons); screen.addPreference(category); try { JSONArray pokemonList = new JSONArray(Utils.loadJSONFromFile(this, "pokemon.json")); for (int i = 0; i < pokemonList.length(); i++) { JSONObject pokemon = pokemonList.getJSONObject(i); CheckBoxPreference checkBox = new CheckBoxPreference(this); checkBox.setTitle(pokemon.getString("Name")); checkBox.setIcon(new BitmapDrawable(getResources(), Utils.bitmapForPokemon(this, Integer.parseInt(pokemon.getString("Number"))))); checkBox.setDefaultValue(true); checkBox.setSummary(String.format(getString(R.string.setting_filter_pokemon_summary), pokemon.getString("Name"))); checkBox.setKey("pref_key_show_pokemon_" + Integer.parseInt(pokemon.getString("Number"))); category.addPreference(checkBox); } } catch (JSONException e) { e.printStackTrace(); } setPreferenceScreen(screen); }
From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java
@Override protected void setNotNullValueFromMapToDatabase(final ContentValues values, final String value, final MobeelizerFieldAccessor field, final Map<String, String> options, final MobeelizerErrorsBuilder errors) { try {//from w ww . jav a 2s . c o m JSONObject json = new JSONObject(value); values.put(field.getName() + _GUID, json.getString(JSON_GUID)); values.put(field.getName() + _NAME, json.getString(JSON_NAME)); } catch (JSONException e) { throw new IllegalStateException(e.getMessage(), e); } }
From source file:com.ibm.hellotodoadvanced.MainActivity.java
/** * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list. */// w w w .ja v a 2s.co m private void loadList() { // Send GET Request to Bluemix backend to retreive item list with response listener Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET); request.send(getApplicationContext(), new ResponseListener() { // Loop through JSON response and create local TodoItems if successful @Override public void onSuccess(Response response) { if (response.getStatus() != 200) { Log.e(TAG, "Error pulling items from Bluemix: " + response.toString()); } else { try { mTodoItemList.clear(); JSONArray jsonArray = new JSONArray(response.getResponseText()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject tempTodoJSON = jsonArray.getJSONObject(i); TodoItem tempTodo = new TodoItem(); tempTodo.idNumber = tempTodoJSON.getInt("id"); tempTodo.text = tempTodoJSON.getString("text"); tempTodo.isDone = tempTodoJSON.getBoolean("isDone"); mTodoItemList.add(tempTodo); } // Need to notify adapter on main thread in order for list changes to update visually runOnUiThread(new Runnable() { @Override public void run() { mTodoItemAdapter.notifyDataSetChanged(); Log.i(TAG, "List updated successfully"); if (mSwipeLayout.isRefreshing()) { mSwipeLayout.setRefreshing(false); } } }); } catch (Exception exception) { Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage()); } } } // Log Errors on failure @Override public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) { String errorMessage = ""; if (response != null) { errorMessage += response.toString() + "\n"; } if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); errorMessage += "THROWN" + sw.toString() + "\n"; } if (extendedInfo != null) { errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n"; } if (errorMessage.isEmpty()) errorMessage = "Request Failed With Unknown Error."; Log.e(TAG, "loadList failed with error: " + errorMessage); } }); }
From source file:com.habzy.syncontacts.platform.User.java
/** * Creates and returns an instance of the user from the provided JSON data. * /*from w w w .ja v a 2s. c o m*/ * @param user The JSONObject containing user data * @return user The new instance of Voiper user created from the JSON data. */ public static User valueOf(JSONObject user) { try { final String userName = user.getString("u"); final String firstName = user.has("f") ? user.getString("f") : null; final String lastName = user.has("l") ? user.getString("l") : null; final String cellPhone = user.has("m") ? user.getString("m") : null; final String officePhone = user.has("o") ? user.getString("o") : null; final String homePhone = user.has("h") ? user.getString("h") : null; final String email = user.has("e") ? user.getString("e") : null; final boolean deleted = user.has("d") ? user.getBoolean("d") : false; final int userId = user.getInt("i"); return new User(userName, firstName, lastName, cellPhone, officePhone, homePhone, email, deleted, userId); } catch (final Exception ex) { Log.i("User", "Error parsing JSON user object" + ex.toString()); } return null; }
From source file:org.dasein.cloud.aws.compute.EC2Instance.java
@Override public Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options, Architecture architecture) throws InternalException, CloudException { ProviderContext ctx = getProvider().getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); }/*from w w w . j a v a2 s .co m*/ // FIXME: until core fixes the annotation for architecture let's assume it's nullable String cacheName = "productsALL"; if (architecture != null) { cacheName = "products" + architecture.name(); } Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), cacheName, VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY)); Iterable<VirtualMachineProduct> products = cache.get(ctx); if (products == null) { List<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>(); try { InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json"); if (input != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder json = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { json.append(line); json.append("\n"); } JSONArray arr = new JSONArray(json.toString()); JSONObject toCache = null; for (int i = 0; i < arr.length(); i++) { JSONObject productSet = arr.getJSONObject(i); String cloud, providerName; if (productSet.has("cloud")) { cloud = productSet.getString("cloud"); } else { continue; } if (productSet.has("provider")) { providerName = productSet.getString("provider"); } else { continue; } if (!productSet.has("products")) { continue; } if (toCache == null || (providerName.equals("AWS") && cloud.equals("AWS"))) { toCache = productSet; } if (providerName.equalsIgnoreCase(getProvider().getProviderName()) && cloud.equalsIgnoreCase(getProvider().getCloudName())) { toCache = productSet; break; } } if (toCache == null) { logger.warn("No products were defined"); return Collections.emptyList(); } JSONArray plist = toCache.getJSONArray("products"); for (int i = 0; i < plist.length(); i++) { JSONObject product = plist.getJSONObject(i); boolean supported = false; if (architecture != null) { if (product.has("architectures")) { JSONArray architectures = product.getJSONArray("architectures"); for (int j = 0; j < architectures.length(); j++) { String a = architectures.getString(j); if (architecture.name().equals(a)) { supported = true; break; } } } if (!supported) { continue; } } if (product.has("excludesRegions")) { JSONArray regions = product.getJSONArray("excludesRegions"); for (int j = 0; j < regions.length(); j++) { String r = regions.getString(j); if (r.equals(ctx.getRegionId())) { supported = false; break; } } } if (!supported) { continue; } VirtualMachineProduct prd = toProduct(product); if (prd != null) { if (options != null) { if (options.matches(prd)) { list.add(prd); } } else { list.add(prd); } } } } else { logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json"); } input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json"); if (input != null) { ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>(); TreeSet<String> discard = new TreeSet<String>(); boolean discardAll = false; BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder json = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { json.append(line); json.append("\n"); } JSONArray arr = new JSONArray(json.toString()); JSONObject toCache = null; for (int i = 0; i < arr.length(); i++) { JSONObject listing = arr.getJSONObject(i); String cloud, providerName, endpoint = null; if (listing.has("cloud")) { cloud = listing.getString("cloud"); } else { continue; } if (listing.has("provider")) { providerName = listing.getString("provider"); } else { continue; } if (listing.has("endpoint")) { endpoint = listing.getString("endpoint"); } if (!cloud.equals(getProvider().getCloudName()) || !providerName.equals(getProvider().getProviderName())) { continue; } if (endpoint != null && endpoint.equals(ctx.getCloud().getEndpoint())) { toCache = listing; break; } if (endpoint == null && toCache == null) { toCache = listing; } } if (toCache != null) { if (toCache.has("discardDefaults")) { discardAll = toCache.getBoolean("discardDefaults"); } if (toCache.has("discard")) { JSONArray dlist = toCache.getJSONArray("discard"); for (int i = 0; i < dlist.length(); i++) { discard.add(dlist.getString(i)); } } if (toCache.has("products")) { JSONArray plist = toCache.getJSONArray("products"); for (int i = 0; i < plist.length(); i++) { JSONObject product = plist.getJSONObject(i); boolean supported = false; if (architecture != null) { if (product.has("architectures")) { JSONArray architectures = product.getJSONArray("architectures"); for (int j = 0; j < architectures.length(); j++) { String a = architectures.getString(j); if (architecture.name().equals(a)) { supported = true; break; } } } if (!supported) { continue; } } if (product.has("excludesRegions")) { JSONArray regions = product.getJSONArray("excludesRegions"); for (int j = 0; j < regions.length(); j++) { String r = regions.getString(j); if (r.equals(ctx.getRegionId())) { supported = false; break; } } } if (!supported) { continue; } VirtualMachineProduct prd = toProduct(product); if (prd != null) { customList.add(prd); } } } if (!discardAll) { for (VirtualMachineProduct product : list) { if (!discard.contains(product.getProviderProductId())) { customList.add(product); } } } list = customList; } } products = list; cache.put(ctx, products); } catch (IOException e) { throw new InternalException(e); } catch (JSONException e) { throw new InternalException(e); } } return products; }
From source file:org.dasein.cloud.aws.compute.EC2Instance.java
private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException { /*//from www . j a v a2 s.c om { "architectures":["I32"], "id":"m1.small", "name":"Small Instance (m1.small)", "description":"Small Instance (m1.small)", "cpuCount":1, "rootVolumeSizeInGb":160, "ramSizeInMb": 1700 }, */ VirtualMachineProduct prd = new VirtualMachineProduct(); try { if (json.has("id")) { prd.setProviderProductId(json.getString("id")); } else { return null; } if (json.has("name")) { prd.setName(json.getString("name")); } else { prd.setName(prd.getProviderProductId()); } if (json.has("description")) { prd.setDescription(json.getString("description")); } else { prd.setDescription(prd.getName()); } if (json.has("cpuCount")) { prd.setCpuCount(json.getInt("cpuCount")); } else { prd.setCpuCount(1); } if (json.has("rootVolumeSizeInGb")) { prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE)); } else { prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE)); } if (json.has("ramSizeInMb")) { prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE)); } else { prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE)); } if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) { prd.setStatusDeprecated(); } if (json.has("standardHourlyRates")) { JSONArray rates = json.getJSONArray("standardHourlyRates"); for (int i = 0; i < rates.length(); i++) { JSONObject rate = rates.getJSONObject(i); if (rate.has("rate")) { prd.setStandardHourlyRate((float) rate.getDouble("rate")); } } } } catch (JSONException e) { throw new InternalException(e); } return prd; }