List of usage examples for org.json JSONException getMessage
public String getMessage()
From source file:com.ryandymock.consumptionvisualization.ParticleRenderer.java
public void onSurfaceCreated(Context context) { // Create the render surfaces for (int i = 0; i < mRenderSurface.length; i++) { mRenderSurface[i] = new RenderSurface(FB_SIZE, FB_SIZE); mRenderSurface[i].setClearColor(Color.argb(0, 255, 255, 255)); }//from w w w .j a v a2 s .com // Create the blur renderer mBlurRenderer = new BlurRenderer(); // Read in our specific json file String materialFile = FileHelper.loadAsset(context.getAssets(), JSON_FILE); try { JSONObject json = new JSONObject(materialFile); // Water particle material. We are utilizing the position and color // buffers returned from LiquidFun directly. mWaterParticleMaterial = new WaterParticleMaterial(context, json.getJSONObject("waterParticlePointSprite")); // Initialize attributes specific to this material mWaterParticleMaterial.addAttribute("aPosition", 2, Material.AttrComponentType.FLOAT, 4, false, 0); mWaterParticleMaterial.addAttribute("aColor", 4, Material.AttrComponentType.UNSIGNED_BYTE, 1, true, 0); mWaterParticleMaterial.addAttribute("aWeight", 1, Material.AttrComponentType.FLOAT, 1, false, 0); mWaterParticleMaterial.setBlendFunc(Material.BlendFactor.ONE, Material.BlendFactor.ONE_MINUS_SRC_ALPHA); // Non-water particle material. We are utilizing the position and // color buffers returned from LiquidFun directly. mParticleMaterial = new ParticleMaterial(context, json.getJSONObject("otherParticlePointSprite")); // Initialize attributes specific to this material mParticleMaterial.addAttribute("aPosition", 2, Material.AttrComponentType.FLOAT, 4, false, 0); mParticleMaterial.addAttribute("aColor", 4, Material.AttrComponentType.UNSIGNED_BYTE, 1, true, 0); mParticleMaterial.setBlendFunc(Material.BlendFactor.ONE, Material.BlendFactor.ONE_MINUS_SRC_ALPHA); // Scrolling texture when we copy water particles from FBO to screen mWaterScreenRenderer = new ScreenRenderer(context, json.getJSONObject("waterParticleToScreen"), mRenderSurface[0].getTexture()); // Scrolling texture when we copy water particles from FBO to screen mScreenRenderer = new ScreenRenderer(context, json.getJSONObject("otherParticleToScreen"), mRenderSurface[1].getTexture()); // Texture for paper JSONObject materialData = json.getJSONObject(PAPER_MATERIAL_NAME); String textureName = materialData.getString(DIFFUSE_TEXTURE_NAME); mPaperTexture = new Texture(context, textureName); } catch (JSONException ex) { Log.e(TAG, "Cannot parse" + JSON_FILE + "\n" + ex.getMessage()); } }
From source file:org.vaadin.addons.locationtextfield.OpenStreetMapGeocoder.java
protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException { final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>(); try {//w w w . ja va 2 s . c o m JSONArray results = new JSONArray(input); boolean ambiguous = results.length() > 1; for (int i = 0; i < results.length(); i++) { JSONObject result = results.getJSONObject(i); GeocodedLocation loc = new GeocodedLocation(); loc.setAmbiguous(ambiguous); loc.setOriginalAddress(address); loc.setGeocodedAddress(result.getString("display_name")); loc.setLat(Double.parseDouble(result.getString("lat"))); loc.setLon(Double.parseDouble(result.getString("lon"))); loc.setType(getLocationType(result)); if (result.has("address")) { JSONObject obj = result.getJSONObject("address"); if (obj.has("house_number")) loc.setStreetNumber(obj.getString("house_number")); if (obj.has("road")) loc.setRoute(obj.getString("road")); if (obj.has("city")) loc.setLocality(obj.getString("city")); if (obj.has("county")) loc.setAdministrativeAreaLevel2(obj.getString("county")); if (obj.has("state")) loc.setAdministrativeAreaLevel1(obj.getString("state")); if (obj.has("postcode")) loc.setPostalCode(obj.getString("postcode")); if (obj.has("country_code")) loc.setCountry(obj.getString("country_code").toUpperCase()); } locations.add(loc); } } catch (JSONException e) { throw new GeocodingException(e.getMessage(), e); } return locations; }
From source file:io.openkit.okcloud.OKCloudAsyncRequest.java
private void postWithCompletionHandler(String relativeURL, final CompletionHandler h) { JSONObject requestParamsJSON = new JSONObject(); try {// ww w . ja v a2 s . com requestParamsJSON.put("app_key", OpenKit.getOKAppID()); for (Map.Entry<String, String> entry : params.entrySet()) { requestParamsJSON.put(entry.getKey(), entry.getValue()); } } catch (JSONException e) { h.complete(null, new OKCloudException("Could not add post params to json object")); return; } OKHTTPClient.postJSON(relativeURL, requestParamsJSON, new AsyncHttpResponseHandler() { @Override public void onStart() { OKLog.v("POST started."); } @Override public void onSuccess(String response) { OKLog.v("POST succeeded, got response: %s", response); h.complete(response, null); } @Override public void onFailure(Throwable e, String response) { String errMessage = e.getMessage(); OKLog.v("POST failed, %s", errMessage); h.complete(null, new OKCloudException(errMessage)); } @Override public void onFinish() { OKLog.v("POST finished."); } }); }
From source file:edu.txstate.dmlab.clusteringwiki.sources.AbsSearchResultCol.java
/** * Creates a collection of results from JSON response * Note that firstPosition must be set before adding * results as result ids depend on that value. * @param res/*from w w w . ja va2 s . c om*/ */ public AbsSearchResultCol(JSONObject res) { if (res == null) return; JSONObject search = null; try { search = res.getJSONObject("search"); JSONArray errors = search.getJSONArray("errors"); if (errors != null && errors.length() > 0) { for (int i = 0; i < errors.length(); i++) { String error = errors.getString(i); addError("AbS API exception: " + error); } return; } } catch (JSONException e) { addError("AbS API exception: " + e.getMessage()); } try { totalResults = search.getInt("totalResults"); firstPosition = search.getInt("firstPosition"); JSONArray j = search.getJSONArray("results"); returnedCount = j.length(); for (int i = 0; i < j.length(); i++) { ICWSearchResult r = new AbsSearchResult(j.getJSONObject(i)); r.setIndex(i); addResult(r); } } catch (JSONException e) { addError("Could not retrieve AbS results: " + e.getMessage()); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Fetch inbox items/*from w ww .j a va 2s.co m*/ * @param args * @param callbackContext */ protected void fetchInbox(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "FETCHINBOX"); if (Notificare.shared().getInboxManager() != null) { int size = Notificare.shared().getInboxManager().getItems().size(); int limit = args.optInt(1, DEFAULT_LIST_SIZE); if (limit <= 0) { limit = DEFAULT_LIST_SIZE; } int skip = args.optInt(0); if (skip < 0) { skip = 0; } if (skip > size) { skip = size; } int end = limit + skip; if (end > size) { end = size; } List<NotificareInboxItem> items = new ArrayList<NotificareInboxItem>( Notificare.shared().getInboxManager().getItems()).subList(skip, end); JSONArray inbox = new JSONArray(); for (NotificareInboxItem item : items) { try { JSONObject result = new JSONObject(); result.put("itemId", item.getItemId()); result.put("notification", item.getNotification().getNotificationId()); result.put("message", item.getNotification().getMessage()); result.put("status", item.getStatus()); result.put("timestamp", dateFormatter.format(item.getTimestamp())); inbox.put(result); } catch (JSONException e) { // Ignore this item Log.w(TAG, "failed to serialize inboxitem: " + e.getMessage()); } } if (callbackContext == null) { return; } JSONObject results = new JSONObject(); try { results.put("inbox", inbox); results.put("total", size); results.put("unread", Notificare.shared().getInboxManager().getUnreadCount()); } catch (JSONException e) { Log.w(TAG, "failed to serialize inbox: " + e.getMessage()); } callbackContext.success(results); } else { if (callbackContext == null) { return; } callbackContext.error("No inbox manager"); } }
From source file:org.nuclearbunny.icybee.net.impl.BitlyImpl.java
public String shrinkURL(String url) throws IOException { /**/*from w w w . ja va 2 s .c o m*/ * bit.ly provides an elegant REST API that returns results in either JSON * or XML format. See http://bitly.com/app/developers for more information. */ StringBuilder buffer = new StringBuilder(BITLY_URL); buffer.append("?version=2.0.1").append("&format=json").append("&login=").append(BITLY_API_LOGIN) .append("&apiKey=").append(BITLY_API_KEY).append("&longUrl=") .append(URLEncoder.encode(url, "UTF-8")); URL bitlyURL = new URL(buffer.toString()); URLConnection connection = bitlyURL.openConnection(); String newURL = url; try { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); JSONObject jsonObject = new JSONObject(new JSONTokener(in)); if ("OK".equals(jsonObject.opt("statusCode"))) { JSONObject results = (JSONObject) jsonObject.get("results"); results = (JSONObject) results.get(url); newURL = results.get("shortUrl").toString(); } } catch (JSONException e) { e.printStackTrace(System.err); throw new IOException(e.getMessage()); } return newURL; }
From source file:org.rapidandroid.activity.FormCreator.java
private void saveState() { // TODO Auto-generated method stub // this.d//from w ww .j ava 2 s. c om JSONObject savedstate = new JSONObject(); EditText etxFormName = (EditText) findViewById(R.id.etx_formname); EditText etxFormPrefix = (EditText) findViewById(R.id.etx_formprefix); EditText etxDescription = (EditText) findViewById(R.id.etx_description); // ListView lsv = (ListView) findViewById(R.id.lsv_createfields); try { savedstate.put(STATE_FORMNAME, etxFormName.getText().toString()); savedstate.put(STATE_PREFIX, etxFormPrefix.getText().toString()); savedstate.put(STATE_DESC, etxDescription.getText().toString()); savedstate.put(STATE_PARSER, mChosenParser.getName()); if (mCurrentFields != null) { int numFields = this.mCurrentFields.size(); for (int i = 0; i < numFields; i++) { Field f = mCurrentFields.get(i); JSONObject fieldobj = new JSONObject(); fieldobj.put(AddField.ResultConstants.RESULT_KEY_FIELDNAME, f.getName()); fieldobj.put(AddField.ResultConstants.RESULT_KEY_DESCRIPTION, f.getDescription()); fieldobj.put(AddField.ResultConstants.RESULT_KEY_FIELDTYPE_ID, ((SimpleFieldType) f.getFieldType()).getId()); savedstate.put("Field" + i, fieldobj); } } getIntent().putExtra("current_form", savedstate.toString()); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Log.d("FormCreator", e1.getMessage()); } }
From source file:com.moarub.kipptapi.KipptAPIToken.java
@Override protected void onPostExecute(StringBuilder builder) { if (builder == null) { return;/*from w w w . ja va2s. c o m*/ } try { JSONObject jobj = (JSONObject) new JSONTokener(builder.toString()).nextValue(); fToken = jobj.getString("api_token"); setUserName(jobj.getString("username")); } catch (JSONException e) { Log.d("ApiTokenFailure", "Can't fetch API Token (Broken JSON) " + e.getMessage()); fListener.setAPIToken(false); return; } Log.d("Result", fToken); fListener.setAPIToken(true); }
From source file:com.tune.reporting.base.endpoints.EndpointBase.java
/** * Fetch all fields from model and related models of this endpoint. * * @return Map All endpoint fields./*ww w . jav a 2 s . c o m*/ * * @throws TuneServiceException If service fails to handle post request. * @throws TuneSdkException If error within SDK. */ protected final Map<String, Map<String, String>> getEndpointFields() throws TuneServiceException, TuneSdkException { Map<String, String> mapQueryString = new HashMap<String, String>(); mapQueryString.put("controllers", this.controller); mapQueryString.put("details", "modelName,fields"); TuneServiceClient client = new TuneServiceClient("apidoc", "get_controllers", this.getAuthKey(), this.getAuthType(), mapQueryString); client.call(); TuneServiceResponse response = client.getResponse(); int httpCode = response.getHttpCode(); JSONArray data = (JSONArray) response.getData(); if (httpCode != HTTP_STATUS_OK) { String requestUrl = response.getRequestUrl(); throw new TuneServiceException( String.format("Connection failure '%s': Request: '%s'", httpCode, requestUrl)); } if ((null == data) || (data.length() == 0)) { String requestUrl = response.getRequestUrl(); throw new TuneServiceException(String.format("Failed to get fields for endpoint: '%s', Request: '%s'", this.controller, requestUrl)); } try { JSONObject endpointMetaData = data.getJSONObject(0); this.endpointModelName = endpointMetaData.getString("modelName"); JSONArray endpointFields = endpointMetaData.getJSONArray("fields"); Map<String, Map<String, String>> fieldsFound = new HashMap<String, Map<String, String>>(); Map<String, Set<String>> relatedFields = new HashMap<String, Set<String>>(); for (int i = 0; i < endpointFields.length(); i++) { JSONObject endpointField = endpointFields.getJSONObject(i); Boolean fieldRelated = endpointField.getBoolean("related"); String fieldType = endpointField.getString("type"); String fieldName = endpointField.getString("name"); Boolean fieldDefault = endpointField.has("fieldDefault") ? endpointField.getBoolean("fieldDefault") : false; if (fieldRelated) { if (fieldType.equals("property")) { String relatedProperty = fieldName; if (!relatedFields.containsKey(relatedProperty)) { relatedFields.put(relatedProperty, new HashSet<String>()); } continue; } String[] fieldRelatedNameParts = fieldName.split("\\."); String relatedProperty = fieldRelatedNameParts[0]; String relatedFieldName = fieldRelatedNameParts[1]; if (!relatedFields.containsKey(relatedProperty)) { relatedFields.put(relatedProperty, new HashSet<String>()); } Set<String> relatedFieldFields = relatedFields.get(relatedProperty); relatedFieldFields.add(relatedFieldName); relatedFields.put(relatedProperty, relatedFieldFields); continue; } Map<String, String> fieldFoundInfo = new HashMap<String, String>(); fieldFoundInfo.put("default", Boolean.toString(fieldDefault)); fieldFoundInfo.put("related", "false"); fieldsFound.put(fieldName, fieldFoundInfo); } Map<String, Map<String, String>> fieldsFoundMerged = new HashMap<String, Map<String, String>>(); Iterator<Map.Entry<String, Map<String, String>>> it = fieldsFound.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Map<String, String>> pairs = it.next(); String fieldFoundName = pairs.getKey(); Map<String, String> fieldFoundInfo = pairs.getValue(); fieldsFoundMerged.put(fieldFoundName, fieldFoundInfo); if ((fieldFoundName != "_id") && fieldFoundName.endsWith("_id")) { String relatedProperty = fieldFoundName.substring(0, fieldFoundName.length() - 3); if (relatedFields.containsKey(relatedProperty) && !relatedFields.get(relatedProperty).isEmpty()) { for (String relatedFieldName : relatedFields.get(relatedProperty)) { if ("id" == relatedFieldName) { continue; } String relatedPropertyFieldName = String.format("%s.%s", relatedProperty, relatedFieldName); Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>(); relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default")); relatedPropertyFieldInfo.put("related", "true"); fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo); } } else { Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>(); relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default")); relatedPropertyFieldInfo.put("related", "true"); String relatedPropertyFieldName = String.format("%s.%s", relatedProperty, "name"); fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo); } } } this.endpointFields = fieldsFoundMerged; } catch (JSONException ex) { throw new TuneSdkException(ex.getMessage(), ex); } catch (Exception ex) { throw new TuneSdkException(ex.getMessage(), ex); } return this.endpointFields; }
From source file:com.tune.reporting.base.endpoints.EndpointBase.java
/** * Helper function for fetching report document given provided job identifier. * * <p>//from www . j ava 2s . c o m * 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; }