List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder
ConfigurationBuilder
From source file:stream.PrintUserStream.java
License:Apache License
public static void main(String[] args) throws TwitterException { ConfigurationBuilder confbuilder = new ConfigurationBuilder(); confbuilder.setOAuthAccessToken(TWITTER_ACCESS_TOKEN).setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET) .setOAuthConsumerKey(TWITTER_CONSUMER_KEY).setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); confbuilder.setJSONStoreEnabled(true); TwitterStream twitterStream = new TwitterStreamFactory(confbuilder.build()).getInstance(); // TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); // user() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.user();/*from w w w. j a va 2 s . c o m*/ }
From source file:stream.Sample.java
License:Apache License
/** * @param args//from w ww. j a va 2 s . c om */ public static void main(String[] args) { // Check how many arguments were passed in if ((args == null) || (args.length == 0)) { System.err.println("Please provide output directory path"); System.exit(-1); } try { OutputDirPath = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } dataStoreManager(); StatusListener listener = new StatusListener() { public void onStatus(Status status) { // System.out.println(status.getUser().getName() + " : " + // status.getText()); String rawJSON = TwitterObjectFactory.getRawJSON(status); // System.out.println(rawJSON); writer.println(rawJSON); counter++; System.out.println(counter); if (counter >= 1000) { dataStoreManager(); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onException(Exception ex) { } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; // mozellecandi ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("****").setOAuthConsumerSecret("****") .setOAuthAccessToken("****").setOAuthAccessTokenSecret("****").setJSONStoreEnabled(true); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); twitterStream.addListener(listener); // sample() method internally creates a thread which manipulates // TwitterStream and calls these adequate listener methods continuously. twitterStream.sample(); }
From source file:streamflow.spout.twitter.TwitterSampleSpout.java
License:Apache License
@Override public void open(Map config, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; logger.info(/* www . j a v a2 s.c o m*/ "Twitter Sampler Started: Consumer Key = " + consumerKey + ", Consumer Secret = " + consumerSecret + ", Access Token = " + accessToken + ", Access Token Secret = " + accessTokenSecret); if (StringUtils.isNotBlank(consumerKey) && StringUtils.isNotBlank(consumerSecret) && StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(accessTokenSecret)) { // Build the twitter config to authenticate the requests ConfigurationBuilder twitterConfig = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret).setJSONStoreEnabled(true) .setIncludeEntitiesEnabled(true).setIncludeEntitiesEnabled(true); // Add the proxy settings to the Twitter config if they were specified if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { try { twitterConfig.setHttpProxyPort(proxyPort).setHttpProxyHost(proxyHost); } catch (Exception ex) { } } // Status listener which handle the status events and add them to the queue StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { queue.offer(status); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { logger.debug("Twitter Deletion Notice: " + statusDeletionNotice.getUserId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { logger.debug("Twitter On Track Limitation Notice: Number Of Limited Statuses" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { logger.debug("Twitter Scrub Geo: UserID = " + userId + ", UpToStatusId = " + upToStatusId); } @Override public void onException(Exception exception) { logger.debug("Twitter Exception: " + exception.getMessage()); } @Override public void onStallWarning(StallWarning stallWarning) { logger.debug("Twitter Stall Warning: " + stallWarning.toString()); } }; TwitterStreamFactory twitterFactory = new TwitterStreamFactory(twitterConfig.build()); twitterStream = twitterFactory.getInstance(); twitterStream.addListener(listener); twitterStream.sample(); logger.info("Twitter Sample Stream Initialized"); } else { logger.info("Twitter Sampler missing required OAuth properties. " + "Pleast check your settings and try again."); } }
From source file:StringMatching.GetTweet.java
/** * @param args the command line arguments *///w ww.j ava2 s . c om public static void main(String[] args) throws JSONException, IOException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH") .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK") .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA") .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC") .setHttpProxyHost("cache.itb.ac.id").setHttpProxyPort(8080).setHttpProxyUser("jonathan.benedict") .setHttpProxyPassword("rollingonthefloor"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); JSONObject obj = new JSONObject(); int counterTweet = 0; FileWriter file = new FileWriter("C:\\Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt"); file.flush(); try { Query query = new Query("barca".toLowerCase()); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { counterTweet++; System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); obj.put("user", tweet.getUser().getScreenName()); obj.put("tweets", tweet.getText()); //Tulis file ke dalam txt try { file.write(obj.toString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + obj); } catch (IOException e) { e.printStackTrace(); } } } while (counterTweet < 1000); file.close(); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } System.exit(0); }
From source file:study.bot.OAuth.java
License:Open Source License
public void authenicate() { cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY) .setOAuthConsumerSecret(Constants.TWITTER_SECRET_KEY) .setOAuthAccessToken(Constants.TWITTER_ACCESS_TOKEN) .setOAuthAccessTokenSecret(Constants.TWITTER_ACCESS_TOKEN_SECRET); }
From source file:summarizer.NewApplication.java
private void HashtagSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HashtagSearchButtonActionPerformed // TODO add your handling code here: ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("uEeExq1FHARMvAGTJAY0dGxPh") .setOAuthConsumerSecret("jMcofTKFsayd4bpA6HFNlgkMfiveoS3ffRSCy9FCSs9pWYqdAD") .setOAuthAccessToken("2443437752-PrbVsDrQCxthX3T7lV3dtHs3FCXFXfBBHsdNrOS") .setOAuthAccessTokenSecret("MbauBu7R6vUUKqFD9ogK7VTIfce4nmvewYsgYqBOQ2ZbC"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance();// ww w. j a v a 2s . c o m String hashtag; hashtag = HashtagTextField.getText(); Query query = new Query(hashtag); query.count(100); if (TwitterComboBox.getSelectedIndex() == 0) { query.resultType(Query.ResultType.mixed); } else if (TwitterComboBox.getSelectedIndex() == 0) { query.resultType(Query.ResultType.recent); } else { query.resultType(Query.ResultType.popular); } QueryResult result = null; try { result = twitter.search(query); } catch (TwitterException ex) { Logger.getLogger(NewApplication.class.getName()).log(Level.SEVERE, null, ex); } String alltweets = "", temp = ""; for (Status status : result.getTweets()) { temp = status.getText(); temp = temp.replaceAll("[\\t\\n\\r]", " "); if (!"".equals(temp)) { if ("RT".equals(temp.substring(0, 2))) { temp = temp.split(":", 2)[1]; } alltweets += (temp + "\n"); } } InputTextArea.setText(alltweets); }
From source file:t.twitter.TTwitterModule.java
License:Open Source License
@Kroll.method public void connect(HashMap args) { KrollDict arg = new KrollDict(args); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", "")) .setOAuthConsumerSecret(arg.optString("apisecret", "")) .setOAuthAccessToken(arg.optString("accesstoken", "")) .setOAuthAccessTokenSecret(arg.optString("accesssecret", "")); AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build()); twitter = tf.getInstance();/*ww w .j av a2 s . c o m*/ twitter.addListener(new TwitterAdapter() { @Override public void updatedStatus(Status status) { Log.d("Twitter", "text: " + status.getText()); } @Override public void searched(QueryResult result) { HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>(); List<Status> tweets = result.getTweets(); KrollDict[] dList = new KrollDict[tweets.size()]; // sort tweets Collections.sort(tweets, new Comparator<Status>() { public int compare(Status o1, Status o2) { if (desc) { if (o2.getId() < o1.getId()) { return 1; } else { return -1; } } else { if (o2.getId() > o1.getId()) { return 1; } else { return -1; } } } }); // return tweets to titanium int i = 0; for (Status tweet : tweets) { if (lastID == -1 || lastID < tweet.getId()) { KrollDict d = new KrollDict(); d.put("username", tweet.getUser().getScreenName()); d.put("userimage", tweet.getUser().getProfileImageURL()); d.put("text", tweet.getText()); d.put("date", tweet.getCreatedAt()); d.put("id", Long.toString(tweet.getId())); dList[i] = d; lastID = tweet.getId(); i++; } } KrollDict[] dList2 = new KrollDict[i]; // shorten array System.arraycopy(dList, 0, dList2, 0, i); event.put("tweets", dList2); success.call(getKrollObject(), event); synchronized (LOCK) { LOCK.notify(); } } @Override public void verifiedCredentials(User user) { HashMap<String, KrollDict> event = new HashMap<String, KrollDict>(); KrollDict d = new KrollDict(); d.put("user_name", user.getName()); d.put("screen_name", user.getScreenName()); d.put("image_path", user.getProfileImageURL()); event.put("user_info", d); success.call(getKrollObject(), event); synchronized (LOCK) { LOCK.notify(); } } @Override public void onException(TwitterException e, TwitterMethod method) { synchronized (LOCK) { LOCK.notify(); } Log.e("twitter", "error: " + e.getErrorMessage()); } }); Log.d("Twitter", "connected"); }
From source file:tfg.twitterservice.TwitterContextBuilder.java
public TwitterContextBuilder(UserTwitterTokens userTwitterTokens) { this.confBuilder = new ConfigurationBuilder(); this.confBuilder.setOAuthConsumerKey(consumerKey); this.confBuilder.setOAuthConsumerSecret(consumerSecret); this.confBuilder.setOAuthAccessToken(userTwitterTokens.getAccessToken()); this.confBuilder.setOAuthAccessTokenSecret(userTwitterTokens.getAccessTokenSecret()); }
From source file:the_vaps_project.The_vaps_project.java
public static void main(String[] args)/* throws TwitterException */ { // TODO code application logic here /*/* w w w.j a v a 2s . c om*/ List<Status> status = twitter.getHomeTimeline(); for(Status st : status){ System.out.println(st.getUser().getName()+"--------"+st.getText()); System.out.println(st.getCreatedAt()); }*/ // The factory instance is re-useable and thread safe. /*Twitter twitter2 = tf.getSingleton(); Query query = new Query("source:twitter4j yusukey"); QueryResult result = twitter.search(query); for (Status statuss : result.getTweets()) { System.out.println("@" + statuss.getUser().getName() + ":" + statuss.getText()); }*/ TwitterCriteria criteria = null; Tweet t = null; criteria = TwitterCriteria.create() .setMaxTweets(10).setUntil("2016-11-08").setQuerySearch("#NeverTrump"); /*Scribe s = new Scribe(); s.detruireFichier("tweets.xml"); s.ouvrir("tweets.xml"); s.ecrire("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); s.ecrire("<tweets>\n"); for (int i = 0; i < TweetManager.getTweets(criteria).size(); i++) { t = TweetManager.getTweets(criteria).get(i); s.ecrire("\t<tweet>\n"); s.ecrire("\t\t<text><![CDATA["+t.getText()+"]]></text>\n"); s.ecrire("\t\t<hashtags>"+t.getHashtags()+"</hashtags>\n"); s.ecrire("\t\t<date>"+t.getDate()+"</date>\n"); s.ecrire("\t\t<username>"+t.getUsername()+"</username>\n"); s.ecrire("\t\t<retweets>"+t.getRetweets()+"</retweets>\n"); s.ecrire("\t\t<favorites>"+t.getFavorites()+"</favorites>\n"); s.ecrire("\t\t<id>"+t.getId()+"</id>\n"); s.ecrire("\t\t<geo>"+t.getGeo()+"</geo>\n"); s.ecrire("\t\t<mentions>"+t.getMentions()+"</mentions>\n"); s.ecrire("\t\t<permalink>"+t.getPermalink()+"</permalink>\n"); s.ecrire("\t\t<smileys>"+t.getSmileys()+"</smileys>\n"); s.ecrire("\t\t<polarite>"+t.getPolarite()+"</polarite>\n"); s.ecrire("\t</tweet>\n"); corpus.ecrire(s.filtrerTexte(t.getText() + "\n")); } s.ecrire("</tweets>"); s.fermer();*/ /* SUPER SITE D'EXEMPLES https://github.com/yusuke/twitter4j/tree/master/twitter4j-examples/src/main/java/twitter4j/examples*/ /*PARTIE GRAPHE DES RETWEETS*/ Set<String> nameOfUsers = new HashSet<>(); for (int i = 0; i < TweetManager.getTweets(criteria).size(); i++) { t = TweetManager.getTweets(criteria).get(i); System.out.println(t.getUsername()); nameOfUsers.add(t.getUsername()); } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("gVaO166IGfSCun5Esj1sZ5bX3") .setOAuthConsumerSecret("KhN1L4pXCG5U6d6tee1IGUnIV1bqxieQJDxE2HOx3AGI5npQRE") .setOAuthAccessToken("822018210178469888-4Pr1KRE2rmFvof0O5IUdTlxtkGKamU4") .setOAuthAccessTokenSecret("D1thDl7k8v2s1SupU5ZGhK3U7Mphb69fpUW4JuDou5O65"); TwitterFactory tf = new TwitterFactory(cb.build()); twitter4j.Twitter twitter = tf.getInstance(); /*String[] screenNames = nameOfUsers.toArray(new String[0]); ResponseList<User> usersNames; long cursor = -1; IDs ids; try { usersNames = twitter.lookupUsers(screenNames); for(User u: usersNames){ System.out.println(u.getId()+" "+u.getName()+" "+u.getName()); ids = twitter.getFollowersIDs("username", cursor); twitter.getFollowers } } catch (TwitterException ex) { Exceptions.printStackTrace(ex); }*/ Set<DuoKey> utilisateurs = new HashSet<>(); Set<DuoKey> liens = new HashSet<>(); //User us; try { int nbpages = 0; long cursor = -1; PagableResponseList<User> listeFollowersTemp; ArrayList<User> listeFollowers = new ArrayList<User>(); for (String s : nameOfUsers) { if (!utilisateurs.contains(new DuoKey(s, "auteurTweet"))) { utilisateurs.add(new DuoKey(s, "auteurTweet")); //listeFollowersTemp = twitter.getFollowersList(s, -1); do { TimeUnit.MINUTES.sleep(1); listeFollowersTemp = twitter.getFollowersList(s, cursor); for (User u : listeFollowersTemp) { listeFollowers.add(u); } nbpages++; } while (((cursor = listeFollowersTemp.getNextCursor()) != 0) && nbpages <= 9); //4=100 followers par auteur de tweet recherch } System.out.println(s + ", mes followers sont :"); for (User u : listeFollowers) { utilisateurs.add(new DuoKey(u.getName(), "auteurTweet")); liens.add(new DuoKey(u.getName(), s)); System.out.println("\t" + u.getName()); } listeFollowers.clear(); nbpages = 0; } } catch (TwitterException | InterruptedException ex) { Exceptions.printStackTrace(ex); } Scribe sc = new Scribe(); sc.detruireFichier("graphFollowers.gexf"); sc.ouvrir("graphFollowers.gexf"); sc.ecrire("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); sc.ecrire( "<gexf xmlns=\"http://www.gexf.net/1.2draft/gexf.xsd\" version=\"1.2\" xmlns:viz=\"http://www.gexf.net/1.1draft/viz\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd\">\n"); sc.ecrire("\t<meta lastmodifieddate=\"2017-02-17\">\n"); sc.ecrire("\t\t<creator>Pirboss</creator>\n"); sc.ecrire("\t\t<description>Test v2</description>\n"); sc.ecrire("\t</meta>\n"); sc.ecrire("\t<graph defaultedgetype=\"directed\" mode=\"static\">\n"); sc.ecrire("\t\t<nodes>\n"); ArrayList<DuoKey> distinctListOfUsers = new ArrayList(utilisateurs); System.out.println(distinctListOfUsers.size()); for (int i = 0; i < distinctListOfUsers.size(); i++) { sc.ecrire("\t\t\t<node id=\"" + distinctListOfUsers.get(i).getX().replace("&", "&") + "\" label=\"" + distinctListOfUsers.get(i).getX().replace("&", "&") + "\"/>\n"); } sc.ecrire("\t\t</nodes>\n"); sc.ecrire("\t\t<edges>\n"); ArrayList<DuoKey> distinctListOfLinks = new ArrayList(liens); System.out.println(distinctListOfLinks.size()); for (int i = 0; i < liens.size(); i++) { sc.ecrire("\t\t\t<edge id=\"" + i + "\" source=\"" + distinctListOfLinks.get(i).getX().replace("&", "&") + "\" target=\"" + distinctListOfLinks.get(i).getY().replace("&", "&") + "\"/>\n"); } sc.ecrire("\t\t</edges>\n"); sc.ecrire("\t</graph>\n"); sc.ecrire("</gexf>"); sc.fermer(); PreviewJFrame p = new PreviewJFrame(); p.script(); /*PARTIE GRAPHE DES MENTIONS*/ //NE PAS OUBLIE LE COUP DE REMPLACER LES .replace("&", "&") POUR LE XML /*Set<String> users = new HashSet<>(); HashMap<DuoKey, Integer> map; map = new HashMap<DuoKey, Integer>(); DuoKey duokey; for (int i = 0; i < TweetManager.getTweets(criteria).size(); i++) { System.out.println(i); t = TweetManager.getTweets(criteria).get(i); users.add(t.getUsername()); if(!t.getMentions().isEmpty()){ for(String target : t.getMentions().split(" ")){ target = target.replaceFirst("@", ""); users.add(target); duokey = new DuoKey(t.getUsername(), target); if(map.get(duokey) != null){ map.put(duokey, map.get(duokey)+1); }else{ map.put(duokey, 1); } } } } Scribe s = new Scribe(); s.detruireFichier("tweets.gexf"); s.ouvrir("tweets.gexf"); s.ecrire("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); s.ecrire("<gexf xmlns=\"http://www.gexf.net/1.2draft/gexf.xsd\" version=\"1.2\" xmlns:viz=\"http://www.gexf.net/1.1draft/viz\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd\">\n"); s.ecrire("\t<meta lastmodifieddate=\"2017-02-17\">\n"); s.ecrire("\t\t<creator>Pirboss</creator>\n"); s.ecrire("\t\t<description>Test v1</description>\n"); s.ecrire("\t</meta>\n"); s.ecrire("\t<graph defaultedgetype=\"directed\" mode=\"static\">\n"); s.ecrire("\t\t<nodes>\n"); ArrayList distinctList = new ArrayList(users); for(int i=0; i<distinctList.size(); i++){ s.ecrire("\t\t\t<node id=\""+i+"\" label=\""+distinctList.get(i)+"\"/>\n"); } s.ecrire("\t\t</nodes>\n"); s.ecrire("\t\t<edges>\n"); Iterator ite = map.entrySet().iterator(); int jj=0; while (ite.hasNext()) { Map.Entry pair = (Map.Entry)ite.next(); s.ecrire("\t\t\t<edge id=\""+(jj++)+"\" source=\""+distinctList.indexOf(((DuoKey)pair.getKey()).getX())+"\" target=\""+distinctList.indexOf(((DuoKey)pair.getKey()).getY())+"\" weight=\""+pair.getValue()+"\"/>\n"); ite.remove(); // avoids a ConcurrentModificationException } s.ecrire("\t\t</edges>\n"); s.ecrire("\t</graph>\n"); s.ecrire("</gexf>"); s.fermer(); PreviewJFrame pr = new PreviewJFrame(); pr.script();*/ }
From source file:tientx.supercode.myproejectdemov3.connection.TwitterConnection.java
private TwitterConnection() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(TwitterConfig.API_KEY) .setOAuthConsumerSecret(TwitterConfig.API_SECRET).setOAuthAccessToken(TwitterConfig.ACCES_TOKEN) // .setOAuthAccessTokenSecret(TwitterConfig.ACCES_TOKEN_SECRET).setHttpConnectionTimeout(100000) .setOAuthAccessTokenSecret(TwitterConfig.ACCES_TOKEN_SECRET).setHttpConnectionTimeout(100000); // .setHttpProxyHost(TwitterConfig.PROXY_HOST) // .setHttpProxyPort(TwitterConfig.PROXY_PORT); TwitterFactory factory = new TwitterFactory(cb.build()); twitter = factory.getInstance();//ww w . j av a2 s. c om }