Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

In this page you can find the example usage for twitter4j Status getUser.

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file:com.temenos.interaction.example.mashup.twitter.Twitter4JConsumer.java

License:Open Source License

/**
 * @param otherUser// ww  w.  ja  va2 s .c o m
 * @return
 */
public Collection<Tweet> requestTweetsByUser(String otherUser) {
    List<Tweet> tweets = new ArrayList<Tweet>();
    try {
        // The factory instance is re-useable and thread safe.
        Twitter twitter = new TwitterFactory().getInstance();
        AccessToken accessToken = loadAccessToken(1);
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(accessToken);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Fetching latest 100 tweets for [" + otherUser + "]");
        }
        // First param of Paging() is the page number, second is the number per page (this is capped around 200 I think.
        Paging paging = new Paging(1, 100);
        List<Status> statuses = twitter.getUserTimeline(otherUser, paging);
        for (Status status : statuses) {
            tweets.add(new Tweet(otherUser, status.getText(),
                    (status.getGeoLocation() != null
                            ? status.getGeoLocation().getLatitude() + ","
                                    + status.getGeoLocation().getLongitude()
                            : "")));
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(
                        status.getUser().getName() + "(" + status.getGeoLocation() + "):" + status.getText());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error on requestTweetsByUser", e);
        throw new TwitterMashupException(e);
    }
    return tweets;
}

From source file:com.tuncaysenturk.jira.plugins.jtp.twitter.JiraTwitterUserStreamListener.java

@Override
public void onStatus(Status status) {
    PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet();
    if (!licenseValidator.isValid()) {
        logger.error(JTPConstants.LOG_PRE + "License problem, see configuration page");
        ExceptionMessagesUtil.addLicenseExceptionMessage();
    } else {//from w ww . j  av a2  s. c  om
        logger.info(JTPConstants.LOG_PRE + "onStatus @" + status.getUser().getScreenName() + " - "
                + status.getText());

        ExceptionMessagesUtil.cleanAllExceptionMessages();

        checkAndSetScreenName();
        if (StringUtils.isEmpty(screenName)) {
            ExceptionMessagesUtil
                    .addExceptionMessage("No Screen name found, please authorize Twitter account!");
            return;
        }
        if (status.getUser().getScreenName().equals(screenName)) {
            // tweet is mine, do not respond it
            return;
        }
        String text = StringUtils.trim(status.getText().replace("@" + screenName, ""));

        if (propSet.getBoolean("onlyFollowers") && !isFollower(status.getUser().getId())) {
            logger.warn(JTPConstants.LOG_PRE + status.getUser().getScreenName()
                    + " is not a follower but mentioned to create issue");
            return;
        }
        String userName = propSet.getString("userId");
        String issueTypeId = propSet.getString("issueTypeId");
        if (status.getInReplyToStatusId() == -1) {
            // -1 means that this is not reply, it's main tweet
            String projectId = propSet.getString("projectId");
            issueService.createIssue(userName, status.getUser().getScreenName(), text,
                    Long.parseLong(projectId), issueTypeId);
        } else if (status.getInReplyToStatusId() > 0) {
            // this is a reply tweet, so add comment to main issue
            long statusId = status.getInReplyToStatusId();
            TweetIssueRel rel = tweetIssueRelService.findTweetIssueRelByTweetStatusId(statusId);
            Long issueId = null;
            if (null != rel)
                issueId = rel.getIssueId();
            if (null != issueId) {
                issueService.addComment(userName, status.getUser().getScreenName(), issueId, text);
                // assosiate this tweet with issue,
                // so that replies to this tweet will be comments to the issue
                tweetIssueRelService.persistRelation(issueId, status.getId());
            }
        }
    }
}

From source file:com.tuncaysenturk.jira.plugins.jtp.twitter.JiraTwitterUserStreamListener.java

public void onRetweet(User source, User target, Status retweetedStatus) {
    logger.info(JTPConstants.LOG_PRE + "just logging, onRetweet @" + retweetedStatus.getUser().getScreenName()
            + " - " + retweetedStatus.getText());
}

From source file:com.twasyl.slideshowfx.server.service.TwitterService.java

License:Apache License

