List of usage examples for twitter4j.auth AccessToken AccessToken
public AccessToken(String token, String tokenSecret)
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 .j a v a 2 s . c om*/ //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 w w w . j a v a2s .c o m*/ return statuses; }
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();// www. j a v a2 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"); }/* w w w . j av a 2 s . c o 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 v a 2s. com*/ 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: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 ww . j a v a 2 s . c om 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(); } } }
From source file:it.polimi.meteocal.ejb.HandleAuthTwitterImpl.java
License:Open Source License
/** * Method that return the Twitter object that allows the access to the * Twitter API//from w w w.j a v a2 s .c o m * * @param user the user in MeteoCal * @return null if there was a problem with the creation of the Twitter * object */ public static Twitter getTwitterObject(User user) { Twitter twitter; if (user.getTwitterToken() == null) { // Twitter not connected return null; } ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(CLIENT_ID); builder.setOAuthConsumerSecret(CLIENT_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); AccessToken at = new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()); LOGGER.log(Level.INFO, at); try { twitter.setOAuthAccessToken(at); } catch (Exception e) { LOGGER.log(Level.ERROR, e); return null; } return twitter; }
From source file:javatwiter4j.NewJFrame.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String tweet = ""; tweet = jTextField1.getText();//w ww . j a va 2 s . c o m try { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(apiKey, apiSecretKey); AccessToken accessTokenn = new AccessToken(accessToken, accessTokenSecret); twitter.setOAuthAccessToken(accessTokenn); twitter.updateStatus(tweet); } catch (Exception ex) { jLabel1.setText("Son Tweet: Gnderilemedi"); } jLabel1.setText("Son Tweet: Gnderildi"); }
From source file:javatwitterserver.JavaTwitter.java
public JavaTwitter(String consumerKeyStr, String consumerSecretStr, String accessTokenStr, String accessTokenSecretStr) { this.consumerKeyStr = consumerKeyStr; this.consumerSecretStr = consumerSecretStr; this.accessTokenStr = accessTokenStr; this.accessTokenSecretStr = accessTokenSecretStr; twitter = null;//from ww w . j a v a2 s . c om accessToken = null; try { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(this.consumerKeyStr, this.consumerSecretStr); accessToken = new AccessToken(this.accessTokenStr, this.accessTokenSecretStr); twitter.setOAuthAccessToken(accessToken); } catch (Exception e) { e.printStackTrace(); } }
From source file:jp.co.tweetmap.util.TwitterUtils.java
License:Apache License
/** * Load the access token to shared preference. * * @param context {@link Context}, not {@code null}. * @return access token to use Twitter API. *//*from w ww .jav a 2s . c o m*/ public static AccessToken loadAccessToken(@NonNull Context context) { SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); String token = preferences.getString(ACCESS_TOKEN, null); String tokenSecret = preferences.getString(ACCESS_TOKEN_SECRET, null); if (token != null && tokenSecret != null) { return new AccessToken(token, tokenSecret); } else { return null; } }