List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:com.ecml.MidiOptions.java
/** Initialize the options from a json string * //from ww w.ja v a 2 s.c om * @param jsonString */ public static MidiOptions fromJson(String jsonString) { if (jsonString == null) { return null; } MidiOptions options = new MidiOptions(); try { JSONObject json = new JSONObject(jsonString); JSONArray jsonTracks = json.getJSONArray("tracks"); options.tracks = new boolean[jsonTracks.length()]; for (int i = 0; i < options.tracks.length; i++) { options.tracks[i] = jsonTracks.getBoolean(i); } JSONArray jsonMute = json.getJSONArray("mute"); options.mute = new boolean[jsonMute.length()]; for (int i = 0; i < options.mute.length; i++) { options.mute[i] = jsonMute.getBoolean(i); } JSONArray jsonInstruments = json.getJSONArray("instruments"); options.instruments = new int[jsonInstruments.length()]; for (int i = 0; i < options.instruments.length; i++) { options.instruments[i] = jsonInstruments.getInt(i); } if (json.has("time")) { JSONObject jsonTime = json.getJSONObject("time"); int numer = jsonTime.getInt("numerator"); int denom = jsonTime.getInt("denominator"); int quarter = jsonTime.getInt("quarter"); int tempo = jsonTime.getInt("tempo"); options.time = new TimeSignature(numer, denom, quarter, tempo); } options.useDefaultInstruments = json.getBoolean("useDefaultInstruments"); options.scrollVert = json.getBoolean("scrollVert"); options.showPiano = json.getBoolean("showPiano"); options.showNoteColors = json.getBoolean("showNoteColors"); options.showLyrics = json.getBoolean("showLyrics"); options.delay = json.getInt("delay"); options.twoStaffs = json.getBoolean("twoStaffs"); options.showNoteLetters = json.getInt("showNoteLetters"); options.transpose = json.getInt("transpose"); options.key = json.getInt("key"); options.combineInterval = json.getInt("combineInterval"); options.shade1Color = json.getInt("shade1Color"); options.shade2Color = json.getInt("shade2Color"); options.showMeasures = json.getBoolean("showMeasures"); options.playMeasuresInLoop = json.getBoolean("playMeasuresInLoop"); options.playMeasuresInLoopStart = json.getInt("playMeasuresInLoopStart"); options.playMeasuresInLoopEnd = json.getInt("playMeasuresInLoopEnd"); } catch (Exception e) { return null; } return options; }
From source file:blink.Message.java
/** * a Message object that represents a received message that will be processed from JSON * @param jsonReceived given JSON content of the message * @throws JSONException //w w w . ja v a 2 s . c o m */ public Message(String jsonReceived) { JSONObject json; try { json = new JSONObject(jsonReceived); if (json.has("timestamp")) { timestamp = Long.parseLong((String) json.get("timestamp")); } if (json.has("content")) { text = (String) json.get("content"); } userId = i++; try { type = (String) json.get("type"); } catch (Exception e) { System.err.println("Error receiving message. No type in JSON received."); System.exit(-1); } } catch (JSONException ex) { Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex); } this.json = jsonReceived; }
From source file:org.rapidandroid.activity.FormCreator.java
@Override protected synchronized void onResume() { super.onResume(); Intent intent = getIntent();/* w ww . j a v a 2s.com*/ String currentForm = intent.getStringExtra("current_form"); if (currentForm != null) { try { String contents = new String(currentForm); JSONObject readobject = new JSONObject(contents); EditText etxFormName = (EditText) findViewById(R.id.etx_formname); EditText etxFormPrefix = (EditText) findViewById(R.id.etx_formprefix); EditText etxDescription = (EditText) findViewById(R.id.etx_description); etxFormName.setText(readobject.getString(STATE_FORMNAME)); etxFormPrefix.setText(readobject.getString(STATE_PREFIX)); etxDescription.setText(readobject.getString(STATE_DESC)); boolean checkForFields = true; int i = 0; do { checkForFields = readobject.has("Field" + i); if (checkForFields) { JSONObject fieldBundle = (JSONObject) readobject.get("Field" + i); restoreFieldFromState(fieldBundle); i++; } } while (checkForFields); } catch (Exception e) { Log.e("FOOBAR", e.getMessage(), e); } } }
From source file:org.wso2.emm.agent.services.ProcessMessage.java
public ProcessMessage(Context context, int mode, String message, String recepient) { // TODO Auto-generated constructor stub JSONParser jp = new JSONParser(); params = new HashMap<String, String>(); try {/*from w w w .j a v a2s . co m*/ JSONObject jobj = new JSONObject(message); params.put("code", (String) jobj.get("message")); if (jobj.has("data")) { params.put("data", ((JSONObject) jobj.get("data")).toString()); } operation = new Operation(context, mode, params, recepient); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.clearcenter.mobile_demo.mdRest.java
static public String Login(String host, String username, String password, String token) throws JSONException { if (password == null) Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username); else//from w ww.ja va2 s .com Log.i(TAG, "Login by password, host: " + host + ", username: " + username); try { URL url = new URL("https://" + host + URL_LOGIN); HttpsURLConnection http = CreateConnection(url); if (password != null) { // Setup HTTPS POST request String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&submit=submit"; http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length)); // Write request DataOutputStream outputStream = new DataOutputStream(http.getOutputStream()); outputStream.writeBytes(urlParams); outputStream.flush(); outputStream.close(); } else { http.setRequestMethod("GET"); http.setRequestProperty("Cookie", token); } final StringBuffer response = ProcessRequest(http); // Process response JSONObject json_data = null; try { Log.i(TAG, "response: " + response.toString()); json_data = new JSONObject(response.toString()); } catch (JSONException e) { Log.e(TAG, "JSONException", e); return ""; } if (json_data.has("result")) { final String cookie = http.getHeaderField("Set-Cookie"); Integer result = RESULT_UNKNOWN; try { result = Integer.valueOf(json_data.getString("result")); } catch (NumberFormatException e) { } Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie); if (result == RESULT_SUCCESS) { if (cookie != null) return cookie; else return token; } // All other results are failures... return ""; } } catch (Exception e) { Log.e(TAG, "Exception", e); } Log.i(TAG, "Malformed result"); return ""; }
From source file:com.clearcenter.mobile_demo.mdRest.java
static public String GetSystemInfo(String host, String token, long last_sample) throws JSONException, ParseException, IOException, AuthenticationException { try {/*from w w w .ja v a 2 s.com*/ URL url = new URL("https://" + host + URL_SYSINFO + "/" + last_sample); Log.v(TAG, "GetSystemInfo: host: " + host + ", token: " + token + ", URL: " + url); HttpsURLConnection http = CreateConnection(url); http.setRequestMethod("GET"); http.setRequestProperty("Cookie", token); final StringBuffer response = ProcessRequest(http); // Process response JSONObject json_data = null; try { //Log.i(TAG, "response: " + response.toString()); json_data = new JSONObject(response.toString()); } catch (JSONException e) { Log.e(TAG, "JSONException", e); return ""; } if (json_data.has("result")) { Integer result = RESULT_UNKNOWN; try { result = Integer.valueOf(json_data.getString("result")); } catch (NumberFormatException e) { } Log.d(TAG, "result: " + result.toString()); if (result == RESULT_SUCCESS && json_data.has("data")) { //Log.i(TAG, "data: " + json_data.getString("data")); return json_data.getString("data"); } if (result == RESULT_ACCESS_DENIED) throw new AuthenticationException(); // New cookies? final String cookie = http.getHeaderField("Set-Cookie"); if (cookie != null) { Log.d(TAG, "New cookie!"); } // All other results are failures... throw new IOException(); } } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException", e); throw new ParseException(); } Log.i(TAG, "Malformed result"); throw new IOException(); }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFiles() { URL urlO = null;//from w w w .ja v a2 s . co m try { urlO = new URL(fileUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(fileJson.get("_id").toString()); if (file == null) { file = new File(fileJson, false); } else { file.setName(fileJson.getString("name")); file.setPath(fileJson.getString("path")); file.setCreationDate(fileJson.getString("creationDate")); file.setLastModification(fileJson.getString("lastModification")); file.setTags(fileJson.getString("tags")); if (fileJson.has("binary")) { file.setBinary(fileJson.getJSONObject("binary").toString()); } file.setIsFile(true); file.setFileClass(fileJson.getString("class")); file.setMimeType(fileJson.getString("mime")); file.setSize(fileJson.getLong("size")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing file : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName())); file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory() + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files" + file.getPath() + "/" + file.getName())); file.save(); allFiles.add(file); } } else { EventBus.getDefault() .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error"))); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java
/** * *///from ww w. j av a 2 s. c om @Override protected void onPostExecute(final JSONArray resultList) { try { if (serverConn.hasError()) hasError = true; else if (resultList != null && resultList.length() > 0) { JSONObject resultListItem; try { resultListItem = resultList.getJSONObject(0); /* UUID */ final String uuid = resultListItem.optString("uuid", ""); if (uuid != null && uuid.length() != 0) ConfigHelper.setUUID(activity.getApplicationContext(), uuid); /* urls */ final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings(); final JSONObject urls = resultListItem.optJSONObject("urls"); if (urls != null) { final Iterator<String> keys = urls.keys(); while (keys.hasNext()) { final String key = keys.next(); final String value = urls.optString(key, null); if (value != null) { volatileSettings.put("url_" + key, value); if ("statistics".equals(key)) { ConfigHelper.setCachedStatisticsUrl(value, activity); } else if ("control_ipv4_only".equals(key)) { ConfigHelper.setCachedControlServerNameIpv4(value, activity); } else if ("control_ipv6_only".equals(key)) { ConfigHelper.setCachedControlServerNameIpv6(value, activity); } else if ("url_ipv4_check".equals(key)) { ConfigHelper.setCachedIpv4CheckUrl(value, activity); } else if ("url_ipv6_check".equals(key)) { ConfigHelper.setCachedIpv6CheckUrl(value, activity); } } } } /* qos names */ final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc"); if (qosNames != null) { final Map<String, String> qosNamesMap = new HashMap<String, String>(); for (int i = 0; i < qosNames.length(); i++) { JSONObject json = qosNames.getJSONObject(i); qosNamesMap.put(json.optString("test_type"), json.optString("name")); } ConfigHelper.setCachedQoSNames(qosNamesMap, activity); } /* map server */ final JSONObject mapServer = resultListItem.optJSONObject("map_server"); if (mapServer != null) { final String host = mapServer.optString("host"); final int port = mapServer.optInt("port"); final boolean ssl = mapServer.optBoolean("ssl"); if (host != null && port > 0) ConfigHelper.setMapServer(host, port, ssl); } /* control server version */ final JSONObject versions = resultListItem.optJSONObject("versions"); if (versions != null) { if (versions.has("control_server_version")) { ConfigHelper.setControlServerVersion(activity, versions.optString("control_server_version")); } } // /////////////////////////////////////////////////////// // HISTORY / FILTER final JSONObject historyObject = resultListItem.getJSONObject("history"); final JSONArray deviceArray = historyObject.getJSONArray("devices"); final JSONArray networkArray = historyObject.getJSONArray("networks"); final String historyDevices[] = new String[deviceArray.length()]; for (int i = 0; i < deviceArray.length(); i++) historyDevices[i] = deviceArray.getString(i); final String historyNetworks[] = new String[networkArray.length()]; for (int i = 0; i < networkArray.length(); i++) historyNetworks[i] = networkArray.getString(i); // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// activity.setSettings(historyDevices, historyNetworks); activity.setHistoryDirty(true); } catch (final JSONException e) { e.printStackTrace(); } } else Log.i(DEBUG_TAG, "LEERE LISTE"); } finally { if (endTaskListener != null) endTaskListener.taskEnded(resultList); } }
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./*from w ww . j ava 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>/* w w w. j a va2s . c om*/ * 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; }