private StatusListener buildTwitterStreamListener() {
    final StatusListener listener = new StatusListener() {
        @Override/*from   w  w w .  ja v a 2 s.  c om*/
        public void onStatus(Status status) {
            final ChatMessage chatMessage = new ChatMessage();
            chatMessage.setId(System.currentTimeMillis() + "");
            chatMessage.setSource(ChatMessageSource.TWITTER);
            chatMessage.setStatus(ChatMessageStatus.NEW);
            chatMessage.setAuthor("@" + status.getUser().getScreenName());
            chatMessage.setContent(status.getText());

            final JsonObject jsonTweet = chatMessage.toJSON();

            TwitterService.this.vertx.eventBus().publish("slideshowfx.chat.attendee.message.add", jsonTweet);
            TwitterService.this.vertx.eventBus().publish("slideshowfx.chat.presenter.message.add", jsonTweet);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

        }

        @Override
        public void onTrackLimitationNotice(int i) {

        }

        @Override
        public void onScrubGeo(long l, long l1) {

        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {

        }

        @Override
        public void onException(Exception e) {
            e.printStackTrace();
        }
    };

    return listener;
}

From source file:com.tweet.analysis.SearchTweets.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param args search query//from   w  w  w  .  j a  va  2  s. c  om
 */
public static void main(String[] args) {
    if (args.length < 1) {
        //System.out.println("java twitter4j.examples.search.SearchTweets [query]");
        //System.exit(-1);
    }
    Twitter twitter = new TwitterFactory().getInstance();
    //twitter.getFollowersList("Kuldeep.loveiit");
    try {
        Query query = new Query("Modi");
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.tweetmyhome.TweetMyHome.java

/**
 * funcion se dispara cuando te mencionan sin ser amigo
 * funcion se dipara cuando alguien que sigues habla cualquier wea
 * funcion se dispara cuando la propia casa twittea
 * @param status /*from w  w w.j av a2  s .  co  m*/
 */
@Override
public void onStatus(Status status) {
    User user = status.getUser();
    debug("onStatus @" + status.getUser().getScreenName() + " : " + status.getText());
    if (TwitterUserUtil.equals(status.getUser().getScreenName(), p.getValueByKey(Key.twitterSuperUser))) {
        debug("Own tweet detected... EXITING function");
        return;
    }
    TweetStringAnalizer tsa;
    try {
        tsa = new TweetStringAnalizer(status.getText(), tweetDictionary);
    } catch (TweetStringException ex) {
        error(ex.toString(), ex);
        return;
    }
    Map<Integer, String> mencionedUsers = tsa.getMencionedUsers();
    if (mencionedUsers != null) {
        boolean isHomeMencioned = false;
        for (Map.Entry<Integer, String> entry : mencionedUsers.entrySet()) {
            if (TwitterUserUtil.equals(entry.getValue(), p.getValueByKey(Key.twitterSuperUser))) {
                isHomeMencioned = true;
                break;
            }
        }
        if (isHomeMencioned) {
            if (!tsa.isErrorFounded()) {
                try {
                    db.add(new SimpleMention(this, status.getId(), status.getUser().getId(), null,
                            status.getText(), Calendar.getInstance().getTimeInMillis()));
                    analyzeAndRespond(user, tsa, false);
                } catch (TwitterException | TweetMyHomeException ex) {
                    error(ex.toString(), ex);
                }
            } else {
                error(tsa.getErrorString().toString());
            }
        } else {
            debug("Users were mencioned, but not this home...");
        }
    } else {
        debug("None user Mencioned...");
    }
}

From source file:com.tweetmyhome.TweetMyHome.java

@Override
public void onFavorite(User source, User target, Status favoritedStatus) {
    debug("onFavorite source:@" + source.getScreenName() + " target:@" + target.getScreenName() + " @"
            + favoritedStatus.getUser().getScreenName() + " - " + favoritedStatus.getText());
}

From source file:com.tweetmyhome.TweetMyHome.java

@Override
public void onUnfavorite(User source, User target, Status unfavoritedStatus) {
    debug("onUnFavorite source:@" + source.getScreenName() + " target:@" + target.getScreenName() + " @"
            + unfavoritedStatus.getUser().getScreenName() + " - " + unfavoritedStatus.getText());
}

From source file:com.twit.AppCrawler.java

public static void main(String[] args) throws TwitterException {

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();//from w w w .ja  va 2 s . c  o  m

    CidadeController cidadeController = new CidadeController(new Cidade());
    List<Cidade> cidades = cidadeController.findEntities();

    String searchStr = "\"#viagem\" ";

    for (Cidade cidade : cidades) {

        //searchStr += "\"" + cidade.getNome() + "\" "; 

    }

    // Create a Query object.
    Query query = new Query(searchStr);

    // Send API request to execute a search with the given query.
    QueryResult result = twitter.search(query);

    // Display search results.
    for (Status status : result.getTweets()) {
        System.out.println("\n@" + status.getUser().getName() + ": " + status.getText());
    }

}

From source file:com.twitstreet.twitter.AdsListenerMgrImpl.java

License:Open Source License

@Override
public void start() {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    Announcer announcer = announcerMgr.randomAnnouncerData();
    twitterStream.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
    twitterStream/*  w  ww .ja  va 2 s .c  o m*/
            .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) {
            HashtagEntity[] hashtagEntities = status.getHashtagEntities();
            String screenName = status.getUser().getScreenName();
            User user = status.getUser();
            if (user != null && (System.currentTimeMillis() - lastMessage > TEN_MIN)) {
                lastMessage = System.currentTimeMillis();

                int action = (int) (ACTION_TYPES * Math.random());
                switch (action) {
                case REGULAR_TWEET:
                    LocalizationUtil lutil = LocalizationUtil.getInstance();
                    int sentenceSize = Integer
                            .parseInt(lutil.get("announcer.sentence.size", LocalizationUtil.DEFAULT_LANGUAGE));
                    int random = (int) (Math.random() * sentenceSize);
                    String rndMessage = lutil.get("announcer.sentence." + random,
                            LocalizationUtil.DEFAULT_LANGUAGE);
                    announcerMgr.announceFromRandomAnnouncer(rndMessage);
                    break;
                case RETWEEET:
                    announcerMgr.retweet(status.getId());
                    break;
                case FAVOURITE:
                    announcerMgr.favourite(status.getId());
                    break;
                default:
                    String message = constructAdsMessage(screenName, hashtagEntities,
                            status.getUser().getLang());
                    announcerMgr.reply(message, status.getId());
                    break;
                }

            }
        }

        @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);
}