List of usage examples for twitter4j Twitter getOAuthRequestToken
RequestToken getOAuthRequestToken() throws TwitterException;
From source file:Demo.java
/** * Main method.//from www.j ava 2s . com * * @param args * @throws TwitterException */ public static void main(String[] args) throws TwitterException, IOException { // The TwitterFactory object provides an instance of a Twitter object // via the getInstance() method. The Twitter object is the API consumer. // It has the methods for interacting with the Twitter API. TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance(); boolean keepItGoinFullSteam = true; do { // Main menu Scanner input = new Scanner(System.in); System.out.print("\n--------------------" + "\nH. Home Timeline\nS. Search\nT. Tweet" + "\n--------------------" + "\nA. Get Access Token\nQ. Quit" + "\n--------------------\n> "); String choice = input.nextLine(); try { // Home Timeline if (choice.equalsIgnoreCase("H")) { // Display the user's screen name. User user = twitter.verifyCredentials(); System.out.println("\n@" + user.getScreenName() + "'s timeline:"); // Display recent tweets from the Home Timeline. for (Status status : twitter.getHomeTimeline()) { System.out.println("\n@" + status.getUser().getScreenName() + ": " + status.getText()); } } // Search else if (choice.equalsIgnoreCase("S")) { // Ask the user for a search string. System.out.print("\nSearch: "); String searchStr = input.nextLine(); // Create a Query object. Query query = new Query(searchStr); // Send API request to execute a search with the given query. QueryResult result = twitter.search(query); // Display search results. result.getTweets().stream().forEach((Status status) -> { System.out.println("\n@" + status.getUser().getName() + ": " + status.getText()); }); } // Tweet else if (choice.equalsIgnoreCase("T")) { boolean isOkayLength = true; String tweet; do { // Ask the user for a tweet. System.out.print("\nTweet: "); tweet = input.nextLine(); // Ensure the tweet length is okay. if (tweet.length() > 140) { System.out.println("Too long! Keep it under 140."); isOkayLength = false; } } while (isOkayLength == false); // Send API request to create a new tweet. Status status = twitter.updateStatus(tweet); System.out.println("Just tweeted: \"" + status.getText() + "\""); } // Get Access Token else if (choice.equalsIgnoreCase("A")) { // First, we ask Twitter for a request token. RequestToken reqToken = twitter.getOAuthRequestToken(); System.out.println("\nRequest token: " + reqToken.getToken() + "\nRequest token secret: " + reqToken.getTokenSecret()); AccessToken accessToken = null; while (accessToken == null) { // The authorization URL sends the request token to Twitter in order // to request an access token. At this point, Twitter asks the user // to authorize the request. If the user authorizes, then Twitter // provides a PIN. System.out .print("\nOpen this URL in a browser: " + "\n " + reqToken.getAuthorizationURL() + "\n" + "\nAuthorize the app, then enter the PIN here: "); String pin = input.nextLine(); try { // We use the provided PIN to get the access token. The access // token allows this app to access the user's account without // knowing his/her password. accessToken = twitter.getOAuthAccessToken(reqToken, pin); } catch (TwitterException te) { System.out.println(te.getMessage()); } } System.out.println("\nAccess token: " + accessToken.getToken() + "\nAccess token secret: " + accessToken.getTokenSecret() + "\nSuccess!"); } // Quit else if (choice.equalsIgnoreCase("Q")) { keepItGoinFullSteam = false; GeoApiContext context = new GeoApiContext() .setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y"); System.out.println(GeocodingApi.geocode(context, "Sigma Phi Epsilon, Lincoln, Nebraska, USA") .await()[0].geometry.location.toString()); System.out.println(GeocodingApi.geocode(context, "16th and R, Lincoln, Nebraska, USA") .await()[0].geometry.location.toString()); File htmlFile = new File("map.html"); Desktop.getDesktop().browse(htmlFile.toURI()); } // Bad choice else { System.out.println("Invalid option."); } } catch (IllegalStateException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { System.out.println(ex.getMessage()); } } while (keepItGoinFullSteam == true); }
From source file:GetTweetsAndSaveToFile.java
License:Apache License
/** * Usage: java twitter4j.examples.user.ShowUser [screen name] * * @param args message/*w ww. j a v a2 s . c o m*/ * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("men2JyLEaAsxcbfmgzOAwUnTp", "2AGN0ie9TfCDJyWeH8qhTLtMhqRvRlNBtQU3lAP2M8k3Xk1KWl"); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Authorization URL: \n" + requestToken.getAuthorizationURL()); AccessToken accessToken = new AccessToken("2811255124-zigkuv8MwDQbr5s9HdjLRSbg8aCOyxeD2gYGMfH", "D7jFABWHQa8QkTWwgYj1ISUbWP8twdfbzNgYkXI3jwySR"); twitter.setOAuthAccessToken(accessToken); /* 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()); User user = twitter.showUser(args[0]); if (user.getStatus() != null) { System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText()); } else { // the user is protected System.out.println("@" + user.getScreenName()); } FileWriter file = new FileWriter("./" + user.getScreenName() + "_Tweets.txt"); List<Status> list = twitter.getHomeTimeline(); for (Status each : list) { file.write("Sent by: @" + each.getUser().getScreenName() + " - " + each.getUser().getName() + "---" + each.getText() + "\n"); } file.close(); System.exit(0); } catch (Exception te) { te.printStackTrace(); System.exit(-1); } }
From source file:GetAccessToken.java
License:Apache License
/** * Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret] * * @param args message//from w w w . ja va 2 s . c o m */ public void getToken() throws TwitterException, IOException { File file = new File("twitter4j.properties"); Properties prop = new Properties(); InputStream is = null; OutputStream os = null; MainActivity m = new MainActivity(); Twitter twitter = new TwitterFactory().getInstance(); try { try { if (file.exists()) { is = new FileInputStream(file); prop.load(is); } if (true) { if (null == prop.getProperty("oauth.consumerKey") && null == prop.getProperty("oauth.consumerSecret")) { // consumer key/secret are not set in twitter4j.properties System.out.println( "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]"); // System.exit(-1); } } } catch (IOException ioe) { ioe.printStackTrace(); //System.exit(-1); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (os != null) { try { os.close(); } catch (IOException ignore) { } } } try { 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()); try { Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL())); } catch (UnsupportedOperationException ignore) { } catch (IOException ignore) { } catch (URISyntaxException e) { throw new AssertionError(e); } 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 { System.out.println("fdfgghd"); te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); try { prop.setProperty("oauth.accessToken", accessToken.getToken()); prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret()); os = new FileOutputStream(file); prop.store(os, "twitter4j.properties"); os.close(); } catch (IOException ioe) { ioe.printStackTrace(); // System.exit(-1); } finally { if (os != null) { try { os.close(); } catch (IOException ignore) { } } } System.out.println("Successfully stored access token to " + file.getAbsolutePath() + "."); m.setTwitter(twitter); m.setVisible(true); //System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get accessToken: " + te.getMessage()); //System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); // System.exit(-1); } } catch (java.lang.IllegalStateException jli) { System.out.println("Already registered"); m.setTwitter(twitter); m.setVisible(true); } }
From source file:Register.java
License:Open Source License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message/*from ww w . j a va 2 s . com*/ */ public static void main(String[] args) { try { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("wIb1qVNc0CNXQJxduYIXw") .setOAuthConsumerSecret("vTES3U9862wYaxFRdMyD1LRatkq2R42mDyOjXLHIdk"); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); AccessToken accessToken = null; try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); 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("Access granted to Twitter."); 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); } } twitter.updateStatus("Minecraft server successfully registered at " + (new Date()).toString()); System.out.println("Successfully connected to Twitter."); // Write the properties file PrintWriter pw = new PrintWriter(new FileWriter("../TwitterEvents.properties")); pw.println("accessToken=" + accessToken.getToken()); pw.println("accessTokenSecret=" + accessToken.getTokenSecret()); pw.close(); System.out.println("Your TwitterEvents.properties file has been created with your access tokens."); System.out.println("Start Minecraft server to load the remaining default values."); System.out.println("Then reload TwitterEvents if you make any changes."); System.exit(0); } catch (TwitterException te) { System.out.println("Failed to get timeline: " + te.getMessage()); System.out .println("Try revoking access to the hModEvents application from your Twitter settings page."); System.exit(-1); } catch (IOException ioe) { System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:NewJFrame.java
private void TweetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TweetButtonActionPerformed String message = TweetArea.getText(); Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(API_KEY, API_SECRET); try {/*www . ja va 2 s. com*/ RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { String pin = br.readLine(); if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } storeAccessToken(twitter.verifyCredentials().getId(), accessToken); } catch (TwitterException | IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ac.simons.tweetarchive.Application.java
License:Apache License
static void createTwitterOauthTokens(final String consumerKey, final String consumerSecret) throws Exception { final Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerSecret); final RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from w ww. j a v a2s. c o m*/ final 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 { throw te; } } } final Properties properties = new Properties(); properties.put("twitter4j.oauth.consumerKey", consumerKey); properties.put("twitter4j.oauth.consumerSecret", consumerSecret); properties.put("twitter4j.oauth.accessToken", accessToken.getToken()); properties.put("twitter4j.oauth.accessTokenSecret", accessToken.getTokenSecret()); try (final FileOutputStream out = new FileOutputStream("application.properties", true)) { properties.store(out, null); } }
From source file:be.ugent.tiwi.sleroux.newsrec.twittertest.GrantAccess.java
public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer("tQjT8XvB7OPNTl8qdhchDo3J2", "FXWVS3OEW7omiUDSLpET0aRInoUumGPWRxOVyk7GrhiwcfLBnV"); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//from w ww .j a v a 2 s . c o m 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(); } } } storeAccessToken(twitter.verifyCredentials().getId(), accessToken); }
From source file:br.shura.team.mpsbot.runtime.ConnectedBot.java
License:Open Source License
public void prepare(Function<URL, String> pinEvaluator) throws IllegalStateException, MalformedURLException, TwitterException { ApiKeys keys = getBot().getApiKeys(); if (!isPrepared()) { Twitter handler = TwitterFactory.getSingleton(); handler.setOAuthConsumer(keys.getConsumerKey(), keys.getConsumerSecret()); RequestToken requestToken = handler.getOAuthRequestToken(); URL url = new URL(requestToken.getAuthorizationURL()); while (accessToken == null) { String pin = pinEvaluator.apply(url); try { if (pin != null && !pin.isEmpty()) { this.accessToken = handler.getOAuthAccessToken(requestToken, pin); this.handler = handler; } else { return; }// www.j av a2 s. com } catch (TwitterException exception) { System.err.println("Could not evaluate OAuth access token:"); System.err.println(exception); } } } getHandler().verifyCredentials(); }
From source file:cojoytuerto.TAuth.java
public TAuth() throws IOException, TwitterException { //Constructor de la clase File file = new File("auth_file.txt"); if (!file.exists()) { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.setDebugEnabled(true).setOAuthConsumerKey("wCWSOW8xHlxfQq24kSxXuXNm9") .setOAuthConsumerSecret("5B1R4bxZv7TcO7Vmq3NvhM3Bo3YcO0qCIJP2vDD9HnOaPL63YD"); configBuilder.setHttpProxyHost("127.0.0.1"); configBuilder.setUseSSL(true);/* ww w. j a va 2s .com*/ configBuilder.setHttpProxyPort(3128); 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 Token obtenido con xito."); System.out.println("Request Token: " + requestToken.getToken()); System.out.println("Request Token secret: " + requestToken.getTokenSecret()); url = requestToken.getAuthorizationURL(); url = url.replace("http://", "https://"); System.out.println("URL:"); System.out.println(url); } catch (TwitterException ex) { Logger.getLogger(TAuth.class.getName()).log(Level.SEVERE, null, ex); } BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in)); //Abro el navegador. Firefox, en este caso. Runtime runtime = Runtime.getRuntime(); try { runtime.exec("firefox " + url); } catch (Exception e) { } //Nos avisa de que introduciremos el PIN a continuacin System.out.print("Introduce el PIN del navegador y pulsa intro.nn PIN: "); //Leemos el PIN // String pin = lectorTeclado.readLine(); String pin = JOptionPane.showInputDialog(null, "Introduce el PIN del navegador y pulsa intro.nn PIN: "); if (pin.length() > 0) { accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = OAuthTwitter.getOAuthAccessToken(requestToken); } } while (accessToken == null); System.out.println("nnAccess 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("auth_file.txt"); 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(); } } } }
From source file:ColourUs.OAuth.java
private void reauthorize() throws Exception { // In case we lose the A_SECRET Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(C_KEY, C_SECRET); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from w ww.j a va2 s . com*/ 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(); } } } show((int) twitter.verifyCredentials().getId(), accessToken); }