List of usage examples for twitter4j TwitterFactory TwitterFactory
public TwitterFactory()
From source file:Group5.Model.java
public static void Tweet(String inputTweet) throws TwitterException { //Your Twitter App's Consumer Key String consumerKey = "wK7lQLpl3t8xvIABqpgoJzYYd"; //Your Twitter App's Consumer Secret String consumerSecret = "4M5TgmNfS0EKeaSqna8eHTNaNi970Plq3dynX5gvYsh848j0mj"; //Your Twitter Access Token String accessToken = "829891753473892361-7jkKyXLYc6HOStzCPGjWOnVoAVNU7cd"; //Your Twitter Access Token Secret String accessTokenSecret = "ATidrzRzhVqAamuMbYiskcHBPSisB9MWsCsYYY2Bec4y9"; //Instantiate a re-usable and thread-safe factory TwitterFactory twitterFactory = new TwitterFactory(); //Instantiate a new Twitter instance Twitter twitter = twitterFactory.getInstance(); //setup OAuth Consumer Credentials twitter.setOAuthConsumer(consumerKey, consumerSecret); //setup OAuth Access Token twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate( //your tweet or status message inputTweet);/*from w w w . ja va2 s . c o m*/ //tweet or update status Status status = twitter.updateStatus(statusUpdate); //response from twitter server 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.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); }
From source file:Group5.Model.java
public static List GetTimeline() throws TwitterException { //Your Twitter App's Consumer Key String consumerKey = "wK7lQLpl3t8xvIABqpgoJzYYd"; //Your Twitter App's Consumer Secret String consumerSecret = "4M5TgmNfS0EKeaSqna8eHTNaNi970Plq3dynX5gvYsh848j0mj"; //Your Twitter Access Token String accessToken = "829891753473892361-7jkKyXLYc6HOStzCPGjWOnVoAVNU7cd"; //Your Twitter Access Token Secret String accessTokenSecret = "ATidrzRzhVqAamuMbYiskcHBPSisB9MWsCsYYY2Bec4y9"; //Instantiate a re-usable and thread-safe factory TwitterFactory twitterFactory = new TwitterFactory(); //Instantiate a new Twitter instance Twitter twitter = twitterFactory.getInstance(); //setup OAuth Consumer Credentials twitter.setOAuthConsumer(consumerKey, consumerSecret); //setup OAuth Access Token twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); List<Status> statuses = twitter.getHomeTimeline(); System.out.println("Showing home timeline."); for (Status status : statuses) { System.out.println(status.getUser().getName() + ":" + status.getText()); }//from ww w . ja va2 s .c o m return statuses; }
From source file:h2weibo.controllers.AuthServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpServletRouter r = new HttpServletRouter(request); r.setPattern("/:type"); response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); String serverPath = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();/*from ww w .j ava 2s . c om*/ HttpSession session = request.getSession(); if (r.is(":type", "weibo")) { try { Weibo weibo = new Weibo(); RequestToken requestToken = weibo.getOAuthRequestToken(serverPath + "/callback/weibo"); response.setStatus(302); response.setHeader("Location", requestToken.getAuthenticationURL()); session.setAttribute(Keys.SESSION_TOKEN, requestToken.getToken()); session.setAttribute(Keys.SESSION_TOKEN_SECRET, requestToken.getTokenSecret()); log.info("Redirecting Weibo..."); } catch (WeiboException e) { log.error(e); } } else if (r.is(":type", "twitter")) { try { TwitterFactory factory = new TwitterFactory(); Twitter t = factory.getInstance(); twitter4j.auth.RequestToken requestToken = t.getOAuthRequestToken(serverPath + "/callback/twitter"); response.setStatus(302); response.setHeader("Location", requestToken.getAuthenticationURL()); session.setAttribute(Keys.SESSION_REQUEST_TOKEN, requestToken); log.info("Redirecting Twitter..."); } catch (TwitterException e) { log.error(e); } writer.close(); } else { response.setStatus(200); writer.println("Wrong parameter, not working!"); writer.close(); } }
From source file:h2weibo.controllers.CallbackServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpServletRouter r = new HttpServletRouter(request); r.setPattern("/:type"); if (request.getParameter("denied") != null) { response.sendRedirect("/"); return;// w ww . java2 s . c om } HttpSession session = request.getSession(false); String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER); String token = (String) session.getAttribute(Keys.SESSION_TOKEN); String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET); String oauthVerifier = request.getParameter("oauth_verifier"); DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER); if (r.is(":type", "weibo")) { try { Weibo weibo = new Weibo(); AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier); if (accessToken != null) { T2WUser tid = helper.findOneByUser(loginUser); if (tid.getToken() == null) { // send for the first time session.setAttribute(Keys.SESSION_PROMPT_TWEET, "You are ready to go! Do you want to tweet about this service and share it with your friends?"); } tid.setToken(accessToken.getToken()); tid.setTokenSecret(accessToken.getTokenSecret()); helper.saveUser(tid); } else { log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString()); } } catch (WeiboException e) { log.error("Weibo Exception", e); throw new RuntimeException(e); } } else if (r.is(":type", "twitter")) { try { TwitterFactory factory = new TwitterFactory(); Twitter t = factory.getInstance(); twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN); twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier); session.removeAttribute(Keys.SESSION_REQUEST_TOKEN); if (accessToken != null) { t.setOAuthAccessToken(accessToken); User user = t.verifyCredentials(); loginUser = user.getScreenName(); T2WUser tid = helper.findOneByUser(loginUser); if (tid.getTwitterToken() == null) { // save latest id for the first time. sync from that tweet ResponseList<Status> tl = t.getUserTimeline(); if (tl.size() > 0) { Status s = tl.get(0); tid.setLatestId(s.getId()); } } tid.setTwitterToken(accessToken.getToken()); tid.setTwitterTokenSecret(accessToken.getTokenSecret()); helper.saveUser(tid); session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser); } } catch (TwitterException e) { log.error("Twitter Exception", e); throw new RuntimeException(e); } } String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL); if (requestUrl != null) { session.removeAttribute(Keys.SESSION_REQUEST_URL); response.sendRedirect(requestUrl); } else { response.sendRedirect("/u/" + loginUser); } }
From source file:h2weibo.controllers.TweetServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER); DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER); T2WUser t2wUser = helper.findOneByUser(loginUser); TwitterFactory factory = new TwitterFactory(); Twitter t = factory.getInstance();/*from w w w.ja v a 2 s .c o m*/ t.setOAuthAccessToken(new AccessToken(t2wUser.getTwitterToken(), t2wUser.getTwitterTokenSecret())); try { t.updateStatus( "Twitter, say hello to Weibo! Now syncing Twitter 2 Weibo using http://h2weibo.cloudfoundry.com #t2w_sync"); } catch (TwitterException e) { log.error("Failed to send tweets", e); } response.setStatus(200); }
From source file:h2weibo.controllers.UserServlet.java
License:Open Source License
@Override protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) { HttpServletRouter r = new HttpServletRouter(request); r.setPattern("/:id"); HttpSession session = request.getSession(false); DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER); // Service limit String uId = r.get(":id"); if (!helper.isUser(uId) && helper.getUserCount() > 50) { return getTemplate("full.vm"); }/*from w w w .j av a 2 s. co m*/ T2WUser user = helper.findOneByUser(uId); if (r.has(":id")) { log.info("Displaying user info for @" + uId); ctx.put("user_id", uId); ctx.put("user", helper.findOneByUser(uId)); try { weibo4j.User weiboUser = (weibo4j.User) session.getAttribute(Keys.SESSION_WEIBO_USER); if (weiboUser == null) { Weibo w = new Weibo(); w.setToken(user.getToken(), user.getTokenSecret()); weiboUser = w.verifyCredentials(); session.setAttribute(Keys.SESSION_WEIBO_USER, weiboUser); } ctx.put("weibo_user", weiboUser.getScreenName()); ctx.put("weibo_user_image", weiboUser.getProfileImageURL().toString()); ctx.put("weibo_login", 1); // save weiboUser ID mapping helper.setWeiboId(user.getUserId(), weiboUser.getScreenName()); } catch (Exception e) { // 401 = not logged in if (e instanceof WeiboException && ((WeiboException) e).getStatusCode() != 401) { e.printStackTrace(); } } try { twitter4j.User twitterUser = (twitter4j.User) session.getAttribute(Keys.SESSION_TWITTER_USER); if (twitterUser == null) { TwitterFactory factory = new TwitterFactory(); Twitter t = factory.getInstance(); t.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret())); twitterUser = t.verifyCredentials(); session.setAttribute(Keys.SESSION_TWITTER_USER, twitterUser); } ctx.put("twitter_user", twitterUser.getScreenName()); ctx.put("twitter_user_image", twitterUser.getProfileImageURL().toString()); ctx.put("twitter_login", 1); } catch (Exception e) { // 401 = not logged in if (e instanceof TwitterException && ((TwitterException) e).getStatusCode() != 401) { e.printStackTrace(); } } } Object message = session.getAttribute(Keys.SESSION_MESSAGE); if (message != null) { ctx.put("message", message); session.removeAttribute(Keys.SESSION_MESSAGE); } Object prompt = session.getAttribute(Keys.SESSION_PROMPT_TWEET); if (prompt != null) { ctx.put("prompt", prompt); session.removeAttribute(Keys.SESSION_PROMPT_TWEET); } return getTemplate("user.vm"); }
From source file:h2weibo.Twitter2Weibo.java
License:Open Source License
public void syncTwitter(String userId) { T2WUser user = helper.findOneByUser(userId); weibo.setToken(user.getToken(), user.getTokenSecret()); Twitter twitter = new TwitterFactory().getInstance(); if (user.getTwitterToken() != null) { twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret())); log.debug(String.format("Using OAuth for %s", user.getUserId())); }/* w w w. j a va2s.c om*/ StatusFilters filters = new StatusFilters(); filters.use(new NoSyncFilter()); // should be used first filters.use(new TcoStatusFilter()).use(new URLStatusFilter()).use(new TagStatusFilter()) .use(new FlickrImageFilter()); NoMentionFilter mentionFilter = new NoMentionFilter(); UserMappingFilter mappingFilter = new UserMappingFilter(helper); if (!user.ready()) { log.debug(String.format("Skipping @%s ...", user.getUserId())); return; } // gets Twitter instance with default credentials String screenName = user.getUserId(); long latestId = user.getLatestId(); log.debug(String.format("Checking @%s's timeline, latest ID = %d.", userId, latestId)); try { if (latestId == 0) { List<Status> statuses = twitter.getUserTimeline(screenName); if (statuses.size() > 0) { user.setLatestId(statuses.get(0).getId()); // Record latestId, and sync next time } log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId)); } else { Paging paging = new Paging(latestId); List<Status> statuses = twitter.getUserTimeline(screenName, paging); // sync from the oldest one for (int i = statuses.size() - 1; i >= 0; i--) { Status status = statuses.get(i); if (status.getId() < user.getLatestId()) continue; // safe keeper String name = status.getUser().getScreenName(); String statusText = status.getText(); log.info(String.format("%s - %s", name, statusText)); try { if (status.isRetweet()) { if (user.isDropRetweets()) { user.setLatestId(status.getId()); log.debug("Skipped " + statusText + " because status is a retweet."); continue; } else { filters.remove(mentionFilter); filters.use(mappingFilter); } } else { if (user.isDropMentions()) { filters.remove(mappingFilter); filters.use(mentionFilter); } else { filters.remove(mentionFilter); filters.use(mappingFilter); } } statusText = filters.filter(statusText); if (statusText == null) { user.setLatestId(status.getId()); log.info(String.format("Skipped %s because of the filter.", statusText)); continue; } if (!user.isNoImage()) { // add twitter images to status text MediaEntity[] mediaEntities = status.getMediaEntities(); if (mediaEntities != null) { for (MediaEntity entity : mediaEntities) { statusText += " " + entity.getMediaURL(); } log.info("with media url: " + statusText); } StatusImageExtractor ex = new StatusImageExtractor(); StringBuffer buf = new StringBuffer(statusText); byte[] image = ex.extract(buf); if (image != null) { user.setLatestId(status.getId()); try { statusText = buf.toString(); // with image urls removed weibo.uploadStatus(statusText, new ImageItem(image)); log.info(String.format("@%s - %s sent with image.", name, statusText)); } catch (WeiboException e) { log.error("Faile to update image.", e); } continue; } } GeoLocation location = status.getGeoLocation(); if (user.isWithGeo() && location != null) { weibo.updateStatus(statusText, location.getLatitude(), location.getLongitude()); log.info(String.format("@%s - %s sent with geo locations.", name, statusText)); } else { weibo.updateStatus(statusText); log.info(String.format("@%s - %s sent.", name, statusText)); } } catch (WeiboException e) { if (e.getStatusCode() != 400) { // resending same tweet log.error("Failed to update Weibo", e); break; } else { log.error("Sending same message", e); } } log.info(String.format("Sent: by %s - %s", name, statusText)); user.setLatestId(status.getId()); } } helper.saveUser(user); } catch (Exception e) { if (!(e instanceof TwitterException)) { log.error("Failed to update.", e); } } }
From source file:hashimotonet.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * //from w ww. j a v a 2 s . com * @param args * message */ public static void main(String[] args) { /* try { new UpdateStatus().connectTwitter(); } catch(Exception e) { e.printStackTrace(); } */ if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); System.exit(-1); } String message = ""; for (int i = 0; i < args.length; i++) { message += args[i] + " "; } try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is // already available RequestToken requestToken = twitter.getOAuthRequestToken(); // RequestToken requestToken = new RequestToken(Globals.KEY,Globals.SECRET); String url = requestToken.getAuthenticationURL(); System.out.println("url = " + url); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is // not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(message); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:info.usbo.skypetwitter.Run.java
License:Apache License
public static void main(String[] args) throws SkypeException, IOException { System.out.println("Working Directory = " + System.getProperty("user.dir")); Properties props = new Properties(); loadProperties(props, "twitter4j.properties"); loadProperties(props, "skype.properties"); loadProperties(props, "app.properties"); String chat_group_id = props.getProperty("skype.chat_group_id"); String twitter_user_id = props.getProperty("twitter.user"); data_dir = props.getProperty("data.dir"); Integer twitter_timeout = Integer.parseInt(props.getProperty("twitter.timeout")); System.out.println("Twitter user: " + twitter_user_id); System.out.println("Twitter timeout: " + twitter_timeout); if ("".equals(twitter_user_id)) { return;/*from ww w . java2 s. c o m*/ } if (load_file() == 0) { System.out.println("File not found"); return; } while (true) { bChanged = 0; SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); System.out.println("Looking at " + sdf.format(Calendar.getInstance().getTime())); Chat ch = Skype.chat(chat_group_id); Twitter twitter = new TwitterFactory().getInstance(); try { List<Status> statuses; statuses = twitter.getUserTimeline(twitter_user_id); String sText; for (Status status : statuses) { Date d = status.getCreatedAt(); // ? Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.HOUR_OF_DAY, 7); d = cal.getTime(); sText = "@" + status.getUser().getScreenName() + " " + sdf.format(d) + " ( https://twitter.com/" + twitter_user_id + "/status/" + status.getId() + " ): \r\n" + status.getText() + "\r\n***"; for (URLEntity e : status.getURLEntities()) { sText = sText.replaceAll(e.getURL(), e.getExpandedURL()); } for (MediaEntity e : status.getMediaEntities()) { sText = sText.replaceAll(e.getURL(), e.getMediaURL()); } if (twitter_ids.indexOf(status.getId()) == -1) { System.out.println(sText); ch.send(sText); twitter_ids.add(status.getId()); bChanged = 1; } } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); // System.exit(-1); } catch (SkypeException ex) { ex.printStackTrace(); System.out.println("Failed to send message: " + ex.getMessage()); } // VK try { vk(); for (VK v : vk) { if (vk_ids.indexOf(v.getId()) == -1) { Date d = v.getDate(); // ? Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.HOUR_OF_DAY, 7); d = cal.getTime(); String sText = "@Depersonilized (VK) " + sdf.format(d) + " ( http://vk.com/Depersonilized?w=wall-0_" + v.getId() + " ): \r\n" + v.getText(); if (!"".equals(v.getAttachment())) { sText += "\r\n" + v.getAttachment(); } sText += "\r\n***"; System.out.println(sText); ch.send(sText); vk_ids.add(v.getId()); bChanged = 1; } } } catch (ParseException e) { e.printStackTrace(); System.out.println("Failed to get vk: " + e.getMessage()); // System.exit(-1); } catch (SkypeException ex) { ex.printStackTrace(); System.out.println("Failed to send message: " + ex.getMessage()); } if (bChanged == 1) { save_file(); } try { Thread.sleep(1000 * 60 * twitter_timeout); } catch (InterruptedException ex) { ex.printStackTrace(); System.out.println("Failed to sleep: " + ex.getMessage()); } } }
From source file:it.baywaylabs.jumpersumo.PilotingActivity.java
License:Open Source License
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_piloting); initIHM();/* w w w . j a va 2s .c o m*/ initVideo(); Intent intent = getIntent(); service = intent.getParcelableExtra(EXTRA_DEVICE_SERVICE); TwitterFactory twitterFactory = new TwitterFactory(); this.twitter = twitterFactory.getInstance(); twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET); twitter.setOAuthAccessToken(new AccessToken(Constants.ACCESS_TOKEN, Constants.ACCESS_TOKEN_SECRET)); //create the device try { device = new ARDiscoveryDevice(); ARDiscoveryDeviceNetService netDeviceService = (ARDiscoveryDeviceNetService) service.getDevice(); this.ip_host = netDeviceService.getIp(); device.initWifi(ARDISCOVERY_PRODUCT_ENUM.ARDISCOVERY_PRODUCT_JS, netDeviceService.getName(), netDeviceService.getIp(), netDeviceService.getPort()); } catch (ARDiscoveryException e) { e.printStackTrace(); Log.e(TAG, "Error: " + e.getError()); } if (device != null) { try { //create the deviceController deviceController = new ARDeviceController(device); deviceController.addListener(this); deviceController.addStreamListener(this); } catch (ARControllerException e) { e.printStackTrace(); } } }