List of usage examples for twitter4j Twitter setOAuthAccessToken
void setOAuthAccessToken(AccessToken accessToken);
From source file:com.gmail.altakey.joanne.service.TwitterAuthService.java
License:Apache License
public static void updateRelations(final Context context, final AccessToken token) { final SharedPreferences prefs = context.getSharedPreferences(PREFERENCE, MODE_PRIVATE); try {//from ww w . j a v a2 s. co m final Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthAccessToken(token); final Set<Long> friends = new HashSet<Long>(); for (IDs ids = twitter.getFriendsIDs(-1);; ids = twitter.getFriendsIDs(ids.getNextCursor())) { for (Long id : ids.getIDs()) { friends.add(id); } if (!ids.hasNext()) { break; } } final Set<Long> followers = new HashSet<Long>(); for (IDs ids = twitter.getFollowersIDs(-1);; ids = twitter.getFollowersIDs(ids.getNextCursor())) { for (Long id : ids.getIDs()) { followers.add(id); } if (!ids.hasNext()) { break; } } prefs.edit().putString(KEY_FRIENDS, new IdListCoder().encode(friends)) .putString(KEY_FOLLOWERS, new IdListCoder().encode(followers)).commit(); UserRelation.notifyRelationsChanged(); Log.d(TAG, String.format("got %d friends", friends.size())); Log.d(TAG, String.format("got %d followers", followers.size())); } catch (TwitterException e) { Log.w(TAG, "cannot get follower list", e); } }
From source file:com.isitbusythere.reporter.TwitterSessionStore.java
License:Apache License
public static boolean restore(Twitter session, Context context) { SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE); session.setOAuthConsumer(context.getString(R.string.TWITTER_APP_KEY), context.getString(R.string.TWITTER_APP_SECRET)); String userToken = savedSession.getString(TOKEN, null); if (userToken == null) { session = null;/*from ww w. jav a 2 s . com*/ return false; } try { session.setOAuthAccessToken(new AccessToken(userToken, savedSession.getString(SECRET, null))); } catch (IllegalStateException e) { //I don't care } return true; }
From source file:com.jeanchampemont.wtfdyum.service.impl.TwitterServiceImpl.java
License:Apache License
private Twitter twitter(final Principal principal) { final Twitter instance = twitter(); instance.setOAuthAccessToken(new AccessToken(principal.getToken(), principal.getTokenSecret())); return instance; }
From source file:com.mastfrog.acteur.twitter.TwitterSign.java
@SuppressWarnings("unchecked") RemoteUserInfo zgetUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential, AuthorizationResponse auth)//from ww w .j a v a2s . co m throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException { System.setProperty("twitter4j.http.useSSL", "false"); Twitter twitter = TwitterFactory.getSingleton(); try { // Idiotic - shutdown does not clear state twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); } catch (Exception e) { e.printStackTrace(); } twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret)); OAuthAuthorization a = new OAuthAuthorization(twitter.getConfiguration()); a.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); URL url = URL.builder(Protocols.HTTPS) // URL url = URL.builder(Protocols.HTTP) // XXX NOT UNENCRYPTED! JUST FOR DEBUGING .setHost(Host.parse("api.twitter.com")).setPath("1.1/account/verify_credentials.json").create(); String hdr = new SigBuilder().add(oauth_token, auth.accessToken).add(OAuthHeaders.oauth_nonce, oauth_nonce) .toHeader(Method.GET, url.getPathAndQuery(), auth); // XXX encode URL? String franken = a.xgenerateAuthorizationHeader(oauth_nonce, "GET", "/1.1/account/verify_credentials.json", new HttpParameter[0], new twitter4j.auth.AccessToken(auth.accessToken, auth.accessTokenSecret)); OAuthAuthorization oa = new OAuthAuthorization(twitter.getConfiguration()); oa.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); oa.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret)); twitter4j.internal.http.HttpRequest r = new twitter4j.internal.http.HttpRequest(RequestMethod.GET, "https://api.twitter.com/twitter4j.internal.http.HttpRequest", new HttpParameter[0], oa, Collections.<String, String>emptyMap()); ResponseLatch latch = new ResponseLatch(); RH rh = new RH(); client.get().setURL(url).addHeader(Headers.stringHeader("Authorization"), hdr) .addHeader(Headers.stringHeader("X-Twitter-Client-URL"), "http://twitter4j.org/en/twitter4j-3.0.4-SNAPSHOT.xml") .addHeader(Headers.stringHeader("X-Twitter-Client"), "Twitter4J") .addHeader(Headers.stringHeader("Accept-Encoding"), "gzip") .addHeader(Headers.stringHeader("X-Twitter-Client-Version"), "3.0.4-SNAPSHOT") .addHeader(Headers.stringHeader("Accept"), "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2") // .addHeader(Headers.stringHeader("Accept"), "*/*") // .addHeader(Headers.stringHeader("Connection"), "keep-alive") .noDateHeader() // .noConnectionHeader() // .addHeader(Headers.stringHeader("Content-Type"), "application/x-www-form-urlencoded") // .setBody("screen_name=kablosna", MediaType.PLAIN_TEXT_UTF_8) .on(StateType.Closed, latch).on(StateType.Timeout, latch).execute(rh); rh.await(1, TimeUnit.MINUTES); latch.latch.await(1, TimeUnit.MINUTES); String responseBody = rh.getResponse(); RUI rui = new RUI(); if (responseBody == null) { // System.out.println("NULL RESPONSE BODY."); throw new IOException(rh.toString()); } rui.putAll(new ObjectMapper().readValue(responseBody, Map.class)); return rui; }
From source file:com.mastfrog.acteur.twitter.TwitterSign.java
RemoteUserInfo getUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential, AuthorizationResponse auth)/*from ww w .j a v a2s .c o m*/ throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException { // System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.StdOutLogger"); System.setProperty("twitter4j.debug", "true"); System.setProperty("twitter4j.http.useSSL", "false"); Twitter twitter = TwitterFactory.getSingleton(); try { // Idiotic twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret); } catch (Exception e) { e.printStackTrace(); } twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret)); try { User user = twitter.verifyCredentials(); RUI rui = new RUI(); rui.put("displayName", user.getName()); rui.put("name", user.getScreenName() + "@api.twitter.com"); rui.put("screen_name", user.getScreenName()); rui.put("picture", user.getProfileImageURLHttps()); rui.put("pictureLarge", user.getBiggerProfileImageURLHttps()); rui.put("id", user.getId()); return rui; } catch (TwitterException ex) { throw new IOException(ex); } finally { twitter.shutdown(); } }
From source file:com.michaelstark.twitteroauth.OAuthCallbackServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request/*from ww w .j av a2s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String verificationToken = request.getParameter("oauth_verifier"); HttpSession session = request.getSession(true); // Get the stored Twitter client from LoginServlet. Twitter twitter = (Twitter) session.getAttribute("twitterClient"); // Get the saved request token. RequestToken requestToken = (RequestToken) session.getAttribute("requestToken"); try { // Get an access token so we can do stuff. AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verificationToken); // Store the access token for later. session.setAttribute("accessToken", accessToken); // Configure the Twitter client to use our access token. twitter.setOAuthAccessToken(accessToken); // Get the current user info from Twitter and store it in the session. session.setAttribute("user", twitter.showUser(twitter.getScreenName())); } catch (TwitterException e) { logger.log(Level.SEVERE, "Could not get the user info: ", e); } request.getRequestDispatcher("/index.jsp").forward(request, response); }
From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java
License:Apache License
@Override public void open(@NonNull final Callback callback) { Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey) .setOAuthConsumerSecret(mConsumerSecret).build(); final Twitter instance = new TwitterFactory(configuration).getInstance(); if (mAccessToken != null) { instance.setOAuthAccessToken(mAccessToken); }//from w ww . j a v a 2 s . c o m doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() { @Override public Task<AccessToken> then(Task<User> task) throws Exception { if (task.isFaulted()) { SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().clear().apply(); mAccessToken = null; instance.setOAuthAccessToken(null); return doGetAuthenticationURL(instance) .onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() { @Override public Task<Bundle> then(Task<RequestToken> task) throws Exception { return doDialogAuthentication(task.getResult()); } }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() { @Override public Task<AccessToken> then(Task<Bundle> task) throws Exception { return doGetAccessToken(instance, task.getResult()); } }).continueWith(new Continuation<AccessToken, AccessToken>() { @Override public AccessToken then(Task<AccessToken> task) throws Exception { if (task.isFaulted()) { Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError()); // Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show(); callback.onCancelled(); } else if (task.isCompleted()) { AccessToken accessToken = task.getResult(); String serialized = Base64.encodeToString( SerializationUtils.serialize(accessToken), Base64.DEFAULT); SharedPreferences preferences = getActivity() .getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().putString("access_token_str", serialized).apply(); callback.onSessionOpened(accessToken); mAccessToken = accessToken; return accessToken; } return null; } }); } else { callback.onSessionOpened(mAccessToken); return Task.forResult(mAccessToken); } } }); }
From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java
License:Apache License
@Override public void validate(@NonNull final Callback callback) { Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey) .setOAuthConsumerSecret(mConsumerSecret).build(); final Twitter instance = new TwitterFactory(configuration).getInstance(); if (mAccessToken != null) { instance.setOAuthAccessToken(mAccessToken); }/*from w w w.j a v a 2 s .co m*/ doValidate(mAccessToken, instance).continueWith(new Continuation<User, AccessToken>() { @Override public AccessToken then(Task<User> task) throws Exception { if (task.isFaulted()) { SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().clear().apply(); mAccessToken = null; callback.onSessionOpened(null); return null; } else { callback.onSessionOpened(mAccessToken); return mAccessToken; } } }); }
From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java
License:Apache License
@Override public void tweets(final StatusUpdate latestStatus, @NonNull final ResponseCallback callback) { Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey) .setOAuthConsumerSecret(mConsumerSecret).build(); final Twitter instance = new TwitterFactory(configuration).getInstance(); if (mAccessToken != null) { instance.setOAuthAccessToken(mAccessToken); }//from ww w . ja v a 2 s.c om doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() { @Override public Task<AccessToken> then(Task<User> task) throws Exception { if (task.isFaulted()) { final Task<AccessToken>.TaskCompletionSource source = Task.<AccessToken>create(); SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().clear().apply(); mAccessToken = null; instance.setOAuthAccessToken(null); doGetAuthenticationURL(instance).onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() { @Override public Task<Bundle> then(Task<RequestToken> task) throws Exception { return doDialogAuthentication(task.getResult()); } }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() { @Override public Task<AccessToken> then(Task<Bundle> task) throws Exception { return doGetAccessToken(instance, task.getResult()); } }).continueWith(new Continuation<AccessToken, AccessToken>() { @Override public AccessToken then(Task<AccessToken> task) throws Exception { if (task.isFaulted()) { Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError()); // Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show(); // callback.onCancelled(task.getError()); source.trySetError(task.getError()); } else if (task.isCompleted()) { AccessToken accessToken = task.getResult(); String serialized = Base64.encodeToString(SerializationUtils.serialize(accessToken), Base64.DEFAULT); SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().putString("access_token_str", serialized).apply(); instance.setOAuthAccessToken(accessToken); mAccessToken = accessToken; source.trySetResult(mAccessToken); return accessToken; } return null; } }); return source.getTask(); } else { return Task.forResult(mAccessToken); } // } // }).onSuccessTask(new Continuation<AccessToken, Task<Map<String, RateLimitStatus>>>() { // @Override // public Task<Map<String, RateLimitStatus>> then(Task<AccessToken> task) throws Exception { // return doCheckStatus(instance); } }).onSuccessTask(new Continuation<AccessToken, Task<Status>>() { @Override public Task<Status> then(Task<AccessToken> task) throws Exception { // Map<String, RateLimitStatus> result = task.getResult(); return doTweet(instance, latestStatus); } }).continueWith(new Continuation<Status, Object>() { @Override public Object then(Task<Status> task) throws Exception { if (task.isFaulted()) { Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError()); String message = task.getError().getMessage(); if (!TextUtils.isEmpty(message)) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } callback.onCancelled(task.getError()); } else if (task.isCompleted()) { callback.onCompleted(task.getResult()); } return null; } }); }
From source file:com.mysentosa.android.sg.share.SessionStore.java
License:Apache License
public static boolean restoreTwitterAuthorizationToken(Twitter session, Context context) { SharedPreferences savedSession = context.getSharedPreferences(TWITTER_SESSION, Context.MODE_PRIVATE); String token = savedSession.getString(TWITTER_ACCESS_TOKEN, null); String token_secret = savedSession.getString(TWITTER_ACCESS_TOKEN_SECRET, null); if (token != null && token_secret != null) { AccessToken at = new AccessToken(token, token_secret); session.setOAuthAccessToken(at); return true; }//from www. j a v a 2 s .c om return false; }