List of usage examples for twitter4j TwitterFactory TwitterFactory
public TwitterFactory()
From source file:com.springsource.greenhouse.connect.providers.Twitter4JServiceProvider.java
License:Apache License
protected Twitter createServiceOperations(OAuthToken accessToken) { TwitterFactory twitterFactory = new TwitterFactory(); AccessToken oauthToken = new AccessToken(accessToken.getValue(), accessToken.getSecret()); Configuration configuration = new PropertyConfiguration(new Properties()); Authorization authorization = new OAuthAuthorization(configuration, getApiKey(), getSecret(), oauthToken); return accessToken != null ? twitterFactory.getInstance(authorization) : twitterFactory.getInstance(); }
From source file:com.stepinmobile.fantasticbutton.api.ButtonHandle.java
License:Apache License
/** * Method post tweet./* w w w . ja va 2s . co m*/ */ private void postTweet() { Twitter twitter = new TwitterFactory().getInstance(); AccessToken accessToken = new AccessToken(twitterHandle.getToken(), twitterHandle.getSecret()); twitter.setOAuthConsumer(twitterAppId, twitterAppSecret); twitter.setOAuthAccessToken(accessToken); Status status = null; try { status = twitter.updateStatus(tweetToBeTweeted); } catch (TwitterException e) { Log.e(TAG, Log.getStackTraceString(e)); } }
From source file:com.temenos.interaction.example.mashup.twitter.OAuthRequestor.java
License:Open Source License
public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//from w w w . j a v a 2s. c o m BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Open the following URL and grant access to your account:"); LOGGER.debug(requestToken.getAuthorizationURL()); LOGGER.debug("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); } String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode() && LOGGER.isInfoEnabled()) { LOGGER.info("Unable to get the access token."); } else { LOGGER.error("Error writing the object.", te); } } } // persist to the accessToken for future reference. storeAccessToken(twitter.verifyCredentials().getId(), accessToken); // Tweet! // Status status = twitter.updateStatus(args[0]); // System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); }
From source file:com.temenos.interaction.example.mashup.twitter.Twitter4JConsumer.java
License:Open Source License
/** * @param otherUser//from w ww .ja v a 2s. co m * @return */ public Collection<Tweet> requestTweetsByUser(String otherUser) { List<Tweet> tweets = new ArrayList<Tweet>(); try { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); AccessToken accessToken = loadAccessToken(1); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); twitter.setOAuthAccessToken(accessToken); if (LOGGER.isInfoEnabled()) { LOGGER.info("Fetching latest 100 tweets for [" + otherUser + "]"); } // First param of Paging() is the page number, second is the number per page (this is capped around 200 I think. Paging paging = new Paging(1, 100); List<Status> statuses = twitter.getUserTimeline(otherUser, paging); for (Status status : statuses) { tweets.add(new Tweet(otherUser, status.getText(), (status.getGeoLocation() != null ? status.getGeoLocation().getLatitude() + "," + status.getGeoLocation().getLongitude() : ""))); if (LOGGER.isInfoEnabled()) { LOGGER.info( status.getUser().getName() + "(" + status.getGeoLocation() + "):" + status.getText()); } } } catch (Exception e) { LOGGER.error("Error on requestTweetsByUser", e); throw new TwitterMashupException(e); } return tweets; }
From source file:com.tuncaysenturk.jira.plugins.compatibility.servlet.TwitterLoginServlet.java
private void twitterCallback(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> context) { if (null == req.getParameter("denied") && null != req.getParameter("oauth_verifier")) { String verifier = req.getParameter("oauth_verifier").toString(); PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet(); propSet.setString("accessTokenVerifier", verifier); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(propSet.getString("consumerKey"), propSet.getString("consumerSecret")); RequestToken requestToken = new RequestToken(propSet.getString("requestToken"), propSet.getString("requestTokenSecret")); propSet.remove("requestToken"); propSet.remove("requestTokenSecret"); try {//from w ww .java 2s .com AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); propSet.setString("accessToken", accessToken.getToken()); propSet.setString("accessTokenSecret", accessToken.getTokenSecret()); User user = twitter.verifyCredentials(); logger.info(JTPConstants.LOG_PRE + "User :" + user.getScreenName() + " logged in successfully"); restartListener(req, resp, context); } catch (TwitterException e) { logger.error(JTPConstants.LOG_PRE + "Error while streaming", e); ExceptionMessagesUtil.addExceptionMessage("Error while streaming : ", e); } } else { logger.warn(JTPConstants.LOG_PRE + "User denied Twitter authorization, plugin will not work properly"); ExceptionMessagesUtil .addExceptionMessage("User denied Twitter authorization, plugin will not work properly"); } }
From source file:com.tuncaysenturk.jira.plugins.compatibility.servlet.TwitterLoginServlet.java
public void login(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> context) { Twitter twitter = new TwitterFactory().getInstance(); try {//from w w w . j a v a2 s.c o m PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet(); URI servletConfigureTwitter = URI .create(applicationProperties.getBaseUrl() + JTPConstants.URL_CONFIGURE_TWITTER); String callbackURL = servletConfigureTwitter + QUESTION_MARK + IS_CALLBACK + EQUALS + TRUE; twitter.setOAuthConsumer(propSet.getString("consumerKey"), propSet.getString("consumerSecret")); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL); String requestToken_token = requestToken.getToken(); String requestToken_secret = requestToken.getTokenSecret(); propSet.setString("requestToken", requestToken_token); propSet.setString("requestTokenSecret", requestToken_secret); String redirectUrl = requestToken.getAuthorizationURL(); resp.sendRedirect(redirectUrl); } catch (TwitterException e) { logger.error(JTPConstants.LOG_PRE + "Exception while logging to Twitter", e); @SuppressWarnings("unchecked") List<String> errorMessages = (List<String>) context.get("errorMessages"); errorMessages.add(e.getMessage()); } catch (IOException e) { logger.error(JTPConstants.LOG_PRE + "Exception while logging to Twitter", e); } }
From source file:com.tweet.analysis.SearchTweets.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param args search query/*from w w w.j a va2 s .co m*/ */ 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(); //twitter.getFollowersList("Kuldeep.loveiit"); try { Query query = new Query("Modi"); 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:com.twit.AppCrawler.java
public static void main(String[] args) throws TwitterException { TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();/*from w w w . j a v a 2 s . com*/ CidadeController cidadeController = new CidadeController(new Cidade()); List<Cidade> cidades = cidadeController.findEntities(); String searchStr = "\"#viagem\" "; for (Cidade cidade : cidades) { //searchStr += "\"" + cidade.getNome() + "\" "; } // 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. for (Status status : result.getTweets()) { System.out.println("\n@" + status.getUser().getName() + ": " + status.getText()); } }
From source file:com.twitstreet.servlet.CallBackServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1 response.setHeader("Pragma", "no-cache"); //HTTP 1.0 response.setDateHeader("Expires", 0); //prevents caching at the proxy server Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret()); RequestToken requestToken = (RequestToken) request.getSession().getAttribute(REQUEST_TOKEN); String verifier = request.getParameter(OAUTH_VERIFIER); try {//from ww w . ja v a2s .co m AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); long userId = accessToken.getUserId(); String screenName = accessToken.getScreenName(); String oauthToken = accessToken.getToken(); String oauthTokenSecret = accessToken.getTokenSecret(); User user = null; user = userMgr.getUserById(userId); //new user if (user == null) { twitter4j.User twUser = twitter.showUser(userId); user = new User(); user.setId(userId); user.setUserName(screenName); user.setLastIp(request.getRemoteAddr()); user.setOauthToken(oauthToken); user.setOauthTokenSecret(oauthTokenSecret); user.setCash(configMgr.getInitialMoney()); user.setPictureUrl(twUser.getProfileImageURL().toExternalForm()); user.setDescription(twUser.getDescription()); user.setLongName(twUser.getName()); user.setLocation(twUser.getLocation()); user.setLanguage(twUser.getLang()); user.setUrl(twUser.getURL() == null ? null : twUser.getURL().toExternalForm()); userMgr.saveUser(user); String referenceId = (String) request.getSession().getAttribute(HomePageServlet.REFERENCE_ID); long referenceLong = -1; try { referenceLong = Long.parseLong(referenceId); } catch (NumberFormatException e) { logger.error("Parsing reference id failed: " + referenceId); } if (referenceLong > -1) { userMgr.invite(referenceLong, user.getId()); } request.getSession().removeAttribute(HomePageServlet.REFERENCE_ID); } else { //existing user logging in again user = new User(); user.setId(userId); user.setUserName(screenName); user.setLastIp(request.getRemoteHost()); user.setOauthToken(oauthToken); user.setOauthTokenSecret(oauthTokenSecret); user.setAutoPlayer(false); userMgr.updateUser(user); } request.getSession().setAttribute(User.USER_ID, user.getId()); Cookie cookies[] = createCookie(userId, oauthToken); writeCookies(response, cookies); } catch (TwitterException e) { throw new ServletException(e); } response.sendRedirect(request.getContextPath() + "/"); }
From source file:com.twitstreet.servlet.SigninServlet.java
License:Open Source License
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1 response.setHeader("Pragma", "no-cache"); //HTTP 1.0 response.setDateHeader("Expires", 0); //prevents caching at the proxy server Twitter twitter = new TwitterFactory().getInstance(); try {/*from w w w.j a v a 2 s .co m*/ StringBuffer callbackURL = request.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/callback"); logger.debug("Callback url is: " + callbackURL.toString()); twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret()); logger.debug("Consumer Key: " + configMgr.getConsumerKey() + ", Consumer Secret: " + configMgr.getConsumerSecret()); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); request.getSession().setAttribute(CallBackServlet.REQUEST_TOKEN, requestToken); response.sendRedirect(requestToken.getAuthenticationURL()); logger.debug("Redirect sent to authentication URL: " + requestToken.getAuthenticationURL()); } catch (TwitterException e) { throw new ServletException(e); } }