@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Uri uri = intent.getData(); if (uri != null && CALLBACK_URL.getScheme().equals(uri.getScheme())) { String oauth_verifier = uri.getQueryParameter("oauth_verifier"); try { acToken = twitter.getOAuthAccessToken(rqToken, oauth_verifier); accountdb.insert_twitter(token, token, stoken); } catch (TwitterException e) { e.printStackTrace(); } } }
private static void primeiraTwittada() throws TwitterException, IOException { Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer("HSPokkXFfwsjWwTGy8kfw", "zMNRv0G9kORPiSXcJuPrnWFOBESewPirr8Lf6fRLpA"); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } // persist to the accessToken for future reference. storeAccessToken(twitter.verifyCredentials().getId(), accessToken); Status status = twitter.updateStatus("GO GO GO"); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); }
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print( "Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(args[0]); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
public void testDesktopClient() throws Exception { RequestToken rt; Twitter twitter = new Twitter(); HttpClient http; HttpResponse response; String resStr; String authorizeURL; HttpParameter[] params; AccessToken at; String cookie; http = new HttpClient(); // desktop client - requiring pin unauthenticated.setOAuthConsumer(desktopConsumerKey, desktopConsumerSecret); rt = unauthenticated.getOAuthRequestToken(); // trying to get an access token without permitting the request token. try { rt.getAccessToken(); fail(); } catch (TwitterException te) { assertEquals(401, te.getStatusCode()); } twitter.setOAuthConsumer(desktopConsumerKey, desktopConsumerSecret); rt = twitter.getOAuthRequestToken(); // trying to get an access token without permitting the request token. try { twitter.getOAuthAccessToken(rt.getToken(), rt.getTokenSecret()); fail(); } catch (TwitterException te) { assertEquals(401, te.getStatusCode()); } Map<String, String> props = new HashMap<String, String>(); response = http.get(rt.getAuthorizationURL()); cookie = response.getResponseHeader("Set-Cookie"); // http.setRequestHeader("Cookie", cookie); props.put("Cookie", cookie); resStr = response.asString(); authorizeURL = catchPattern(resStr, "<form action=\"", "\" id=\"login_form\""); params = new HttpParameter[4]; params[0] = new HttpParameter( "authenticity_token", catchPattern(resStr, "\"authenticity_token\" type=\"hidden\" value=\"", "\" />")); params[1] = new HttpParameter( "oauth_token", catchPattern(resStr, "name=\"oauth_token\" type=\"hidden\" value=\"", "\" />")); params[2] = new HttpParameter("session[username_or_email]", id1.screenName); params[3] = new HttpParameter("session[password]", id1.pass); response = http.request(new HttpRequest(RequestMethod.POST, authorizeURL, params, null, props)); resStr = response.asString(); String pin = catchPattern(resStr, "<div id=\"oauth_pin\">\n ", "\n</div>"); at = twitter.getOAuthAccessToken(rt.getToken(), rt.getTokenSecret(), pin); assertEquals(at.getScreenName(), id1.screenName); assertEquals(at.getUserId(), 6358482); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fun_app_with_twitter); mSharedPreferences = getSharedPreferences(Const.PREFERENCE_NAME, MODE_PRIVATE); getTweetButton = (Button) findViewById(R.id.getTweet); getTweetButton.setOnClickListener(this); buttonLogin = (Button) findViewById(R.id.twitterLogin); buttonLogin.setOnClickListener(this); keyword = (EditText) findViewById(R.id.keyword); if (!isConnected()) { buttonLogin.setText(R.string.label_connect); } else { buttonLogin.setText(R.string.label_disconnect); } /** Handle OAuth Callback */ Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL)) { String verifier = uri.getQueryParameter(Const.IEXTRA_OAUTH_VERIFIER); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); Editor e = mSharedPreferences.edit(); e.putString(Const.PREF_KEY_TOKEN, accessToken.getToken()); e.putString(Const.PREF_KEY_SECRET, accessToken.getTokenSecret()); e.commit(); } catch (Exception e) { // System.out.println(e.toString()); Log.e(TAG, e.getMessage()); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } } }
public boolean connect() throws InterruptedException { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(TwitterApp.CONSUMER_KEY, TwitterApp.CONSUMER_SECRET); Session session = HibernateUtil.openSession(); while (true) { try { RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = getAccessToken(session, TwitterApp.TWITTER_USER); while (null == accessToken) { Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); String pin = JOptionPane.showInputDialog( null, "Insert OAuth Twitter PIN", "Twitter", JOptionPane.ERROR_MESSAGE); accessToken = twitter.getOAuthAccessToken(requestToken, pin); if (accessToken != null) saveAccessToken(session, accessToken.getToken(), accessToken.getTokenSecret()); } twitter = new TwitterFactory() .getOAuthAuthorizedInstance( TwitterApp.CONSUMER_KEY, TwitterApp.CONSUMER_SECRET, accessToken); } catch (Exception e) { System.err.println(e.getMessage()); session.close(); Thread.sleep(60000); return false; } session.close(); return true; } }
@Override public String input() throws Exception { if (!isEmpty(denied)) { // todo: inform user that authorization has been denied return SUCCESS; } TwitterFactory tf = new TwitterFactory(TwitterConfigFactory.getConfig()); Twitter twitter = tf.getInstance(); RequestToken requestToken = (RequestToken) session.get("requestToken"); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier); try (GroupTwitterCredentialsDao groupTwitterCredentialsDao = new DbiFactory().getDbi().open(GroupTwitterCredentialsDao.class)) { groupTwitterCredentialsDao.createGroupTwitterCredentials( groupId, accessToken.getScreenName(), accessToken.getUserId(), accessToken.getToken(), accessToken.getTokenSecret()); } // todo: inform user that authorization was successful return SUCCESS; }
@SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* initializing twitter parameters from string.xml */ initTwitterConfigs(); /* Enabling strict mode */ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); /* Setting activity layout file */ setContentView(R.layout.activity_main); loginLayout = (RelativeLayout) findViewById(R.id.login_layout); /* register button click listeners */ findViewById(R.id.btn_login).setOnClickListener(this); /* Check if required twitter keys are set */ if (TextUtils.isEmpty(consumerKey) || TextUtils.isEmpty(consumerSecret)) { Toast.makeText(this, "Twitter key and secret not configured", Toast.LENGTH_SHORT).show(); return; } /* Initialize application preferences */ mSharedPreferences = getSharedPreferences(PREF_NAME, 0); boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false); /* if already logged in, then hide login layout and show share layout */ if (isLoggedIn) { Intent intent = new Intent(MainActivity.this, MenuActivity.class); startActivity(intent); } else { loginLayout.setVisibility(View.VISIBLE); Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(callbackUrl)) { String verifier = uri.getQueryParameter(oAuthVerifier); try { /* Getting oAuth authentication token */ AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); /* Getting user id form access token */ long userID = accessToken.getUserId(); final User user = twitter.showUser(userID); final String username = user.getName(); /* save updated token */ saveTwitterInfo(accessToken); // loginLayout.setVisibility(View.GONE); } catch (Exception e) { Log.e("Failed login Twitter!!", e.getMessage()); } } } }
/** * 認証 * * @param pin PIN * @return 成功したか */ public boolean OAuthAccess(String pin) { if (this.access != null) { return false; } if (this.request == null) { OAuthRequest(); } try { if (pin.length() > 0) { access = twitter.getOAuthAccessToken(request, pin); } else { access = twitter.getOAuthAccessToken(); } } catch (Exception e) { return false; } return true; }
/** * Grava a autorização para o programa acessar a conta do twitter gerando um token, tokenSecret. */ @RequestMapping(value = "/{id}/autorizacaoTwitter") public String autorizacaoTwitter( @PathVariable("id") Integer id, @Valid Pin pin, ModelMap modelMap) { AutorizacaoTwitterRequest autorizacaoTwitterRequest = autorizacaoTwitterRequestService.find(AutorizacaoTwitterRequest.class, id); Usuario usuarioAutorizado = usuarioService.getUsuarioByLogin( SecurityContextHolder.getContext().getAuthentication().getName()); Twitter twitter = autorizacaoTwitterRequest.getTwitter(); RequestToken requestToken = autorizacaoTwitterRequest.getRequestToken(); AccessToken accessToken = null; try { if (pin.getPin().length() > 0) { System.out.println(pin.getPin()); accessToken = twitter.getOAuthAccessToken(requestToken, pin.getPin()); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Não foi possível obter o token de acesso." + te.getMessage()); } else { te.printStackTrace(); } } AutorizacaoTwitter autorizacaoTwitter = new AutorizacaoTwitter(); autorizacaoTwitter.setId((int) accessToken.getUserId()); autorizacaoTwitter.setToken(accessToken.getToken()); autorizacaoTwitter.setTokenSecret(accessToken.getTokenSecret()); autorizacaoTwitter.setUsuario(usuarioAutorizado); autorizacaoTwitterService.save(autorizacaoTwitter); usuarioAutorizado.setAutorizacaoTwitter(autorizacaoTwitter); usuarioService.update(usuarioAutorizado); autorizacaoTwitterRequestService.delete(autorizacaoTwitterRequest); modelMap.addAttribute("usuario", usuarioAutorizado); return "redirect:/usuario/listar"; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); try { AccessToken oAuthAccessToken = twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute("requestToken"); String cookie = UUID.randomUUID().toString(); Cookie c = new Cookie(SigninServlet.COOKIE_NAME, cookie); c.setMaxAge(365 * 24 * 60 * 60); // one year response.addCookie(c); UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:jboss/UserTransaction"); ut.begin(); User user = entityManager.find(User.class, twitter.getScreenName()); if (user == null) { user = new User(); user.setScreenName(twitter.getScreenName()); // user.setAccessToken(oAuthAccessToken.getToken()); // user.setAccessTokenSecret(oAuthAccessToken.getTokenSecret()); entityManager.persist(user); twitterCredentialManager.setAccessToken( user, oAuthAccessToken.getToken(), oAuthAccessToken.getTokenSecret()); } else { user.getFeeds().size(); user.getCircles().size(); user.getTweeters().size(); user.getSentStories().size(); if (twitterCredentialManager.getAccessToken(user) == null) { twitterCredentialManager.setAccessToken( user, oAuthAccessToken.getToken(), oAuthAccessToken.getTokenSecret()); } } Login login = new Login(); login.setCookie(cookie); login.setUser(user); entityManager.persist(login); request.getSession().setAttribute("user", user); ut.commit(); } catch (Exception e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
@Override public void accessToken(Uri uri) { if (requestToken != null) { String verifier = uri.getQueryParameter(INTENT_OAUTH_VERIFIER); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); PersistUtils.getInstance(context) .persistAccessToken(accessToken.getToken(), accessToken.getTokenSecret()); } catch (TwitterException e) { e.printStackTrace(); } } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); try { twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute("requestToken"); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
/** Handle OAuth Callback */ public void handleOauthCallback(Uri uri) { if (uri != null && uri.toString().startsWith(TwitterConsts.CALLBACK_URL)) { String verifier = uri.getQueryParameter(TwitterConsts.IEXTRA_OAUTH_VERIFIER); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); Editor ed = sharedPreferences.edit(); ed.putString(TwitterConsts.PREF_KEY_TOKEN, accessToken.getToken()); ed.putString(TwitterConsts.PREF_KEY_SECRET, accessToken.getTokenSecret()); ed.commit(); } catch (Exception e) { Log.e("TwitterHelper", e.getMessage()); } } }
/* * Called after authenticating with Acess Token from the Twitter */ protected void onNewIntent(Intent intent) { Uri uri = intent.getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); AUTH_TOKEN = accessToken.getToken(); AUTH_TOKEN_SECRET = accessToken.getTokenSecret(); } catch (Exception ex) { Log.d("SN", ex.getMessage()); } super.onNewIntent(intent); } }
private AccessToken requestToken() { RequestToken requestToken = null; try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { e.printStackTrace(); } AccessToken accessToken = null; Scanner scanner = new Scanner(System.in); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:"); String pin = scanner.nextLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } // persist to the accessToken for future reference. try { storeAccessToken(twitter.verifyCredentials().getId(), accessToken); } catch (TwitterException e) { e.printStackTrace(); } return accessToken; }
public void storeData(Intent intent) { AccessToken accessToken = null; try { String oauthVerifier = intent.getExtras().getString(Const.IEXTRA_OAUTH_VERIFIER); accessToken = mTwitter.getOAuthAccessToken(mRequestToken, oauthVerifier); SharedPreferences pref = context.getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString(Const.PREF_KEY_ACCESS_TOKEN, accessToken.getToken()); editor.putString(Const.PREF_KEY_ACCESS_TOKEN_SECRET, accessToken.getTokenSecret()); editor.commit(); } catch (TwitterException e) { e.printStackTrace(); } }
public void testBrowserClientWithCustomCallback() throws Exception { RequestToken rt; Twitter twitter = new Twitter(); HttpClient http; HttpResponse response; String resStr; String authorizeURL; HttpParameter[] params; AccessToken at; String cookie; http = new HttpClient(); // browser client - not requiring pin / overriding callback url twitter = new Twitter(); twitter.setOAuthConsumer(browserConsumerKey, browserConsumerSecret); rt = twitter.getOAuthRequestToken("http://yusuke.homeip.net/twitter4j/custom_callback"); http = new HttpClient(); System.out.println("AuthorizationURL: " + rt.getAuthorizationURL()); response = http.get(rt.getAuthorizationURL()); Map<String, String> props = new HashMap<String, String>(); cookie = response.getResponseHeader("Set-Cookie"); // http.setRequestHeader("Cookie", cookie); props.put("Cookie", cookie); resStr = response.asString(); authorizeURL = catchPattern(resStr, "<form action=\"", "\" id=\"login_form\""); params = new HttpParameter[4]; params[0] = new HttpParameter( "authenticity_token", catchPattern(resStr, "\"authenticity_token\" type=\"hidden\" value=\"", "\" />")); params[1] = new HttpParameter( "oauth_token", catchPattern(resStr, "name=\"oauth_token\" type=\"hidden\" value=\"", "\" />")); params[2] = new HttpParameter("session[username_or_email]", id1.screenName); params[3] = new HttpParameter("session[password]", id1.pass); response = http.request(new HttpRequest(RequestMethod.POST, authorizeURL, params, null, props)); // response = http.post(authorizeURL, params); resStr = response.asString(); String oauthVerifier = catchPattern(resStr, "&oauth_verifier=", "\">"); at = twitter.getOAuthAccessToken(rt.getToken(), rt.getTokenSecret(), oauthVerifier); assertEquals(at.getScreenName(), id1.screenName); assertEquals(at.getUserId(), 6358482); }
/** * Create an access token for this new user</br> Fill out the Twitter4j helper</br> And save these * credentials so we can log the user straight in next time * * @param oauthVerifier */ private void authoriseNewUser(String oauthVerifier) { try { AccessToken at = oTwitter.getOAuthAccessToken(mReqToken, oauthVerifier); oTwitter.setOAuthAccessToken(at); saveAccessToken(at); // Set the content view back after we changed to a webview setContentView(R.layout.new_user_details); } catch (TwitterException e) { Log.e(this.getClass().getCanonicalName(), "Twitter auth error"); } catch (IllegalStateException e) { Log.e(this.getClass().getCanonicalName(), "Twitter IllegalStateException error"); } catch (NullPointerException e) { Log.e(this.getClass().getCanonicalName(), "Twitter NullPointerException error"); } }
/** * Requests an access token from Twitter. * * @return */ public AccessToken requestAccessToken() throws IOException, URISyntaxException { AccessToken accessToken = null; try { while (null == accessToken) { java.awt.Desktop.getDesktop().browse(new URI(myRequestToken.getAuthorizationURL())); String pin = javax.swing.JOptionPane.showInputDialog("Enter PIN:"); accessToken = myTwitter.getOAuthAccessToken(myRequestToken, pin); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } return accessToken; }
private AccessToken getAccessToken() { try { // Get an access token. This triggers network access. AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier); if (isDebugEnabled()) { Log.d(TAG, "Got an access token for " + token.getScreenName()); } return token; } catch (TwitterException e) { // Failed to get an access token. e.printStackTrace(); Log.e(TAG, "Failed to get an access token.", e); // No access token. return null; } }
public boolean tryConnect() { /** Handle OAuth Callback */ Uri uri = oIntent.getData(); if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL)) { String verifier = uri.getQueryParameter(Const.IEXTRA_OAUTH_VERIFIER); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); Editor e = mSharedPreferences.edit(); e.putString(Const.PREF_KEY_TOKEN, accessToken.getToken()); e.putString(Const.PREF_KEY_SECRET, accessToken.getTokenSecret()); e.commit(); Log.v( this.getClass().getCanonicalName(), "tryConnect-> Twitter KEY:" + accessToken.getToken() + " SEGRET" + accessToken.getTokenSecret()); return true; } catch (Exception e) { Log.e(this.getClass().getCanonicalName(), e.getMessage()); return false; } } else { Log.v(this.getClass().getCanonicalName(), "tryConnect-> Twitter KEY no"); SharedPreferences mSharedPreferences = oContext.getSharedPreferences(Const.PREFERENCE_NAME, Context.MODE_PRIVATE); String oauthAccessToken = mSharedPreferences.getString(Const.PREF_KEY_TOKEN, ""); String oAuthAccessTokenSecret = mSharedPreferences.getString(Const.PREF_KEY_SECRET, ""); Log.v( this.getClass().getCanonicalName(), "oauthAccessToken: " + oauthAccessToken + " oAuthAccessTokenSecret:" + oAuthAccessTokenSecret); if (mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "").length() == 0) { askOAuth(); } // checkConnected(); return false; } }
public void testSigninWithTwitter() throws Exception { RequestToken rt; Twitter twitter = new TwitterFactory().getInstance(); HttpClient http; HttpResponse response; String resStr; String authorizeURL; HttpParameter[] params; AccessToken at; String cookie; http = new HttpClient(); // browser client - not requiring pin twitter.setOAuthConsumer(browserConsumerKey, browserConsumerSecret); rt = twitter.getOAuthRequestToken(); Map<String, String> props = new HashMap<String, String>(); response = http.get(rt.getAuthenticationURL()); cookie = response.getResponseHeader("Set-Cookie"); // http.setRequestHeader("Cookie", cookie); props.put("Cookie", cookie); resStr = response.asString(); authorizeURL = catchPattern(resStr, "<form action=\"", "\" id=\"login_form\""); params = new HttpParameter[4]; params[0] = new HttpParameter( "authenticity_token", catchPattern(resStr, "\"authenticity_token\" type=\"hidden\" value=\"", "\" />")); params[1] = new HttpParameter( "oauth_token", catchPattern(resStr, "name=\"oauth_token\" type=\"hidden\" value=\"", "\" />")); params[2] = new HttpParameter("session[username_or_email]", id1.screenName); params[3] = new HttpParameter("session[password]", id1.pass); response = http.request(new HttpRequest(RequestMethod.POST, authorizeURL, params, null, props)); // response = http.post(authorizeURL, params); at = twitter.getOAuthAccessToken(rt.getToken(), rt.getTokenSecret()); assertEquals(at.getScreenName(), id1.screenName); assertEquals(at.getUserId(), 6358482); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { String verifier = data.getExtras().getString(oAuthVerifier); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // long userID = accessToken.getUserId(); // final User user = twitter.showUser(userID); // String username = user.getName(); saveTwitterInfo(accessToken); } catch (Exception e) { Log.e("Twitter Login Failed", e.getMessage()); } } super.onActivityResult(requestCode, resultCode, data); }
// make sure to enable read, write, direct permission and // check the allow applications on settings protected User getUserLogin(Twitter twitter, HttpSession session, String oauthVerifier) { // try to get credentials User user = null; if (session.getAttribute("requestToken") != null) { try { RequestToken requestToken = (RequestToken) session.getAttribute("requestToken"); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauthVerifier); session.setAttribute("accessToken", accessToken); twitter.setOAuthAccessToken(accessToken); user = twitter.verifyCredentials(); } catch (TwitterException e) { if (e.getStatusCode() == 401) { Logger.getLogger(TwitterInfo.class.getName()).info(e.getMessage()); } else { Logger.getLogger(TwitterInfo.class.getName()).severe(e.getMessage()); } } } return user; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute("requestToken"); User user = twitter.verifyCredentials(); // Store Access Token so that we can constantly poll twitter CallbackServlet.storeAccessToken(user, accessToken); response.sendRedirect( request.getContextPath() + "/enqueueTweets?twitterId=" + user.getId() + "&twitterHandle=" + user.getScreenName()); } catch (TwitterException e) { throw new ServletException(e); } // response.sendRedirect(request.getContextPath() + "/"); }
/** * ユーザー情報取得用トークン取得メソッド * * @author 北山知輝 * @since 2015/03/16 * @return result 結果 * @throws TwitterException * @throws IOException */ public String[] loginOAuth(HttpServletResponse response, HttpServletRequest request) throws TwitterException, IOException { HttpSession session = request.getSession(); Twitter twitter = (Twitter) session.getAttribute("Twitter"); String verifier = request.getParameter("oauth_verifier"); AccessToken accessToken = null; String userData[] = new String[2]; try { // RequestTokenからAccessTokenを取得 if (session.getAttribute("RequestToken") != null) { accessToken = twitter.getOAuthAccessToken( (RequestToken) session.getAttribute("RequestToken"), verifier); } else { userData[0] = "ゲスト"; userData[1] = "ゲスト"; return userData; } } catch (Exception e) { } if (accessToken != null) { // AccessTokenをセッションに保持 session.setAttribute("AccessToken", accessToken.getToken()); session.setAttribute("AccessTokenSecret", accessToken.getTokenSecret()); } User user = twitter.verifyCredentials(); userData[0] = user.getName(); userData[1] = user.getScreenName(); return userData; }
@Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate!"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(R.id.login_activitycontainer, new LoginActivityFragment()) .commit(); } // GOOGLE mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Plus.SCOPE_PLUS_LOGIN) .build(); // FACEBOOK uiHelper = new UiLifecycleHelper(this, callback); uiHelper.onCreate(savedInstanceState); // TWITTER // Check if twitter keys are set if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) { // Internet Connection is not present alert.showAlertDialog( LoginActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // TODO: please us threads correctly! if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Check if Internet present cd = new ConnectionDetector(getApplicationContext()); if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog( LoginActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences("AndroidSocialTemplate", 0); /** * This if conditions is tested once is redirected from twitter page. Parse the uri to get oAuth * Verifier */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // Shared Preferences Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.d("Twitter OAuth Token", "> " + accessToken.getToken()); Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivityForResult(i, REQUEST_CODE_TWITTER_LOGIN); } catch (Exception e) { // Check log for login errors Log.e("Twitter Login Error", "> " + e.getMessage()); } } } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter(Pages.PARAM_ACTION); if (action == null) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } Twitter twitter = new Twitter(); twitter.setOAuthConsumer( ApplicationProperty.read(ApplicationProperty.CONSUMER_KEY), ApplicationProperty.read(ApplicationProperty.CONSUMER_SECRET)); log.warning( "action=" + action + ", Using consumer key " + ApplicationProperty.read(ApplicationProperty.CONSUMER_KEY) + ", isTesting()=" + ApplicationProperty.isTesting()); try { User user = AuthFilter.getCurrentUser(req).getOpenId(); if (ApplicationProperty.isTesting() && action.equalsIgnoreCase(Pages.PARAM_ACTION_ADD)) { saveToken("token", "tokenSecret", "papaya_" + (new Date().getTime()), user); resp.sendRedirect(Pages.PAGE_MAIN); } else if (action.equalsIgnoreCase(Pages.PARAM_ACTION_ADD)) { RequestToken requestToken = twitter.getOAuthRequestToken(); log.warning( "requestToken=" + requestToken + ", token=" + requestToken.getToken() + ", secret=" + requestToken.getTokenSecret() + ", url=" + requestToken.getAuthorizationURL()); resp.addCookie(new Cookie(COOKIE_TOKEN, requestToken.getToken())); resp.addCookie(new Cookie(COOKIE_TOKEN_SECRET, requestToken.getTokenSecret())); resp.sendRedirect(requestToken.getAuthorizationURL()); } else if (action.equalsIgnoreCase(Pages.PARAM_OAUTH)) { String token = null, tokenSecret = null; Cookie[] cookies = req.getCookies(); log.warning("back from twitter, req=" + req.getQueryString()); for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_TOKEN)) { token = cookie.getValue(); } if (cookie.getName().equals(COOKIE_TOKEN_SECRET)) { tokenSecret = cookie.getValue(); } } AccessToken accessToken = twitter.getOAuthAccessToken(token, tokenSecret); if (accessToken == null) { log.warning( "twitter token cann't be retrieved for token=" + token + ", secret=" + tokenSecret); } this.saveToken(accessToken, user); resp.sendRedirect(Pages.PAGE_MAIN); } else if (action.equalsIgnoreCase(Pages.PARAM_ACTION_DELETE)) { this.deleteToken(req.getParameter(Pages.PARAM_SCREENNAME), user); resp.getWriter().write("Delete Successful"); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } catch (TwitterException e) { e.printStackTrace(resp.getWriter()); } catch (Exception e) { e.printStackTrace(resp.getWriter()); } }
public AccessToken getAccessToken(String oAuthVerifier) throws TwitterException { return twitter.getOAuthAccessToken(requestToken, oAuthVerifier); }