List of usage examples for twitter4j Twitter setOAuthAccessToken
void setOAuthAccessToken(AccessToken accessToken);
From source file:org.yukung.following2ldr.command.impl.FindFeedUrlCommand.java
License:Apache License
@Override public void run() throws Throwable { // Twitter??/* ww w .j ava 2 s. c o m*/ long start = System.currentTimeMillis(); String consumerKey = config.getProperty(Constants.CONSUMER_KEY); String consumerSecret = config.getProperty(Constants.CONSUMER_SECRET); String userName = params.get(0); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken = twitter.getOAuthRequestToken(); String authorizationURL = requestToken.getAuthorizationURL(); System.out.println(":" + authorizationURL); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter the PIN:"); String pin = br.readLine(); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin); twitter.setOAuthAccessToken(accessToken); long cursor = -1L; IDs friendIDs; List<Long> iDsList = new ArrayList<Long>(5000); do { friendIDs = twitter.getFriendsIDs(userName, cursor); long[] iDs = friendIDs.getIDs(); for (long iD : iDs) { iDsList.add(iD); } cursor = friendIDs.getNextCursor(); } while (friendIDs.hasNext()); List<long[]> list = new ArrayList<long[]>(); int offset = 0; long[] tmp = new long[100]; for (Long id : iDsList) { if (offset < 100) { tmp[offset] = id; offset++; } else { list.add(tmp); offset = 0; tmp = new long[100]; } } list.add(tmp); List<URL> urlList = new ArrayList<URL>(); for (long[] array : list) { ResponseList<User> lookupUsers = twitter.lookupUsers(array); for (User user : lookupUsers) { log.info("URL:" + user.getURL()); urlList.add(user.getURL()); } } String path = "C:\\Users\\ikeda_yusuke\\Documents\\sandbox\\java\\data\\" + userName + ".txt"; FileWriter writer = new FileWriter(path); BufferedWriter out = new BufferedWriter(writer); // PrintWriter pw = new PrintWriter(writer); for (URL url : urlList) { if (url != null) { out.write(url.toString() + "\n"); } } out.flush(); out.close(); long end = System.currentTimeMillis(); log.info("?:" + (end - start) + " ms"); // ??IDor?? // Twitter API??????ID? // ?????ID?URL100??? // ??URL? }
From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java
License:Open Source License
public static ArrayList<Item> getFluxFromSearch(String search, String sourceUri) { ArrayList<Item> result = new ArrayList<Item>(); try {// w w w. ja va 2s . c o m Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"), Config.getVar("Twitter-OAuth-customerKey")); twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"), Config.getVar("Twitter-OAuth-accessKey"))); Query query = new Query(search); QueryResult items = twitter.search(query); for (Status r : items.getTweets()) { result.add(TwitterApi.getItemFromStatus(r, sourceUri)); } return result; } catch (TwitterException ex) { Logger.getLogger(TwitterApi.class.getName()).log(Level.WARNING, null, ex); return result; } }
From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java
License:Open Source License
public static ArrayList<Item> getFluxFromUser(String user, String sourceUri) { ArrayList<Item> result = new ArrayList<Item>(); try {/* w ww . j a va2 s. com*/ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"), Config.getVar("Twitter-OAuth-customerKey")); twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"), Config.getVar("Twitter-OAuth-accessKey"))); List<Status> statusess = twitter.getUserTimeline(user); for (Status r : statusess) { result.add(TwitterApi.getItemFromStatus(r, sourceUri)); } return result; } catch (TwitterException ex) { logger.warn(ex.getErrorMessage()); return result; } }
From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java
License:Open Source License
public static ArrayList<Item> getFluxFromTimeline(String sourceUri) { ArrayList<Item> result = new ArrayList<Item>(); AccessToken userToken = TwitterApi.getAccessToken(sourceUri); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"), Config.getVar("Twitter-OAuth-customerKey")); twitter.setOAuthAccessToken(userToken); ResponseList<Status> status;//from w w w .j a v a 2s . com try { status = twitter.getHomeTimeline(); for (Status r : status) { result.add(TwitterApi.getItemFromStatus(r, sourceUri)); } } catch (Exception ex) { logger.info(ex); } return result; }
From source file:ru.ideast.SocialServices.OAuthHelp.java
License:Apache License
/** * Depricated method has been used// w w w . ja v a2s. co m * * @param twitter */ public void configureOAuth(Twitter twitter) { try { twitter.setOAuthConsumer(consumerKey, consumerSecretKey); twitter.setOAuthAccessToken(accessToken); } catch (IllegalStateException e) { } }
From source file:se.aceone.housenews.UpdateStatus.java
License:Apache License
private static void handleAccessToken(Twitter twitter) throws IOException, FileNotFoundException, ClassNotFoundException, TwitterException, URISyntaxException { AccessToken accessToken = null;/*from ww w . j a v a 2 s .c o m*/ File settingsDir = new File(System.getenv("HOMEPATH"), ".housenews"); File accessTokenFile = new File(settingsDir, "accessToken"); if (settingsDir.isDirectory() && accessTokenFile.isFile()) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(accessTokenFile)); accessToken = (AccessToken) ois.readObject(); ois.close(); } else { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Open the following URL and grant access to your account:"); 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()); String authorizationURL = requestToken.getAuthorizationURL(); System.out.println(authorizationURL); java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) { System.err.println("Desktop doesn't support the browse action (fatal)"); System.exit(1); } URI uri = new URI(authorizationURL); desktop.browse(uri); System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } if (!settingsDir.isDirectory()) { settingsDir.mkdirs(); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(accessTokenFile)); oos.writeObject(accessToken); oos.close(); } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); twitter.setOAuthAccessToken(accessToken); }
From source file:servlet.TwitterClient.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . j a v a 2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { String consumerKey = "acdi5Tpjda5dshPSgsNdc2YuP"; String consumerSecret = "5mZuFFShjXdwTCbk1hRZ9c47BJz9vKwoPFDPDHyG9xdxLGdZRi"; String accessToken = "224428346-hU7uwq12mUSvxT7jClIEnpCN5Lj6Rp1YgnQiwG6h"; String accessTokenSecret = "8kPqai6ciArmiWinkBOGvxHfYbif2OL7N96NbQYvEHfiH"; Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); AccessToken accessTok = new AccessToken(accessToken, accessTokenSecret); twitter.setOAuthAccessToken(accessTok); String action = (request.getParameter("action") != null) ? request.getParameter("action") : "fresh"; if (action.equalsIgnoreCase("Send")) { String latestStatus = request.getParameter("newTweet"); Status status = twitter.updateStatus(latestStatus); } //cargamos todos los tweets ResponseList<Status> a = twitter.getUserTimeline(new Paging(1, 20)); request.setAttribute("Tweets", a); //mandamos los tweets en una lista a la vista request.getRequestDispatcher("twitter.jsp").forward(request, response); }
From source file:tokyo.ryogo.dropkick.sns.twitter.DKTwitter.java
License:Apache License
public static Twitter getTwitterInstance(Context context) { String consumerKey = TwitterSecret.getTwitterConsumerKey(context.getString(R.string.cryption)); String consumerSecret = TwitterSecret.getTwitterConsumerKeySecret(context.getString(R.string.cryption)); TwitterFactory factory = new TwitterFactory(); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); if (hasAccessToken(context)) { twitter.setOAuthAccessToken(loadAccessToken(context)); }/* ww w . j a va2s .c om*/ return twitter; }
From source file:twitterapidemo.TwitterAPIDemo.java
License:Apache License
public static void main(String[] args) throws IOException, TwitterException { //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(consumerKey); builder.setOAuthConsumerSecret(consumerSecret); Configuration configuration = builder.build(); TwitterFactory twitterFactory = new TwitterFactory(configuration); Twitter twitter = twitterFactory.getInstance(); twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); Scanner sc = new Scanner(System.in); System.out.println(//ww w . j a v a 2 s . c om "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic"); int choice = sc.nextInt(); switch (choice) { case 1: System.out.println("What's happening: "); String post = sc.next(); StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI"); Status status = twitter.updateStatus(statusUpdate); System.out.println("status.toString() = " + status.toString()); System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName()); System.out.println("status.getSource() = " + status.getSource()); System.out.println("status.getText() = " + status.getText()); System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors())); System.out.println("status.getCreatedAt() = " + status.getCreatedAt()); System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId()); System.out.println("status.getGeoLocation() = " + status.getGeoLocation()); System.out.println("status.getId() = " + status.getId()); System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId()); System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId()); System.out.println("status.getPlace() = " + status.getPlace()); System.out.println("status.getRetweetCount() = " + status.getRetweetCount()); System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus()); System.out.println("status.getUser() = " + status.getUser()); System.out.println("status.getAccessLevel() = " + status.getAccessLevel()); System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities())); System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities())); if (status.getRateLimitStatus() != null) { System.out.println( "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit()); System.out.println("status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining()); System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = " + status.getRateLimitStatus().getResetTimeInSeconds()); System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = " + status.getRateLimitStatus().getSecondsUntilReset()); } System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println( "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); break; case 2: System.out.println("Enter keyword"); String keyword = sc.next(); try { Query query = new Query(keyword); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); break; } case 3: //WOEID for India = 23424848 Trends trends = twitter.getPlaceTrends(23424848); int count = 0; for (Trend trend : trends.getTrends()) { if (count < 3) { Query query = new Query(trend.getName()); QueryResult result; int numberofpost = 0; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { numberofpost++; } } while ((query = result.nextQuery()) != null); System.out .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost); count++; } else break; } break; default: System.out.println("Invalid input"); } }
From source file:twitterbot.example.tweet.RetweetMethods.java
static public void RetweetTweet(String id) { try {/* w w w .j a v a 2 s .c o m*/ String consumerKey = ""; // key obtained after registering app. String consumerSecret = ""; // secret key obtained from the registered app. String twitterToken = ""; // access_token received by authentication user's twitter account String twitterSecret = ""; // access_secret obtained by authentication user's twitter account String tweetId = id; //messageId of the tweet to be retweeted Twitter factory = new TwitterFactory().getInstance(); Twitter twitter = factory; twitter.setOAuthConsumer(consumerKey, consumerSecret); AccessToken accessToken = new AccessToken(twitterToken, twitterSecret); twitter.setOAuthAccessToken(accessToken); twitter.retweetStatus(Long.valueOf(tweetId)); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); } }