List of usage examples for twitter4j Twitter setOAuthAccessToken
void setOAuthAccessToken(AccessToken accessToken);
From source file:controllers.modules.CorpusModule.java
License:Open Source License
public static Result update(UUID corpus) { OpinionCorpus corpusObj = null;/*from w ww .j a va 2 s . c o m*/ if (corpus != null) { corpusObj = fetchResource(corpus, OpinionCorpus.class); } OpinionCorpusFactory corpusFactory = null; MultipartFormData formData = request().body().asMultipartFormData(); if (formData != null) { // if we have a multi-part form with a file. if (formData.getFiles() != null) { // get either the file named "file" or the first one. FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"), Iterables.getFirst(formData.getFiles(), null)); if (filePart != null) { corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile()) .setFormat(FilenameUtils.getExtension(filePart.getFilename())); } } } else { // otherwise try as a json body. JsonNode json = request().body().asJson(); if (json != null) { OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class); if (optionsVM != null) { corpusFactory = optionsVM.toFactory(); } else { throw new IllegalArgumentException(); } if (optionsVM.grabbers != null) { if (optionsVM.grabbers.twitter != null) { if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) { TwitterFactory tFactory = new TwitterFactory(); Twitter twitter = tFactory.getInstance(); twitter.setOAuthConsumer( Play.application().configuration().getString("twitter4j.oauth.consumerKey"), Play.application().configuration().getString("twitter4j.oauth.consumerSecret")); twitter.setOAuthAccessToken(new AccessToken( Play.application().configuration().getString("twitter4j.oauth.accessToken"), Play.application().configuration() .getString("twitter4j.oauth.accessTokenSecret"))); Query query = new Query(optionsVM.grabbers.twitter.query); query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10)); query.resultType(Query.RECENT); if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) { query.lang(corpusFactory.getLanguage()); } else if (corpusObj != null) { query.lang(corpusObj.getLanguage()); } QueryResult qr; try { qr = twitter.search(query); } catch (TwitterException e) { throw new IllegalArgumentException(); } StringBuilder tweets = new StringBuilder(); for (twitter4j.Status status : qr.getTweets()) { // quote for csv, normalize space, and remove higher unicode characters. String text = StringEscapeUtils.escapeCsv(StringUtils .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", ""))); tweets.append(text + System.lineSeparator()); } corpusFactory.setContent(tweets.toString()); corpusFactory.setFormat("txt"); } } } } else { // if not json, then just create empty. corpusFactory = new OpinionCorpusFactory(); } } if (corpusFactory == null) { throw new IllegalArgumentException(); } if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) { corpusFactory.setTitle("Untitled corpus"); } corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em()); DocumentCorpusModel corpusVM = null; corpusObj = corpusFactory.create(); if (!em().contains(corpusObj)) { em().persist(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return created(corpusVM.asJson()); } for (PersistentObject obj : corpusObj.getDocuments()) { if (em().contains(obj)) { em().merge(obj); } else { em().persist(obj); } } em().merge(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return ok(corpusVM.asJson()); }
From source file:de.dev.eth0.retweeter.TwitterAuthenticator.java
License:BEER-WARE LICENSE
public void authenticate() throws TwitterException, IOException { Twitter twitter = getTwitter(); twitter.setOAuthAccessToken(null); AccessToken accessToken = null;/* ww w . j a va2 s . co m*/ RequestToken requestToken = twitter.getOAuthRequestToken(); 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 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) { logger.error("Couldnt get access token", te); } } System.out.println("Your accessToken: " + accessToken.getToken()); System.out.println("Your accessTokenSecret: " + accessToken.getTokenSecret()); System.out.println("add this to your config: "); System.out.println("\"accessToken\":\"" + accessToken.getToken() + "\","); System.out.println("\"accessSecret\":\"" + accessToken.getTokenSecret() + "\","); }
From source file:es.upm.oeg.examples.watson.servlets.TwitterAnalysisServlet.java
License:Apache License
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//* ww w . j av a 2 s. c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String twitterUsername = request.getParameter("twitter_name"); // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); env = System.getenv(); consumer_key = env.get("TWITTER_CONSUMER_KEY"); consumer_secret = env.get("TWITTER_CONSUMER_SECRET"); access_token = env.get("TWITTER_ACCESS_TOKEN"); access_key = env.get("TWITTER_ACCESS_KEY"); AccessToken accessToken = new AccessToken(access_token, access_key); try { twitter.setOAuthConsumer(consumer_key, consumer_secret); twitter.setOAuthAccessToken(accessToken); twitter4j.User a_name = twitter.showUser(twitterUsername); int followerCount = a_name.getFollowersCount(); List<Status> retweets = twitter.getUserTimeline(twitterUsername, new Paging(1, 20)); // get the first twenty tweets int retweetCount = 0; List<String> langs = new ArrayList<>(); List<String> translated = new ArrayList<>(); StringBuilder aggregatedTextBuilder = new StringBuilder(); String personalityInsights = null; for (Status tweet : retweets) { String tweetText = tweet.getText(); try { String lang = languageIdentification.getLang(tweetText); langs.add(lang); String englishText; //TODO do the same for french and portuguese if (LanguageIdentificationService.ES_ES.equals(lang)) { englishText = machineTranslation.translate(tweetText, MachineTranslationService.ES_TO_EN); } else if (LanguageIdentificationService.FR_FR.equals(lang)) { englishText = machineTranslation.translate(tweetText, MachineTranslationService.FR_TO_EN); } else if (LanguageIdentificationService.PT_BR.equals(lang)) { englishText = machineTranslation.translate(tweetText, MachineTranslationService.PT_TO_EN); } else { englishText = tweetText; } translated.add(englishText); aggregatedTextBuilder.append(englishText); personalityInsights = personalityInsightsService.analyse(aggregatedTextBuilder.toString()); } catch (Exception e) { // Log something and return an error message logger.log(Level.SEVERE, "got error: " + e.getMessage(), e); request.setAttribute("error", e.getMessage()); } } request.setAttribute("t_name", twitterUsername); request.setAttribute("rtweets", retweets); request.setAttribute("langs", langs); request.setAttribute("translated", translated); request.setAttribute("personalityInsights", personalityInsights); request.setAttribute("aggregatedText", aggregatedTextBuilder.toString()); request.getRequestDispatcher("/myTweets.jsp").forward(request, response); } catch (TwitterException e) { e.printStackTrace(); if (e.getErrorCode() == 215 || e.getErrorCode() == 32) { response.sendRedirect("../index.html?message=errorcode215"); } else if (e.getErrorCode() == -1 || e.getErrorCode() == 34) { response.sendRedirect("../index.html?message=errorcode-1"); } else { response.sendRedirect("../index.html?message=errorcode99"); } //throw new ServletException("Encountered a problem fetching data from Twitter - " + e.getErrorMessage()); } }
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 ww .jav a2s . co 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 w w w . j a va 2 s . com return statuses; }
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;//from ww w . ja va 2 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(); t.setOAuthAccessToken(new AccessToken(t2wUser.getTwitterToken(), t2wUser.getTwitterTokenSecret())); try {/*from w ww.ja v a 2 s. co m*/ 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 .ja v 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())); }//from w w w . ja v a2s.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.polimi.meteocal.ejb.HandleAuthTwitterImpl.java
License:Open Source License
/** * Method that return the Twitter object that allows the access to the * Twitter API/*from ww w. j a v a 2s.co 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; }