List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:org.wso2.emm.agent.services.ProcessMessage.java
private void messageExecute(String msg) { stillProcessing = true;// w ww. ja v a 2s . c o m JSONArray repArray = new JSONArray(); JSONObject jsReply = null; String msgId = ""; JSONArray dataReply = null; try { JSONArray jArr = new JSONArray(msg.trim()); for (int i = 0; i < jArr.length(); i++) { JSONArray innerArr = new JSONArray(jArr.getJSONObject(i).getString("data")); String featureCode = jArr.getJSONObject(i).getString("code"); dataReply = new JSONArray(); jsReply = new JSONObject(); jsReply.put("code", featureCode); for (int x = 0; x < innerArr.length(); x++) { msgId = innerArr.getJSONObject(x).getString("messageId"); jsReply.put("messageId", msgId); if (featureCode.equals(CommonUtilities.OPERATION_POLICY_BUNDLE)) { SharedPreferences mainPrefp = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); Editor editorp = mainPrefp.edit(); editorp.putString("policy", ""); editorp.commit(); SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); Editor editor = mainPref.edit(); String arrToPut = innerArr.getJSONObject(0).getJSONArray("data").toString(); editor.putString("policy", arrToPut); editor.commit(); } String msgData = innerArr.getJSONObject(x).getString("data"); JSONObject dataObj = new JSONObject("{}"); operation = new Operation(context); if (featureCode.equalsIgnoreCase(CommonUtilities.OPERATION_POLICY_REVOKE)) { operation.operate(featureCode, jsReply); jsReply.put("status", msgId); } else { if (msgData.charAt(0) == '[') { JSONArray dataArr = new JSONArray(msgData); for (int a = 0; a < dataArr.length(); a++) { JSONObject innterDataObj = dataArr.getJSONObject(a); featureCode = innterDataObj.getString("code"); String dataTemp = innterDataObj.getString("data"); if (!dataTemp.isEmpty() && dataTemp != null && !dataTemp.equalsIgnoreCase("null")) dataObj = innterDataObj.getJSONObject("data"); dataReply = operation.operate(featureCode, dataObj); //dataReply.put(resultJson); } } else { if (!msgData.isEmpty() && msgData != null && !msgData.equalsIgnoreCase("null")) if (msgData.charAt(0) == '{') { dataObj = new JSONObject(msgData); } dataReply = operation.operate(featureCode, dataObj); //dataReply.put(resultJson); } } } jsReply.put("data", dataReply); repArray.put(jsReply); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (Operation.enterpriseWipe == false) { SharedPreferences mainPref = context.getSharedPreferences( context.getResources().getString(R.string.shared_pref_package), Context.MODE_PRIVATE); String regId = mainPref.getString(context.getResources().getString(R.string.shared_pref_regId), ""); PayloadParser ps = new PayloadParser(); replyPayload = ps.generateReply(repArray, regId); if (CommonUtilities.DEBUG_MODE_ENABLED) { Log.e(TAG, "replyPlayload -" + replyPayload); } stillProcessing = false; getOperations(replyPayload); } } }
From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java
private void parseArgs(JSONArray args) { Log.d(TAG, "Execute args: " + args.toString()); if (args.length() > 0) { try {// w ww . j a v a2 s .c om final JSONObject obj = args.getJSONObject(0); _minTime = obj.getLong("minTime"); _minDistance = obj.getLong("minDistance"); _noWarn = obj.getBoolean("noWarn"); _providers = obj.getString("providers"); _useCache = obj.getBoolean("useCache"); _returnSatelliteData = obj.getBoolean("satelliteData"); _buffer = obj.getBoolean("buffer"); _signalStrength = obj.getBoolean("signalStrength"); _bufferSize = obj.getInt("bufferSize"); } catch (Exception exc) { Log.d(TAG, ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage()); sendCallback(PluginResult.Status.ERROR, ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage()); } } }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFiles() { URL urlO = null;//from w w w . j a va 2s . c o 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:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFolders() { //File.deleteAllFolders(); URL urlO = null;//w w w . j a v a 2 s .c o m try { urlO = new URL(folderUrl); 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 folderJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(folderJson.get("_id").toString()); if (file == null) { file = new File(folderJson, true); } else { file.setName(folderJson.getString("name")); file.setPath(folderJson.getString("path")); file.setCreationDate(folderJson.getString("creationDate")); file.setLastModification(folderJson.getString("lastModification")); file.setTags(folderJson.getString("tags")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing remote folder : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName())); file.save(); createFolder(file.getPath(), file.getName()); allFiles.add(file); } } else { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response")); 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:mr.robotto.engine.loader.components.mesh.MrMeshLoader.java
private void loadKeys(Map<Integer, MrBufferKey> list, JSONArray keys) throws JSONException { for (int i = 0; i < keys.length(); i++) { JSONObject jsonKey = keys.getJSONObject(i); MrBufferKeyLoader loader = new MrBufferKeyLoader(jsonKey); MrBufferKey key = loader.parse(); //list.addAttributeKey(key); list.put(key.getAttributeType(), key); }//from w w w . j a v a 2 s. co m }
From source file:com.wglxy.example.dashL.SearchActivity.java
ArrayList<User> parseJSON(String results) throws JSONException, NullPointerException { ArrayList<User> list = new ArrayList<User>(); JSONObject jsonResult = new JSONObject(results); int status = jsonResult.getInt("status"); int numResults = jsonResult.getInt("numResults"); if (status != 200 && numResults <= 0) return list; else {/* w w w. j a va 2 s .co m*/ JSONArray arr = jsonResult.getJSONArray("results"); Log.e(LOG_TAG, "results: " + arr.length()); for (int i = 0; i < arr.length(); i++) { JSONObject jsonObject = arr.getJSONObject(i); User user = new User(); int id = jsonObject.getInt("id"); String email = jsonObject.getString("email"); String first_name = jsonObject.getString("first_name"); String last_name = jsonObject.getString("last_name"); String business_name = jsonObject.getString("business_name"); String services = jsonObject.getString("services"); String address = jsonObject.getString("address"); int stars = jsonObject.getInt("stars"); String image = Constants.API_BASE_IMAGE_URL + jsonObject.getString("image"); Log.e(LOG_TAG, "image: " + image); user.setId(id); user.setEmail(email); user.setFirst_name(first_name); user.setLast_name(last_name); user.setBusiness_name(business_name); user.setAddress(address); user.setServices(services); user.setStars(stars); user.setImage(image); list.add(user); } return list; } }
From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java
/** * *///from ww w . ja v a2 s . c o m @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.brennasoft.facebookdashclockextension.fbclient.NotificationsRequest.java
private NotificationsResponse parseResponse(Response response) { NotificationsResponse notificationsResponse = new NotificationsResponse(); GraphObject graphObject = response.getGraphObject(); try {/*w w w .j a va 2 s .c o m*/ JSONArray data = graphObject.getInnerJSONObject().getJSONArray("data"); notificationsResponse.count = data.length(); for (int i = 0; i < data.length(); i++) { JSONObject object = data.getJSONObject(i); notificationsResponse.addNotification(object.getString("notification_id"), object.getLong("updated_time"), object.getString("title_text")); } notificationsResponse.success = true; } catch (JSONException e) { Crashlytics.logException(e); } return notificationsResponse; }
From source file:org.hydracache.client.partition.PartitionAwareClient.java
@Override public synchronized List<Identity> listNodes() throws Exception { log.info("Retrieving list of nodes."); RequestMessage requestMessage = new RequestMessage(); requestMessage.setMethod(GET);// ww w . j a v a 2s. com requestMessage.setPath("registry"); // Pick a random node to connect to Random rnd = new Random(); int nextInt = rnd.nextInt(seedServerIds.size()); Identity identity = seedServerIds.get(nextInt); ResponseMessage responseMessage = messager.sendMessage(identity, nodePartition, requestMessage); if (responseMessage == null) throw new ClientException("Failed to retrieve node registry."); List<Identity> identities = new LinkedList<Identity>(); String registry = new String(responseMessage.getResponseBody()); log.debug("Received registry: " + registry); JSONArray seedServerArray = new JSONArray(registry); for (int i = 0; i < seedServerArray.length(); i++) { JSONObject seedServer = seedServerArray.getJSONObject(i); identities.add(new Identity(InetAddress.getByName(seedServer.getString(IP)), seedServer.getInt(PORT))); } return identities; }
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 . j a va 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; }