List of usage examples for twitter4j TwitterFactory TwitterFactory
public TwitterFactory()
From source file:TimeLine.java
private void btTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTwitActionPerformed // Tombol update status, show setelah update txtStatus.setText(""); TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();//from w w w .j a v a2 s. c om try { Status status = twitter.updateStatus(txStatus.getText()); JOptionPane.showMessageDialog(rootPane, "Twit \n [ " + status.getText() + " ]\nTerkirim!"); } catch (TwitterException ex) { JOptionPane.showMessageDialog(rootPane, "Tidak bisa mengirim : " + ex.getMessage()); Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex); } List<Status> statuses = null; try { statuses = twitter.getUserTimeline(); statuses.stream().forEach((status) -> { txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - " + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n"); }); txStatus.setText(""); //reload field } catch (TwitterException te) { JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage()); } }
From source file:TimeLine.java
private void btTimelineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTimelineActionPerformed // TODO add your handling code here: txtTimeline.setText(""); TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();//from w w w .ja v a2 s. c o m List<Status> statuses = null; try { statuses = twitter.getHomeTimeline(); statuses.stream().forEach((status) -> { txtTimeline.append(status.getUser().getName() + " : " + status.getText() + " - " + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n"); }); } catch (TwitterException ex) { Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + ex.getMessage()); } }
From source file:TimeLine.java
private void btReloadTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReloadTwitActionPerformed // Tombol reload twit saya txtStatus.setText(""); TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();//ww w . j av a 2s. c om List<Status> statuses = null; try { statuses = twitter.getUserTimeline(); statuses.stream().forEach((status) -> { txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - " + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n"); }); txStatus.setText(""); //reload field } catch (TwitterException te) { JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage()); } }
From source file:TwitterGateway.java
public void Tweet(String user, String paramStatusUpdate) throws TwitterException { Twitter twitter = new TwitterFactory().getInstance(); int userLength = user.length(); int maxTweet = 140 - (userLength + 2 + 9); // ditambah 2 untuk @ dan " ", ditambah 9 untuk waktu " HH:mm:ss"; String[] tampung = paramStatusUpdate.split(" ", 0); //misahin semua kata jadi array of kata StatusUpdate[] statusUpdate = new StatusUpdate[(paramStatusUpdate.length() / maxTweet) + 1]; //panjang status dibagi batas maksimal huruf yang diperbolehkan, ditambah 1 karena 130/140 = 0 String[] tampungStatusUpdate = new String[statusUpdate.length]; //bikin banyaknya array sepanjang tweet yang mau di tweet int increment = 0; int incTampung = 0; for (int i = 0; i < tampungStatusUpdate.length; i++) { tampungStatusUpdate[i] = "@" + user + " "; //setiap tweet harus dimasukin nama user yang dituju }/*w ww . ja v a 2 s. co m*/ while (increment < statusUpdate.length) { while (incTampung < tampung.length) { tampungStatusUpdate[increment] += tampung[incTampung]; //nambahin kata if (tampungStatusUpdate[increment].length() >= 131) { //melakukan cek apakah tweet sudah over 140 kata atau belom, 131 soalnya 140 dikurang 9 untuk waktu " HH:mm:ss"; tampungStatusUpdate[increment] = tampungStatusUpdate[increment].substring(0, tampungStatusUpdate[increment].length() - tampung[incTampung].length()); //ngebuang kata terakhir yang ditambahin tampungStatusUpdate[increment] += " " + dateFormat.format(date); System.out.println(tampungStatusUpdate[increment]); increment++; //tampungStatusUpdate[increment] += tampung[incTampung] + " "; //kata yang tadi dibuang dimasukin lagi ke tampungStatusUpdate index selanjutnya break; } else { tampungStatusUpdate[increment] += " "; //Jika belum 140 kata maka ditambahkan spasi } incTampung++; if (incTampung >= tampung.length) { tampungStatusUpdate[increment] += " " + dateFormat.format(date); System.out.println(tampungStatusUpdate[increment]); increment++; //kalo kata-kata sudah habis, keluarin dari statement } } } for (int i = 0; i < statusUpdate.length; i++) { statusUpdate[i] = new StatusUpdate(tampungStatusUpdate[i]); } try { for (int i = 0; i < statusUpdate.length; i++) { twitter.updateStatus(statusUpdate[i]); } } catch (TwitterException ex) { twitter.updateStatus("@" + user + " Maaf anda sudah penah melakukan pencarian ini sebelumnya. " + dateFormat.format(date)); System.out.println("Error : " + ex); } }
From source file:TwitterGateway.java
public void Tweet2(String user, String paramStatusUpdate) throws TwitterException { Twitter twitter = new TwitterFactory().getInstance(); int userLength = user.length(); int maxTweet = 140 - (userLength + 2); // ditambah 2 untuk @ dan " ", ditambah 9 untuk waktu " HH:mm:ss"; String[] tampung = paramStatusUpdate.split(" ", 0); //misahin semua kata jadi array of kata StatusUpdate[] statusUpdate = new StatusUpdate[(paramStatusUpdate.length() / maxTweet) + 1]; //panjang status dibagi batas maksimal huruf yang diperbolehkan, ditambah 1 karena 130/140 = 0 String[] tampungStatusUpdate = new String[statusUpdate.length]; //bikin banyaknya array sepanjang tweet yang mau di tweet int increment = 0; int incTampung = 0; for (int i = 0; i < tampungStatusUpdate.length; i++) { tampungStatusUpdate[i] = "@" + user + " "; //setiap tweet harus dimasukin nama user yang dituju }/*w ww . ja v a 2 s.c o m*/ while (increment < statusUpdate.length) { while (incTampung < tampung.length) { tampungStatusUpdate[increment] += tampung[incTampung]; //nambahin kata if (tampungStatusUpdate[increment].length() >= 140) { //melakukan cek apakah tweet sudah over 140 kata atau belom, 131 soalnya 140 dikurang 9 untuk waktu " HH:mm:ss"; tampungStatusUpdate[increment] = tampungStatusUpdate[increment].substring(0, tampungStatusUpdate[increment].length() - tampung[incTampung].length()); //ngebuang kata terakhir yang ditambahin System.out.println(tampungStatusUpdate[increment]); increment++; //tampungStatusUpdate[increment] += tampung[incTampung] + " "; //kata yang tadi dibuang dimasukin lagi ke tampungStatusUpdate index selanjutnya break; } else { tampungStatusUpdate[increment] += " "; //Jika belum 140 kata maka ditambahkan spasi } incTampung++; if (incTampung >= tampung.length) { System.out.println(tampungStatusUpdate[increment]); increment++; //kalo kata-kata sudah habis, keluarin dari statement } } } for (int i = 0; i < statusUpdate.length; i++) { statusUpdate[i] = new StatusUpdate(tampungStatusUpdate[i]); } try { for (int i = 0; i < statusUpdate.length; i++) { twitter.updateStatus(statusUpdate[i]); } } catch (TwitterException ex) { twitter.updateStatus("@" + user + " Maaf anda sudah penah melakukan pencarian ini sebelumnya. "); System.out.println("Error : " + ex); } }
From source file:RandomPicBot.java
License:Open Source License
public static void main(String[] args) { /*/*from ww w . j a va 2 s .c om*/ * initialize the yaml setup * reads from keys.yml in the classpath, or same directory as the program */ Yaml yaml = new Yaml(); InputStream fileInput = null; try { fileInput = new FileInputStream(new File("keys.yml")); } catch (FileNotFoundException e1) { System.out.println("keys.yml not found!"); e1.printStackTrace(); System.exit(0); } @SuppressWarnings("unchecked") //unchecked cast, who cares. Map<String, String> map = (Map<String, String>) yaml.load(fileInput); /* * extracts values from the map */ String CONSUMER_KEY = map.get("CONSUMER_KEY"); String CONSUMER_SECRET = map.get("CONSUMER_SECRET"); String TOKEN = map.get("TOKEN"); String TOKEN_SECRET = map.get("TOKEN_SECRET"); long USER_ID = Long.parseLong(map.get("USER_ID")); /* * initialize Twitter using the keys we got from the yaml file */ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); twitter.setOAuthAccessToken(new AccessToken(TOKEN, TOKEN_SECRET, USER_ID)); /* * set up our picture folder * gets the folder from the command line argument * may change this to yaml too in the future */ File directory = new File(args[0]); File[] pictures = directory.listFiles(new FileFilter() { /* * check to make sure the file is under 3mb(with some wiggle room) and is an acceptable image(non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ public boolean accept(File pathname) { if (pathname.isFile() && pathname.length() < 3000000 && isImage(pathname)) { return true; } else return false; } }); System.out.println(pictures.length + " usable files found."); Random rand = new Random(); /* * convert our minute value into milliseconds since thats what Thread.sleep() uses */ int WAIT_TIME = Integer.parseInt(args[1]) * 60 * 1000; String statusText = ""; if (args[2] != null) { for (int i = 2; i < args.length; i++) { statusText += args[i] + " "; } statusText.trim(); } if (statusText.length() > 117) { System.out.println("Your message is too long!"); System.out.println("Only messages up to 117 characters are supported!"); System.exit(5); } StatusUpdate status = new StatusUpdate(statusText); /* * main loop * generate a random number to choose our image with * then upload the image to twitter * then wait for the defined time(gotten from the command line in minutes) */ while (true) { int index = rand.nextInt(pictures.length); status.setMedia(pictures[index]); try { System.out.print("uploading picture: " + pictures[index].getName()); if (!statusText.equals("")) System.out.println(" with text: " + statusText); else System.out.println(); twitter.updateStatus(status); } catch (TwitterException e) { System.out.println("Problem uploading the file!"); e.printStackTrace(); } try { Thread.sleep(WAIT_TIME); } catch (InterruptedException e) { System.out.println("Program was interrupted!"); e.printStackTrace(); } } }
From source file:MapDemo.java
public static void main(String[] args) throws TwitterException, IOException, Exception { TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();//from ww w .j a v a 2 s . com boolean flag = true; // Ask the user for a search string. String searchStr = "ParkandGoUNL"; // 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.getText() + status.getCreatedAt()); }); if (flag) { GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y"); List<Marker> markers = new ArrayList<>(); Marker e = new Marker(GeocodingApi.geocode(context, "616 North 16th Street, Lincoln, Nebraska, USA") .await()[0].geometry.location, "marker1", "KKG", new Date()); markers.add(e); StreetExtractor se = new StreetExtractor(); List<Address> address = se.find("Park and Go 601 North 16th Street"); address.forEach(((Address a) -> { try { Marker m = new Marker( GeocodingApi.geocode(context, a.getAddress()).await()[0].geometry.location, "marker0", "A Tweet", new Date()); markers.add(m); } catch (Exception ex) { Logger.getLogger(MapDemo.class.getName()).log(Level.SEVERE, null, ex); } })); Map map = new Map(markers); map.create(); } }
From source file:TweetMapManager.java
public static void main(String[] args) { TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();//from ww w.j a va 2 s. c om String searchStr = "#ParkandGoUNL"; Query query = new Query(searchStr); GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y"); List<Marker> markers = new LinkedList<>(); StreetExtractor se = new StreetExtractor(); LocalTime now = LocalTime.now(); while (true) { DayOfWeek today = LocalDate.now().getDayOfWeek(); if (today.getValue() < WEEKEND) { if (now.isAfter(STARTTIME) && now.isBefore(ENDTIME)) { // Send API request to execute a search with the given query. QueryResult results = null; try { results = twitter.search(query); } catch (TwitterException ex) { LOGGER.warn(ex.getMessage()); } // Display search results. if (results != null) { results.getTweets().stream().forEach((Status status) -> { try { Date created = status.getCreatedAt(); String text = status.getText(); LOGGER.info(status.getText()); LatLng location; if (status.getGeoLocation() != null) { location = new LatLng(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()); } else { String modified = text.replace("#ParkAndGoUNL", ""); List<Address> address = se.find(modified); location = GeocodingApi.geocode(context, address.get(0).getAddress()) .await()[0].geometry.location; } String id = UUID.randomUUID().toString().substring(0, 8); Marker m = new Marker(location, "m" + id, text, created); markers.add(m); } catch (Exception ex) { LOGGER.warn(ex.getMessage()); } }); } if (!markers.isEmpty()) { Marker m = markers.get(markers.size() - 1); if (m.getTimestamp().getTime() < Time.valueOf(now.minusMinutes(30)).getTime()) { DailyLogs.addMarkerToLog(m, today); markers.remove(m); } } Map map = new Map(markers); map.create(); } else { //wait 5 hours try { LOGGER.info("Sleeping 5 hours"); Thread.sleep((long) 1.8e+7); } catch (InterruptedException ex) { LOGGER.warn(ex.getMessage()); } } now = LocalTime.now(); } else { try { //Wait a day LOGGER.info("Sleeping 1 day"); Thread.sleep((long) 8.64e+7); } catch (InterruptedException ex) { LOGGER.warn(ex.getMessage()); } } try { LOGGER.info("Successful Loop, Resting"); Thread.sleep(1000); } catch (InterruptedException ex) { LOGGER.warn(ex.getMessage()); } } }
From source file:twitterGateway_v2_06.java
License:Creative Commons License
public void GetRequestToken() { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(TwitterConsumerKey, TwitterConsumerSecret); try {/*from w w w . jav a 2 s .com*/ requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException ex) { println(ex); } println("Open the following URL and grant access to your account:"); println(requestToken.getAuthorizationURL()); link(requestToken.getAuthorizationURL()); }
From source file:DumpRetrievedTweet.java
private void GetTweetData() throws TwitterException, IOException { System.out.println("Seting up twitter"); Twitter twitter = new TwitterFactory().getInstance(); // String CONSUMER_KEY = "9zVRlQTXlTKf4QeYMiucyXqg9"; // String CONSUMER_SECRET = "xH0H2SfcXj914z1DGB7HgZZ012ntSqRbfnLFw5A6v1TB94Y2O1"; // String TWITTER_TOKEN = "753222147695259648-QnzInB98PtwpFb75dqlP1J7SSOQMcMX"; // String TWITTER_TOKEN_SECRET = "uxJHGE1e2kFBJYoNRRFfy5gBLXYaRrzCUycRncSkoLsle"; // String CONSUMER_KEY = "nNV9KxWFVmdI0a2shhJImcEGk"; // String CONSUMER_SECRET = "I4AvaGOZRFtLFTqAkpKrfFOnV13Ej2seiwnNQ47z0qE9ORoBhW"; // String TWITTER_TOKEN = "753222147695259648-kY3Gq1O6FqHw6LQViuTQAhLbEQLZRZX"; // String TWITTER_TOKEN_SECRET = "a6hsmYipeGvqJcrIUUZah4ZhH7B8wbY77hqNWwojQysiO"; // String CONSUMER_KEY = "PBMKK9P2YD9MFgDfdANQt2Zzc"; // String CONSUMER_SECRET = "ldB0FybCQIjfYLzuYE4CeGtvcevaSkFxPENGbFd19Yn2crXa5R"; // String TWITTER_TOKEN = "753222147695259648-ZWqj3CvdQAXeVl9zfa71BCRcxeD2yAi"; // String TWITTER_TOKEN_SECRET = "1bypYSL1D1t1Gt6nQLwEbyRg5rniOUHfJhTYuVWYWvAvP"; // String CONSUMER_KEY = "tf0Cbp3ZQcJh9vwkQ9vInw6WS"; // String CONSUMER_SECRET = "gRmcjuqrSH40K47CkRFEO5OVthUtExEW7xrZU2oWiRcpPmzRz9"; // String TWITTER_TOKEN = "126239739-qaXgO4urp91PXLT2RgkxlyONwAQyXnq236dhqtTe"; // String TWITTER_TOKEN_SECRET = "AIykIeAKGFHRucTPgNYZd9bqdbZEJQhMsF5cGiyBLUII7"; String CONSUMER_KEY = "EmmSsTEML5XrB3SYBUOOKxqn6"; String CONSUMER_SECRET = "J1TrjmcqhBd1cURBTjUCwNqcf5IxCfdInAs74TVT9axvSwLnlJ"; String TWITTER_TOKEN = "126239739-ktoaE8NhM4S9CjFhrktTdpuvY7fkbqj1nYxfaQsD"; String TWITTER_TOKEN_SECRET = "a5fFQbKO9meoqnY31wwlZF0nqDHtqfxlwUla1uaAT8Y0p"; twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); AccessToken accesstoken = new AccessToken(TWITTER_TOKEN, TWITTER_TOKEN_SECRET); twitter.setOAuthAccessToken(accesstoken); writer.write("\n"); for (int i = 0; i < tweet_ids.size(); i++) { Long tweet_id = tweet_ids.get(i); System.out.println("[" + i + "] Getting Tweet id " + tweet_id); Status status = twitter.showStatus((long) tweet_ids.get(i)); if (status == null) { System.out.println("[FAILED] Doesnot exist twitter with tweet id : " + tweet_id); } else {/*from w w w. ja va 2 s .com*/ System.out.println("status asli : " + status.getText()); writer.write(tweet_id + "\t" + status.getText().replaceAll("\n", " ")); writer.write("\n"); updateIsLabelledAnotator3(tweet_id); } } }