List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Delete an inbox item/*w ww . jav a 2 s.c o m*/ * @param args * @param callbackContext */ protected void deleteInboxItem(JSONArray args, final CallbackContext callbackContext) { if (Notificare.shared().getInboxManager() != null) { try { JSONObject item = args.getJSONObject(0); item.put("_id", item.getString("itemId")); item.put("opened", item.getBoolean("status")); item.put("time", item.getString("timestamp")); final NotificareInboxItem inboxItem = new NotificareInboxItem(item); Notificare.shared().deleteInboxItem(inboxItem.getItemId(), new NotificareCallback<Boolean>() { @Override public void onSuccess(Boolean result) { Notificare.shared().getInboxManager().removeItem(inboxItem); if (callbackContext == null) { return; } callbackContext.success(); } @Override public void onError(NotificareError notificareError) { if (callbackContext == null) { return; } callbackContext.error("Could not delete inbox item"); } }); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } } else { if (callbackContext == null) { return; } callbackContext.error("No inbox manager"); } }
From source file:com.norman0406.slimgress.API.Knobs.ClientFeatureKnobs.java
public ClientFeatureKnobs(JSONObject json) throws JSONException { super(json);/*from ww w . j a v a2s .c om*/ mEnableInviteNag = json.getBoolean("enableInviteNag"); mFireMode = json.getInt("fireMode"); mEnableRecycle = json.getBoolean("enableRecycle"); mInviteNagDelayDays = json.getInt("inviteNagDelayDays"); mRefreshTimeMS = json.getInt("refreshTimeMs"); }
From source file:org.stockchart.series.LinearSeries.java
public void fromJSONObject(JSONObject j) throws JSONException { super.fromJSONObject(j); fPointSizeInPercents = (float) j.getDouble("pointSize"); fPointStyle = PointStyle.valueOf(j.getString("pointStyle")); fPointsVisible = j.getBoolean("pointsVisible"); fPointAppearance.fromJSONObject(j.getJSONObject("pointAppearance")); }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Fills articles in index.ftl./*from ww w . j a v a 2 s. c o m*/ * * @param dataModel data model * @param currentPageNum current page number * @param preference the specified preference * @throws ServiceException service exception */ public void fillIndexArticles(final Map<String, Object> dataModel, final int currentPageNum, final JSONObject preference) throws ServiceException { Stopwatchs.start("Fill Index Articles"); try { final int pageSize = preference.getInt(Preference.ARTICLE_LIST_DISPLAY_COUNT); final int windowSize = preference.getInt(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE); final JSONObject statistic = statisticQueryService.getStatistic(); final int publishedArticleCnt = statistic.getInt(Statistic.STATISTIC_PUBLISHED_ARTICLE_COUNT); final int pageCount = (int) Math.ceil((double) publishedArticleCnt / (double) pageSize); final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize) .setPageCount(pageCount) .setFilter(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, PUBLISHED)) .addSort(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING).index(Article.ARTICLE_PERMALINK); if (preference.getBoolean(Preference.ENABLE_ARTICLE_UPDATE_HINT)) { query.addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING); } else { query.addSort(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING); } final JSONObject result = articleRepository.get(query); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); if (0 != pageNums.size()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); final List<JSONObject> articles = org.b3log.latke.util.CollectionUtils .jsonArrayToList(result.getJSONArray(Keys.RESULTS)); final boolean hasMultipleUsers = Users.getInstance().hasMultipleUsers(); if (hasMultipleUsers) { setArticlesExProperties(articles, preference); } else { if (!articles.isEmpty()) { final JSONObject author = articleUtils.getAuthor(articles.get(0)); setArticlesExProperties(articles, author, preference); } } dataModel.put(Article.ARTICLES, articles); } catch (final JSONException e) { LOGGER.log(Level.SEVERE, "Fills index articles failed", e); throw new ServiceException(e); } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, "Fills index articles failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Sets some extra properties into the specified article with the specified author and preference, performs content and * abstract editor processing.//from w ww . java 2s . co m * * <p> * Article ext properties: * <pre> * { * ...., * "authorName": "", * "authorId": "", * "hasUpdated": boolean * } * </pre> * </p> * * @param article the specified article * @param author the specified author * @param preference the specified preference * @throws ServiceException service exception * @see #setArticlesExProperties(java.util.List, org.json.JSONObject) */ private void setArticleExProperties(final JSONObject article, final JSONObject author, final JSONObject preference) throws ServiceException { try { final String authorName = author.getString(User.USER_NAME); article.put(Common.AUTHOR_NAME, authorName); final String authorId = author.getString(Keys.OBJECT_ID); article.put(Common.AUTHOR_ID, authorId); if (preference.getBoolean(Preference.ENABLE_ARTICLE_UPDATE_HINT)) { article.put(Common.HAS_UPDATED, articleUtils.hasUpdated(article)); } else { article.put(Common.HAS_UPDATED, false); } processArticleAbstract(preference, article); articleQueryService.markdown(article); } catch (final Exception e) { LOGGER.log(Level.SEVERE, "Sets article extra properties failed", e); throw new ServiceException(e); } }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Sets some extra properties into the specified article with the specified preference, performs content and * abstract editor processing.//w ww . j a v a 2 s . c o m * * <p> * Article ext properties: * <pre> * { * ...., * "authorName": "", * "authorId": "", * "hasUpdated": boolean * } * </pre> * </p> * * @param article the specified article * @param preference the specified preference * @throws ServiceException service exception * @see #setArticlesExProperties(java.util.List, org.json.JSONObject) */ private void setArticleExProperties(final JSONObject article, final JSONObject preference) throws ServiceException { try { final JSONObject author = articleUtils.getAuthor(article); final String authorName = author.getString(User.USER_NAME); article.put(Common.AUTHOR_NAME, authorName); final String authorId = author.getString(Keys.OBJECT_ID); article.put(Common.AUTHOR_ID, authorId); if (preference.getBoolean(Preference.ENABLE_ARTICLE_UPDATE_HINT)) { article.put(Common.HAS_UPDATED, articleUtils.hasUpdated(article)); } else { article.put(Common.HAS_UPDATED, false); } processArticleAbstract(preference, article); articleQueryService.markdown(article); } catch (final Exception e) { LOGGER.log(Level.SEVERE, "Sets article extra properties failed", e); throw new ServiceException(e); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitCherryPickTest.java
@Test public void testCherryPick() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); String branchesLocation = clone.getString(GitConstants.KEY_BRANCH); // 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 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); JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "first line\nsec. line\nthird line\n"); addFile(testTxt);//from ww w. ja v a 2 s . com commitFile(testTxt, "lines in test.txt", false); // create new file String fileName = "new.txt"; request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); // add all request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "added new.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // modify modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n"); // add addFile(testTxt); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enlarged test.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // modify modifyFile(testTxt, "first line\nsecond line\nthird line\nfourth line\n"); // add addFile(testTxt); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "fixed test.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // remember starting point and commit to cherry-pick JSONArray commitsArray = log(gitHeadUri); assertEquals(5, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toCherryPick = commit.getString(ProtocolConstants.KEY_NAME); commit = commitsArray.getJSONObject(3); assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String startingPoint = commit.getString(ProtocolConstants.KEY_NAME); // branch response = branch(branchesLocation, "side", startingPoint); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); response = checkoutBranch(cloneLocation, "side"); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // modify modifyFile(testTxt, "first line\nsec. line\nthird line\nfeature++\n"); // add addFile(testTxt); // commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enhanced test.txt", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // CHERRY-PICK JSONObject cherryPick = cherryPick(gitHeadUri, toCherryPick); CherryPickStatus mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT)); assertEquals(CherryPickStatus.OK, mergeResult); assertTrue(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED)); // try again, should be OK, but nothing changed cherryPick = cherryPick(gitHeadUri, toCherryPick); mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT)); assertEquals(CherryPickStatus.OK, mergeResult); assertFalse(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED)); // 'new.txt' should be not there JSONObject newTxt = getChild(folder, "new.txt"); assertNull(newTxt); // check cherry-pick result in the file request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("first line\nsecond line\nthird line\nfeature++\n", response.getText()); // check log commitsArray = log(gitHeadUri); assertEquals(4, commitsArray.length()); commit = commitsArray.getJSONObject(0); assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(1); assertEquals("enhanced test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(2); assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(3); assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); } }
From source file:com.ecml.MidiOptions.java
/** Initialize the options from a json string * /*from www .ja v a 2s .c o m*/ * @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:com.esri.cordova.geolocation.AdvancedGeolocation.java
private void parseArgs(JSONArray args) { Log.d(TAG, "Execute args: " + args.toString()); if (args.length() > 0) { try {/*w w w . j a va2s.co m*/ 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: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 w w . j a v a 2 s . co 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; }