List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:ai.susi.mind.SusiReader.java
public SusiReader learn(JSONObject json) { // initialize temporary json objects JSONObject syn = json.has("synonyms") ? json.getJSONObject("synonyms") : new JSONObject(); JSONArray fill = json.has("filler") ? json.getJSONArray("filler") : new JSONArray(); JSONObject cat = json.has("categories") ? json.getJSONObject("categories") : new JSONObject(); // add synonyms for (String canonical : syn.keySet()) { JSONArray a = syn.getJSONArray(canonical); a.forEach(synonym -> synonyms.put(((String) synonym).toLowerCase(), canonical)); }//w w w.ja va 2 s . co m // add filler fill.forEach(word -> filler.add((String) word)); // add categories for (String canonical : cat.keySet()) { JSONArray a = cat.getJSONArray(canonical); a.forEach(synonym -> categories.put(((String) synonym).toLowerCase(), canonical)); } return this; }
From source file:com.jellymold.boss.ImageSearch.java
protected void parseResults(JSONObject jobj) throws JSONException { if (jobj != null) { setResponseCode(jobj.getInt("responsecode")); if (jobj.has("nextpage")) setNextPage(jobj.getString("nextpage")); if (jobj.has("prevpage")) setPrevPage(jobj.getString("prevpage")); setTotalResults(jobj.getLong("totalhits")); long count = jobj.getLong("count"); setPagerCount(count);//from w ww.j av a2s. c o m setPagerStart(jobj.getLong("start")); this.setResults(new ArrayList<ImageSearchResult>((int) count)); if (jobj.has("resultset_images")) { JSONArray res = jobj.getJSONArray("resultset_images"); for (int i = 0; i < res.length(); i++) { JSONObject thisResult = res.getJSONObject(i); ImageSearchResult imageSearchResult = new ImageSearchResult(); imageSearchResult.setDescription(thisResult.getString("abstract")); imageSearchResult.setClickUrl(thisResult.getString("clickurl")); imageSearchResult.setDate(thisResult.getString("date")); imageSearchResult.setTitle(thisResult.getString("title")); imageSearchResult.setUrl(thisResult.getString("url")); imageSearchResult.setSize(thisResult.getLong("size")); imageSearchResult.setFilename(thisResult.getString("filename")); imageSearchResult.setFormat(thisResult.getString("format")); imageSearchResult.setHeight(thisResult.getLong("height")); imageSearchResult.setMimeType(thisResult.getString("mimetype")); imageSearchResult.setRefererClickUrl(thisResult.getString("refererclickurl")); imageSearchResult.setRefererUrl(thisResult.getString("refererurl")); imageSearchResult.setThumbnailHeight(thisResult.getLong("thumbnail_height")); imageSearchResult.setThumbnailWidth(thisResult.getLong("thumbnail_width")); imageSearchResult.setThumbnailUrl(thisResult.getString("thumbnail_url")); this.getResults().add(imageSearchResult); } } } }
From source file:it.moondroid.chatbot.alice.Sraix.java
public static String sraixPannous(String input, String hint, Chat chatSession) { try {/*from w ww . jav a2 s.c om*/ String rawInput = input; if (hint == null) hint = MagicStrings.sraix_no_hint; input = " " + input + " "; input = input.replace(" point ", "."); input = input.replace(" rparen ", ")"); input = input.replace(" lparen ", "("); input = input.replace(" slash ", "/"); input = input.replace(" star ", "*"); input = input.replace(" dash ", "-"); // input = chatSession.bot.preProcessor.denormalize(input); input = input.trim(); input = input.replace(" ", "+"); int offset = CalendarUtils.timeZoneOffset(); //System.out.println("OFFSET = "+offset); String locationString = ""; if (chatSession.locationKnown) { locationString = "&location=" + chatSession.latitude + "," + chatSession.longitude; } // https://weannie.pannous.com/api?input=when+is+daylight+savings+time+in+the+us&locale=en_US&login=pandorabots&ip=169.254.178.212&botid=0&key=CKNgaaVLvNcLhDupiJ1R8vtPzHzWc8mhIQDFSYWj&exclude=Dialogues,ChatBot&out=json // exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true String url = "https://ask.pannous.com/api?input=" + input + "&locale=en_US&timeZone=" + offset + locationString + "&login=" + MagicStrings.pannous_login + "&ip=" + NetworkUtils.localIPAddress() + "&botid=0&key=" + MagicStrings.pannous_api_key + "&exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true"; MagicBooleans.trace("in Sraix.sraixPannous, url: '" + url + "'"); String page = NetworkUtils.responseContent(url); //MagicBooleans.trace("in Sraix.sraixPannous, page: " + page); String text = ""; String imgRef = ""; String urlRef = ""; if (page == null || page.length() == 0) { text = MagicStrings.sraix_failed; } else { JSONArray outputJson = new JSONObject(page).getJSONArray("output"); //MagicBooleans.trace("in Sraix.sraixPannous, outputJson class: " + outputJson.getClass() + ", outputJson: " + outputJson); if (outputJson.length() == 0) { text = MagicStrings.sraix_failed; } else { JSONObject firstHandler = outputJson.getJSONObject(0); //MagicBooleans.trace("in Sraix.sraixPannous, firstHandler class: " + firstHandler.getClass() + ", firstHandler: " + firstHandler); JSONObject actions = firstHandler.getJSONObject("actions"); //MagicBooleans.trace("in Sraix.sraixPannous, actions class: " + actions.getClass() + ", actions: " + actions); if (actions.has("reminder")) { //MagicBooleans.trace("in Sraix.sraixPannous, found reminder action"); Object obj = actions.get("reminder"); if (obj instanceof JSONObject) { if (MagicBooleans.trace_mode) System.out.println("Found JSON Object"); JSONObject sObj = (JSONObject) obj; String date = sObj.getString("date"); date = date.substring(0, "2012-10-24T14:32".length()); if (MagicBooleans.trace_mode) System.out.println("date=" + date); String duration = sObj.getString("duration"); if (MagicBooleans.trace_mode) System.out.println("duration=" + duration); Pattern datePattern = Pattern.compile("(.*)-(.*)-(.*)T(.*):(.*)"); Matcher m = datePattern.matcher(date); String year = "", month = "", day = "", hour = "", minute = ""; if (m.matches()) { year = m.group(1); month = String.valueOf(Integer.parseInt(m.group(2)) - 1); day = m.group(3); hour = m.group(4); minute = m.group(5); text = "<year>" + year + "</year>" + "<month>" + month + "</month>" + "<day>" + day + "</day>" + "<hour>" + hour + "</hour>" + "<minute>" + minute + "</minute>" + "<duration>" + duration + "</duration>"; } else text = MagicStrings.schedule_error; } } else if (actions.has("say") && !hint.equals(MagicStrings.sraix_pic_hint) && !hint.equals(MagicStrings.sraix_shopping_hint)) { MagicBooleans.trace("in Sraix.sraixPannous, found say action"); Object obj = actions.get("say"); //MagicBooleans.trace("in Sraix.sraixPannous, obj class: " + obj.getClass()); //MagicBooleans.trace("in Sraix.sraixPannous, obj instanceof JSONObject: " + (obj instanceof JSONObject)); if (obj instanceof JSONObject) { JSONObject sObj = (JSONObject) obj; text = sObj.getString("text"); if (sObj.has("moreText")) { JSONArray arr = sObj.getJSONArray("moreText"); for (int i = 0; i < arr.length(); i++) { text += " " + arr.getString(i); } } } else { text = obj.toString(); } } if (actions.has("show") && !text.contains("Wolfram") && actions.getJSONObject("show").has("images")) { MagicBooleans.trace("in Sraix.sraixPannous, found show action"); JSONArray arr = actions.getJSONObject("show").getJSONArray("images"); int i = (int) (arr.length() * Math.random()); //for (int j = 0; j < arr.length(); j++) System.out.println(arr.getString(j)); imgRef = arr.getString(i); if (imgRef.startsWith("//")) imgRef = "http:" + imgRef; imgRef = "<a href=\"" + imgRef + "\"><img src=\"" + imgRef + "\"/></a>"; //System.out.println("IMAGE REF="+imgRef); } if (hint.equals(MagicStrings.sraix_shopping_hint) && actions.has("open") && actions.getJSONObject("open").has("url")) { urlRef = "<oob><url>" + actions.getJSONObject("open").getString("url") + "</oob></url>"; } } if (hint.equals(MagicStrings.sraix_event_hint) && !text.startsWith("<year>")) return MagicStrings.sraix_failed; else if (text.equals(MagicStrings.sraix_failed)) return AIMLProcessor.respond(MagicStrings.sraix_failed, "nothing", "nothing", chatSession); else { text = text.replace("'", "'"); text = text.replace("'", "'"); text = text.replaceAll("\\[(.*)\\]", ""); String[] sentences; sentences = text.split("\\. "); //System.out.println("Sraix: text has "+sentences.length+" sentences:"); String clippedPage = sentences[0]; for (int i = 1; i < sentences.length; i++) { if (clippedPage.length() < 500) clippedPage = clippedPage + ". " + sentences[i]; //System.out.println(i+". "+sentences[i]); } clippedPage = clippedPage + " " + imgRef + " " + urlRef; clippedPage = clippedPage.trim(); log(rawInput, clippedPage); return clippedPage; } } } catch (Exception ex) { ex.printStackTrace(); System.out.println("Sraix '" + input + "' failed"); } return MagicStrings.sraix_failed; }
From source file:jessmchung.groupon.parsers.RedemptionLocationParser.java
@Override public RedemptionLocation parse(JSONObject json) throws JSONException { RedemptionLocation obj = new RedemptionLocation(); if (json.has("streetAddress1")) obj.setStreetAddress1(json.getString("streetAddress1")); if (json.has("streetAddress2")) obj.setStreetAddress2(json.getString("streetAddress2")); if (json.has("state")) obj.setState(json.getString("state")); if (json.has("city")) obj.setCity(json.getString("city")); if (json.has("lat")) obj.setLat(json.getDouble("lat")); if (json.has("lng")) obj.setLng(json.getDouble("lng")); if (json.has("postalCode")) obj.setPostalCode(json.getString("postalCode")); if (json.has("name")) obj.setName(json.getString("name")); return obj;/*from ww w .ja v a 2 s. co m*/ }
From source file:org.eclipse.flux.client.SingleResponseHandler.java
/** * Should inspect the message to determine if it is an 'error' * response and throw an exception in that case. Do nothing otherwise. *//*w w w .j a v a2 s.c om*/ protected void errorParse(String messageType, JSONObject message) throws Exception { if (message.has(ERROR)) { if (message.has("errorDetails")) { System.err.println(message.get("errorDetails")); } throw new Exception(message.getString(ERROR)); } }
From source file:org.brickred.socialauth.provider.FourSquareImpl.java
private Profile getProfile() throws Exception { LOG.debug("Obtaining user profile"); Profile profile = new Profile(); Response serviceResponse;//from w w w. j av a 2s . co m try { serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL); } catch (Exception e) { throw new SocialAuthException("Failed to retrieve the user profile from " + PROFILE_URL, e); } String res; try { res = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception exc) { throw new SocialAuthException("Failed to read response from " + PROFILE_URL, exc); } JSONObject jobj = new JSONObject(res); JSONObject rObj; JSONObject uObj; if (jobj.has("response")) { rObj = jobj.getJSONObject("response"); } else { throw new SocialAuthException("Failed to parse the user profile json : " + res); } if (rObj.has("user")) { uObj = rObj.getJSONObject("user"); } else { throw new SocialAuthException("Failed to parse the user profile json : " + res); } if (uObj.has("id")) { profile.setValidatedId(uObj.getString("id")); } if (uObj.has("firstName")) { profile.setFirstName(uObj.getString("firstName")); } if (uObj.has("lastName")) { profile.setLastName(uObj.getString("lastName")); } if (uObj.has("photo")) { profile.setProfileImageURL(uObj.getString("photo")); } if (uObj.has("gender")) { profile.setGender(uObj.getString("gender")); } if (uObj.has("homeCity")) { profile.setLocation(uObj.getString("homeCity")); } if (uObj.has("contact")) { JSONObject cobj = uObj.getJSONObject("contact"); if (cobj.has("email")) { profile.setEmail(cobj.getString("email")); } } profile.setProviderId(getProviderId()); userProfile = profile; return profile; }
From source file:org.brickred.socialauth.provider.FourSquareImpl.java
/** * Gets the list of contacts of the user. * //from w w w. jav a 2 s . com * @return List of contact objects representing Contacts. Only name and * profile URL will be available */ @Override public List<Contact> getContactList() throws Exception { LOG.info("Fetching contacts from " + CONTACTS_URL); Response serviceResponse; try { serviceResponse = authenticationStrategy.executeFeed(CONTACTS_URL); } catch (Exception e) { throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL, e); } if (serviceResponse.getStatus() != 200) { throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL + "Status : " + serviceResponse.getStatus()); } String respStr; try { respStr = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception exc) { throw new SocialAuthException("Failed to read response from " + CONTACTS_URL, exc); } LOG.debug("User Contacts list in JSON " + respStr); JSONObject resp = new JSONObject(respStr); List<Contact> plist = new ArrayList<Contact>(); JSONArray items = new JSONArray(); if (resp.has("response")) { JSONObject robj = resp.getJSONObject("response"); if (robj.has("friends")) { JSONObject fobj = robj.getJSONObject("friends"); if (fobj.has("items")) { items = fobj.getJSONArray("items"); } } else { throw new SocialAuthException("Failed to parse the user profile json : " + respStr); } } else { throw new SocialAuthException("Failed to parse the user profile json : " + respStr); } LOG.debug("Contacts Found : " + items.length()); for (int i = 0; i < items.length(); i++) { JSONObject obj = items.getJSONObject(i); Contact c = new Contact(); if (obj.has("firstName")) { c.setFirstName(obj.getString("firstName")); } if (obj.has("lastName")) { c.setLastName(obj.getString("lastName")); } if (obj.has("id")) { c.setProfileUrl(VIEW_PROFILE_URL + obj.getString("id")); c.setId(obj.getString("id")); } plist.add(c); } return plist; }
From source file:com.sdspikes.fireworks.FireworksTurn.java
static public FireworksTurn unpersist(JSONObject obj) { FireworksTurn retVal = new FireworksTurn(); try {//from w w w . j a v a 2s . co m if (!obj.has("state")) { return null; } else { retVal.state = new GameState(obj.getJSONObject("state")); } if (obj.has("turn")) { retVal.turnCounter = obj.getInt("turn"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return retVal; }
From source file:com.intel.xdk.facebook.IntelXDKFacebook.java
@JavascriptInterface public void showAppRequestDialog(final String parameters) { if (!session.isOpened()) { currentCommand = APP_REQUEST_DIALOG; currentCommandArguments = new String[] { parameters }; login(defaultLoginPermissions);/*from w w w .j a v a 2 s . c o m*/ return; } else { //busy=true; } activity.runOnUiThread(new Runnable() { //@Override public void run() { JSONObject json = new JSONObject(); try { json = new JSONObject(parameters); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Bundle params = JSONtoBundle(json); params.putString("frictionless", useFrictionless); WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(activity, session, params)) .setOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { if (error != null) { if (error instanceof FacebookOperationCanceledException) { String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);"); webView.loadUrl(js); resetFBStatus(); } else { String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);", error.toString()); webView.loadUrl(js); resetFBStatus(); } } else { final String requestId = values.getString("request"); if (requestId != null) { JSONObject jsonData = BundleToJSON(values); String extra = ""; try { String request = jsonData.getString("request"); extra += "e.request=" + request + ";"; } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int index = 0; if (jsonData.has("to[" + index + "]")) { extra += "e.to=["; while (jsonData.has("to[" + index + "]")) { try { extra += jsonData.getString("to[" + index + "]") + ","; } catch (JSONException e) { } index++; } extra += "];"; } String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);", jsonData.toString(), extra); webView.loadUrl(js); resetFBStatus(); } else { String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);"); webView.loadUrl(js); resetFBStatus(); } } } }).build(); requestsDialog.show(); } }); }
From source file:com.intel.xdk.facebook.IntelXDKFacebook.java
@JavascriptInterface public void showNewsFeedDialog(final String parameters) { if (!session.isOpened()) { currentCommand = NEWS_FEED_DIALOG; currentCommandArguments = new String[] { parameters }; login(defaultLoginPermissions);/*from w w w .jav a 2 s.c o m*/ return; } else { busy = true; } activity.runOnUiThread(new Runnable() { //@Override public void run() { JSONObject json = new JSONObject(); try { json = new JSONObject(parameters); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //facebook.dialog(activity, "feed", JSONtoBundle(json), FBDialogListener ); // Bundle params = new Bundle(); // params.putString("name", "Facebook SDK for Android"); // params.putString("caption", "Build great social apps and get more installs."); // params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps."); // params.putString("link", "https://developers.facebook.com/android"); // params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png"); Bundle params = JSONtoBundle(json); params.putString("frictionless", useFrictionless); WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, session, params)) .setOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { if (error == null) { // When the story is posted, echo the success // and the post Id. final String postId = values.getString("post_id"); if (postId != null) { // Toast.makeText(activity, // "Posted story, id: "+postId, // Toast.LENGTH_SHORT).show(); JSONObject jsonData = BundleToJSON(values); String extra = ""; try { String request = jsonData.getString("request"); extra += "e.request=" + request + ";"; } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int index = 0; if (jsonData.has("to[" + index + "]")) { extra += "e.to=["; while (jsonData.has("to[" + index + "]")) { try { extra += jsonData.getString("to[" + index + "]") + ","; } catch (JSONException e) { } index++; } extra += "];"; } String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='%s';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}%sdocument.dispatchEvent(e);", jsonData.toString(), extra); webView.loadUrl(js); resetFBStatus(); } else { // User clicked the Cancel button // Toast.makeText(activity.getApplicationContext(), // "Publish cancelled", // Toast.LENGTH_SHORT).show(); String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);"); webView.loadUrl(js); resetFBStatus(); } } else if (error instanceof FacebookOperationCanceledException) { // User clicked the "x" button // Toast.makeText(activity.getApplicationContext(), // "Publish cancelled", // Toast.LENGTH_SHORT).show(); String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);"); webView.loadUrl(js); resetFBStatus(); } else { // Generic, ex: network error // Toast.makeText(activity.getApplicationContext(), // "Error posting story", // Toast.LENGTH_SHORT).show(); String js = String.format( "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='%s';e.raw='';e.data={};document.dispatchEvent(e);", error.toString()); webView.loadUrl(js); resetFBStatus(); } } }).build(); feedDialog.show(); } }); }