List of usage examples for twitter4j TwitterFactory TwitterFactory
public TwitterFactory()
From source file:AwsConsoleApp.java
License:Open Source License
public static void searchTweets(String searchString) throws Exception { Twitter twitter = new TwitterFactory().getInstance(); QueryResult result;/*w w w . j a v a 2 s . c o m*/ Query query = new Query(searchString); query.setRpp(100); for (int i = 1; i < 16; i++) { System.out.println("CURRENT PAGE: " + i); query.setPage(i); result = twitter.search(query); for (Tweet tweet : result.getTweets()) { System.out.println(tweet.getFromUser() + ":" + tweet.getText()); } } }
From source file:Pencarian.java
private void btSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSearchActionPerformed // TODO add your handling code here: txtSearchTimeline.setText(""); TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();//w ww . j a v a 2 s .com Query query = new Query(txSearch.getText()); QueryResult result = null; try { result = twitter.search(query); result.getTweets().stream().forEach((status) -> { txtSearchTimeline.append("@" + status.getUser().getScreenName() + ":" + status.getText() + " - " + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n"); }); } catch (TwitterException ex) { Logger.getLogger(Pencarian.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, "Failed !! " + ex.getMessage()); } }
From source file:Demo.java
/** * Main method.// w ww . ja va 2s . c o m * * @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:CreateFriendship.java
License:Apache License
/** * Usage: java twitter4j.examples.friendship.CreateFriendship [screen name] * * @param args message/*from w w w .ja v a 2s . c o m*/ */ public void Follow(ArrayList<String> args) { try { for (String values : args) { Twitter twitter = new TwitterFactory().getInstance(); twitter.createFriendship(values); } } catch (TwitterException te) { System.out.println("Failed to follow: "); } }
From source file:TwitterPull.java
private void init() { this.twitterFactory = new TwitterFactory(); this.twitter = this.twitterFactory.getInstance(); this.twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); this.twitter.setOAuthAccessToken(new AccessToken(DEFAULT_ACCESS_TOKEN, DEFAULT_ACCESS_TOKEN_SECRET)); }
From source file:GetTweetsAndSaveToFile.java
License:Apache License
/** * Usage: java twitter4j.examples.user.ShowUser [screen name] * * @param args message// w ww . j a v a 2s .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/* w w w. j ava2 s . c om*/ */ 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:SearchTweets.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param args//from w ww . jav a2 s . c om */ public static void main(String[] args) { if (args.length < 1) { System.out.println("java twitter4j.examples.search.SearchTweets [query]"); System.exit(-1); } Twitter twitter = new TwitterFactory().getInstance(); try { Query query = new Query(args[0]); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }
From source file:SendDirectMessage.java
License:Apache License
/** * Usage: java twitter4j.examples.directMessage.DirectMessage [recipient screen name] [message] * * @param args String[]//from w ww.j a va 2 s .co m */ public static void main(String[] args) { if (args.length < 2) { System.out.println( "Usage: java twitter4j.examples.directmessage.SendDirectMessage [recipient screen name] [message]"); System.exit(-1); } Twitter twitter = new TwitterFactory().getInstance(); try { DirectMessage message = twitter.sendDirectMessage(args[0], args[1]); System.out.println("Direct message successfully sent to " + message.getRecipientScreenName()); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to send a direct message: " + te.getMessage()); System.exit(-1); } }
From source file:MyUpdateTweetTimeToDB.java
public void GetTweetTime() { Twitter twitter = new TwitterFactory().getInstance(); String CONSUMER_KEY = "4enxNevEGWMqBuKzcJoQ"; String CONSUMER_SECRET = "UUDCNSvkFoZRaRUV4b8eHBcgR2N1LSrHXX7IELxdIk"; String TWITTER_TOKEN = "470084145-qwjAlIxq7GFB1I62TO5ebyoO10tXgUuZJfgTLu7G"; String TWITTER_TOKEN_SECRET = "9y47ww1xk0Nc5DhL9ZW0HOC6Qoig2wP101tOjsERnqNNv"; twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); AccessToken accesstoken = new AccessToken(TWITTER_TOKEN, TWITTER_TOKEN_SECRET); twitter.setOAuthAccessToken(accesstoken); Iterator iterator = tweet_id_to_time.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry pair = (Map.Entry) iterator.next(); try {/*from ww w . j a v a 2 s. c o m*/ Status status = twitter.showStatus((long) pair.getKey()); if (status == null) { System.out.println("Doesnot exist twitter with tweet id : " + pair.getKey()); } else { tweet_id_to_time.put((Long) pair.getKey(), status.getCreatedAt().getTime()); } } catch (TwitterException e) { tweet_id_to_time.put((Long) pair.getKey(), 1L); e.printStackTrace(); } System.out.println("Id : " + pair.getKey() + "value " + pair.getValue()); } }