List of usage examples for org.json JSONObject optString
public String optString(String key)
From source file:com.fortydegree.ra.data.JsonUnmarshaller.java
public static Marker processGeoserviceJSONObject(JSONObject jo) throws JSONException { String type = jo.getString("type"); String metadata = jo.getString("metadata"); JSONObject jsonMetadata = new JSONObject(metadata); String title = jsonMetadata.optString("title"); Marker m = new Marker(jo.getDouble("latitude"), jo.getDouble("longitude"), jo.getDouble("altitude")); m.title = title;/*from w w w .j a v a2 s. c o m*/ m.distance = jo.getDouble("distance"); @SuppressWarnings("rawtypes") Iterator metadataIter = jsonMetadata.keys(); while (metadataIter.hasNext()) { String key = metadataIter.next().toString(); m.setData(key, jsonMetadata.getString(key)); } m.setData("title", title); m.setData("type", type); return m; }
From source file:org.b3log.solo.dev.ArticleGenerator.java
/** * Generates some dummy articles with the specified context. * // w w w.ja v a2s .co m * @param context the specified context * @param request the specified request * @param response the specified response * @throws IOException io exception */ @RequestProcessing(value = "/dev/articles/gen/*", method = HTTPRequestMethod.GET) public void genArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (RuntimeMode.DEVELOPMENT != Latkes.getRuntimeMode()) { LOGGER.log(Level.WARNING, "Article generation just for development mode, " + "current runtime mode is [{0}]", Latkes.getRuntimeMode()); response.sendRedirect("/"); return; } Stopwatchs.start("Gen Articles"); final String requestURI = request.getRequestURI(); final int num = Integer .valueOf(requestURI.substring((Latkes.getContextPath() + "/dev/articles/gen/").length())); try { final ArticleMgmtService articleMgmtService = ArticleMgmtService.getInstance(); final UserQueryService userQueryService = UserQueryService.getInstance(); final JSONObject admin = userQueryService.getAdmin(); final String authorEmail = admin.optString(User.USER_EMAIL); for (int i = 0; i < num; i++) { final JSONObject article = new JSONObject(); // XXX: http://en.wikipedia.org/wiki/Markov_chain article.put(Article.ARTICLE_TITLE, "article title" + i); article.put(Article.ARTICLE_ABSTRACT, "article" + i + " abstract"); article.put(Article.ARTICLE_TAGS_REF, "tag1,tag2"); article.put(Article.ARTICLE_AUTHOR_EMAIL, authorEmail); article.put(Article.ARTICLE_COMMENT_COUNT, 0); article.put(Article.ARTICLE_VIEW_COUNT, 0); article.put(Article.ARTICLE_CONTENT, "article content"); article.put(Article.ARTICLE_PERMALINK, "article" + i + " permalink"); article.put(Article.ARTICLE_HAD_BEEN_PUBLISHED, true); article.put(Article.ARTICLE_IS_PUBLISHED, true); article.put(Article.ARTICLE_PUT_TOP, false); article.put(Article.ARTICLE_CREATE_DATE, new Date()); article.put(Article.ARTICLE_UPDATE_DATE, new Date()); article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random()); article.put(Article.ARTICLE_COMMENTABLE, true); article.put(Article.ARTICLE_VIEW_PWD, ""); article.put(Article.ARTICLE_SIGN_ID, "1"); articleMgmtService.addArticle(new JSONObject().put(Article.ARTICLE, article)); } } catch (final Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } Stopwatchs.end(); response.sendRedirect("/"); }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
private void store_set(Storage storage, UIRequest request, String path) throws UIException { try {//w w w .ja va 2 s. c o m JSONObject restrictions = new JSONObject(); JSONObject data = request.getJSONBody(); if (this.base.equals("role")) { JSONObject fields = data.optJSONObject("fields"); if ((fields.optString("roleName") == null || fields.optString("roleName").equals("")) && fields.optString("displayName") != null) { String test = fields.optString("displayName"); test = test.toUpperCase(); test.replaceAll("\\W", "_"); fields.put("roleName", "ROLE_" + test); data.put("fields", fields); } // If we are updating a role, then we need to clear the userperms cache // Note that creating a role does not impact things until we assign it if (!create) { ResponseCache.clearCache(ResponseCache.USER_PERMS_CACHE); } } if (this.record.getID().equals("media")) { JSONObject fields = data.optJSONObject("fields"); // Handle linked media references if (!fields.has("blobCsid") || StringUtils.isEmpty(fields.getString("blobCsid"))) { // If has blobCsid, already has media link so do nothing more // No media, so consider the source // "sourceUrl" is not a declared field in the app layer config, but the UI passes it in // Can consider mapping srcUri to this if want to clean that up if (fields.has("sourceUrl")) { // We have a source - see where it is from String uri = fields.getString("sourceUrl"); if (uri.contains(BLOBS_SERVICE_URL_PATTERN)) { // This is an uploaded blob, so just pull the csid and set into blobCsid String[] parts = uri.split(BLOBS_SERVICE_URL_PATTERN); // Split to get CSID String[] bits = parts[1].split("/"); // Strip off anything trailing the CSID fields.put("blobCsid", bits[0]); } else { // This must be an external Url source // External Source is handled as params to the CREATE/UPDATE of the media record restrictions.put(Record.BLOB_SOURCE_URL, uri); // Tell the Services to delete the original after creating derivatives restrictions.put(Record.BLOB_PURGE_ORIGINAL, Boolean.toString(true)); } fields.remove("sourceUrl"); data.put("fields", fields); } } } if (this.record.getID().equals("output")) { // // Invoke a report // ReportUtils.invokeReport(this, storage, request, path); } else if (this.record.getID().equals("batchoutput")) { //do a read instead of a create as reports are special and evil JSONObject fields = data.optJSONObject("fields"); JSONObject payload = new JSONObject(); payload.put("mode", "single"); if (fields.has("mode")) { payload.put("mode", fields.getString("mode")); } if (fields.has("docType")) { String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg(); payload.put("docType", type); } if (fields.has("singleCSID")) { payload.put("singleCSID", fields.getString("singleCSID")); } else if (fields.has("groupCSID")) { payload.put("singleCSID", fields.getString("csid")); } JSONObject out = storage.retrieveJSON(base + "/" + path, payload); byte[] data_array = (byte[]) out.get("getByteBody"); String contentDisp = out.has("contentdisposition") ? out.getString("contentdisposition") : null; request.sendUnknown(data_array, out.getString("contenttype"), contentDisp); request.setCacheMaxAgeSeconds(0); // Ensure we do not cache report output. //request.sendJSONResponse(out); request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE); } else { // // <Please document this clause.> // FieldSet displayNameFS = this.record.getDisplayNameField(); String displayNameFieldName = (displayNameFS != null) ? displayNameFS.getID() : null; boolean remapDisplayName = false; String remapDisplayNameValue = null; boolean quickie = false; if (create) { quickie = (data.has("_view") && data.getString("_view").equals("autocomplete")); remapDisplayName = quickie && !"displayName".equals(displayNameFieldName); // Check to see if displayName field needs remapping from UI if (remapDisplayName) { // Need to map the field for displayName, and put it into a proper structure JSONObject fields = data.getJSONObject("fields"); remapDisplayNameValue = fields.getString("displayName"); if (remapDisplayNameValue != null) { // This needs generalizing, in case the remapped name is nested /* * From vocab handling where we know where the termDisplayName is FieldSet parentTermGroup = (FieldSet)displayNameFS.getParent(); JSONArray parentTermInfoArray = new JSONArray(); JSONObject termInfo = new JSONObject(); termInfo.put(displayNameFieldName, remapDisplayNameValue); parentTermInfoArray.put(termInfo); */ fields.put(displayNameFieldName, remapDisplayNameValue); fields.remove("displayName"); } } path = sendJSON(storage, null, data, restrictions); // REM - We needed a way to send query params, so I'm adding "restrictions" here data.put("csid", path); data.getJSONObject("fields").put("csid", path); // Is this needed??? /* String refName = data.getJSONObject("fields").getString("refName"); data.put("urn", refName); data.getJSONObject("fields").put("urn", refName); // This seems wrong - especially when we create from existing. if(remapDisplayName){ JSONObject newdata = new JSONObject(); newdata.put("urn", refName); newdata.put("displayName",quickieDisplayName); data = newdata; } */ } else { path = sendJSON(storage, path, data, restrictions); } if (path == null) { throw new UIException("Insufficient data for create (no fields?)"); } if (this.base.equals("role")) { assignPermissions(storage, path, data); } if (this.base.equals("termlist")) { assignTerms(storage, path, data); } data = reader.getJSON(storage, path); // We do a GET now to read back what we created. if (quickie) { JSONObject newdata = new JSONObject(); JSONObject fields = data.getJSONObject("fields"); String displayName = fields.getString(remapDisplayName ? displayNameFieldName : "displayName"); newdata.put("displayName", remapDisplayNameValue); String refName = fields.getString("refName"); newdata.put("urn", refName); data = newdata; } request.sendJSONResponse(data); request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE); if (create) request.setSecondaryRedirectPath(new String[] { url_base, path }); } } catch (JSONException x) { throw new UIException("Failed to parse JSON: " + x, x); } catch (ExistException x) { UIException uiexception = new UIException(x.getMessage(), 0, "", x); request.sendJSONResponse(uiexception.getJSON()); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: " + x, x); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x); request.setStatus(x.getStatus()); request.setFailure(true, uiexception); request.sendJSONResponse(uiexception.getJSON()); } catch (Exception x) { throw new UIException(x); } }
From source file:com.google.blockly.model.FieldDropdown.java
/** * Loads a FieldDropdown from JSON. This is usually used for the {@link BlockFactory}'s * prototype instances./*w ww . j a v a 2s.c o m*/ * * @param json The JSON representing the object. * @return A new FieldDropdown instance. * @throws BlockLoadingException */ public static FieldDropdown fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_dropdown \"name\" attribute must not be empty."); } JSONArray jsonOptions = json.optJSONArray("options"); ArrayList<Option> optionList = null; if (jsonOptions != null) { int count = jsonOptions == null ? 0 : jsonOptions.length(); optionList = new ArrayList<>(count); for (int i = 0; i < count; i++) { JSONArray option = null; try { option = jsonOptions.getJSONArray(i); } catch (JSONException e) { throw new BlockLoadingException("Error reading dropdown options.", e); } if (option != null && option.length() == 2) { try { String displayName = option.getString(0); String value = option.getString(1); if (TextUtils.isEmpty(value)) { throw new BlockLoadingException("Option values may not be empty"); } optionList.add(new Option(value, displayName)); } catch (JSONException e) { throw new BlockLoadingException("Error reading option values.", e); } } } } return new FieldDropdown(name, new Options(optionList)); }
From source file:edu.stanford.junction.provider.irc.Junction.java
protected void handleScriptRequest(String from, JSONObject req) { if (mActivityScript == null) return;/* w w w . j av a 2 s .c o m*/ try { JSONObject response = new JSONObject(); response.put("scriptResponse", true); response.put("requestId", req.optString("requestId")); response.put("script", mActivityScript.getJSON()); sendMessageToActor(from, response); } catch (JSONException e) { e.printStackTrace(System.err); } }
From source file:edu.stanford.junction.provider.irc.Junction.java
@Override public ActivityScript getActivityScript() { scriptQ.clear();/* w w w . ja v a 2 s .c o m*/ JSONObject req = new JSONObject(); String requestId = UUID.randomUUID().toString(); try { req.put("scriptRequest", "true"); req.put("requestId", requestId); sendMessageToSession(req); } catch (JSONException e) { e.printStackTrace(System.err); return null; } try { int maxTries = 5; long maxWaitPerTry = 2000L; for (int i = 0; i < maxTries; i++) { JSONObject response = scriptQ.poll(maxWaitPerTry, TimeUnit.MILLISECONDS); if (response == null) { return null; } else if (response.optString("requestId").equals(requestId)) { JSONObject script = response.optJSONObject("script"); return new ActivityScript(script); } } } catch (InterruptedException e) { return null; } return null; }
From source file:com.vk.sdkweb.api.model.VKApiCity.java
/** * Fills a City instance from JSONObject. *//*from w w w . j a v a 2 s . c o m*/ public VKApiCity parse(JSONObject from) { id = from.optInt("id"); title = from.optString("title"); return this; }
From source file:com.norman0406.slimgress.API.Interface.RequestResult.java
public static void handleRequest(JSONObject json, RequestResult result) { if (result == null) throw new RuntimeException("invalid result object"); try {/* ww w. j a v a2 s. c om*/ // handle exception string if available String excString = json.optString("exception"); if (excString.length() > 0) result.handleException(excString); // handle error code if available String error = json.optString("error"); if (error.length() > 0) result.handleError(error); else if (json.has("error")) Log.w("RequestResult", "request contains an unknown error type"); // handle game basket if available JSONObject gameBasket = json.optJSONObject("gameBasket"); if (gameBasket != null) result.handleGameBasket(new GameBasket(gameBasket)); // handle result if available JSONObject resultObj = json.optJSONObject("result"); JSONArray resultArr = json.optJSONArray("result"); String resultStr = json.optString("result"); if (resultObj != null) result.handleResult(resultObj); else if (resultArr != null) result.handleResult(resultArr); else if (resultStr != null) result.handleResult(resultStr); else if (json.has("result")) Log.w("RequestResult", "request contains an unknown result type"); result.finished(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:io.github.runassudo.launchert.InstallShortcutReceiver.java
private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) { synchronized (sLock) { Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null); if (DBG)//from w ww. ja v a2 s . c o m Log.d(TAG, "Getting and clearing APPS_PENDING_INSTALL: " + strings); if (strings == null) { return new ArrayList<PendingInstallShortcutInfo>(); } ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>(); for (String json : strings) { try { JSONObject object = (JSONObject) new JSONTokener(json).nextValue(); Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0); Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0); String name = object.getString(NAME_KEY); String iconBase64 = object.optString(ICON_KEY); String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY); String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY); if (iconBase64 != null && !iconBase64.isEmpty()) { byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT); Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length); data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b); } else if (iconResourceName != null && !iconResourceName.isEmpty()) { Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource(); iconResource.resourceName = iconResourceName; iconResource.packageName = iconResourcePackageName; data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); } data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent); PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent); infos.add(info); } catch (org.json.JSONException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } catch (java.net.URISyntaxException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } } sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit(); return infos; } }
From source file:com.funzio.pure2D.particles.nova.vo.MotionTrailVO.java
public MotionTrailVO(final JSONObject json) throws JSONException { name = json.optString("name"); type = json.optString("type", SHAPE); num_points = json.optInt("num_points", 10); }