List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioSong GetCurrentSongInformation(Context context, RadioRedditApplication application) { RadioSong radiosong = new RadioSong(); radiosong.ErrorMessage = ""; try {/* www. j a va 2 s . c o m*/ String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status + context.getString(R.string.radio_reddit_status); String outputStatus = ""; boolean errorGettingStatus = false; try { outputStatus = HTTPUtil.get(context, status_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingStatus = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingStatus && outputStatus.length() > 0) { JSONTokener status_tokener = new JSONTokener(outputStatus); JSONObject status_json = new JSONObject(status_tokener); radiosong.Playlist = status_json.getString("playlist"); JSONObject songs = status_json.getJSONObject("songs"); JSONArray songs_array = songs.getJSONArray("song"); // get the first song in the array JSONObject song = songs_array.getJSONObject(0); radiosong.ID = song.getInt("id"); radiosong.Title = song.getString("title"); radiosong.Artist = song.getString("artist"); radiosong.Redditor = song.getString("redditor"); radiosong.Genre = song.getString("genre"); radiosong.CumulativeScore = song.getString("score"); if (radiosong.CumulativeScore.equals("{}")) radiosong.CumulativeScore = null; radiosong.Reddit_title = song.getString("reddit_title"); radiosong.Reddit_url = song.getString("reddit_url"); if (song.has("preview_url")) radiosong.Preview_url = song.getString("preview_url"); if (song.has("download_url")) radiosong.Download_url = song.getString("download_url"); if (song.has("bandcamp_link")) radiosong.Bandcamp_link = song.getString("bandcamp_link"); if (song.has("bandcamp_art")) radiosong.Bandcamp_art = song.getString("bandcamp_art"); if (song.has("itunes_link")) radiosong.Itunes_link = song.getString("itunes_link"); if (song.has("itunes_art")) radiosong.Itunes_art = song.getString("itunes_art"); if (song.has("itunes_price")) radiosong.Itunes_price = song.getString("itunes_price"); // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radiosong.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Song hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radiosong.Score = score; radiosong.Likes = likes; radiosong.Name = name; } else { radiosong.Score = "?"; radiosong.Likes = "null"; radiosong.Name = ""; } return radiosong; } return null; } catch (Exception ex) { // We fail to get the current song information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); radiosong.ErrorMessage = ex.toString(); return radiosong; } }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioEpisode GetCurrentEpisodeInformation(Context context, RadioRedditApplication application) { RadioEpisode radioepisode = new RadioEpisode(); radioepisode.ErrorMessage = ""; try {//from w ww . j av a 2 s . c o m String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status + context.getString(R.string.radio_reddit_status); String outputStatus = ""; boolean errorGettingStatus = false; try { outputStatus = HTTPUtil.get(context, status_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingStatus = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingStatus && outputStatus.length() > 0) { JSONTokener status_tokener = new JSONTokener(outputStatus); JSONObject status_json = new JSONObject(status_tokener); radioepisode.Playlist = status_json.getString("playlist"); JSONObject episodes = status_json.getJSONObject("episodes"); JSONArray episodes_array = episodes.getJSONArray("episode"); // get the first episode in the array JSONObject song = episodes_array.getJSONObject(0); radioepisode.ID = song.getInt("id"); radioepisode.EpisodeTitle = song.getString("episode_title"); radioepisode.EpisodeDescription = song.getString("episode_description"); radioepisode.EpisodeKeywords = song.getString("episode_keywords"); radioepisode.ShowTitle = song.getString("show_title"); radioepisode.ShowHosts = song.getString("show_hosts").replaceAll(",", ", "); radioepisode.ShowRedditors = song.getString("show_redditors").replaceAll(",", ", "); radioepisode.ShowGenre = song.getString("show_genre"); radioepisode.ShowFeed = song.getString("show_feed"); radioepisode.Reddit_title = song.getString("reddit_title"); radioepisode.Reddit_url = song.getString("reddit_url"); if (song.has("preview_url")) radioepisode.Preview_url = song.getString("preview_url"); if (song.has("download_url")) radioepisode.Download_url = song.getString("download_url"); // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radioepisode.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Episode hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radioepisode.Score = score; radioepisode.Likes = likes; radioepisode.Name = name; } else { radioepisode.Score = "?"; radioepisode.Likes = "null"; radioepisode.Name = ""; } return radioepisode; } return null; } catch (Exception ex) { // We fail to get the current song information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); radioepisode.ErrorMessage = ex.toString(); return radioepisode; } }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static List<RadioSong> GetTopChartsByType(Context context, RadioRedditApplication application, String type) {// w ww . j a v a 2 s . co m List<RadioSong> radiosongs = new ArrayList<RadioSong>(); try { String chart_url = ""; if (type.equals("all")) chart_url = context.getString(R.string.radio_reddit_charts_all); else if (type.equals("month")) chart_url = context.getString(R.string.radio_reddit_charts_month); else if (type.equals("week")) chart_url = context.getString(R.string.radio_reddit_charts_week); else if (type.equals("day")) chart_url = context.getString(R.string.radio_reddit_charts_day); // TODO: might could merge this code with GetCurrentSongInformation String outputStatus = ""; boolean errorGettingStatus = false; try { outputStatus = HTTPUtil.get(context, chart_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingStatus = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingStatus && outputStatus.length() > 0) { JSONTokener status_tokener = new JSONTokener(outputStatus); JSONObject status_json = new JSONObject(status_tokener); JSONObject songs = status_json.getJSONObject("songs"); JSONArray songs_array = songs.getJSONArray("song"); // get the first song in the array for (int i = 0; i < songs_array.length(); i++) { RadioSong radiosong = new RadioSong(); radiosong.ErrorMessage = ""; JSONObject song = songs_array.getJSONObject(i); //radiosong.ID = song.getInt("id"); radiosong.Title = song.getString("title"); radiosong.Artist = song.getString("artist"); radiosong.Redditor = song.getString("redditor"); radiosong.Genre = song.getString("genre"); //radiosong.CumulativeScore = song.getString("score"); //if(radiosong.CumulativeScore.equals("{}")) // radiosong.CumulativeScore = null; radiosong.Reddit_title = song.getString("reddit_title"); radiosong.Reddit_url = song.getString("reddit_url"); if (song.has("preview_url")) radiosong.Preview_url = song.getString("preview_url"); if (song.has("download_url")) radiosong.Download_url = song.getString("download_url"); if (song.has("bandcamp_link")) radiosong.Bandcamp_link = song.getString("bandcamp_link"); if (song.has("bandcamp_art")) radiosong.Bandcamp_art = song.getString("bandcamp_art"); if (song.has("itunes_link")) radiosong.Itunes_link = song.getString("itunes_link"); if (song.has("itunes_art")) radiosong.Itunes_art = song.getString("itunes_art"); if (song.has("itunes_price")) radiosong.Itunes_price = song.getString("itunes_price"); radiosongs.add(radiosong); } } } catch (Exception ex) { // We fail to get the current song information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); // TODO: return error message?? Might need to wrap List<RadioSong> in an object that has an ErrorMessage data member //radiosong.ErrorMessage = ex.toString(); //return radiosong; } return radiosongs; }
From source file:com.fortydegree.ra.data.JsonUnmarshaller.java
public static List<Marker> load(JSONObject root) throws JSONException { JSONObject jo = null;/*from ww w . ja va2 s . co m*/ JSONArray dataArray = null; List<Marker> markers = new ArrayList<Marker>(); if (root.has("results")) { dataArray = root.getJSONArray("results"); int top = Math.min(MAX_JSON_OBJECTS, dataArray.length()); for (int i = 0; i < top; i++) { jo = dataArray.getJSONObject(i); Marker ma = processGeoserviceJSONObject(jo); if (ma != null) markers.add(ma); } } return markers; }
From source file:de.kp.ames.web.function.domain.model.ImageObject.java
/** * Create RegistryObject representation of ImageObject * //from w w w. ja va 2 s .c om * @param data * @return * @throws Exception */ public RegistryObjectImpl create(JSONObject jForm) throws Exception { /* * Create extrinsic object that serves as a wrapper * for the respective image */ // ExtrinsicObjectImpl eo = jaxrLCM.createExtrinsicObject(); if (eo == null) throw new JAXRException("[ImageObject] Creation of ExtrinsicObject failed."); /* * Identifier */ String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.IMAGE_PRE); eo.setLid(eid); eo.getKey().setId(eid); /* * Home url */ String home = jaxrHandle.getEndpoint().replace("/saml", ""); eo.setHome(home); /* * The document is actually transient and managed by the image cache */ ImageCacheManager cacheManager = ImageCacheManager.getInstance(); String key = jForm.getString(JsonConstants.J_KEY); DmsImage image = (DmsImage) cacheManager.getFromCache(key); if (image == null) throw new Exception("[ImageObject] Image with id <" + key + "> not found."); /* * Name & description */ String name = jForm.has(RIM_NAME) ? jForm.getString(RIM_NAME) : null; String desc = jForm.has(RIM_DESC) ? jForm.getString(RIM_DESC) : null; name = (name == null) ? image.getName() : name; int pos = name.lastIndexOf("."); if (pos != -1) name = name.substring(0, pos); eo.setName(jaxrLCM.createInternationalString(name)); desc = (desc == null) ? FncMessages.NO_DESCRIPTION_DESC : desc; eo.setDescription(jaxrLCM.createInternationalString(desc)); /* * Classifications */ JSONArray jClases = jForm.has(RIM_CLAS) ? new JSONArray(jForm.getString(RIM_CLAS)) : null; if (jClases != null) { List<ClassificationImpl> classifications = createClassifications(jClases); /* * Set composed object */ eo.addClassifications(classifications); } /* * Mimetype & repository item */ String mimetype = image.getMimetype(); DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(image.getBytes(), mimetype)); eo.setMimeType(mimetype); eo.setRepositoryItem(handler); /* * Indicate as created */ this.created = true; return eo; }
From source file:gmc.hotplate.util.JsonParser.java
public Recipe parseRecipeObject(JSONObject obj) { Recipe recipe = null;//from www .ja v a2 s. co m try { int recipeId = obj.getInt(TAG_RECIPE_ID); String recipeName = obj.getString(TAG_RECIPE_NAME); String recipeDescription = obj.getString(TAG_RECIPE_DESCRIPTION); int personCount = obj.getInt(TAG_RECIPE_PERSON); JSONArray jsonSteps = obj.getJSONArray(TAG_RECIPE_STEPS); List<Step> steps = new ArrayList<Step>(); for (int i = 0; i < jsonSteps.length(); i++) { Step step = parseStepObject(jsonSteps.getJSONObject(i)); if (step != null) { steps.add(step); } } List<Ingredient> ingredients = new ArrayList<Ingredient>(); JSONArray jsonIngredients = obj.getJSONArray(TAG_RECIPE_INGREDIENTS); for (int i = 0; i < jsonIngredients.length(); i++) { Ingredient ingredient = parseIngredientObject(jsonIngredients.getJSONObject(i)); if (ingredient != null) { ingredients.add(ingredient); } } List<String> categories = new ArrayList<String>(); if (obj.has(TAG_RECIPE_CATEGORIES)) { JSONArray jsonCategories = obj.getJSONArray(TAG_RECIPE_CATEGORIES); for (int i = 0; i < jsonCategories.length(); i++) { String tag = jsonCategories.getString(i); categories.add(tag); } } recipe = new Recipe(recipeId, recipeName, recipeDescription, personCount, steps); recipe.setIngredients(ingredients); recipe.setCategories(categories); } catch (JSONException e) { Log.w(LOG_TAG, "ParseRecipe() error: " + e.getMessage()); } return recipe; }
From source file:org.loklak.api.iot.NetmonPushServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query post = RemoteAccess.evaluate(request); String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode())); // manage DoS if (post.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return;//from w w w . jav a 2 s . c o m } String url = post.get("url", ""); if (url == null || url.length() == 0) { response.sendError(400, "your request does not contain an url to your data object"); return; } String screen_name = post.get("screen_name", ""); if (screen_name == null || screen_name.length() == 0) { response.sendError(400, "your request does not contain required screen_name parameter"); return; } JSONArray nodesList = new JSONArray(); byte[] xmlText; try { xmlText = ClientConnection.download(url); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(new String(xmlText)))); NodeList routerList = document.getElementsByTagName("router"); for (int i = 0; i < routerList.getLength(); i++) { JSONObject node = convertDOMNodeToMap(routerList.item(i)); if (node != null) nodesList.put(node); } } catch (Exception e) { Log.getLog().warn(e); response.sendError(400, "error reading json file from url"); return; } JsonFieldConverter converter = new JsonFieldConverter( JsonFieldConverter.JsonConversionSchemaEnum.NETMON_NODE); JSONArray nodes = converter.convert(nodesList); for (Object node_obj : nodes) { JSONObject node = (JSONObject) node_obj; if (!node.has("text")) { node.put("text", ""); } node.put("source_type", SourceType.NETMON.toString()); if (!node.has("user")) { node.put("user", new JSONObject()); } List<Object> location_point = new ArrayList<>(); location_point.add(0, Double.parseDouble((String) node.get("latitude"))); location_point.add(1, Double.parseDouble((String) node.get("longitude"))); node.put("location_point", location_point); node.put("location_mark", location_point); node.put("location_source", LocationSource.USER.name()); try { node.put("id_str", PushServletHelper.computeMessageId(node, SourceType.NETMON)); } catch (Exception e) { DAO.log("Problem computing id" + e.getMessage()); continue; } try { JSONObject user = (JSONObject) node.get("user"); user.put("screen_name", computeUserId(user.get("update_date"), user.get("id"), SourceType.NETMON)); } catch (Exception e) { DAO.log("Problem computing user id : " + e.getMessage()); } } PushReport pushReport = PushServletHelper.saveMessagesAndImportProfile(nodes, Arrays.hashCode(xmlText), post, SourceType.NETMON, screen_name); String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), pushReport); response.getOutputStream().println(res); DAO.log(request.getServletPath() + " -> records = " + pushReport.getRecordCount() + ", new = " + pushReport.getNewCount() + ", known = " + pushReport.getKnownCount() + ", from host hash " + remoteHash); }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
public String sendJSON(Storage storage, String path, JSONObject data, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { final String WORKFLOW_TRANSITION = "workflowTransition"; final String WORKFLOW_TRANSITION_LOCK = "lock"; JSONObject fields = data.optJSONObject("fields"); JSONArray relations = data.optJSONArray("relations"); if (path != null) { // Update if (fields != null) storage.updateJSON(base + "/" + path, fields, restrictions); } else {//w w w . j a va2 s . c o m // Create if (fields != null) path = storage.autocreateJSON(base, fields, restrictions); } if (relations != null) setRelations(storage, path, relations); if (record.supportsLocking() && data.has(WORKFLOW_TRANSITION) && WORKFLOW_TRANSITION_LOCK.equalsIgnoreCase(data.getString(WORKFLOW_TRANSITION))) { // If any problem, will throw exception. storage.transitionWorkflowJSON(base + "/" + path, WORKFLOW_TRANSITION_LOCK); } return path; }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
private void assignTerms(Storage storage, String path, JSONObject data) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException { JSONObject fields = data.optJSONObject("fields"); String insId = ""; if (fields.has("terms")) { Record vr = this.spec.getRecord("vocab"); Record thisr = spec.getRecord("vocab"); String sid = fields.getString("shortIdentifier"); String name = fields.getString("displayName"); insId = "vocab-" + sid; if (create) { Map<String, String> options = new HashMap<String, String>(); options.put("id", insId); options.put("title", name); options.put("web-url", sid); options.put("title-ref", sid); Instance ins = new Instance(thisr, options); vr.addInstance(ins);// w ww. j a va2s .com } ctl.get(storage, sid, vr, 0); } }
From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java
private void assignPermissions(Storage storage, String path, JSONObject data) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException { JSONObject fields = data.optJSONObject("fields"); JSONArray permdata = new JSONArray(); JSONObject permcheck = new JSONObject(); if (fields.has("permissions")) { JSONArray permissions = fields.getJSONArray("permissions"); for (int i = 0; i < permissions.length(); i++) { JSONObject perm = permissions.getJSONObject(i); Record recordForPermResource = Generic.RecordNameServices(spec, perm.getString("resourceName")); if (recordForPermResource != null) { if (recordForPermResource.hasSoftDeleteMethod()) { JSONObject permitem = getWorkflowPerm(storage, recordForPermResource, perm.getString("resourceName"), perm.getString("permission"), DELETE_WORKFLOW_TRANSITION); if (permitem.has("permissionId")) { if (permcheck.has(permitem.getString("resourceName"))) { //ignore as we have duplicate name - eek log.warn(// ww w . j a v a 2 s. c o m "RecordCreateUpdate.assignPermissions got duplicate workflow/delete permission for: " + permitem.getString("resourceName")); } else { permcheck.put(permitem.getString("resourceName"), permitem); permdata.put(permitem); } } } if (recordForPermResource.supportsLocking()) { JSONObject permitem = getWorkflowPerm(storage, recordForPermResource, perm.getString("resourceName"), perm.getString("permission"), LOCK_WORKFLOW_TRANSITION); if (permitem.has("permissionId")) { if (permcheck.has(permitem.getString("resourceName"))) { //ignore as we have duplicate name - eek log.warn( "RecordCreateUpdate.assignPermissions got duplicate workflow/lock permission for: " + permitem.getString("resourceName")); } else { permcheck.put(permitem.getString("resourceName"), permitem); permdata.put(permitem); } } } } JSONObject permitem = getPerm(storage, recordForPermResource, perm.getString("resourceName"), perm.getString("permission")); if (permitem.has("permissionId")) { if (permcheck.has(permitem.getString("resourceName"))) { //ignore as we have duplicate name - eek log.warn("RecordCreateUpdate.assignPermissions got duplicate permission for: " + permitem.getString("resourceName")); } else { permcheck.put(permitem.getString("resourceName"), permitem); permdata.put(permitem); } } } } //log.info("permdata"+permdata.toString()); JSONObject roledata = new JSONObject(); roledata.put("roleName", fields.getString("roleName")); String[] ids = path.split("/"); roledata.put("roleId", ids[ids.length - 1]); JSONObject accountrole = new JSONObject(); JSONObject arfields = new JSONObject(); arfields.put("role", roledata); arfields.put("permission", permdata); accountrole.put("fields", arfields); //log.info("WAAA"+arfields.toString()); if (fields != null) path = storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(), arfields, null); }