List of usage examples for twitter4j.auth RequestToken getAuthorizationURL
public String getAuthorizationURL()
From source file:generatetwittertokens.GenerateTwitterTokens.java
License:Open Source License
public static void main(String[] args) { String username = ""; ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(consumerKey); configurationBuilder.setOAuthConsumerSecret(consumerSecret); try {/*from ww w. j a v a 2 s. c om*/ Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance(); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); while (accessToken == null) { System.out.println("PhantomBot Twitter API Connection Tool\r\n\r\n" + "This tool will request access to read and write to your Twitter account.\r\n" + "You will be presented with a URL to open in your local browser to approve\r\n" + "access, however, this application will attempt to launch a browser for\r\n" + "you automatically.\r\n\r\n" + "You will be presented with a PIN that you must provide back to this\r\n" + "application. After that is completed, Twitter will generate OAuth keys\r\n" + "which will be stored in the PhantomBot directory as twitter.txt.\r\n\r\n" + "Do keep this file safe! The keys are the same as a password to your Twitter\r\n" + "account!\r\n\r\n" + "You may regenerate the OAuth keys at any time if needed.\r\n"); System.out.println("Open the following URL in your browser if a browser does not automatically\r\n" + "launch within a few seconds:"); System.out.println(" " + requestToken.getAuthorizationURL() + "\r\n"); /* * Attempt to launch a local browser. Ignore exceptions, except if the URL is bad. */ try { Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); } catch (UnsupportedOperationException ignore) { } catch (IOException ignore) { } catch (URISyntaxException e) { throw new AssertionError(e); } /* * Request the username from the user. */ username = ""; while (username.length() < 1) { System.out.print("Provide your Twitter username: "); try { username = bufferedReader.readLine(); } catch (IOException ex) { username = ""; System.out.println("Failed to read input. Please try again."); } } /* * Request the PIN from the user. */ String pin = ""; while (pin.length() < 1) { System.out.print("Enter the PIN provided by Twitter: "); try { pin = bufferedReader.readLine(); accessToken = twitter.getOAuthAccessToken(requestToken, pin); } catch (TwitterException ex) { if (ex.getStatusCode() == 401) { pin = ""; System.out.println("Twitter failed to provide access tokens. Please try again."); } else { System.out.println("Twitter returned an error:\r\n" + ex.getMessage()); System.exit(1); } } catch (IOException ex) { pin = ""; System.out.println("Failed to read input. Please try again."); } } } System.out.println("Twitter has provided PhantomBot with OAuth Access Tokens."); String twitterData = ""; try { twitterData = "# Twitter Configuration File\r\n" + "# Generated by PhantomBot GenerateTwitterTokens\r\n" + "# If new tokens are required, run the application again.\r\n" + "#\r\n" + "# PROTECT THIS FILE AS IF IT HAD YOUR TWITTER PASSWORD IN IT!\r\n" + "twitter_username=" + username + "\r\n" + "twitter_access_token=" + accessToken.getToken() + "\r\n" + "twitter_secret_token=" + accessToken.getTokenSecret() + "\r\n"; Files.write(Paths.get("./twitter.txt"), twitterData.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); System.out.println("Data has been successfully stored in twitter.txt."); } catch (IOException ex) { System.out.println("Unable to create twitter.txt.\r\nPlease create with the following content:\r\n" + twitterData); System.exit(1); } } catch (TwitterException ex) { System.out.println("Twitter returned an error:\r\n" + ex.getMessage()); System.exit(1); } }
From source file:hashimotonet.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * /*from ww w . j a v a2s.c o m*/ * @param args * message */ public static void main(String[] args) { /* try { new UpdateStatus().connectTwitter(); } catch(Exception e) { e.printStackTrace(); } */ if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); System.exit(-1); } String message = ""; for (int i = 0; i < args.length; i++) { message += args[i] + " "; } try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is // already available RequestToken requestToken = twitter.getOAuthRequestToken(); // RequestToken requestToken = new RequestToken(Globals.KEY,Globals.SECRET); String url = requestToken.getAuthenticationURL(); System.out.println("url = " + url); 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(message); 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); } }
From source file:hashimotonet.UpdateStatus.java
License:Apache License
/** * Twitter?// ww w. j a va 2 s .com * @throws TwitterException */ private void connectTwitter() throws TwitterException { // Twitetr4j?? Configuration conf = ConfigurationContext.getInstance(); // OauthF?IuWFNg?? OAuthAuthorization Oauth = new OAuthAuthorization(conf); // OauthF?IuWFNgconsumerKeyconsumerSecret? Oauth.setOAuthConsumer(Globals.KEY, Globals.SECRET); // // NGXgg?[N?? RequestToken sRequestToken = null; try { sRequestToken = Oauth.getOAuthRequestToken(); } catch (TwitterException e) { throw new TwitterException(e.toString()); } String url = sRequestToken.getAuthorizationURL(); System.out.println("Url = " + url); }
From source file:info.maslowis.twitterripper.twitter.OAuthTwitter.java
License:Open Source License
/** * Displays authorization URL and gets PIN for connection to twitter under authorized user *///from w w w. java2 s . c om public void authorization() throws IOException { try { Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerKeySecret); RequestToken requestToken = twitter.getOAuthRequestToken(); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Authorization URL:").reset()); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.CYAN).a(requestToken.getAuthorizationURL())); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.RED).a("Enter PIN please:").reset()); String pin = reader.readLine(); twitter.getOAuthAccessToken(requestToken, pin); } catch (TwitterException e) { logger.error("Authorization fail! Please try to run application again and enter PIN."); exit(1); } }
From source file:it.greenvulcano.gvesb.social.twitter.TwitterSocialAdapterAccount.java
License:Open Source License
/** * Returns the Request token and URL to be used to confirm the token. * // w ww . j a v a 2 s .c om */ @Override public Tokens getRequestTokenAndURL() throws SocialAdapterException { Tokens tokens = new Tokens(); RequestToken requestToken; try { requestToken = this.getProxyObject().getOAuthRequestToken(); this.requestToken = requestToken; } catch (TwitterException e) { logger.error("Call to Social Adapter Account: " + accountName + " failed.", e); throw new SocialAdapterException("Call to Social Adapter Account: " + accountName + " failed.", e); } tokens.setRequestToken(requestToken.getToken()); tokens.setAuthorizationURL(requestToken.getAuthorizationURL()); return tokens; }
From source file:jimmysharp.kanaclogger.presenter.SettingsFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); subscription = new CompositeSubscription(); addPreferencesFromResource(R.xml.preference); twitter = new TwitterManager(this.getActivity()); onSharedPreferenceChanged(null, "hashtag_text"); onSharedPreferenceChanged(null, "twitter_authentication"); Preference twitterAuthPref = (Preference) findPreference("twitter_authentication"); twitterAuthPref.setOnPreferenceClickListener(preference1 -> { subscription.add(twitter.getAccessTokenUrl().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleSubscriber<RequestToken>() { @Override// w ww. ja v a2 s. co m public void onSuccess(RequestToken token) { requestToken = token; Log.v(TAG, "Move to browser for Twitter authentication"); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(token.getAuthorizationURL())); startActivity(intent); } @Override public void onError(Throwable error) { Toast.makeText(getActivity(), getString(R.string.msg_twitter_oauth_url_failed), Toast.LENGTH_LONG).show(); Log.e(TAG, "Failed to get Twitter oauth URL", error); } })); return true; }); Preference licensePref = (Preference) findPreference("license"); licensePref.setOnPreferenceClickListener(preference -> { final LicenseDialog licenseDialog = new LicenseDialog(); licenseDialog.setTargetFragment(this, 100); licenseDialog.show(getChildFragmentManager(), LICENSE_DIALOG_TAG); return true; }); }
From source file:jp.ky.twittersample.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message/*from w w w. j av a 2s . c o m*/ */ public static void main(String[] args) { // if (args.length < 1) { // System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); // System.exit(-1); // } String message = "Test5"; 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(message); //System.out.println("Successfully updated the status to [" + status.getText() + "]."); AccountSettings as = twitter.getAccountSettings(); System.out.println("accountsettings:" + as.getScreenName()); 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); } }
From source file:jp.wda.azeda.core.logics.impl.TwitterServiceImpl.java
License:Apache License
/** {@inheritDoc} */ @Override/*w ww.j av a2s . c o m*/ public CheckAuthorizedResult checkAuthorized(String account, String callbackURL) throws TwitterException { CheckAuthorizedResult result = new CheckAuthorizedResult(); StoredAccessToken at = accessTokensDao.getAccessToken(account); if (at != null) { return result; } Twitter twitter = new TwitterFactory().getInstance(); String requestID = UUID.randomUUID().toString(); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL + requestID); requestTokens.put(requestID, requestToken); result.status = -1; result.redirectTo = requestToken.getAuthorizationURL(); return result; }
From source file:jp.xxxxxxxx.l3fish.twnyaan.service.AuthenticationService.java
License:Open Source License
/** * RequestToken????URL???????PIN???/*from ww w .j a v a2s . c o m*/ * RequestToken??????{@code null}? * * @return ???RequestToken??????????{@code null} */ public RequestToken authorize() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(TwitterAPIKey.getConsumerKey()) .setOAuthConsumerSecret(TwitterAPIKey.getConsumerSecret()); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); RequestToken requestToken = null; try { requestToken = twitter.getOAuthRequestToken(); URI authorizationURI = new URI(requestToken.getAuthorizationURL()); Desktop desktop = Desktop.getDesktop(); desktop.browse(authorizationURI); } catch (URISyntaxException | IOException e) { System.err.println(ErrorCode.CANNOT_OPEN_AUTHORIZATION_URI); } catch (TwitterException e) { System.err.println(ErrorCode.TWITTER_SERVICE_UNAVAILABLE); } return requestToken; }
From source file:me.chester.myretweetedtweets.User.java
License:Apache License
public void setupForAuthorization() throws TwitterException { RequestToken requestToken = twitter.getOAuthRequestToken(); token = requestToken.getToken();//from w w w. jav a 2 s . co m tokenSecret = requestToken.getTokenSecret(); authorizationURL = requestToken.getAuthorizationURL(); }