List of usage examples for twitter4j Status getUser
User getUser();
From source file:com.twitstreet.twitter.FollowBackMgrImpl.java
License:Open Source License
@Override public void start() { Announcer announcer = announcerMgr.randomAnnouncerData(); twitterProxy = twitterProxyFactory.create(announcer.getAccessToken(), announcer.getAccessTokenSecret()); TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret()); twitterStream/* w w w . ja va 2 s. c om*/ .setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret())); twitterStream.addListener(new StatusListener() { @Override public void onException(Exception arg0) { } @Override public void onTrackLimitationNotice(int arg0) { } @Override public void onStatus(Status status) { if (System.currentTimeMillis() - lastFollow > FOLLOW_INTERVAL) { twitter4j.User user = status.getUser(); announcerMgr.follow(user.getId()); lastFollow = System.currentTimeMillis(); } // if(System.currentTimeMillis() - lastFollowDiabloBird > FOLLOW_INTERVAL/6){ // twitter4j.User user = status.getUser(); // announcerMgr.followForDiabloBird(user.getId()); // lastFollowDiabloBird = System.currentTimeMillis(); // } } @Override public void onScrubGeo(long arg0, long arg1) { } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { } }); FilterQuery filterQuery = new FilterQuery(); filterQuery.count(0); filterQuery.track(FILTER_TERMS); twitterStream.filter(filterQuery); }
From source file:com.twitt4droid.data.dao.impl.sqlite.ListSQLiteDAO.java
License:Apache License
/** {@inheritDoc} */ @Override//from w w w .j ava 2s.c om public void save(final List<Status> statuses, final Long listId) { getSQLiteTemplate().batchExecute(getSqlString(R.string.twitt4droid_insert_list_status_sql), new SQLiteTemplate.BatchSQLiteStatementBinder() { @Override public int getBatchSize() { return statuses.size(); } @Override public void bindValues(SQLiteStatement statement, int i) { Status status = statuses.get(i); int index = 0; statement.bindLong(++index, status.getId()); statement.bindLong(++index, listId); statement.bindString(++index, status.getText()); statement.bindString(++index, status.getUser().getScreenName()); statement.bindString(++index, status.getUser().getName()); statement.bindLong(++index, status.getCreatedAt().getTime()); statement.bindString(++index, status.getUser().getProfileImageURL()); } }); }
From source file:com.twitt4droid.data.dao.impl.sqlite.TimelineSQLiteDAO.java
License:Apache License
/** {@inheritDoc} */ @Override/*from w ww .jav a 2s .c o m*/ public void save(final List<Status> statuses) { getSQLiteTemplate().batchExecute( String.format(getSqlString(R.string.twitt4droid_insert_status_sql), tableName), new SQLiteTemplate.BatchSQLiteStatementBinder() { @Override public int getBatchSize() { return statuses.size(); } @Override public void bindValues(SQLiteStatement statement, int i) { Status status = statuses.get(i); int index = 0; statement.bindLong(++index, status.getId()); statement.bindString(++index, status.getText()); statement.bindString(++index, status.getUser().getScreenName()); statement.bindString(++index, status.getUser().getName()); statement.bindLong(++index, status.getCreatedAt().getTime()); statement.bindString(++index, status.getUser().getProfileImageURL()); } }); }
From source file:com.twitter.graphjet.demo.TwitterStreamReader.java
License:Open Source License
public static void main(String[] argv) throws Exception { final TwitterStreamReaderArgs args = new TwitterStreamReaderArgs(); CmdLineParser parser = new CmdLineParser(args, ParserProperties.defaults().withUsageWidth(90)); try {//from www . ja v a 2 s. c o m parser.parseArgument(argv); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); return; } final Date demoStart = new Date(); final MultiSegmentPowerLawBipartiteGraph userTweetBigraph = new MultiSegmentPowerLawBipartiteGraph( args.maxSegments, args.maxEdgesPerSegment, args.leftSize, args.leftDegree, args.leftPowerLawExponent, args.rightSize, args.rightDegree, args.rightPowerLawExponent, new IdentityEdgeTypeMask(), new NullStatsReceiver()); final MultiSegmentPowerLawBipartiteGraph tweetHashtagBigraph = new MultiSegmentPowerLawBipartiteGraph( args.maxSegments, args.maxEdgesPerSegment, args.leftSize, args.leftDegree, args.leftPowerLawExponent, args.rightSize, args.rightDegree, args.rightPowerLawExponent, new IdentityEdgeTypeMask(), new NullStatsReceiver()); // Note that we're keeping track of the nodes on the left and right sides externally, apart from the bigraphs, // because the bigraph currently does not provide an API for enumerating over nodes. Currently, this is liable to // running out of memory, but this is fine for the demo. Long2ObjectOpenHashMap<String> users = new Long2ObjectOpenHashMap<>(); LongOpenHashSet tweets = new LongOpenHashSet(); Long2ObjectOpenHashMap<String> hashtags = new Long2ObjectOpenHashMap<>(); // It is accurate of think of these two data structures as holding all users and tweets observed on the stream since // the demo program was started. StatusListener listener = new StatusListener() { long statusCnt = 0; public void onStatus(Status status) { String screenname = status.getUser().getScreenName(); long userId = status.getUser().getId(); long tweetId = status.getId(); long resolvedTweetId = status.isRetweet() ? status.getRetweetedStatus().getId() : status.getId(); HashtagEntity[] hashtagEntities = status.getHashtagEntities(); userTweetBigraph.addEdge(userId, resolvedTweetId, (byte) 0); if (!users.containsKey(userId)) { users.put(userId, screenname); } if (!tweets.contains(tweetId)) { tweets.add(tweetId); } if (!tweets.contains(resolvedTweetId)) { tweets.add(resolvedTweetId); } for (HashtagEntity entity : hashtagEntities) { long hashtagHash = (long) entity.getText().toLowerCase().hashCode(); tweetHashtagBigraph.addEdge(tweetId, hashtagHash, (byte) 0); if (!hashtags.containsKey(hashtagHash)) { hashtags.put(hashtagHash, entity.getText().toLowerCase()); } } statusCnt++; // Note that status updates are currently performed synchronously (i.e., blocking). Best practices dictate that // they should happen on another thread so as to not interfere with ingest, but this is okay for the pruposes // of the demo and the volume of the sample stream. // Minor status update: just print counters. if (statusCnt % args.minorUpdateInterval == 0) { long duration = (new Date().getTime() - demoStart.getTime()) / 1000; System.out.println(String.format( "%tc: %,d statuses, %,d unique tweets, %,d unique hashtags (observed); " + "%.2f edges/s; totalMemory(): %,d bytes, freeMemory(): %,d bytes", new Date(), statusCnt, tweets.size(), hashtags.size(), (float) statusCnt / duration, Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory())); } // Major status update: iterate over right and left nodes. if (statusCnt % args.majorUpdateInterval == 0) { int leftCnt = 0; LongIterator leftIter = tweets.iterator(); while (leftIter.hasNext()) { if (userTweetBigraph.getLeftNodeDegree(leftIter.nextLong()) != 0) leftCnt++; } int rightCnt = 0; LongIterator rightIter = hashtags.keySet().iterator(); while (rightIter.hasNext()) { if (userTweetBigraph.getRightNodeDegree(rightIter.nextLong()) != 0) rightCnt++; } System.out.println(String.format("%tc: Current user-tweet graph state: %,d left nodes (users), " + "%,d right nodes (tweets)", new Date(), leftCnt, rightCnt)); } } public void onScrubGeo(long userId, long upToStatusId) { } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onStallWarning(StallWarning warning) { } public void onException(Exception e) { e.printStackTrace(); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); Server jettyServer = new Server(args.port); jettyServer.setHandler(context); context.addServlet(new ServletHolder(new TopUsersServlet(userTweetBigraph, users)), "/userTweetGraph/topUsers"); context.addServlet( new ServletHolder( new TopTweetsServlet(userTweetBigraph, tweets, TopTweetsServlet.GraphType.USER_TWEET)), "/userTweetGraph/topTweets"); context.addServlet(new ServletHolder( new TopTweetsServlet(tweetHashtagBigraph, tweets, TopTweetsServlet.GraphType.TWEET_HASHTAG)), "/tweetHashtagGraph/topTweets"); context.addServlet(new ServletHolder(new TopHashtagsServlet(tweetHashtagBigraph, hashtags)), "/tweetHashtagGraph/topHashtags"); context.addServlet(new ServletHolder(new GetEdgesServlet(userTweetBigraph, GetEdgesServlet.Side.LEFT)), "/userTweetGraphEdges/users"); context.addServlet(new ServletHolder(new GetEdgesServlet(userTweetBigraph, GetEdgesServlet.Side.RIGHT)), "/userTweetGraphEdges/tweets"); context.addServlet(new ServletHolder(new GetEdgesServlet(tweetHashtagBigraph, GetEdgesServlet.Side.LEFT)), "/tweetHashtagGraphEdges/tweets"); context.addServlet(new ServletHolder(new GetEdgesServlet(tweetHashtagBigraph, GetEdgesServlet.Side.RIGHT)), "/tweetHashtagGraphEdges/hashtags"); context.addServlet(new ServletHolder(new GetSimilarHashtagsServlet(tweetHashtagBigraph, hashtags)), "/similarHashtags"); System.out.println(String.format("%tc: Starting service on port %d", new Date(), args.port)); try { jettyServer.start(); jettyServer.join(); } finally { jettyServer.destroy(); } }
From source file:com.twitter.tokyo.kucho.daemon.KuchoController.java
License:Apache License
@Override public void onStatus(Status status) { String screenName = status.getUser().getScreenName(); // lookup modules for the user's seat List<String> modules = seatingList.getVentilationModules(status.getUser().getScreenName()); if (modules.size() == 0) { // user is not in the list. do nothing return;//from w w w .ja v a 2 s . c om } String text = status.getText().toLowerCase().replaceAll("", "#"); // does the tweet contain room name? for (String roomName : seatingList.getRooms()) { if (text.contains(roomName)) { modules = seatingList.getVentilationModulesIn(roomName); break; } } int degree = 2; if (text.matches( ".*(???|????|??|??|??|???|???|?|max|||???|?|?|????|??|?|" + "|???|?|?||??|??|???|????|???|???|??|?|??" + "|too|very|extremely|intensively).*")) { degree = 4; } for (String hot : HOT) { if (text.contains(hot)) { degree = degree * -1; break; } } String message = null; String imagePath = null; String powerfully = Math.abs(degree) == 4 ? "????" : ""; if (degree < 0) { if (ehills.adjust(degree, modules)) { message = "@" + screenName + " " + powerfully + "?????? " + Message.getMessage(); imagePath = "/atsui.jpg"; } else { message = "@" + screenName + " ???????????"; imagePath = "/kucho.jpg"; } } else { if (ehills.adjust(degree, modules)) { message = "@" + screenName + " " + powerfully + "?????? " + Message.getMessage(); imagePath = "/samui.jpg"; } else { message = "@" + screenName + " ??????????????"; imagePath = "/kucho.jpg"; } } System.out.println("messaage:" + message + " " + imagePath); try { if (!dryRun) { imagePath = "src/main/resources" + imagePath; if (!new File(".").getAbsolutePath().contains("kucho-daemon")) { imagePath = "kucho-daemon/" + imagePath; } File imageFile = new File(imagePath); if (imageFile.exists()) { TwitterFactory.getSingleton().updateStatus( new StatusUpdate(message).media(imageFile).inReplyToStatusId(status.getId())); } else { TwitterFactory.getSingleton() .updateStatus(new StatusUpdate(message).inReplyToStatusId(status.getId())); } } } catch (TwitterException e) { logger.error("failed to update status", e); } }
From source file:com.utad.flume.source.TwitterSource.java
License:Apache License
/** * Start processing events. This uses the Twitter Streaming API to sample * Twitter, and process tweets./*from w ww . j ava 2s . co m*/ */ @Override public void start() { // The channel is the piece of Flume that sits between the Source and Sink, // and is used to process events. final ChannelProcessor channel = getChannelProcessor(); final Map<String, String> headers = new HashMap<String, String>(); // The StatusListener is a twitter4j API, which can be added to a Twitter // stream, and will execute methods every time a message comes in through // the stream. StatusListener listener = new StatusListener() { // The onStatus method is executed every time a new tweet comes in. public void onStatus(Status status) { // The EventBuilder is used to build an event using the headers and // the raw JSON of a tweet logger.debug(status.getUser().getScreenName() + ": " + status.getText()); headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime())); Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers); List<Event> events = Arrays.asList(event); channel.processEventBatch(events); } // This listener will ignore everything except for new tweets public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onScrubGeo(long userId, long upToStatusId) { } public void onException(Exception ex) { } public void onStallWarning(StallWarning warning) { } }; logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}", new String[] { consumerKey, accessToken }); // Set up the stream's listener (defined above), twitterStream.addListener(listener); // Set up a filter to pull out industry-relevant tweets if (keywords.length == 0) { logger.debug("Starting up Twitter sampling..."); twitterStream.sample(); } else { logger.debug("Starting up Twitter filtering..."); FilterQuery query = new FilterQuery().track(keywords); twitterStream.filter(query); } super.start(); }
From source file:com.varaneckas.hawkscope.plugins.twitter.TwitterPlugin.java
License:Open Source License
/** * Lists twitter messages in a menu//from ww w. java2 s . c o m * * @param repMenu * @param messages */ private void listMessages(final Menu repMenu, final List<Status> messages) { try { for (final Status reply : messages) { String msg = reply.getUser().getName().concat(": ").concat(reply.getText().replaceAll("\\n", " ")); MenuItem mi = new MenuItem(repMenu, SWT.PUSH); if (msg.length() > 80) { msg = msg.substring(0, 79).concat("..."); } mi.setText(msg); mi.setImage(twitter.getUserImage(reply.getUser())); mi.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent selectionevent) { widgetSelected(selectionevent); } public void widgetSelected(SelectionEvent selectionevent) { Program.launch(twitter.getBaseURL() + reply.getUser().getScreenName() + "/status/" + reply.getId()); } }); } } catch (final Exception e) { log.warn("Failed listing replies", e); } }
From source file:com.vodafone.twitter.service.TwitterService.java
License:Apache License
private boolean processStatus(Status status) { if (msgWithSameId(status.getId()) != null) { if (Config.LOGD) Log.i(LOGTAG, "processStatus() found msgWithSameId " + status.getId() + " - don't process"); return false; }// ww w . ja v a2 s . co m boolean newMsgReceived = false; User user = status.getUser(); String channelImageString = null; try { java.net.URI uri = user.getProfileImageURL().toURI(); channelImageString = uri.toString(); } catch (java.net.URISyntaxException uriex) { Log.e(LOGTAG, String.format("ConnectThread processStatus() URISyntaxException %s ex=%s", user.getProfileImageURL().toString(), uriex)); errMsg = uriex.getMessage(); } String title = status.getText(); if (linkifyMessages) { title = linkify(title, null, true); // messageLink will contain the link-url } long timeMs = status.getCreatedAt().getTime(); // make timeMs unique in our messageList while (findIdxOfMsgWithSameTimeMs(timeMs) >= 0) timeMs++; EntryTopic feedEntry = new EntryTopic(0, 0, user.getName(), title, null, messageLink, timeMs, status.getId(), channelImageString); feedEntry.shortName = user.getScreenName(); synchronized (messageList) { // messageList is always sorted with the newest items on top int findIdxOfFirstOlder = findIdxOfFirstOlderMsg(feedEntry); if (findIdxOfFirstOlder < maxQueueMessages) { messageList.add(findIdxOfFirstOlder, feedEntry); newMsgReceived = true; totalNumberOfQueuedMessages++; if (activityPaused) numberOfQueuedMessagesSinceLastClientActivity++; // debug: for every regular msg, create 5 additional dummy messages //for(int i=1; i<=5; i++) { // feedEntry = new EntryTopic(0, // region // 0, // prio // "dummy", // "test message "+i, // null, // description // messageLink, // timeMs+i*100, // status.getId()+i, // todo: make sure the id was ot yet stored in messageList // channelImageString); // todo: must make use of this in MyWebView/JsObject/script.js // messageList.add(findIdxOfFirstOlder,feedEntry); // totalNumberOfQueuedMessages++; // if(activityPaused) // numberOfQueuedMessagesSinceLastClientActivity++; //} // if there are now more than 'maxQueueMessages' entrys in the queue, remove the oldest... while (messageList.size() > maxQueueMessages) messageList.removeLast(); } else { if (Config.LOGD) Log.i(LOGTAG, "processStatus() not findIdxOfFirstOlder<maxQueueMessages - don't process"); } } return newMsgReceived; }
From source file:com.vti.managers.TwitterManager.java
License:Apache License
/** * Get homeline of the user/* w ww . ja v a2 s .c o m*/ * * @return List<Twits> */ public List<Twit> getSocialFeed() { List<Twit> twits = null; try { // User user = twitter.verifyCredentials(); final List<Status> statues = twitter.getHomeTimeline(); twits = new ArrayList<Twit>(statues.size()); long oneDayAgo = System.currentTimeMillis() - Constants.THIRTY_MINUTE * 48; for (Status status : statues) { // only return tweets from VTI accounts and that are not old than 1 day if (status.getUser().getName().toLowerCase().startsWith("vti_") && status.getCreatedAt().getTime() > oneDayAgo) { //Log.d(TwitterManager.class.getSimpleName(), status.getUser().getName() + " " + status.getText()); twits.add(new Twit(status.getId(), status.getCreatedAt().getTime(), status.getUser().getName(), status.getUser().getProfileImageURL().toString(), status.getText())); } } } catch (Exception e) { Log.d(TAG, Log.stack2string(e)); } return twits; }
From source file:com.vti.managers.TwitterManager.java
License:Apache License
/** * Get timeline of a specified user/*from w w w. ja v a 2 s .c o m*/ * * @return List<Twits> */ public List<Twit> getUserTimeline(String userName) { List<Twit> twits = null; try { // User user = twitter.verifyCredentials(); final List<Status> statues = twitter.getUserTimeline(userName); twits = new ArrayList<Twit>(statues.size()); for (Status status : statues) { Log.e(TAG, status.getText()); twits.add(new Twit(status.getId(), status.getCreatedAt().getTime(), status.getUser().getName(), status.getUser().getProfileImageURL().toString(), status.getText())); } } catch (Exception e) { Log.d(TAG, Log.stack2string(e)); } return twits; }