List of usage examples for twitter4j TwitterFactory getInstance
public Twitter getInstance()
From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java
License:Educational Community License
/** * {@inheritDoc}/*from w ww .j a va 2 s .c o m*/ */ public String getTwitterName(ExternalIntegrationInfo info) { if (info == null) { return null; } //get values String token = info.getTwitterToken(); String secret = info.getTwitterSecret(); if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(secret)) { //global config Map<String, String> config = getTwitterOAuthConsumerDetails(); //token for user AccessToken accessToken = new AccessToken(token, secret); //setup TwitterFactory factory = new TwitterFactory(); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(config.get("key"), config.get("secret")); twitter.setOAuthAccessToken(accessToken); //check try { return twitter.verifyCredentials().getScreenName(); } catch (TwitterException e) { log.error("Error retrieving Twitter credentials: " + e.getClass() + ": " + e.getMessage()); } } return null; }
From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java
License:Educational Community License
/** * {@inheritDoc}//from ww w. j a v a 2 s. c om */ public void sendMessageToTwitter(final String userUuid, String message) { //setup class thread to call later class TwitterUpdater implements Runnable { private Thread runner; private String userUuid; private String userToken; private String userSecret; private String message; public TwitterUpdater(String userUuid, String userToken, String userSecret, String message) { this.userUuid = userUuid; this.userToken = userToken; this.userSecret = userSecret; this.message = message; runner = new Thread(this, "Profile2 TwitterUpdater thread"); runner.start(); } //do it! public synchronized void run() { //global config Map<String, String> config = getTwitterOAuthConsumerDetails(); //token for user AccessToken accessToken = new AccessToken(userToken, userSecret); //setup TwitterFactory factory = new TwitterFactory(); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(config.get("key"), config.get("secret")); twitter.setOAuthAccessToken(accessToken); try { twitter.updateStatus(message); log.info("Twitter status updated for: " + userUuid); //post update event sakaiProxy.postEvent(ProfileConstants.EVENT_TWITTER_UPDATE, "/profile/" + userUuid, true); } catch (TwitterException e) { log.error( "ProfileLogic.sendMessageToTwitter() failed. " + e.getClass() + ": " + e.getMessage()); } } } //is twitter enabled if (!sakaiProxy.isTwitterIntegrationEnabledGlobally()) { return; } //get user info ExternalIntegrationInfo info = getExternalIntegrationInfo(userUuid); String token = info.getTwitterToken(); String secret = info.getTwitterSecret(); if (StringUtils.isBlank(token) || StringUtils.isBlank(secret)) { return; } //PRFL-423 limit to 140 chars //Hardcoded limit because 140 is the Twitter requirement so no need to make configurable message = ProfileUtils.truncate(message, 140, false); //instantiate class to send the data new TwitterUpdater(userUuid, token, secret, message); }
From source file:org.smarttechie.servlet.TwitterLoginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TwitterLoginServlet:doGet"); ConfigurationBuilder cb = new ConfigurationBuilder(); Properties props = new TwitterProperties().getProperties(); cb.setDebugEnabled(true).setOAuthConsumerKey((String) props.get("twitterConsumerKey")) .setOAuthConsumerSecret((String) props.get("twitterConsumerSecret")) .setOAuthRequestTokenURL((String) props.get("twitterRequestTokenURL")) .setOAuthAuthorizationURL((String) props.get("twitterAuthorizeURL")) .setOAuthAccessTokenURL((String) props.get("twitterAccessTokenURL")); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); request.getSession().setAttribute("twitter", twitter); try {//from www .ja v a2 s .c o m StringBuffer callbackURL = request.getRequestURL(); System.out.println("TwitterLoginServlet:callbackURL:" + callbackURL); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/TwitterCallback"); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); request.getSession().setAttribute("requestToken", requestToken); System.out.println("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL()); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (TwitterException e) { throw new ServletException(e); } }
From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java
License:Open Source License
/** * Establishes a connection with twitter based on the user information given * in the configuration./* w ww . ja v a 2s . c o m*/ * * @return True if it is possible to use the user information for the * connection, false otherwise. */ private boolean establishConnection() { // get property values from configuration String consumerKey = source.getPropertyValue(TwitterProperties.CONSUMER_KEY_PROPERTY); String consumerSecret = source.getPropertyValue(TwitterProperties.CONSUMER_SECRET_PROPERTY); String accessTokenValue = source.getPropertyValue(TwitterProperties.ACCESS_TOKEN_PROPERTY); String accessTokenSecret = source.getPropertyValue(TwitterProperties.ACCESS_TOKEN_SECRET_PROPERTY); // check properties if (consumerKey == null || consumerKey.isEmpty()) { log("A valid consumer key is needed in the configuration specified by " + TwitterProperties.CONSUMER_KEY_PROPERTY, LogService.LOG_WARNING); return false; } else if (consumerSecret == null || consumerSecret.isEmpty()) { log("A valid consumer secret is needed in the configuration specified by " + TwitterProperties.CONSUMER_SECRET_PROPERTY, LogService.LOG_WARNING); return false; } else if (accessTokenValue == null || accessTokenValue.isEmpty()) { log("A valid access token is needed in the configuration specified by " + TwitterProperties.ACCESS_TOKEN_PROPERTY, LogService.LOG_WARNING); return false; } else if (accessTokenSecret == null || accessTokenSecret.isEmpty()) { log("A valid token secret is needed in the configuration specified by " + TwitterProperties.ACCESS_TOKEN_SECRET_PROPERTY, LogService.LOG_WARNING); return false; } // get access with the provided credencials // TODO disable debug ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessTokenValue).setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory tf = new TwitterFactory(cb.build()); twitterAPI = tf.getInstance(); if (twitterAPI == null) { log("Could not create a connection to the twitter api!", LogService.LOG_ERROR); } return true; }
From source file:org.structr.web.auth.TwitterAuthClient.java
License:Open Source License
@Override protected void init(final String authorizationLocation, final String tokenLocation, final String clientId, final String clientSecret, final String redirectUri, final Class tokenResponseClass) { super.init(authorizationLocation, tokenLocation, clientId, clientSecret, redirectUri, tokenResponseClass); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthAuthorizationURL(authorizationLocation); cb.setOAuthAccessTokenURL(tokenLocation); Configuration conf = cb.build(); TwitterFactory tf = new TwitterFactory(conf); twitter = tf.getInstance(); twitter.setOAuthConsumer(clientId, clientSecret); }
From source file:org.voiser.zoe.TwitterAgent.java
License:MIT License
/** * //ww w .j av a 2 s . c om */ public TwitterAgent() { String consumerKey = System.getenv("zoe_twitter_consumer_key"); String consumerSecret = System.getenv("zoe_twitter_consumer_secret"); String accessToken = System.getenv("zoe_twitter_access_token"); String accessTokenSecret = System.getenv("zoe_twitter_access_token_secret"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret).setUseSSL(true); TwitterFactory tf = new TwitterFactory(cb.build()); twitter = tf.getInstance(); }
From source file:org.wso2.cep.uima.demo.TweetExtractor.java
License:Open Source License
public TweetExtractor(String JMSUrl, String topicName) throws ParserConfigurationException, SAXException, IOException { PropertyConfigurator.configure("src/main/resources/log4j.properties"); this.JMSUrl = JMSUrl; this.topicName = topicName; buildConfiguration(); // set the API keys to the Config Builder TwitterFactory tf = new TwitterFactory(cb.build()); twitterApp = tf.getInstance(); }
From source file:Origin.Mypage.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { response.setContentType("text/html;charset=UTF-8"); /* TODO output your page here. You may use following sample code. */ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);/*from w w w .ja v a 2s.c o m*/ cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); User user = twitter.verifyCredentials(); request.setCharacterEncoding("UTF-8"); HttpSession hs = request.getSession(); UserData ud = (UserData) hs.getAttribute("ud"); String search = ud.getLine() + "?"; //String search= request.getParameter("searchtweet"); Query query = new Query(); query.setCount(100); query.setQuery(search); QueryResult queryresult = null; try { queryresult = twitter.search(query); } catch (TwitterException e1) { e1.printStackTrace(); } ArrayList<String> userID = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { userID.add(tweet.getUser().getScreenName()); } ArrayList<String> profileimg = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { profileimg.add(tweet.getUser().getBiggerProfileImageURL()); } ArrayList<String> username = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getName() + "<br>" + "@" + tweet.getUser().getScreenName()); } ArrayList<String> usernameURL = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getURL()); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); ArrayList<String> resulttweet = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { resulttweet.add(tweet.getText() + "<br>" + sdf.format(tweet.getCreatedAt())); } request.setAttribute("search", search); request.setAttribute("userID", userID); request.setAttribute("profileimg", profileimg); request.setAttribute("username", username); request.setAttribute("resulttweet", resulttweet); request.setAttribute("usernameURL", usernameURL); request.getRequestDispatcher("/mypage.jsp").forward(request, response); }
From source file:Origin.Searchtweet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { response.setContentType("text/html;charset=UTF-8"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);// w w w.jav a 2s .c o m cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); User user = twitter.verifyCredentials(); request.setCharacterEncoding("UTF-8"); String search = "?" + request.getParameter("searchtweet"); //String search= request.getParameter("searchtweet"); Query query = new Query(); query.setCount(100); query.setQuery(search); QueryResult queryresult = null; try { queryresult = twitter.search(query); } catch (TwitterException e1) { e1.printStackTrace(); } ArrayList<String> userID = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { userID.add(tweet.getUser().getScreenName()); } ArrayList<String> profileimg = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { profileimg.add(tweet.getUser().getBiggerProfileImageURL()); } ArrayList<String> username = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getName() + "<br>" + "@" + tweet.getUser().getScreenName()); } ArrayList<String> usernameURL = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getURL()); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); ArrayList<String> resulttweet = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { resulttweet.add(tweet.getText() + "<br>" + sdf.format(tweet.getCreatedAt())); } request.setAttribute("search", search); request.setAttribute("userID", userID); request.setAttribute("profileimg", profileimg); request.setAttribute("username", username); request.setAttribute("resulttweet", resulttweet); request.setAttribute("usernameURL", usernameURL); request.getRequestDispatcher("/searchtweet.jsp").forward(request, response); }
From source file:profiles.FilesThreaderParser.java
License:Apache License
public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, FileNotFoundException, UnsupportedEncodingException { // Check how many arguments were passed in if ((args == null) || (args.length < 5)) { System.err.println("5 Parameters are required to launch a Job."); System.err.println("First: String 'INPUT: /input/path/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) This Job Number"); System.err.println("Fifth: (int) Number of seconds to pause"); System.err.println("Example: fileToRun /input/path/ /output/path/ " + "10 1 3"); System.exit(-1);/*www . j ava 2 s . c o m*/ } // TODO documentation for command line AppOAuth AppOAuths = new AppOAuth(); Misc helpers = new Misc(); String endpoint = "/users/lookup"; String inputPath = null; try { inputPath = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument " + args[0] + " must be an String."); System.exit(-1); } String outputPath = null; try { outputPath = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument " + args[1] + " must be an String."); System.exit(-1); } int TOTAL_JOBS = 0; try { TOTAL_JOBS = Integer.parseInt(args[2]); } catch (NumberFormatException e) { System.err.println("Argument " + args[2] + " must be an integer."); System.exit(1); } int JOB_NO = 0; try { JOB_NO = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument " + args[3] + " must be an integer."); System.exit(1); } int secondsToPause = 0; try { secondsToPause = Integer.parseInt(args[4]); } catch (NumberFormatException e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } try { int TotalWorkLoad = 0; ArrayList<String> allFiles = null; try { final File folder = new File(inputPath); allFiles = helpers.listFilesForSingleFolder(folder); TotalWorkLoad = allFiles.size(); } catch (Exception e) { System.err.println("Input folder is not exists: " + e.getMessage()); System.exit(-1); } System.out.println("Total Workload is: " + TotalWorkLoad); if (TotalWorkLoad < 1) { System.err.println("No targeted user file exists in: " + inputPath); System.exit(-1); } if (TOTAL_JOBS > TotalWorkLoad) { System.err.println("Number of jobs are more than total work" + " load. Please reduce 'Number of jobs' to launch."); System.exit(-1); } float TotalWorkLoadf = TotalWorkLoad; float TOTAL_JOBSf = TOTAL_JOBS; float res = (TotalWorkLoadf / TOTAL_JOBSf); int chunkSize = (int) Math.ceil(res); int offSet = JOB_NO * chunkSize; int chunkSizeToGet = (JOB_NO + 1) * chunkSize; System.out.println("My Share is " + chunkSize); System.out.println("My offSet is " + offSet); System.out.println("My chunkSizeToGet is " + chunkSizeToGet); System.out.println(); // Load OAuh User TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO); Twitter twitter = tf.getInstance(); int RemainingCalls = AppOAuths.RemainingCalls; int RemainingCallsCounter = 0; System.out.println("First Time OAuth Remianing Calls: " + RemainingCalls); String Screen_name = AppOAuths.screen_name; System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name); System.out.println(); System.out.println("Going to get Profiles."); if (JOB_NO + 1 == TOTAL_JOBS) { chunkSizeToGet = TotalWorkLoad; } secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause); System.out.println("secondsToPause: " + secondsToPause); helpers.pause(secondsToPause); // to write output in a file System.out.flush(); List<String> fileNamesShare = allFiles.subList(offSet, chunkSizeToGet); for (String fileName : fileNamesShare) { System.out.println("Going to parse file: " + fileName); try { // open file to write all profiles String filesPath = outputPath + "/"; PrintWriter writer = new PrintWriter(filesPath + "/" + fileName, "UTF-8"); try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + fileName))) { String jsonString; while ((jsonString = br.readLine()) != null) { // process the line. List<String> fileContent = new ArrayList<>(); fileContent.add(jsonString); String[] strarray = fileContent.toArray(new String[0]); String ss = Arrays.toString(strarray); JSONArray obj = new JSONArray(ss); JSONObject obj4 = (JSONObject) obj.get(0); JSONArray idsS = (JSONArray) obj4.get("ids"); ArrayList<String> Idslist = new ArrayList<String>(); if (idsS != null) { int len = idsS.length(); for (int i = 0; i < len; i++) { Idslist.add(idsS.get(i).toString()); } } for (int start = 0; start < Idslist.size(); start += 100) { int end = Math.min(start + 100, Idslist.size()); List<String> sublist = Idslist.subList(start, end); long[] idsdata = new long[sublist.size()]; for (int i = 0; i < sublist.size(); i++) { idsdata[i] = Long.valueOf(sublist.get(i)); } ResponseList<User> profiles = null; while (true) { try { profiles = twitter.lookupUsers(idsdata); if (profiles.size() > 0) { for (User user : profiles) { String rawJSON = TwitterObjectFactory.getRawJSON(user); // put profilesJSON in a file try { writer.println(rawJSON); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } } break; } } catch (TwitterException te) { // If rate limit reached then switch Auth // user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // Load OAuth user tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO); twitter = tf.getInstance(); System.out.println("New User Loaded" + " OAuth Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls - 2; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } } } // while get profiles // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // Load OAuth user tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO); twitter = tf.getInstance(); System.out.println( "New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls - 2; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } } } } writer.close(); } // read my single file catch (IOException e) { System.err.println("Failed to read lines from " + fileName); } // delete file if processed File fileToDelete = new File(inputPath + "/" + "/" + fileName); fileToDelete.delete(); // to write output in a file System.out.flush(); } // all my files // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO); twitter = tf.getInstance(); System.out.println("New Loaded OAuth User Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New OAuth Remianing Calls: " + RemainingCalls); } } catch (TwitterException te) { // te.printStackTrace(); System.err.println("Failed to get Profiles: " + te.getMessage()); System.exit(-1); } System.out.println("!!!! DONE !!!!"); // Close System.out for this thread which will // flush and close this thread. System.out.close(); }