@Before public void setUp() throws Exception { when(request.getRequestURL()).thenReturn(new StringBuffer("uri")); when(request.getRequestURI()).thenReturn("uri"); when(request.getSession(true)).thenReturn(session); when(twitter.getOAuthRequestToken(anyString())).thenReturn(new RequestToken("token", "secret")); }
/** * 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 String twitterLogin() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(BUNDLE.getString("twt.client_id")) .setOAuthConsumerSecret(BUNDLE.getString("twt.secret")) .setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token") .setOAuthAuthorizationURL(("https://api.twitter.com/oauth/authorize")) .setOAuthAccessTokenURL(("https://api.twitter.com/oauth/access_token")); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); request.getSession().setAttribute("twitter", twitter); try { RequestToken requestToken = twitter.getOAuthRequestToken(BUNDLE.getString("twt.redirect_uri")); request.getSession().setAttribute("requestToken", requestToken); LOGGER.info("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL()); try { response.sendRedirect(requestToken.getAuthenticationURL()); } catch (IOException e) { e.printStackTrace(); } } catch (TwitterException e) { e.printStackTrace(); } return ""; }
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; } }
private void askOAuth() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(Const.CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(Const.CONSUMER_SECRET); Configuration configuration = configurationBuilder.build(); twitter = new TwitterFactory(configuration).getInstance(); try { requestToken = twitter.getOAuthRequestToken(Const.CALLBACK_URL); // Intent dialogIntent = new Intent(Intent.ACTION_VIEW, // Uri.parse(requestToken.getAuthenticationURL())); // oActivity.startActivity(dialogIntent); // oActivity.startActivityForResult(dialogIntent,0); Intent intent = ActivityHelper.createActivityIntent(oActivity, TwitterAuthActivity.class); intent.putExtra("auth_twitter_url", requestToken.getAuthenticationURL()); // oActivity.startActivity(intent); oActivity.startActivityForResult(intent, 0); Log.v( this.getClass().getCanonicalName(), "askOAuth-> After:" + requestToken.getAuthenticationURL()); } 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); }
private void loginToTwitter() { boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false); if (!isLoggedIn) { final ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(consumerKey); builder.setOAuthConsumerSecret(consumerSecret); final Configuration configuration = builder.build(); final TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); try { requestToken = twitter.getOAuthRequestToken(callbackUrl); /** * Loading twitter login page on webview for authorization Once authorized, results are * received at onActivityResult */ final Intent intent = new Intent(this, WebViewActivity.class); intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL()); startActivityForResult(intent, WEBVIEW_REQUEST_CODE); } catch (TwitterException e) { e.printStackTrace(); } } else { Intent intent = new Intent(MainActivity.this, MenuActivity.class); startActivity(intent); } }
/** * 初期化する * * @return 成功したか */ public boolean OAuthRequest() { try { request = twitter.getOAuthRequestToken(); } catch (Exception e) { e.printStackTrace(); } return true; }
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); }
private void loginNewUser() { try { Log.i(this.getClass().getCanonicalName(), "Request App Authentication"); mReqToken = oTwitter.getOAuthRequestToken(Const.CALLBACK_URL); Log.i(this.getClass().getCanonicalName(), "Starting Webview to login to twitter"); oWeb.loadUrl(mReqToken.getAuthenticationURL()); oWeb.setWebViewClient( new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { // do your handling codes here, which url is the requested url // probably you need to open that url rather than redirect: view.loadUrl(url); Log.i(this.getClass().getCanonicalName(), "Webview url: " + url); Uri uri = Uri.parse(url); if (uri != null && uri.toString() .startsWith(Const.CALLBACK_URL)) { // If the user has just logged in String oauthVerifier = uri.getQueryParameter("oauth_verifier"); authoriseNewUser(oauthVerifier); try { ActivityHelper.startOriginalActivityAndFinish(TwitterAuthActivity.this); } catch (NullPointerException e) { // ActivityHelper.startOriginalActivityAndFinish(getParent()); Intent intentMain = ActivityHelper.createActivityIntent( TwitterAuthActivity.this, MainTrainerActivity.class); // startActivity(intent); ActivityHelper.startNewActivityAndFinish(TwitterAuthActivity.this, intentMain); // Log.e(this.getClass().getCanonicalName(),"Error back"); } } return false; // then it is not handled by default action } }); } catch (TwitterException e) { try { Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_LONG).show(); ActivityHelper.startOriginalActivityAndFinish(this); } catch (NullPointerException e1) { // ActivityHelper.startOriginalActivityAndFinish(getParent()); Intent intentMain = ActivityHelper.createActivityIntent(this, MainTrainerActivity.class); // startActivity(intent); ActivityHelper.startNewActivityAndFinish(this, intentMain); // Log.e(this.getClass().getCanonicalName(),"Error back"); } catch (RuntimeException e2) { Log.e(this.getClass().getCanonicalName(), "Runtime error twitter"); } } }
/** Constructs an instance. */ public TwitterTools() { ourConsumerKey = "z5zRan2VqwBMLdq5VMRzXA"; ourConsumerSecret = "T7whmI8IBtcHUEBNsWoQhu39f68loybHOmSYl8DMDg"; myTwitter = TwitterFactory.getSingleton(); myTwitter.setOAuthConsumer(ourConsumerKey, ourConsumerSecret); try { myRequestToken = myTwitter.getOAuthRequestToken(); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private RequestToken getRequestToken(String dummyUrl) { try { // Get a request token. This triggers network access. RequestToken token; if (TextUtils.isEmpty(dummyUrl)) { token = twitter.getOAuthRequestToken(); } else { token = twitter.getOAuthRequestToken(dummyUrl); } if (isDebugEnabled()) { Log.d(TAG, "Got a request token."); } return token; } catch (TwitterException e) { // Failed to get a request token. e.printStackTrace(); Log.e(TAG, "Failed to get a request token.", e); // No request token. return null; } }
public void askOAuth(Context context) { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(TwitterPrivateKeyAndSecret.CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(TwitterPrivateKeyAndSecret.CONSUMER_SECRET); Configuration configuration = configurationBuilder.build(); twitter = new TwitterFactory(configuration).getInstance(); try { requestToken = twitter.getOAuthRequestToken(TwitterConsts.CALLBACK_URL); context.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } catch (TwitterException e) { e.printStackTrace(); } }
/** Function to login twitter */ private void loginToTwitter() { // Check if already logged in if (!isTwitterLoggedInAlready()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); try { requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); this.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); String status = txtUpdate.getText().toString(); // Check for blank text if (status.trim().length() > 0) { // update status new updateTwitterStatus().execute(status); } else { // EditText is empty Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT) .show(); } } catch (TwitterException e) { e.printStackTrace(); } } else { // user already logged into twitter /*Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();*/ String status = txtUpdate.getText().toString(); // Check for blank text if (status.trim().length() > 0) { // update status new updateTwitterStatus().execute(status); } else { // EditText is empty Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT) .show(); } } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.twitter_add); accountdb = new AccountDB(this); twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); try { rqToken = twitter.getOAuthRequestToken(CALLBACK_URL.toString()); } catch (TwitterException e) { e.printStackTrace(); } token = rqToken.getToken(); stoken = rqToken.getTokenSecret(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(rqToken.getAuthorizationURL()))); }
private void askOAuth() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(Const.CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(Const.CONSUMER_SECRET); Configuration configuration = configurationBuilder.build(); twitter = new TwitterFactory(configuration).getInstance(); try { requestToken = twitter.getOAuthRequestToken(Const.CALLBACK_URL); // System.out.println(requestToken.toString()); Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show(); this.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } 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); }
/** * Gets a request token * * <p>If we decided that we need to do OAuth again to sign in, we get a request token from Twitter * via this call. */ private static void requestToken(Context context) { Log.d(TAG, "Requesting token"); isLoggedIn = false; try { /** * We say that we don't have an access token and then ask for a request token. We also tell * Twitter to redirect us to the callback url when the user finishes signing in via the * browser. Twitter gives us the request token and a url to redirect the user to for them to * sign in. This is all part of the OAuth process. */ twitter.setOAuthAccessToken(null); requestToken = twitter.getOAuthRequestToken(CALLBACK_URL); context.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } catch (TwitterException e) { e.printStackTrace(); } }
/** * Verifica se o programa já tem acesso a conta do usuario, caso negativo redireciona para pagina, * que gera uma autorização. * * @throws TwitterException * @throws IllegalStateException */ @RequestMapping(value = "/verificaAcessoTwitter") public String verificaAcessoTwitter(ModelMap modelMap) throws IllegalStateException, TwitterException { Usuario usuarioAutorizado = usuarioService.getUsuarioByLogin( SecurityContextHolder.getContext().getAuthentication().getName()); Twitter twitter = null; RequestToken requestToken = null; if (usuarioAutorizado.getAutorizacaoTwitter() != null) { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer( "bVqAzGbuR5jsOTDstph9XB1dM", "vi9xVqIc1oMQAydQYIVgbo0GvO4XWwPjdhtJpjAUk6yv19vdDO"); AccessToken accessToken = new AccessToken( usuarioAutorizado.getAutorizacaoTwitter().getToken(), usuarioAutorizado.getAutorizacaoTwitter().getTokenSecret()); twitter.setOAuthAccessToken(accessToken); cadastroIdTwitterAmigos1E2Grau(usuarioAutorizado, twitter); return "redirect:/usuario/listar"; } try { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer( "bVqAzGbuR5jsOTDstph9XB1dM", "vi9xVqIc1oMQAydQYIVgbo0GvO4XWwPjdhtJpjAUk6yv19vdDO"); requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } // AccessToken accessToken = null; String url = requestToken.getAuthorizationURL(); // System.out.println(twitter.getId()); AutorizacaoTwitterRequest autorizacaoTwitterRequest = new AutorizacaoTwitterRequest(); autorizacaoTwitterRequest.setRequestToken(requestToken); autorizacaoTwitterRequest.setTwitter(twitter); autorizacaoTwitterRequestService.save(autorizacaoTwitterRequest); modelMap.addAttribute("url", url); modelMap.addAttribute("id", autorizacaoTwitterRequest.getId()); modelMap.addAttribute("pin", new Pin()); return "usuario/autorizacaoTwitter"; }
@Override public void requestToken() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); Configuration configuration = configurationBuilder .setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET) .build(); TwitterFactory twitterFactory = new TwitterFactory(configuration); twitter = twitterFactory.getInstance(); // TODO: try { requestToken = twitter.getOAuthRequestToken(CALLBACK_URL); } catch (TwitterException e) { e.printStackTrace(); } }
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); }
private TwitterInfo requestToken(Twitter twitter, HttpSession session) { RequestToken requestToken; try { session.setAttribute("token", null); session.setAttribute("tokenSecret", null); requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { Logger.getLogger(TwitterInfo.class.getName()).severe(e.getMessage()); return null; } session.setAttribute("requestToken", requestToken); Object a = requestToken.getAuthenticationURL(); TwitterInfo result = new TwitterInfo(); result.setLoginURL(requestToken.getAuthorizationURL()); return result; }
@Override public Response performLogin(AuthenticationRequest request) { try { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(getConfig().getClientId(), getConfig().getClientSecret()); URI uri = new URI(request.getRedirectUri() + "?state=" + request.getState()); RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString()); ClientSessionModel clientSession = request.getClientSession(); clientSession.setNote("twitter_token", requestToken.getToken()); clientSession.setNote("twitter_tokenSecret", requestToken.getTokenSecret()); URI authenticationUrl = URI.create(requestToken.getAuthenticationURL()); return Response.temporaryRedirect(authenticationUrl).build(); } catch (Exception e) { throw new IdentityBrokerException("Could send authentication request to twitter.", e); } }
/** Function to login twitter */ private void loginToTwitter() { Log.d(TAG, "loginToTwitter!"); // Check if already logged in if (!isTwitterLoggedInAlready()) { Log.d(TAG, "no already logged!"); // Check is we already have tokens boolean already_have_tokens = already_have_twitter_tokens(); if (already_have_tokens == true) { Log.d(TAG, "Already have twitter tokens -> Log in!"); Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivityForResult(i, REQUEST_CODE_TWITTER_LOGIN); } else { Log.d(TAG, "Starting twitter external auth!"); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); try { requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); this.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } catch (TwitterException e) { e.printStackTrace(); } } } else { // user already logged into twitter Log.d(TAG, "Already Logged into twitter"); Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivityForResult(i, REQUEST_CODE_TWITTER_LOGIN); } }
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; }
/** Function to login twitter */ private void loginToTwitter() { // Check if already logged in if (!isTwitterLoggedInAlready()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); try { requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); this.startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } catch (TwitterException e) { e.printStackTrace(); } } else { // user already logged into twitter Toast toast = Toast.makeText(MainActivity.this, "Already Logged into twitter", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }
@Override public void authenticate() { if (httpServletRequest == null) { throw new IllegalStateException("http request not available"); } if (httpServletResponse == null) { throw new IllegalStateException("http response not available"); } if (configuration == null) { throw new IllegalStateException("configuration not available"); } HttpSession session = httpServletRequest.getSession(); ServletContext servletContext = httpServletRequest.getServletContext(); String clientID = configuration.getClientID(); String clientSecret = configuration.getClientSecret(); String returnURL = configuration.getReturnURL(); Principal principal = null; Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(clientID, clientSecret); // See if we are a callback String verifier = httpServletRequest.getParameter("oauth_verifier"); RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); if (verifier != null && requestToken == null) { // Let us fall back String twitterSentRequestToken = httpServletRequest.getParameter("oauth_token"); if (twitterSentRequestToken != null) { requestToken = (RequestToken) servletContext.getAttribute(twitterSentRequestToken); } if (requestToken == null) { throw new IllegalStateException("Verifier present but request token null"); } // Discard the stored request tokens servletContext.removeAttribute(twitterSentRequestToken); session.removeAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); } if (requestToken != null && verifier != null) { try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); session.setAttribute("accessToken", accessToken); session.removeAttribute("requestToken"); } catch (TwitterException e) { throw new AuthenticationException("Twitter Login:"******"Twitter Login:"******"Twitter Login:", e); } if (principal != null) { setStatus(AuthenticationStatus.SUCCESS); setAccount(new User(principal.getName())); } }
Autorizacion() throws IOException, TwitterException { // Constructor de la clase ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder .setDebugEnabled(true) .setOAuthConsumerKey(new Tokens().OAuthConsumerKey) .setOAuthConsumerSecret(new Tokens().OAuthConsumerSecret); Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance(); RequestToken requestToken = null; AccessToken accessToken = null; String url = null; do { try { requestToken = OAuthTwitter.getOAuthRequestToken(); System.out.println("Request Tokens obtenidos con éxito."); /*System.out.println("Request Token: " + requestToken.getToken()); System.out.println("Request Token secret: " + requestToken.getTokenSecret());*/ url = requestToken.getAuthorizationURL(); } catch (TwitterException ex) { Logger.getLogger(twittApp_java.class.getName()).log(Level.SEVERE, null, ex); } BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in)); // Abro el navegador. Runtime runtime = Runtime.getRuntime(); try { runtime.exec("firefox " + url); } catch (Exception e) { } // Nos avisa de que introduciremos el PIN a continuación System.out.print("Introduce el PIN del navegador y pulsa intro.\n\n PIN: "); // Leemos el PIN String pin = lectorTeclado.readLine(); if (pin.length() > 0) { accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = OAuthTwitter.getOAuthAccessToken(requestToken); } } while (accessToken == null); System.out.println("\n\nAccess Tokens obtenidos con éxito."); /*System.out.println("Access Token: " + accessToken.getToken()); System.out.println("Access Token secret: " + accessToken.getTokenSecret());*/ FileOutputStream fileOS = null; File file; String content = accessToken.getToken() + "\n" + accessToken.getTokenSecret(); try { file = new File(System.getProperty("user.home") + "/auth_file.txt".replace("\\", "/")); fileOS = new FileOutputStream(file); // Si el archivo no existe, se crea if (!file.exists()) { file.createNewFile(); } // Se obtiene el contenido en Bytes byte[] contentInBytes = content.getBytes(); fileOS.write(contentInBytes); fileOS.flush(); fileOS.close(); System.out.println("Escritura realizada con éxito."); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileOS != null) { fileOS.close(); } } catch (IOException e) { e.printStackTrace(); } twittApp_java cliente = new twittApp_java(); } }
@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 RequestToken getRequestToken() throws TwitterException { requestToken = twitter.getOAuthRequestToken(Constants.CALLBACK_URL); return requestToken; }