Java Code Examples for org.json.JSONObject#getString()
The following examples show how to use
org.json.JSONObject#getString() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JmessageFlutterPlugin.java From jmessage-flutter-plugin with MIT License | 6 votes |
private void deleteConversation(MethodCall call, Result result) { HashMap<String, Object> map = call.arguments(); try { JSONObject params = new JSONObject(map); String type = params.getString("type"); if (type.equals("single")) { String username = params.getString("username"); if (params.has("appKey") && !TextUtils.isEmpty(params.getString("appKey"))) { JMessageClient.deleteSingleConversation(username, params.getString("appKey")); } else { JMessageClient.deleteSingleConversation(username); } } else if (type.equals("group")) { long groupId = Long.parseLong(params.getString("groupId")); JMessageClient.deleteGroupConversation(groupId); } else if (type.equals("chatRoom")) { long roomId = Long.parseLong(params.getString("roomId")); JMessageClient.deleteChatRoomConversation(roomId); } else { handleResult(ERR_CODE_PARAMETER, "Conversation type is error", result); return; } result.success(null); } catch (JSONException e) { handleResult(ERR_CODE_PARAMETER, ERR_MSG_PARAMETER, result); } }
Example 2
Source File: WhatIfEngineAnalysisState.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private void setCalculatedMember(String cc, WhatIfEngineInstance instance) throws JSONException{ List<CalculatedMember> toreturn = new ArrayList<CalculatedMember>(); if(instance.getPivotModel() instanceof SpagoBIPivotModel){ SpagoBIPivotModel model = (SpagoBIPivotModel)instance.getPivotModel(); if(cc!=null && cc.length()>0){ JSONArray ja = new JSONArray(cc); for(int i=0; i<ja.length(); i++){ JSONObject aSerMember = ja.getJSONObject(i); CalculatedMember cm = new CalculatedMember(model.getCube(), aSerMember.getString("calculateFieldName"), aSerMember.getString("calculateFieldFormula"), aSerMember.getString("parentMemberUniqueName"), aSerMember.getInt("parentMemberAxisOrdinal")); toreturn.add(cm); } } model.setCalculatedFields(toreturn); } }
Example 3
Source File: RESTDataSet.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
protected Map<String, String> getRequestHeadersPropMap(String propName, JSONObject conf, boolean resolveParams) throws JSONException { if (!conf.has(propName) || conf.getString(propName).isEmpty()) { // optional property return Collections.emptyMap(); } Object c = conf.get(propName); if (!(c instanceof JSONObject)) { throw new ConfigurationException(String.format("%s is not another json object in configuration: %s", propName, conf.toString())); } Assert.assertNotNull(c, "property is null"); JSONObject r = (JSONObject) c; Map<String, String> res = new HashMap<String, String>(r.length()); Iterator<String> it = r.keys(); while (it.hasNext()) { String key = it.next(); String value = r.getString(key); if (resolveParams) { key = parametersResolver.resolveAll(key, this); value = parametersResolver.resolveAll(value, this); } res.put(key, value); } return res; }
Example 4
Source File: DScannerParser.java From analysis-model with MIT License | 6 votes |
@Override Optional<Issue> convertToIssue(final JSONObject jsonIssue) { IssueBuilder builder = new IssueBuilder(); if (jsonIssue.has(KEY)) { String key = jsonIssue.getString(KEY); builder.setCategory(key); builder.setSeverity(getSeverityByKey(key)); } if (jsonIssue.has(FILE_NAME)) { builder.setFileName(jsonIssue.getString(FILE_NAME)); } if (jsonIssue.has(LINE)) { builder.setLineStart(jsonIssue.getInt(LINE)); } if (jsonIssue.has(COLUMN)) { builder.setColumnStart(jsonIssue.getInt(COLUMN)); } if (jsonIssue.has(MESSAGE)) { builder.setMessage(jsonIssue.getString(MESSAGE)); } return builder.buildOptional(); }
Example 5
Source File: KernelUpdater.java From SmartFlasher with GNU General Public License v3.0 | 5 votes |
public static String getChangeLog() { try { JSONObject obj = new JSONObject(getKernelInfo()); return (obj.getString("changelog_url")); } catch (JSONException e) { return "Unavailable"; } }
Example 6
Source File: JsonRPC.java From snapdroid with GNU General Public License v3.0 | 5 votes |
void fromJson(JSONObject json) throws JSONException { method = json.getString("method"); if (json.has("params")) params = json.getJSONObject("params"); else params = null; }
Example 7
Source File: RestClient.java From nbp with Apache License 2.0 | 5 votes |
void findDeviceInfo(String ip, int port) throws Exception { request.setUrl(String.format("http://%s:%d/v1beta", ip, port)); JSONObject response = (JSONObject) request.get(String.format("/")); if (isFailed(response)) { String msg = String.format("OpenSDS Device Info error %d: %s", getErrorCode(response), getErrorMessage(response)); throw new Exception(msg); } storage = new StorageMO("OpenSDS", response.getString("name"), "", response.getString("status"), "OpenSDS"); }
Example 8
Source File: BitcoinRPC.java From jelectrum with MIT License | 5 votes |
public SerializedTransaction getTransaction(Sha256Hash hash) { while(true) { try { Random rnd = new Random(); JSONObject msg = new JSONObject(); msg.put("id", "" + rnd.nextInt()); msg.put("method","getrawtransaction"); JSONArray params = new JSONArray(); params.put(hash.toString()); msg.put("params", params); JSONObject reply= sendPost(msg); if (reply.isNull("result")) return null; String str = reply.getString("result"); byte[] data = Hex.decodeHex(str.toCharArray()); return new SerializedTransaction(data); } catch(Throwable t) { event_log.alarm("RPC error on tx "+hash+ " " + t.toString()); t.printStackTrace(); try { Thread.sleep(5000); } catch(Throwable t2){} } } }
Example 9
Source File: TotpAuthenticatorImporter.java From Aegis with GNU General Public License v3.0 | 5 votes |
private static VaultEntry convertEntry(JSONObject obj) throws DatabaseImporterEntryException { try { int base = obj.getInt("base"); String secretString = obj.getString("key"); byte[] secret; switch (base) { case 16: secret = Hex.decode(secretString); break; case 32: secret = Base32.decode(secretString); break; case 64: secret = Base64.decode(secretString); break; default: throw new DatabaseImporterEntryException(String.format("Unsupported secret encoding: base %d", base), obj.toString()); } TotpInfo info = new TotpInfo(secret, "SHA1", 6, 30); String name = obj.optString("name"); String issuer = obj.optString("issuer"); return new VaultEntry(info, name, issuer); } catch (JSONException | OtpInfoException | EncodingException e) { throw new DatabaseImporterEntryException(e, obj.toString()); } }
Example 10
Source File: NoteSync.java From Paperwork-Android with MIT License | 5 votes |
private static Note parseNote(String jsonStr) throws JSONException { JSONObject jsonNote = new JSONObject(jsonStr); JSONObject version = jsonNote.getJSONObject("version"); String id = jsonNote.getString("id"); String title = version.getString("title"); String content = version.getString("content"); Date date = DatabaseHelper.getDateTime(jsonNote.getString("updated_at")); String notebookId = jsonNote.getString("notebook_id"); List<Tag> tags = new ArrayList<>(); JSONArray jsonTags = jsonNote.getJSONArray("tags"); for (int i = 0; i < jsonTags.length(); i++) { JSONObject jsonTag = jsonTags.getJSONObject(i); String tagId = jsonTag.getString("id"); String tagTitle = jsonTag.getString("title"); Tag tag = new Tag(tagId); tag.setTitle(tagTitle); tags.add(tag); } Note note = new Note(id); note.setNotebookId(notebookId); note.setTitle(title); note.setContent(content); note.setUpdatedAt(date); note.setSyncStatus(DatabaseContract.NoteEntry.NOTE_STATUS.synced); note.setTags(tags); return note; }
Example 11
Source File: ServiceSummary.java From mdw with Apache License 2.0 | 5 votes |
public ServiceSummary(JSONObject json) { this.masterRequestId = json.getString("masterRequestId"); this.instanceId = json.optLong("instanceId"); this.attributes = json.optJSONObject("attributes"); if (json.has("microservices")) { JSONArray microservicesArr = json.getJSONArray("microservices"); for (int i = 0; i < microservicesArr.length(); i++) { JSONObject listObj = microservicesArr.getJSONObject(i); String name = listObj.getString("name"); if (listObj.has("instances")) { MicroserviceList instances = new MicroserviceList(name); microservices.put(name, instances); JSONArray instancesArr = listObj.getJSONArray("instances"); for (int j = 0; j < instancesArr.length(); j++) { MicroserviceInstance instance = new MicroserviceInstance(instancesArr.getJSONObject(j)); instance.setMicroservice(name); instances.add(instance); } } } } if (json.has("subServiceSummaries")) { JSONArray serviceSummariesArr = json.getJSONArray("subServiceSummaries"); childServiceSummaryList = new ArrayList<>(); for (int i = 0; i < serviceSummariesArr.length(); i++) childServiceSummaryList.add(new ServiceSummary(serviceSummariesArr.getJSONObject(i))); } }
Example 12
Source File: GitUtilsTest.java From orion.server with Eclipse Public License 1.0 | 5 votes |
@Test public void testGitDirPathLinkedToSubfolder() throws Exception { createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), new File(gitDir, "folder").toURI().toString()); String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION); URI uri = URI.create(toRelativeURI(location)); Set<Entry<IPath, File>> set = GitUtils.getGitDirs(new Path(uri.getPath()), Traverse.GO_UP).entrySet(); assertEquals(1, set.size()); Entry<IPath, File> entry = set.iterator().next(); File gitDirFile = entry.getValue(); assertNotNull(gitDirFile); assertEquals(gitDir, gitDirFile.getParentFile()); IPath path = entry.getKey(); assertEquals(new Path("../"), path); }
Example 13
Source File: Field.java From android_maplib with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void fromJSON(JSONObject jsonObject) throws JSONException { mType = jsonObject.getInt(Constants.JSON_TYPE_KEY); mName = jsonObject.getString(Constants.JSON_NAME_KEY); if (jsonObject.has(JSON_ALIAS_KEY)) { mAlias = jsonObject.getString(JSON_ALIAS_KEY); } }
Example 14
Source File: Closure_47_SourceMapConsumerV3_t.java From coming with MIT License | 5 votes |
/** * Parses the given contents containing a source map. */ public void parse(JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier) throws SourceMapParseException { try { // Check basic assertions about the format. int version = sourceMapRoot.getInt("version"); if (version != 3) { throw new SourceMapParseException("Unknown version: " + version); } String file = sourceMapRoot.getString("file"); if (file.isEmpty()) { throw new SourceMapParseException("File entry is missing or empty"); } if (sourceMapRoot.has("sections")) { // Looks like a index map, try to parse it that way. parseMetaMap(sourceMapRoot, sectionSupplier); return; } lineCount = sourceMapRoot.getInt("lineCount"); String lineMap = sourceMapRoot.getString("mappings"); sources = getJavaStringArray(sourceMapRoot.getJSONArray("sources")); names = getJavaStringArray(sourceMapRoot.getJSONArray("names")); lines = Lists.newArrayListWithCapacity(lineCount); new MappingBuilder(lineMap).build(); } catch (JSONException ex) { throw new SourceMapParseException("JSON parse exception: " + ex); } }
Example 15
Source File: Util.java From barterli_android with Apache License 2.0 | 5 votes |
/** * Parse a server response into a JSON Object. This is a basic * implementation using org.json.JSONObject representation. More * sophisticated applications may wish to do their own parsing. * * The parsed JSON is checked for a variety of error fields and * a FacebookException is thrown if an error condition is set, * populated with the error message and error type or code if * available. * * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ @Deprecated public static JSONObject parseJson(String response) throws JSONException, FacebookError { // Edge case: when sending a POST request to /[post_id]/likes // the return value is 'true' or 'false'. Unfortunately // these values cause the JSONObject constructor to throw // an exception. if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response = "{value : true}"; } JSONObject json = new JSONObject(response); // errors set by the server are not consistent // they depend on the method and endpoint if (json.has("error")) { JSONObject error = json.getJSONObject("error"); throw new FacebookError( error.getString("message"), error.getString("type"), 0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"), "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; }
Example 16
Source File: Server.java From Ptero4J with MIT License | 5 votes |
public Server(PteroAdminAPI api, JSONObject json) { this( api, json.getString("identifier"), json.getString("name"), json.getString("description"), json.getString("uuid"), json.getInt("id"), json.getInt("allocation"), json.getInt("egg"), json.getInt("nest"), json.isNull("external_id") ? -1 : json.getInt("external_id"), json.isNull("pack") ? -1 : json.getInt("pack"), json.getInt("node"), json.getInt("user"), json.getBoolean("suspended"), new ServerContainer( json.getJSONObject("container") ), new ServerLimits( json.getJSONObject("limits") ), new FeatureLimits( json.getJSONObject("feature_limits") ) ); }
Example 17
Source File: BlockcypherAPI.java From cashuwallet with MIT License | 5 votes |
@Override public String broadcast(String transaction) { try { String url = baseUrl + "/txs/push"; String content = "{\"tx\":\"" + transaction + "\"}"; JSONObject data = new JSONObject(urlFetch(url, content)); return data.getString("hash"); } catch (Exception e) { return null; } }
Example 18
Source File: GitMergeSquashTest.java From orion.server with Eclipse Public License 1.0 | 4 votes |
@Test public void testMergeSquashRemovingFolders() throws Exception { // see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders() createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION); String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); String folderName = "folder1"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder1 = getChild(folder, "folder1"); String fileName = "file1.txt"; request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); folderName = "folder2"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder2 = getChild(folder, "folder2"); fileName = "file1.txt"; request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); deleteFile(folder1); deleteFile(folder2); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONArray commitsArray = log(gitHeadUri); assertEquals(3, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toMerge = commit.getString(ProtocolConstants.KEY_NAME); commit = commitsArray.getJSONObject(1); assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toCheckout = commit.getString(ProtocolConstants.KEY_NAME); Repository db1 = getRepositoryForContentLocation(cloneContentLocation); Git git = Git.wrap(db1); git.checkout().setName(toCheckout).call(); JSONObject merge = merge(gitHeadUri, toMerge, true); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD_SQUASHED, mergeResult); request = getGetRequest(folderChildrenLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText())); assertNull(getChildByName(children, "folder1")); assertNull(getChildByName(children, "folder2")); } }
Example 19
Source File: Version6QbeEngineAnalysisStateLoader.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
/** * In previous version, when using IN, NOT IN, BETWEEN or NOT BETWEEN operators, the right operand values contained all values * joined by ","; now those values are converted into an array * @param filterJSON */ private void convertFilter(JSONObject filterJSON) { logger.debug( "IN" ); try { Assert.assertNotNull(filterJSON, "Filter to be converted cannot be null"); JSONArray rightValuesJSON = new JSONArray(); JSONArray rightLastValuesJSON = new JSONArray(); JSONArray rightDefaultValuesJSON = new JSONArray(); logger.debug("Converting filter : " + filterJSON.toString()); String operator = filterJSON.getString("operator"); String rightOperandType = filterJSON.getString( "rightOperandType"); String rightOperandValue = filterJSON.optString( "rightOperandValue"); String rightOperandLastValue = filterJSON.optString( "rightOperandLastValue"); String rightOperandDefaultValue = filterJSON.optString( "rightOperandDefaultValue"); logger.debug("Previous rigth operand : " + rightOperandValue); if ( "Static Value".equalsIgnoreCase(rightOperandType) && ( "IN".equalsIgnoreCase( operator ) || "NOT IN".equalsIgnoreCase( operator ) || "BETWEEN".equalsIgnoreCase( operator ) || "NOT BETWEEN".equalsIgnoreCase( operator ) )) { rightValuesJSON = splitValuesUsingComma(rightOperandValue, operator); rightLastValuesJSON = splitValuesUsingComma(rightOperandLastValue, operator); rightDefaultValuesJSON = splitValuesUsingComma(rightOperandDefaultValue, operator); } else { if (rightOperandValue != null) rightValuesJSON.put( rightOperandValue); if (rightOperandLastValue != null) rightLastValuesJSON.put( rightOperandLastValue); if (rightOperandDefaultValue != null) rightDefaultValuesJSON.put( rightOperandDefaultValue); } logger.debug("New rigth operand : " + rightValuesJSON.toString()); logger.debug("New rigth operand last values : " + rightLastValuesJSON.toString()); logger.debug("New rigth operand default values : " + rightDefaultValuesJSON.toString()); filterJSON.put("rightOperandValue", rightValuesJSON); filterJSON.put("rightOperandLastValue", rightLastValuesJSON); filterJSON.put("rightOperandDefaultValue", rightDefaultValuesJSON); logger.debug("Filter converted properly"); } catch(Throwable t) { throw new SpagoBIEngineRuntimeException("Impossible convert filter " + (filterJSON == null ? "NULL" : filterJSON.toString()), t); } finally { logger.debug( "OUT" ); } }
Example 20
Source File: GitResetTest.java From orion.server with Eclipse Public License 1.0 | 4 votes |
@Test public void testResetMixedAll() throws Exception { createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "hello"); String fileName = "new.txt"; request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder1 = getChild(folder, "folder"); JSONObject folderTxt = getChild(folder1, "folder.txt"); deleteFile(folderTxt); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); // "git status" assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri); // "git add ." request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* add all */); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // "git status" assertStatus(new StatusResult().setAdded(1).setChanged(1).setRemoved(1), gitStatusUri); // "git reset --mixed HEAD" request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // "git status", should be the same result as called for the first time assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri); } }