List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:me.mast3rplan.phantombot.cache.SubscribersCache.java
private void updateCache(int newCount) throws Exception { Map<String, JSONObject> newCache = Maps.newHashMap(); final List<JSONObject> responses = Lists.newArrayList(); List<Thread> threads = Lists.newArrayList(); for (int i = 0; i < Math.ceil(newCount / 100.0); i++) { final int offset = i * 100; Thread thread = new Thread() { @Override/*from w ww . ja v a 2 s.c o m*/ public void run() { JSONObject j = TwitchAPIv3.instance().GetChannelSubscriptions(channel, 100, offset, true); if (j.getBoolean("_success")) { if (j.getInt("_http") == 200) { responses.add(j); } else { try { throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " " + j.getString("error") + ". req=" + j.getString("_type") + " " + j.getString("_url") + " " + j.getString("_post") + " " + (j.has("message") && !j.isNull("message") ? "message=" + j.getString("message") : "content=" + j.getString("_content"))); } catch (Exception e) { com.gmt2001.Console.out .println("SubscribersCache.updateCache>>Failed to update subscribers: " + e.getMessage()); com.gmt2001.Console.err.logStackTrace(e); } } } else { try { throw new Exception( "[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage")); } catch (Exception e) { if (e.getMessage().startsWith("[SocketTimeoutException]") || e.getMessage().startsWith("[IOException]")) { Calendar c = Calendar.getInstance(); if (lastFail.after(new Date())) { numfail++; } else { numfail = 1; } c.add(Calendar.MINUTE, 1); lastFail = c.getTime(); if (numfail >= 5) { timeoutExpire = c.getTime(); } } com.gmt2001.Console.out .println("SubscribersCache.updateCache>>Failed to update subscribers: " + e.getMessage()); com.gmt2001.Console.err.logStackTrace(e); } } } }; threads.add(thread); thread.start(); } for (Thread thread : threads) { thread.join(); } for (JSONObject response : responses) { JSONArray subscribers = response.getJSONArray("subscriptions"); if (subscribers.length() == 0) { break; } for (int j = 0; j < subscribers.length(); j++) { JSONObject subscriber = subscribers.getJSONObject(j); newCache.put(subscriber.getJSONObject("user").getString("name"), subscriber); } } List<String> subscribers = Lists.newArrayList(); List<String> unsubscribers = Lists.newArrayList(); for (String key : newCache.keySet()) { if (cache == null || !cache.containsKey(key)) { subscribers.add(key); } } if (cache != null) { for (String key : cache.keySet()) { if (!newCache.containsKey(key)) { unsubscribers.add(key); } } } this.cache = newCache; this.count = newCache.size(); for (String subscriber : subscribers) { EventBus.instance().post( new TwitchSubscribeEvent(subscriber, PhantomBot.instance().getChannel("#" + this.channel))); } for (String subscriber : unsubscribers) { EventBus.instance().post( new TwitchUnsubscribeEvent(subscriber, PhantomBot.instance().getChannel("#" + this.channel))); } if (firstUpdate) { firstUpdate = false; EventBus.instance().post( new TwitchSubscribesInitializedEvent(PhantomBot.instance().getChannel("#" + this.channel))); } }
From source file:com.soomla.cocos2dx.profile.ProfileBridge.java
/** * Constructor/* ww w . j a va 2 s . c o m*/ * * The main constructor for the bridge. * Registers all glue between native and Cocos2dx */ public ProfileBridge() { profileEventHandlerBridge = new ProfileEventHandlerBridge(); final DomainFactory domainFactory = DomainFactory.getInstance(); domainFactory.registerCreator(ProfileConsts.JSON_JSON_TYPE_USER_PROFILE, new DomainFactory.Creator<UserProfile>() { @Override public UserProfile create(JSONObject jsonObject) { try { return new UserProfile(jsonObject); } catch (JSONException e) { throw new IllegalStateException(e); } } }); final NdkGlue ndkGlue = NdkGlue.getInstance(); ndkGlue.registerCallHandler("CCProfileBridge::init", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { HashMap<IProvider.Provider, HashMap<String, String>> providerParams = parseProviderParams( params.optJSONObject("params")); SoomlaUtils.LogDebug("SOOMLA", "initialize is called from java!"); SoomlaProfile.getInstance().initialize(providerParams); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::login", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().login(ndkGlue.getActivityRef().get(), IProvider.Provider.getEnum(provider), payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::logout", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); SoomlaProfile.getInstance().logout(IProvider.Provider.getEnum(provider)); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::getStoredUserProfile", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); UserProfile userProfile = SoomlaProfile.getInstance() .getStoredUserProfile(IProvider.Provider.getEnum(provider)); if (userProfile != null) { retParams.put("return", userProfile.toJSONObject()); } } }); ndkGlue.registerCallHandler("CCSoomlaProfile::updateStatus", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String status = params.getString("status"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().updateStatus(IProvider.Provider.getEnum(provider), status, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::updateStatusWithConfirmation", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String status = params.getString("status"); String payload = params.getString("payload"); String customMessage = params.optString("customMessage"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().updateStatusWithConfirmation(IProvider.Provider.getEnum(provider), status, payload, reward, ndkGlue.getActivityRef().get(), customMessage); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::updateStatusDialog", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String link = params.optString("link"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().updateStatusDialog(IProvider.Provider.getEnum(provider), link, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::updateStory", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String message = params.getString("message"); String name = params.getString("name"); String caption = params.getString("caption"); String description = params.getString("description"); String link = params.getString("link"); String picture = params.getString("picture"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().updateStory(IProvider.Provider.getEnum(provider), message, name, caption, description, link, picture, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::updateStoryWithConfirmation", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String message = params.getString("message"); String name = params.getString("name"); String caption = params.getString("caption"); String description = params.getString("description"); String link = params.getString("link"); String picture = params.getString("picture"); String payload = params.getString("payload"); String customMessage = params.optString("customMessage"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().updateStoryWithConfirmation(IProvider.Provider.getEnum(provider), message, name, caption, description, link, picture, payload, reward, ndkGlue.getActivityRef().get(), customMessage); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::updateStoryDialog", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String name = params.optString("name"); String caption = params.optString("caption"); String description = params.optString("description"); String link = params.optString("link"); String picture = params.optString("picture"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().updateStoryDialog(IProvider.Provider.getEnum(provider), name, caption, description, link, picture, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::uploadImage", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String message = params.getString("message"); String filePath = params.getString("filePath"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().uploadImage(IProvider.Provider.getEnum(provider), message, filePath, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::uploadImageWithConfirmation", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String message = params.getString("message"); String filePath = params.getString("filePath"); String payload = params.getString("payload"); String customMessage = params.optString("customMessage"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().uploadImageWithConfirmation(IProvider.Provider.getEnum(provider), message, filePath, payload, reward, ndkGlue.getActivityRef().get(), customMessage); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::getContacts", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); Boolean fromStart = params.getBoolean("fromStart"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().getContacts(IProvider.Provider.getEnum(provider), fromStart, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::getFeed", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); Boolean fromStart = params.getBoolean("fromStart"); String payload = params.getString("payload"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().getFeed(IProvider.Provider.getEnum(provider), fromStart, payload, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::isLoggedIn", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); boolean result = SoomlaProfile.getInstance().isLoggedIn(ndkGlue.getActivityRef().get(), IProvider.Provider.getEnum(provider)); retParams.put("return", result); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::like", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String provider = params.getString("provider"); String pageId = params.getString("pageId"); JSONObject rewardJson = params.optJSONObject("reward"); Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson) : null; SoomlaProfile.getInstance().like(ndkGlue.getActivityRef().get(), IProvider.Provider.getEnum(provider), pageId, reward); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::openAppRatingPage", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { SoomlaProfile.getInstance() .openAppRatingPage(ndkGlue.getActivityRef().get().getApplicationContext()); } }); ndkGlue.registerCallHandler("CCSoomlaProfile::multiShare", new NdkGlue.CallHandler() { @Override public void handle(JSONObject params, JSONObject retParams) throws Exception { String text = params.getString("text"); String imageFilePath = params.getString("imageFilePath"); SoomlaProfile.getInstance().multiShare(text, imageFilePath); } }); final NdkGlue.ExceptionHandler exceptionHandler = new NdkGlue.ExceptionHandler() { @Override public void handle(Exception exception, JSONObject params, JSONObject retParams) throws Exception { retParams.put("errorInfo", exception.getClass().getName()); } }; ndkGlue.registerExceptionHandler(ProviderNotFoundException.class.getName(), exceptionHandler); ndkGlue.registerExceptionHandler(UserProfileNotFoundException.class.getName(), exceptionHandler); }
From source file:com.domuslink.elements.AliasMap.java
public AliasMap(JSONObject jsonElement) throws Exception { super();//from w ww . ja va2s . c o m try { setAliasLabel(jsonElement.getString("aliasLabel")); setFloorPlanLabel(jsonElement.getString("floorPlanLabel")); setHiddenFromHome(jsonElement.getString("hiddenFromHome")); setElementType(jsonElement.getString("elementType")); setElementLine(jsonElement.getString("elementLine")); setLineNum(jsonElement.getInt("lineNum")); setArrayNum(jsonElement.getInt("arrayNum")); setEnabled(jsonElement.getBoolean("enabled")); } catch (Exception e) { Log.e(TAG, "Error getting AliasMap from JSONObject", e); throw e; } }
From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenSearch.java
@Override public void run() { try {// w ww .ja v a 2 s. c om String urlString; if (query != null) { /* * Setup URL for a normal station search query. */ urlString = Trafikanten.getApiUrl() + "/ReisRest/Place/FindMatches/" + HelperFunctions.properEncode(query); } else { /* * Setup URL for coordinate search. */ final LatLng latLong = new LatLng(latitude, longitude); final UTMRef utmRef = latLong.toUTMRef(); urlString = Trafikanten.getApiUrl() + "/ReisRest/Stop/GetClosestStopsByCoordinates/?coordinates=(X=" + (int) utmRef.getEasting() + ",Y=" + (int) utmRef.getNorthing() + ")&proposals=10"; } Log.i(TAG, "Searching with url " + urlString); final InputStream stream = HelperFunctions.executeHttpRequest(context, new HttpGet(urlString), false).stream; /* * Parse json */ final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(stream)); final int arraySize = jsonArray.length(); for (int i = 0; i < arraySize; i++) { final JSONObject json = jsonArray.getJSONObject(i); StationData station = new StationData(); // We parse realtimestop first for performance reason. station.realtimeStop = json.has("RealTimeStop") && json.getBoolean("RealTimeStop"); if (isRealtimeStopFiltered && !station.realtimeStop) { continue; } station.stationId = json.getInt("ID"); station.type = json.getInt("Type"); station.stopName = json.getString("Name"); searchForAddress(station); final String district = json.getString("District"); if (district.length() > 0) { if (station.extra == null) { station.extra = district; } else { station.extra = station.extra + ", " + district; } } if (json.has("WalkingDistance")) { station.walkingDistance = json.getInt("WalkingDistance"); } station.utmCoords[0] = json.getInt("X"); station.utmCoords[1] = json.getInt("Y"); ThreadHandlePostData(station); } } catch (Exception e) { if (e.getClass() == InterruptedException.class) { ThreadHandlePostExecute(null); return; } ThreadHandlePostExecute(e); return; } ThreadHandlePostExecute(null); }
From source file:com.mercandalli.android.apps.files.file.cloud.FileCloudFragment.java
@Override public void executeFileModel(final FileModel fileModel, final View view) { final AlertDialog.Builder menuAlert = new AlertDialog.Builder(getActivity()); String[] menuList = { getString(R.string.download) }; if (!fileModel.isDirectory() && mFileManager.isMine(fileModel)) { if (FileTypeModelENUM.IMAGE.type.equals(fileModel.getType())) { menuList = new String[] { getString(R.string.download), getString(R.string.rename), getString(R.string.delete), getString(R.string.cut), getString(R.string.properties), (fileModel.isPublic()) ? "Become private" : "Become public", "Set as profile" }; } else {/*www. ja va2 s .c o m*/ menuList = new String[] { getString(R.string.download), getString(R.string.rename), getString(R.string.delete), getString(R.string.cut), getString(R.string.properties), (fileModel.isPublic()) ? "Become private" : "Become public" }; } } menuAlert.setTitle(getString(R.string.action)); menuAlert.setItems(menuList, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: mFileManager.download(getActivity(), fileModel, new IListener() { @Override public void execute() { Toast.makeText(getActivity(), "Download finished.", Toast.LENGTH_SHORT).show(); } }); break; case 1: DialogUtils.prompt( getActivity(), "Rename", "Rename " + (fileModel.isDirectory() ? "directory" : "file") + " " + fileModel.getName() + " ?", "Ok", new DialogUtils.OnDialogUtilsStringListener() { @Override public void onDialogUtilsStringCalledBack(String text) { mFileManager.rename(fileModel, text, new IListener() { @Override public void execute() { if (!mFilesToCut.isEmpty()) { mFilesToCut.clear(); //refreshFab(); } } }); } }, "Cancel", null, fileModel.getFullName()); break; case 2: DialogUtils.alert( getContext(), "Delete", "Delete " + (fileModel.isDirectory() ? "directory" : "file") + " " + fileModel.getName() + " ?", "Yes", new DialogUtils.OnDialogUtilsListener() { @Override public void onDialogUtilsCalledBack() { mFileManager.delete(fileModel, new IListener() { @Override public void execute() { if (!mFilesToCut.isEmpty()) { mFilesToCut.clear(); //refreshFab(); } } }); } }, "No", null); break; case 3: FileCloudFragment.this.mFilesToCut.add(fileModel); Toast.makeText(getContext(), "File ready to cut.", Toast.LENGTH_SHORT).show(); break; case 4: DialogUtils.alert(getContext(), getString(R.string.properties) + " : " + fileModel.getName(), mFileManager.toSpanned(getActivity(), fileModel), "OK", null, null, null); break; case 5: mFileManager.setPublic(fileModel, !fileModel.isPublic(), new IListener() { @Override public void execute() { } }); break; // Picture set as profile case 6: List<StringPair> parameters = new ArrayList<>(); parameters.add(new StringPair("id_file_profile_picture", "" + fileModel.getId())); (new TaskPost(getActivity(), Constants.URL_DOMAIN + Config.ROUTE_USER_PUT, new IPostExecuteListener() { @Override public void onPostExecute(JSONObject json, String body) { try { if (json != null && json.has("succeed") && json.getBoolean("succeed")) { Config.setUserIdFileProfilePicture(getActivity(), fileModel.getId()); } } catch (JSONException e) { Log.e(getClass().getName(), "Failed to convert Json", e); } } }, parameters)).execute(); break; } } }); AlertDialog menuDrop = menuAlert.create(); menuDrop.show(); }
From source file:com.facebook.internal.BundleJSONConverterTests.java
@SmallTest public void testSimpleValues() throws JSONException { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("1st"); arrayList.add("2nd"); arrayList.add("third"); Bundle innerBundle1 = new Bundle(); innerBundle1.putInt("inner", 1); Bundle innerBundle2 = new Bundle(); innerBundle2.putString("inner", "2"); innerBundle2.putStringArray("deep list", new String[] { "7", "8" }); innerBundle1.putBundle("nested bundle", innerBundle2); Bundle b = new Bundle(); b.putBoolean("boolValue", true); b.putInt("intValue", 7); b.putLong("longValue", 5000000000l); b.putDouble("doubleValue", 3.14); b.putString("stringValue", "hello world"); b.putStringArray("stringArrayValue", new String[] { "first", "second" }); b.putStringArrayList("stringArrayListValue", arrayList); b.putBundle("nested", innerBundle1); JSONObject json = BundleJSONConverter.convertToJSON(b); assertNotNull(json);//from w w w . j av a 2s . c o m assertEquals(true, json.getBoolean("boolValue")); assertEquals(7, json.getInt("intValue")); assertEquals(5000000000l, json.getLong("longValue")); assertEquals(3.14, json.getDouble("doubleValue")); assertEquals("hello world", json.getString("stringValue")); JSONArray jsonArray = json.getJSONArray("stringArrayValue"); assertEquals(2, jsonArray.length()); assertEquals("first", jsonArray.getString(0)); assertEquals("second", jsonArray.getString(1)); jsonArray = json.getJSONArray("stringArrayListValue"); assertEquals(3, jsonArray.length()); assertEquals("1st", jsonArray.getString(0)); assertEquals("2nd", jsonArray.getString(1)); assertEquals("third", jsonArray.getString(2)); JSONObject innerJson = json.getJSONObject("nested"); assertEquals(1, innerJson.getInt("inner")); innerJson = innerJson.getJSONObject("nested bundle"); assertEquals("2", innerJson.getString("inner")); jsonArray = innerJson.getJSONArray("deep list"); assertEquals(2, jsonArray.length()); assertEquals("7", jsonArray.getString(0)); assertEquals("8", jsonArray.getString(1)); Bundle finalBundle = BundleJSONConverter.convertToBundle(json); assertNotNull(finalBundle); assertEquals(true, finalBundle.getBoolean("boolValue")); assertEquals(7, finalBundle.getInt("intValue")); assertEquals(5000000000l, finalBundle.getLong("longValue")); assertEquals(3.14, finalBundle.getDouble("doubleValue")); assertEquals("hello world", finalBundle.getString("stringValue")); List<String> stringList = finalBundle.getStringArrayList("stringArrayValue"); assertEquals(2, stringList.size()); assertEquals("first", stringList.get(0)); assertEquals("second", stringList.get(1)); stringList = finalBundle.getStringArrayList("stringArrayListValue"); assertEquals(3, stringList.size()); assertEquals("1st", stringList.get(0)); assertEquals("2nd", stringList.get(1)); assertEquals("third", stringList.get(2)); Bundle finalInnerBundle = finalBundle.getBundle("nested"); assertEquals(1, finalInnerBundle.getInt("inner")); finalBundle = finalInnerBundle.getBundle("nested bundle"); assertEquals("2", finalBundle.getString("inner")); stringList = finalBundle.getStringArrayList("deep list"); assertEquals(2, stringList.size()); assertEquals("7", stringList.get(0)); assertEquals("8", stringList.get(1)); }
From source file:uk.co.senab.photup.model.Album.java
public Album(JSONObject object, Account account) throws JSONException { super(object, account); mCanUpload = object.getBoolean("can_upload"); mUpdatedTime = object.getLong("updated_time"); }
From source file:de.eorganization.hoopla.server.services.LoginServiceImpl.java
@Override public LoginInfo login(String requestUri) { LoginInfo loginInfo = new LoginInfo(); loginInfo.setLoggedIn(false);//from w ww .ja v a 2s . com loginInfo.setLoginUrl(userService.createLoginURL(requestUri)); Map<String, String> cookies = CookiesUtil.getCookiesStringMap(getThreadLocalRequest().getCookies()); log.info("Got cookies " + cookies); String oauthService = cookies.get("oauth.service"); log.info("Logging in with OAuth service " + oauthService); if (oauthService != null) { try { String accessTokenString = cookies.get("oauth.accessToken"); String accessSecret = cookies.get("oauth.secret"); if (accessTokenString == null) return loginInfo; log.info("Retrieved access token " + accessTokenString); Token accessToken = new Token(accessTokenString, accessSecret); log.info("Token object " + accessToken.getToken() + ", " + accessToken.getSecret()); OAuth2Provider provider = OAuth2Provider.valueOf(oauthService); OAuthService service = provider.getOAuthService(); Cookie serviceTokenCookie = new Cookie("oauth.service", provider.toString()); serviceTokenCookie.setMaxAge(14 * 24 * 60 * 60); serviceTokenCookie.setPath("/"); getThreadLocalResponse().addCookie(serviceTokenCookie); Cookie accessTokenCookie = new Cookie("oauth.accessToken", accessTokenString); accessTokenCookie.setMaxAge(14 * 24 * 60 * 60); accessTokenCookie.setPath("/"); getThreadLocalResponse().addCookie(accessTokenCookie); Cookie accessSecretCookie = new Cookie("oauth.secret", accessSecret); accessSecretCookie.setMaxAge(14 * 24 * 60 * 60); accessSecretCookie.setPath("/"); getThreadLocalResponse().addCookie(accessSecretCookie); if (OAuth2Provider.GOOGLE.equals(provider)) { OAuthRequest req = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo"); service.signRequest(accessToken, req); Response response = req.send(); log.info("Requested user info from google: " + response.getBody()); JSONObject googleUserInfo = new JSONObject(response.getBody()); log.info("got user info: " + googleUserInfo.getString("given_name") + ", " + googleUserInfo.getString("family_name")); Member tempMember = new HooplaServiceImpl() .findMemberBySocialId(googleUserInfo.getString("id")); if (tempMember == null) { tempMember = new Member(); tempMember.setSocialId(googleUserInfo.getString("id")); tempMember.setFirstname(googleUserInfo.getString("given_name")); tempMember.setLastname(googleUserInfo.getString("family_name")); tempMember.setNickname(googleUserInfo.getString("name")); tempMember.setProfilePic(googleUserInfo.getString("picture")); req = new OAuthRequest(Verb.GET, "https://www.googleapis.com/plus/v1/people/me"); service.signRequest(accessToken, req); response = req.send(); log.info("Requested more user info from google: " + response.getBody()); JSONObject googleUserInfo2 = new JSONObject(response.getBody()); log.info("got user info: " + googleUserInfo2.getString("nickname") + ", " + googleUserInfo2.getString("displayName")); if (googleUserInfo2 != null && googleUserInfo2.getJSONArray("emails") != null) for (int i = 0; i < googleUserInfo2.getJSONArray("emails").length(); i++) { JSONObject emailInfo = googleUserInfo2.getJSONArray("emails").optJSONObject(i); if (emailInfo != null && emailInfo.getBoolean("primary")) { tempMember.setEmail(emailInfo.getString("value")); tempMember = new HooplaServiceImpl().registerMember(tempMember); loginInfo.setLoggedIn(true); break; } } } else loginInfo.setLoggedIn(true); loginInfo.setMember(tempMember); } else if (OAuth2Provider.TWITTER.equals(provider)) { OAuthRequest req = new OAuthRequest(Verb.GET, "https://api.twitter.com/1/account/verify_credentials.json"); service.signRequest(accessToken, req); log.info("Requesting from twitter " + req.getCompleteUrl()); Response response = req.send(); log.info("Requested user info from twitter: " + response.getBody()); JSONObject twitterUserInfo = new JSONObject(response.getBody()); log.info("got user info: " + twitterUserInfo.getString("name") + ", " + twitterUserInfo.getString("screen_name")); Member tempMember = new HooplaServiceImpl() .findMemberBySocialId(new Integer(twitterUserInfo.getInt("id")).toString()); if (tempMember == null) { tempMember = new Member(); tempMember.setSocialId(new Integer(twitterUserInfo.getInt("id")).toString()); tempMember.setFirstname(twitterUserInfo.getString("name").split(" ")[0]); tempMember.setLastname(twitterUserInfo.getString("name").split(" ", 2)[1]); tempMember.setNickname(twitterUserInfo.getString("screen_name")); tempMember.setProfilePic(twitterUserInfo.getString("profile_image_url")); } else loginInfo.setLoggedIn(true); loginInfo.setMember(tempMember); } else if (OAuth2Provider.FACEBOOK.equals(provider)) { OAuthRequest req = new OAuthRequest(Verb.GET, "https://graph.facebook.com/me"); service.signRequest(accessToken, req); log.info("Requesting from facebook " + req.getCompleteUrl()); Response response = req.send(); log.info("Requested user info from facebook: " + response.getBody()); JSONObject facebookUserInfo = new JSONObject(response.getBody()); log.info("got user info: " + facebookUserInfo.getString("name") + ", " + facebookUserInfo.getString("username")); Member tempMember = new HooplaServiceImpl() .findMemberBySocialId(facebookUserInfo.getString("id")); if (tempMember == null) { tempMember = new Member(); tempMember.setSocialId(new Integer(facebookUserInfo.getString("id")).toString()); tempMember.setFirstname(facebookUserInfo.getString("first_name")); tempMember.setLastname(facebookUserInfo.getString("last_name")); tempMember.setNickname(facebookUserInfo.getString("username")); tempMember.setProfilePic("https://graph.facebook.com/" + facebookUserInfo.getString("id") + "/picture?type=large"); tempMember.setEmail(facebookUserInfo.getString("email")); tempMember = new HooplaServiceImpl().registerMember(tempMember); } loginInfo.setLoggedIn(true); loginInfo.setMember(tempMember); } loginInfo.setLogoutUrl("/logout/oauth"); log.info("Set loginInfo to " + loginInfo); return loginInfo; } catch (Exception e) { log.log(Level.WARNING, e.getLocalizedMessage(), e); } } else { User user = userService.getCurrentUser(); if (userService.isUserLoggedIn() && user != null) { loginInfo.setLoggedIn(true); loginInfo.setMember(new HooplaServiceImpl().saveOrGetMember(user)); loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri)); } log.info("Logged in with google services " + loginInfo); } return loginInfo; }
From source file:com.google.android.apps.santatracker.service.APIProcessor.java
/** * Access the API from a URL and process its data. * If any values have changed, the appropriate callbacks in * {@link com.google.android.apps.santatracker.service.APIProcessor.APICallback} are called. * Returns {@link #ERROR_CODE} if the data could not be loaded or processed. * Returns the delay to the next API access if the access was successful. *///w ww. java 2 s. co m public long accessAPI(String url) { SantaLog.d(TAG, "URL=" + url); // Get current values from mPreferences long offsetPref = mPreferences.getOffset(); String fingerprintPref = mPreferences.getFingerprint(); boolean switchOffPref = mPreferences.getSwitchOff(); // load data as JSON JSONObject json = loadApi(url); if (json == null) { Log.d(TAG, "Santa Communication Error 3"); return ERROR_CODE; } try { // Error if the status is not OK if (!FIELD_STATUS_OK.equals(json.getString(FIELD_STATUS))) { Log.d(TAG, "Santa Communication Error 4"); return ERROR_CODE; } final int routeOffset = json.getInt(FIELD_ROUTEOFFSET); final long now = json.getLong(FIELD_NOW); final long offset = json.getLong(FIELD_TIMEOFFSET); final String fingerprint = json.getString(FIELD_FINGERPRINT); final long refresh = json.getLong(FIELD_REFRESH); final boolean switchOff = json.getBoolean(FIELD_SWITCHOFF); final JSONArray locations = json.getJSONArray(FIELD_DESTINATIONS); final int streamOffset = json.getInt(FIELD_STREAMOFFSET); final JSONArray stream = json.getJSONArray(FIELD_STREAM); // Notification stream parameters are optional final JSONArray notificationStream = json.has(FIELD_NOTIFICATIONSTREAM) ? json.getJSONArray(FIELD_NOTIFICATIONSTREAM) : null; // Fingerprint has changed, remove route and stream from db if (!fingerprint.equals(fingerprintPref)) { mCallback.notifyRouteUpdating(); //empty the database and reset preferences mDestinationDBHelper.emptyDestinationTable(); mStreamDBHelper.emptyCardTable(); mPreferences.invalidateData(); } // Destinations if (locations != null && locations.length() > 0) { int processedLocations = processRoute(locations); if (processedLocations > 0) { final int newOffset = routeOffset + processedLocations; mCallback.onNewRouteLoaded(); mPreferences.setFingerprint(fingerprint); mPreferences.setRouteOffset(newOffset); SantaLog.d(TAG, "Processed route - new details: " + newOffset + ", " + fingerprint); } } // Stream if (stream != null && stream.length() > 0) { // process non-notification cards int processedCards = processStream(stream, false); if (processedCards > 0) { final int newOffset = streamOffset + processedCards; mCallback.onNewStreamLoaded(); mPreferences.setStreamOffset(newOffset); SantaLog.d(TAG, "Processed stream - new details: " + newOffset); } } // Notification Stream if (notificationStream != null && notificationStream.length() > 0) { // process notification cards int processedCards = processStream(notificationStream, true); if (processedCards > 0) { mCallback.onNewNotificationStreamLoaded(); SantaLog.d(TAG, "Processed notification stream - count: " + processedCards); } } // Offset final long newOffset = now - System.currentTimeMillis() + offset; if (offsetPref != newOffset) { mPreferences.setOffset(newOffset); SantaLog.d(TAG, "New offset: " + newOffset + ", current=" + System.currentTimeMillis() + ", new Santa=" + SantaPreferences.getCurrentTime()); // Log.d(TAG, "new offset: new="+newOffset+", now="+now+", offset="+offset+", // prefOffset="+offsetPref+", time="+System.currentTimeMillis()); // Notify only if offset varies significantly if ((newOffset > offsetPref + SantaPreferences.OFFSET_ACCEPTABLE_RANGE_DIFFERENCE || newOffset < offsetPref - SantaPreferences.OFFSET_ACCEPTABLE_RANGE_DIFFERENCE)) { mCallback.onNewOffset(); } } if (switchOffPref != switchOff) { mPreferences.setSwitchOff(switchOff); mCallback.onNewSwitchOffState(switchOff); } // Check Switches for Changes checkSwitchesDiff(getSwitches()); if (!fingerprint.equals(fingerprintPref)) { // new data has been processed and locations have been stored mCallback.onNewFingerprint(); } return refresh; } catch (JSONException e) { Log.d(TAG, "Santa Communication Error 5"); SantaLog.d(TAG, "JSON Exception", e); return ERROR_CODE; } }
From source file:com.xorcode.andtweet.FriendTimeline.java
/** * Insert a row from a JSONObject.//from ww w .j a v a 2 s. c om * * @param jo * @return * @throws JSONException * @throws SQLiteConstraintException */ public Uri insertFromJSONObject(JSONObject jo) throws JSONException, SQLiteConstraintException { ContentValues values = new ContentValues(); // Construct the Uri to existing record Long lTweetId = Long.parseLong(jo.getString("id")); Uri aTweetUri = ContentUris.withAppendedId(mContentUri, lTweetId); String message = Html.fromHtml(jo.getString("text")).toString(); try { // TODO: Unify databases! switch (mTimelineType) { case AndTweetDatabase.Tweets.TIMELINE_TYPE_FRIENDS: case AndTweetDatabase.Tweets.TIMELINE_TYPE_MENTIONS: JSONObject user; user = jo.getJSONObject("user"); values.put(AndTweetDatabase.Tweets._ID, lTweetId.toString()); values.put(AndTweetDatabase.Tweets.AUTHOR_ID, user.getString("screen_name")); values.put(AndTweetDatabase.Tweets.MESSAGE, message); values.put(AndTweetDatabase.Tweets.SOURCE, jo.getString("source")); values.put(AndTweetDatabase.Tweets.TWEET_TYPE, mTimelineType); values.put(AndTweetDatabase.Tweets.IN_REPLY_TO_STATUS_ID, jo.getString("in_reply_to_status_id")); values.put(AndTweetDatabase.Tweets.IN_REPLY_TO_AUTHOR_ID, jo.getString("in_reply_to_screen_name")); values.put(AndTweetDatabase.Tweets.FAVORITED, jo.getBoolean("favorited") ? 1 : 0); break; case AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES: values.put(AndTweetDatabase.DirectMessages._ID, lTweetId.toString()); values.put(AndTweetDatabase.DirectMessages.AUTHOR_ID, jo.getString("sender_screen_name")); values.put(AndTweetDatabase.DirectMessages.MESSAGE, message); break; } Long created = Date.parse(jo.getString("created_at")); values.put(AndTweetDatabase.Tweets.SENT_DATE, created); } catch (Exception e) { Log.e(TAG, "insertFromJSONObject: " + e.toString()); } if ((mContentResolver.update(aTweetUri, values, null, null)) == 0) { // There was no such row so add new one mContentResolver.insert(mContentUri, values); mNewTweets++; switch (mTimelineType) { case AndTweetDatabase.Tweets.TIMELINE_TYPE_FRIENDS: case AndTweetDatabase.Tweets.TIMELINE_TYPE_MENTIONS: if (mTu.getUsername().equals(jo.getString("in_reply_to_screen_name")) || message.contains("@" + mTu.getUsername())) { mReplies++; } } } return aTweetUri; }