List of usage examples for twitter4j Status getText
String getText();
From source file:org.getlantern.firetweet.util.ContentValuesCreator.java
License:Open Source License
public static ContentValues createStatus(final Status orig, final long accountId) { if (orig == null || orig.getId() <= 0) return null; final ContentValues values = new ContentValues(); values.put(Statuses.ACCOUNT_ID, accountId); values.put(Statuses.STATUS_ID, orig.getId()); values.put(Statuses.STATUS_TIMESTAMP, orig.getCreatedAt().getTime()); final Status status; if (orig.isRetweet()) { final Status retweetedStatus = orig.getRetweetedStatus(); final User retweetUser = orig.getUser(); final long retweetedById = retweetUser.getId(); values.put(Statuses.RETWEET_ID, retweetedStatus.getId()); values.put(Statuses.RETWEET_TIMESTAMP, retweetedStatus.getCreatedAt().getTime()); values.put(Statuses.RETWEETED_BY_USER_ID, retweetedById); values.put(Statuses.RETWEETED_BY_USER_NAME, retweetUser.getName()); values.put(Statuses.RETWEETED_BY_USER_SCREEN_NAME, retweetUser.getScreenName()); values.put(Statuses.RETWEETED_BY_USER_PROFILE_IMAGE, (retweetUser.getProfileImageUrlHttps())); values.put(Statuses.IS_RETWEET, true); if (retweetedById == accountId) { values.put(Statuses.MY_RETWEET_ID, orig.getId()); } else {/* w ww. j av a 2 s .c o m*/ values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet()); } status = retweetedStatus; } else if (orig.isQuote()) { final Status quotedStatus = orig.getQuotedStatus(); final User quoteUser = orig.getUser(); final long quotedById = quoteUser.getId(); values.put(Statuses.QUOTE_ID, quotedStatus.getId()); final String textHtml = TwitterContentUtils.formatStatusText(orig); values.put(Statuses.QUOTE_TEXT_HTML, textHtml); values.put(Statuses.QUOTE_TEXT_PLAIN, orig.getText()); values.put(Statuses.QUOTE_TEXT_UNESCAPED, toPlainText(textHtml)); values.put(Statuses.QUOTE_TIMESTAMP, orig.getCreatedAt().getTime()); values.put(Statuses.QUOTE_SOURCE, orig.getSource()); values.put(Statuses.QUOTED_BY_USER_ID, quotedById); values.put(Statuses.QUOTED_BY_USER_NAME, quoteUser.getName()); values.put(Statuses.QUOTED_BY_USER_SCREEN_NAME, quoteUser.getScreenName()); values.put(Statuses.QUOTED_BY_USER_PROFILE_IMAGE, quoteUser.getProfileImageUrlHttps()); values.put(Statuses.QUOTED_BY_USER_IS_VERIFIED, quoteUser.isVerified()); values.put(Statuses.QUOTED_BY_USER_IS_PROTECTED, quoteUser.isProtected()); values.put(Statuses.IS_QUOTE, true); if (quotedById == accountId) { values.put(Statuses.MY_QUOTE_ID, orig.getId()); // } else { // values.put(Statuses.MY_QUOTE_ID, orig.getCurrentUserRetweet()); } status = quotedStatus; } else { values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet()); status = orig; } final User user = status.getUser(); final long userId = user.getId(); final String profileImageUrl = (user.getProfileImageUrlHttps()); final String name = user.getName(), screenName = user.getScreenName(); values.put(Statuses.USER_ID, userId); values.put(Statuses.USER_NAME, name); values.put(Statuses.USER_SCREEN_NAME, screenName); values.put(Statuses.IS_PROTECTED, user.isProtected()); values.put(Statuses.IS_VERIFIED, user.isVerified()); values.put(Statuses.USER_PROFILE_IMAGE_URL, profileImageUrl); values.put(CachedUsers.IS_FOLLOWING, user.isFollowing()); final String textHtml = TwitterContentUtils.formatStatusText(status); values.put(Statuses.TEXT_HTML, textHtml); values.put(Statuses.TEXT_PLAIN, status.getText()); values.put(Statuses.TEXT_UNESCAPED, toPlainText(textHtml)); values.put(Statuses.RETWEET_COUNT, status.getRetweetCount()); values.put(Statuses.REPLY_COUNT, status.getReplyCount()); values.put(Statuses.FAVORITE_COUNT, status.getFavoriteCount()); values.put(Statuses.DESCENDENT_REPLY_COUNT, status.getDescendentReplyCount()); values.put(Statuses.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId()); values.put(Statuses.IN_REPLY_TO_USER_ID, status.getInReplyToUserId()); values.put(Statuses.IN_REPLY_TO_USER_NAME, TwitterContentUtils.getInReplyToName(status)); values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, status.getInReplyToScreenName()); values.put(Statuses.SOURCE, status.getSource()); values.put(Statuses.IS_POSSIBLY_SENSITIVE, status.isPossiblySensitive()); final GeoLocation location = status.getGeoLocation(); if (location != null) { values.put(Statuses.LOCATION, ParcelableLocation.toString(location.getLatitude(), location.getLongitude())); } final Place place = status.getPlace(); if (place != null) { values.put(Statuses.PLACE_FULL_NAME, place.getFullName()); } values.put(Statuses.IS_FAVORITE, status.isFavorited()); final ParcelableMedia[] media = ParcelableMedia.fromEntities(status); if (media != null) { values.put(Statuses.MEDIA_LIST, SimpleValueSerializer.toSerializedString(media)); } final ParcelableUserMention[] mentions = ParcelableUserMention.fromStatus(status); if (mentions != null) { values.put(Statuses.MENTIONS_LIST, SimpleValueSerializer.toSerializedString(mentions)); } final ParcelableCardEntity card = ParcelableCardEntity.fromCardEntity(status.getCard(), accountId); if (card != null) { values.put(Statuses.CARD_NAME, card.name); values.put(Statuses.CARD, JSONSerializer.toJSONObjectString(card)); } return values; }
From source file:org.glassfish.jersey.sample.sse.TwitterBean.java
License:Open Source License
/** * Since twitter uses the v1.1 API we use twitter4j to get * the search results using OAuth//from w ww .j a v a 2 s . c om * @return a JsonArray containing tweets * @throws TwitterException * @throws IOException */ public JsonArray getFeedData() throws TwitterException, IOException { Properties prop = new Properties(); // try { //load a properties file prop.load(this.getClass().getResourceAsStream("twitter4j.properties")); //get the property value and print it out String consumerKey = prop.getProperty("oauth.consumerKey"); String consumerSecret = prop.getProperty("oauth.consumerSecret"); String accessToken = prop.getProperty("oauth.accessToken"); String accessTokenSecret = prop.getProperty("oauth.accessTokenSecret"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Query query = new Query("glassfish"); QueryResult result = twitter.search(query); JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); for (Status status : result.getTweets()) { jsonArrayBuilder.add(Json.createObjectBuilder().add("text", status.getText()).add("created_at", status.getCreatedAt().toString())); System.out.println( "@" + status.getUser().getScreenName() + ":" + status.getText() + status.getCreatedAt()); } return jsonArrayBuilder.build(); }
From source file:org.graylog2.inputs.twitter.TwitterCodec.java
License:Open Source License
private Message createMessageFromStatus(final Status status) { final Message message = new Message(status.getText(), "twitter.com", new DateTime(status.getCreatedAt())); message.addField("facility", "Tweets"); message.addField("level", 6); message.addField("tweet_id", status.getId()); message.addField("tweet_is_retweet", Boolean.toString(status.isRetweet())); message.addField("tweet_favorite_count", status.getFavoriteCount()); message.addField("tweet_retweet_count", status.getRetweetCount()); message.addField("tweet_language", status.getLang()); final GeoLocation geoLocation = status.getGeoLocation(); if (geoLocation != null) { message.addField("tweet_geo_long", geoLocation.getLongitude()); message.addField("tweet_geo_lat", geoLocation.getLatitude()); }/* w ww .j av a2s. c om*/ final User user = status.getUser(); if (user != null) { message.addField("tweet_url", "https://twitter.com/" + user.getScreenName() + "/status/" + status.getId()); message.addField("user_id", user.getId()); message.addField("user_name", user.getScreenName()); message.addField("user_description", user.getDescription()); message.addField("user_timezone", user.getTimeZone()); message.addField("user_utc_offset", user.getUtcOffset()); message.addField("user_location", user.getLocation()); message.addField("user_language", user.getLang()); message.addField("user_url", user.getURL()); message.addField("user_followers", user.getFollowersCount()); message.addField("user_tweets", user.getStatusesCount()); message.addField("user_favorites", user.getFavouritesCount()); } return message; }
From source file:org.hornetq.integration.twitter.impl.IncomingTweetsHandler.java
License:Apache License
private void putTweetIntoMessage(final Status status, final ServerMessage msg) { msg.getBodyBuffer().writeString(status.getText()); msg.putLongProperty(TwitterConstants.KEY_ID, status.getId()); msg.putStringProperty(TwitterConstants.KEY_SOURCE, status.getSource()); msg.putLongProperty(TwitterConstants.KEY_CREATED_AT, status.getCreatedAt().getTime()); msg.putBooleanProperty(TwitterConstants.KEY_IS_TRUNCATED, status.isTruncated()); msg.putLongProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId()); msg.putIntProperty(TwitterConstants.KEY_IN_REPLY_TO_USER_ID, status.getInReplyToUserId()); msg.putBooleanProperty(TwitterConstants.KEY_IS_FAVORITED, status.isFavorited()); msg.putBooleanProperty(TwitterConstants.KEY_IS_RETWEET, status.isRetweet()); msg.putObjectProperty(TwitterConstants.KEY_CONTRIBUTORS, status.getContributors()); GeoLocation gl;// ww w. j a v a 2 s. c o m if ((gl = status.getGeoLocation()) != null) { msg.putDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE, gl.getLatitude()); msg.putDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LONGITUDE, gl.getLongitude()); } Place place; if ((place = status.getPlace()) != null) { msg.putStringProperty(TwitterConstants.KEY_PLACE_ID, place.getId()); } }
From source file:org.hubiquitus.hubotsdk.adapters.HTwitterAdapterInbox.java
License:Open Source License
/** * Function for transforming Tweet to HMessage * @param tweet from twitter4j//from w w w . java2 s. c o m * @return HMessage of type hTweet */ private HMessage transformtweet(Status tweet) { HMessage message = new HMessage(); HTweet htweet = new HTweet(); if (("complete").equalsIgnoreCase(content)) { HTweetAuthor hauthortweet = new HTweetAuthor(); //Construct the location HLocation location = new HLocation(); if (tweet.getGeoLocation() != null) { HGeo geo = new HGeo(tweet.getGeoLocation().getLatitude(), tweet.getGeoLocation().getLongitude()); location.setPos(geo); message.setLocation(location); } //Construct the Place if (tweet.getPlace() != null) { if (tweet.getPlace().getStreetAddress() != null) { location.setAddr(tweet.getPlace().getStreetAddress()); } if (tweet.getPlace().getCountryCode() != null) { location.setCountryCode(tweet.getPlace().getCountryCode()); } if ((tweet.getPlace().getPlaceType() != null) && ("city".equalsIgnoreCase(tweet.getPlace().getPlaceType()))) { location.setCity(tweet.getPlace().getName()); } } //Construct the Authortweet JSONObject hauthortweet.setStatus(tweet.getUser().getStatusesCount()); hauthortweet.setFollowers(tweet.getUser().getFollowersCount()); hauthortweet.setFriends(tweet.getUser().getFriendsCount()); hauthortweet.setLocation(tweet.getUser().getLocation()); hauthortweet.setDescription(tweet.getUser().getDescription()); hauthortweet.setProfileImg(tweet.getUser().getProfileImageURL().toString()); hauthortweet.setUrl(tweet.getUser().getURL()); hauthortweet.setCreatedAt(tweet.getUser().getCreatedAt()); hauthortweet.setLang(tweet.getUser().getLang()); hauthortweet.setListeds(tweet.getUser().getListedCount()); hauthortweet.setGeo(tweet.getUser().isGeoEnabled()); hauthortweet.setVerified(tweet.getUser().isVerified()); hauthortweet.setName(tweet.getUser().getName()); //Construct the tweet JSONObject htweet.setId(tweet.getId()); try { htweet.setSource(tweet.getSource()); htweet.setAuthor(hauthortweet); } catch (MissingAttrException e) { log.error("message: ", e); } } // now manage the minimal list of attributes to get from twitter try { htweet.setText(tweet.getText()); } catch (MissingAttrException e) { log.error("message: ", e); } message.setPayload(htweet); message.setType("hTweet"); message.setAuthor(tweet.getUser().getScreenName() + "@twitter.com"); Date createdAt = tweet.getCreatedAt(); message.setPublished(createdAt); if (log.isDebugEnabled()) { log.debug("tweet(" + tweet + ") -> hMessage :" + message); } return message; }
From source file:org.iadb.knl.twitter.twitterknlapi.Twitterro.java
public static void main(String[] args) { // Config.registerSmbURLHandler(); // Config.setProperty("jcifs.smb.client.domain", domain); // Config.setProperty("jcifs.smb.client.username", user); // Config.setProperty("jcifs.smb.client.password", password); try {//from w w w .java 2 s. co m // Config.setProperty("jcifs.netbios.hostname", // Config.getProperty("jcifs.netbios.hostname", // InetAddress.getLocalHost().getHostName())); System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); System.setProperty("http.auth.ntlm.domain", domain); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password.toCharArray()); } }; Authenticator.setDefault(authenticator); Twitter twitter = TwitterFactory.getSingleton(); Status status = twitter.updateStatus("Este arbitro va pitar la final de #bra vrs #uru"); System.out.println("Successfully updated the status to [" + status.getText() + "]."); // Query query = new Query(); // query.setQuery(""); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.ipccenter.newsagg.impl.twitterapi.TwitterPuller.java
public void parsePost(Status status) { News post = new News(); post.setSource("Twitter"); post.setStatus(0);//from w ww.j ava 2 s.c o m post.setContent(status.getText()); StringBuilder url = new StringBuilder(); url.append("http://twitter.com/").append(status.getUser().getScreenName()).append("/statuses/") .append(String.valueOf(status.getId())); post.setUrl(url.toString()); post.setDate(status.getCreatedAt()); //post.setAuthor(status.getUser().getName()); postsList.add(post); }
From source file:org.jibble.simplewebserver.RequestThread.java
License:Open Source License
public void run() { InputStream reader = null;/* ww w . j av a 2 s. c o m*/ try { _socket.setSoTimeout(30000); BufferedReader in = new BufferedReader(new InputStreamReader(_socket.getInputStream())); BufferedOutputStream out = new BufferedOutputStream(_socket.getOutputStream()); String request = in.readLine(); if (request == null || !request.startsWith("GET ") || !(request.endsWith(" HTTP/1.0") || request.endsWith("HTTP/1.1"))) { // Invalid request type (no "GET") sendError(out, 500, "Invalid Method."); return; } String path = request.substring(4, request.length() - 9); if (path.indexOf("collection") > -1) { Twitter twitter = TF.getInstance(); try { // Uncomment to send tweet and test credentials // Status status = twitter.updateStatus("Try this tweet."); String id = "custom-549647846786347008"; int collectionIdIdx = path.indexOf("custom-"); if (collectionIdIdx > 0) { id = path.substring(collectionIdIdx); } List<Status> statuses = twitter.getCustomTimeline(id); sendHeader(out, 200, "text/html", -1, System.currentTimeMillis()); String title = "Tweets for '" + id + "'"; out.write(("<html><head><title>" + title + "</title></head><body><h3>" + title + "</h3><p>\n") .getBytes()); for (int i = 0; i < statuses.size(); i++) { Status status = statuses.get(i); User user = status.getUser(); String blockquote = "<blockquote class=\"twitter-tweet\" lang=\"en\"><p>" + status.getText() + "</p>— " + user.getName() + " (" + user.getScreenName() + ") <a href=\"https://twitter.com/" + user.getScreenName() + "/status/" + status.getId() + "\">DATE5</a></blockquote>"; out.write((blockquote + "<br>\n").getBytes()); } out.write(("</p><hr><p>" + SimpleWebServer.VERSION + "</p><script async src=\"//platform.twitter.com/widgets.js\" charset=\"utf-8\"></script></body><html>") .getBytes()); } catch (TwitterException e) { sendError(out, 500, "Invalid Method."); } out.flush(); out.close(); return; } File file = new File(_rootDir, URLDecoder.decode(path, "UTF-8")).getCanonicalFile(); if (file.isDirectory()) { // Check to see if there is an index file in the directory. File indexFile = new File(file, "index.html"); if (indexFile.exists() && !indexFile.isDirectory()) { file = indexFile; } } if (!file.toString().startsWith(_rootDir.toString())) { // Uh-oh, it looks like some lamer is trying to take a peek // outside of our web root directory. sendError(out, 403, "Permission Denied."); } else if (!file.exists()) { // The file was not found. sendError(out, 404, "File Not Found."); } else if (file.isDirectory()) { // print directory listing if (!path.endsWith("/")) { path = path + "/"; } File[] files = file.listFiles(); sendHeader(out, 200, "text/html", -1, System.currentTimeMillis()); String title = "Index of " + path; out.write( ("<html><head><title>" + title + "</title></head><body><h3>Index of " + path + "</h3><p>\n") .getBytes()); for (int i = 0; i < files.length; i++) { file = files[i]; String filename = file.getName(); String description = ""; if (file.isDirectory()) { description = "<DIR>"; } out.write(("<a href=\"" + path + filename + "\">" + filename + "</a> " + description + "<br>\n") .getBytes()); } out.write(("</p><hr><p>" + SimpleWebServer.VERSION + "</p></body><html>").getBytes()); } else { reader = new BufferedInputStream(new FileInputStream(file)); String contentType = (String) SimpleWebServer.MIME_TYPES.get(Utils.getExtension(file)); if (contentType == null) { contentType = "application/octet-stream"; } sendHeader(out, 200, contentType, file.length(), file.lastModified()); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } reader.close(); } out.flush(); out.close(); } catch (IOException e) { if (reader != null) { try { reader.close(); } catch (Exception anye) { // Do nothing. } } } }
From source file:org.jraf.irondad.handler.twitter.links.TwitterLinksHandler.java
License:Open Source License
@Override public void handleChannelMessage(final Connection connection, final String channel, final String fromNickname, String text, List<String> textAsList, Message message, final HandlerContext handlerContext) throws Exception { final String tweetId = getTweetId(text); if (tweetId == null) { // Text doesn't contain a twitter link: ignore return;//from ww w . jav a 2 s . com } mThreadPool.submit(new Runnable() { @Override public void run() { try { Status status = getTwitter(handlerContext).showStatus(Long.valueOf(tweetId)); String tweetText = status.getText(); connection.send(Command.PRIVMSG, channel, tweetText); } catch (Exception e) { Log.w(TAG, "handleMessage" + tweetId, e); } } }); }
From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java
License:Apache License
/** * Gets the Twitter timeline for a given user. If no user is given the user * registered for the app is used as default. *///from w w w .ja v a 2s.c o m private void getTimeline(WebSocketConnector aConnector, Token aToken) { TokenServer lServer = getServer(); // instantiate response token Token lResponse = lServer.createResponse(aToken); String lMsg; String lUsername = aToken.getString("username"); try { if (mLog.isDebugEnabled()) { mLog.debug( "Receiving timeline for user '" + (lUsername != null ? lUsername : "[not given]") + "'..."); } if (!mCheckAuth(lResponse)) { mLog.error(lResponse.getString("msg")); } else { List<Status> lStatuses; // getting timelines is public so we can use the mTwitter object here if (lUsername != null && lUsername.length() > 0) { lStatuses = mTwitter.getUserTimeline(lUsername); } else { lStatuses = mTwitter.getUserTimeline(); } // return the list of messages as an array of strings... List<String> lMessages = new FastList<String>(); for (Status lStatus : lStatuses) { lMessages.add(lStatus.getUser().getName() + ": " + lStatus.getText()); /* * // If each status is supposed to be sent separately... * Token lItem = TokenFactory.createToken(NS_TWITTER, * BaseToken.TT_EVENT); lItem.setString("username", * lStatus.getUser().getName()); lItem.setString("message", * lStatus.getText()); lServer.sendToken(aConnector, lItem); */ } lResponse.setList("messages", lMessages); if (mLog.isInfoEnabled()) { mLog.info("Twitter timeline for user '" + (lUsername != null ? lUsername : "[not given]") + "' successfully received"); } } } catch (Exception lEx) { lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage(); mLog.error(lMsg); lResponse.setInteger("code", -1); lResponse.setString("msg", lMsg); } // send response to requester lServer.sendToken(aConnector, lResponse); }