List of usage examples for twitter4j Status getText
String getText();
From source file:org.wso2.cep.uima.demo.StatusHandler.java
License:Open Source License
/*** * Method to handle arrival of a status to the stream * @param status Recieved Tweet as a Status Object *//*from w w w . j a va2s. c o m*/ @Override public void onStatus(Status status) { Logger.getLogger(StatusHandler.class).info("Tweet Recieved : " + status.getText()); if (producer == null) { throw new NullPointerException("ActiveMQ producer not set for StatusHandler"); } // send the tweet to the queue try { TextMessage tweetMessage = session.createTextMessage(status.getText()); producer.send(tweetMessage); } catch (JMSException e) { e.printStackTrace(); } }
From source file:org.wso2.cep.uima.demo.TweetExtractor.java
License:Open Source License
/*** * *///from w w w . ja v a 2 s. c o m private void retrieveTweets(int maxTweets) { Paging paging; // set the lowest value of the tweet ID initially to one less than Long.MAX_VALUE long min_id = Long.MAX_VALUE - 1; int count = 0; int index = 0; boolean maxValueReached = false; logger.info("Started Extracting Tweets of user: " + userToSearch); // iterate through the timeline untill the iteration returns no tweets while (true) { try { //count = tweetList.size(); // paging tweets at a rate of 100 per page paging = new Paging(1, 100); // if this is not the first iteration set the new min_id value for the page if (count != 0) { logger.info("Extracted Tweet Count : " + count); paging.setMaxId(min_id - 1); } // get a page of the tweet timeline with tweets with ids less than the min_id value List<Status> tweetTempList = twitterApp.getUserTimeline(userToSearch, paging); // iterate the results and add to tweetList for (Status s : tweetTempList) { if (count == maxTweets) { maxValueReached = true; break; } count++; Tweet tweet = new Tweet(s.getId(), s.getCreatedAt(), s.getText()); tweetList.add(tweet); logger.debug(" " + (index++) + " " + tweet.toString()); // set the value for the min value for the next iteration if (s.getId() < min_id) { min_id = s.getId(); } } // if the results for this iteration is zero, means we have reached the API limit or we have extracted the maximum // possible, so break if (tweetTempList.size() == 0 || maxValueReached) { break; } } catch (TwitterException e) { e.printStackTrace(); break; } catch (Exception e) { e.printStackTrace(); break; } } }
From source file:org.wso2.fasttrack.project.roadlk.rest.DatasetGenerator.java
License:Open Source License
/** * @param consumerKey//from w w w. jav a2 s. c om * Twitter Consumer Key (API Key) * @param consumerSecret * Twitter Consumer Secret (API Secret) * @param accessToken * Twitter Access Token * @param accessTokenSecret * Twitter Access Token Secret * @param pageLimit * Maximum pages to be retrieved * @throws IOException * @throws TwitterException */ @SuppressWarnings("resource") public void generateDataset(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, int pageLimit) throws IOException, TwitterException { // Twitter object of Twitter4J library Twitter twitter = TwitterFactory.getSingleton(); // Twitter API authentication twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); PrintWriter printWriter = null; try { printWriter = new PrintWriter(new BufferedWriter(new FileWriter("dataset.txt", true))); } catch (IOException e) { throw new IOException(e); } LOGGER.debug("Twitter feed extraction started."); for (int i = 1; i < pageLimit; i = i + 1) { Paging paging = new Paging(i, 100); ResponseList<Status> statuses = null; try { statuses = twitter.getUserTimeline("road_lk", paging); } catch (TwitterException e) { //LOGGER.error("TwitterException occurred." + e.getMessage()); throw new TwitterException(e); } for (Status status : statuses) { printWriter.println(status.getCreatedAt() + ": " + status.getText()); } } printWriter.close(); LOGGER.debug("Twitter feed extraction completed."); }
From source file:org.xmlsh.twitter.util.TwitterWriter.java
License:BSD License
public void write(Status t) throws XMLStreamException { startElement("tweet"); attribute("id", t.getId()); // write("annotations",t.getAnnotations()); write("created-at", t.getCreatedAt()); write("from-user", sanitizeID(t.getUser().getId()), sanitizeUser(t.getUser().getName())); write("geo-location", t.getGeoLocation()); write("hash-tags", t.getHashtagEntities()); write("iso-language-code", t.getUser().getLang()); write("location", t.getUser().getLocation()); write("media", t.getMediaEntities()); write("place", t.getPlace()); write("profile-image-url", sanitizeUser(t.getUser().getProfileImageURL())); write("source", t.getSource()); write("text", t.getText()); write("to-user", sanitizeID(t.getInReplyToUserId()), sanitizeUser(t.getInReplyToScreenName())); write("url-entities", t.getURLEntities()); write("user-mention-entities", t.getUserMentionEntities()); endElement();/*from w w w . j av a2 s.c om*/ }
From source file:org.xmlsh.twitter.util.TwitterWriter.java
License:BSD License
public void write(String localName, Status status) throws XMLStreamException { if (status != null) { startElement(localName);//from www .j av a2 s. c o m attribute("id", status.getId()); // write("annotations",t.getAnnotations()); write("created-at", status.getCreatedAt()); write("user", status.getUser()); write("geo-location", status.getGeoLocation()); write("hash-tags", status.getHashtagEntities()); write("media", status.getMediaEntities()); write("place", status.getPlace()); write("source", status.getSource()); write("text", status.getText()); write("url-entities", status.getURLEntities()); write("user-mention-entities", status.getUserMentionEntities()); endElement(); } }
From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java
License:Open Source License
/** * create an item by his twitter Status description, will add hashtags and others "metas" * @param s the twitter Status/*from www . ja va2 s . c om*/ * @param source the Uri of the source * @return the item created */ private static Item getItemFromStatus(Status s, String source) { String text = s.getText(); if (s.isRetweet()) { text = s.getRetweetedStatus().getText(); } Item res = new Item(source, "https://twitter.com/" + s.getUser().getScreenName() + "/status/" + Long.toString(s.getId()), text, text, s.getCreatedAt()); String[] hashtags = getHashTags(res.getDescription()); for (String hashtag : hashtags) { res.addProp(new Prop(ZoneOntology.PLUGIN_TWITTER_HASHTAG, hashtag, true, true)); } for (String mentioned : TwitterApi.extractor.extractMentionedScreennames(s.getText())) { res.addProp(new Prop(ZoneOntology.PLUGIN_TWITTER_MENTIONED, "@" + mentioned, true, true)); } if (s.getGeoLocation() != null) { res.addProp(new Prop(ZoneOntology.PLUGIN_TWITTER_POSITION_LONGITUDE, Double.toString(s.getGeoLocation().getLongitude()), true, true)); res.addProp(new Prop(ZoneOntology.PLUGIN_TWITTER_POSITION_LATITUDE, Double.toString(s.getGeoLocation().getLatitude()), true, true)); } res.addProp(new Prop(ZoneOntology.PLUGIN_TWITTER_AUTHOR, "@" + s.getUser().getScreenName(), true, true)); return res; }
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);//w w w .java2 s . co 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);//from www . j ava2 s. c om 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:Principal.Tracker_Twitter.java
License:Minecraft Mod Public
public void guardarResultados_Twitter(List<ObjetoBuscar> lista, BD base, int contadorBase, int TokenIndice) throws NoSuchAlgorithmException, KeyManagementException { int nuevoContadorBase = 0; if (contadorBase >= lista.size()) { System.out.println("Termino en:" + contadorBase); } else {//from w w w . ja v a 2s. c o m System.out.println("---------------------------------------------------------------------:P"); TrustManager[] trustAllCerts = { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); System.out.println("Token : " + TokenIndice); System.out.println(consumerKey[TokenIndice]); try { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(consumerKey[TokenIndice]); cb.setOAuthConsumerSecret(this.consumerSecret[TokenIndice]); cb.setOAuthAccessToken(this.token[TokenIndice]); cb.setOAuthAccessTokenSecret(this.tokenSecret[TokenIndice]); Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance(); for (int numtTweets = contadorBase; numtTweets < contadorBase + 5; numtTweets++) { if (((ObjetoBuscar) lista.get(numtTweets)).getUrl().equals("") || ((ObjetoBuscar) lista.get(numtTweets)).getUrl() == null) { } else { System.out.println("Usuario: " + ((ObjetoBuscar) lista.get(numtTweets)).getUrl()); String usuariosinArroba = ((ObjetoBuscar) lista.get(numtTweets)).getUrl().replace("@", ""); System.out.println("" + usuariosinArroba); try { User usuario = unauthenticatedTwitter.showUser(usuariosinArroba); List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe(); List<Status> favoritos = unauthenticatedTwitter.getFavorites(); Paging paging = new Paging(1, 1000); ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(), paging); System.out.println("Followers: " + usuario.getFollowersCount()); System.out.println("Yo sigo: " + usuario.getFriendsCount()); List<String> listaTweets = new ArrayList(); List<Long> ListaRettewts = new ArrayList(); List<Integer> ListaFavoritos = new ArrayList(); List<Integer> ListaMenciones = new ArrayList(); List<Date> ListaFecha = new ArrayList(); List<Long> ListaIds = new ArrayList(); for (Status sta : statuses) { ListaIds.add(Long.valueOf(sta.getId())); listaTweets.add(sta.getText()); ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + ""))); ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length)); ListaFecha.add(sta.getCreatedAt()); ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount())); } for (int i = 0; i < listaTweets.size(); i++) { base.guardarTrackTwitter_Log((Long) ListaIds.get(i), ((ObjetoBuscar) lista.get(numtTweets)).getUrl(), (String) listaTweets.get(i), (Date) ListaFecha.get(i), (Long) ListaRettewts.get(i), ((Integer) ListaFavoritos.get(i)).intValue(), ((Integer) ListaMenciones.get(i)).intValue()); } } catch (Exception e) { System.err.println("Entro al Try por :" + e); } nuevoContadorBase = numtTweets; } } System.out.println("Numero de Contador Base:" + nuevoContadorBase); guardarResultados_Twitter(lista, base, nuevoContadorBase + 1, TokenIndice + 1); } catch (NumberFormatException e) { System.err.println("Fallo por :" + e); } } }