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.mycompany.twitterproductanalysistool.TwitterAPI.java

public ArrayList<String> getQuery(String qry) {
    tweets = new ArrayList<>();
    tweetCountries = new ArrayList<>();
    tweetDates = new ArrayList<>();
    try {//from   w  w  w .  ja va 2  s.co  m
        Query query = new Query(qry);
        query.setCount(99);
        result = twitter.search(query);
        for (Status status : result.getTweets()) {
            tweets.add(status.getText());
            tweetDates.add(status.getCreatedAt());
            if (status.getUser() == null) {
                tweetCountries.add("NO COUNTRY");
            } else {
                tweetCountries.add(status.getUser().getLocation());
            }
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    for (int i = 0; i < tweets.size(); i++) {
        String s = tweets.get(i);
        tweets.set(i, s.replace("\n", ""));
    }
    return tweets;
}

From source file:com.mycompany.twittersearch.SearchTwitter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww .  j a v a 2s  .c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {

    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    out.println(twitter.toString());
    String searchItem = request.getParameter("term");

    try {
        Query query = new Query(searchItem);

        QueryResult result = twitter.search(query);

        List<Status> tweets = result.getTweets();
        String list = "";
        for (Status tweet : tweets) {
            list += "@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + "<br>";
        }

        request.setAttribute("list", list);

    } catch (TwitterException te) {
        te.printStackTrace();
        out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    request.getRequestDispatcher("showTweets.jsp").forward(request, response);

}

From source file:com.mycompany.twittersearch.StatusListener.java

public void onStatus(Status status) {
    String list = "@" + status.getUser().getScreenName() + " - " + status.getText();
}

From source file:com.narvis.frontend.twitter.input.Input.java

License:Open Source License

private boolean shouldAnswerTweet(Status status) throws TwitterException {
    // Checking for favorite is useless here
    return (status.getUser().getId() != this.stream.getId()) && !status.isRetweet()
            && isMentionnedIn(status.getUserMentionEntities());
}

From source file:com.narvis.frontend.twitter.input.Input.java

License:Open Source License

private TwitterMessageInOut createMessageFromTweet(Status status) throws IllegalKeywordException {
    return new TwitterMessageInOut(this.accessTwitter.getConf().getName(), getCleanTweet(status.getText()),
            status.getUser().getScreenName() + getOtherResponseName(status.getText()), this.accessTwitter,
            status.getId());/*from   www.j  av a 2s  .  c  o  m*/
}

From source file:com.ocpsoft.hatchling.twitter.PersistentStatusListener.java

License:Open Source License

@Override
public void onStatus(final Status status) {
    Tweet t = new Tweet();
    t.setReceived(status.getCreatedAt());
    t.setText(status.getText());//from   w ww.j a  v  a 2s . c  o  m
    t.setScreenName(status.getUser().getScreenName());
    t.setUserName(status.getUser().getName());
    t.setUserProfileImageURL(status.getUser().getProfileImageURL());
    t.setProfileURL(null);
    t.setTweetId(status.getId());

    URLEntity[] urlEntities = status.getURLEntities();
    if (urlEntities != null) {
        for (URLEntity url : urlEntities) {
            TweetURL tweetURL = new TweetURL();
            if (url.getExpandedURL() != null) {
                tweetURL.setURL(url.getExpandedURL());
            } else if (url.getURL() != null) {
                tweetURL.setURL(url.getURL());
            }
            t.getURLs().add(tweetURL);
        }
    }

    buffer.add(t);
}

From source file:com.ofbizian.camelympics.MainApp.java

License:Open Source License

public static void main(String[] args) throws Exception {
    System.out.println("___________________Camelympics___________________");
    System.out.println("Open your web browser on http://localhost:8080");
    System.out.println("Press ctrl+c to stop this application");
    System.out.println("__________________________________________________");
    Main main = new Main();
    main.enableHangupSupport();/*from   w  w  w. j  a  v  a2 s . c  o m*/
    main.addRouteBuilder(new RouteBuilder() {

        @Override
        public void configure() throws Exception {

            PropertiesComponent properties = new PropertiesComponent();
            properties.setLocation("classpath:app.properties");
            properties.setSystemPropertiesMode(PropertiesComponent.SYSTEM_PROPERTIES_MODE_OVERRIDE);
            getContext().addComponent("properties", properties);

            ThreadPoolProfile throttlerPool = new ThreadPoolProfile("throttlerPool");
            throttlerPool.setRejectedPolicy(ThreadPoolRejectedPolicy.Discard);
            throttlerPool.setMaxQueueSize(10);
            throttlerPool.setMaxPoolSize(2);
            throttlerPool.setPoolSize(2);
            getContext().getExecutorServiceManager().registerThreadPoolProfile(throttlerPool);
            getContext().getShutdownStrategy().setTimeout(1);

            from("twitter://streaming/filter?type=event&keywords={{searchTerm}}&accessToken={{accessToken}}&accessTokenSecret={{accessTokenSecret}}&consumerKey={{consumerKey}}&consumerSecret={{consumerSecret}}")

                    .to("log:tweetStream?level=INFO&groupInterval=10000&groupDelay=50000&groupActiveOnly=false")

                    .process(new Processor() {

                        @Override
                        public void process(Exchange exchange) throws Exception {
                            tweetCount++;
                            Status status = exchange.getIn().getBody(Status.class);
                            MediaEntity[] mediaEntities = status.getMediaEntities();
                            if (mediaEntities != null && !status.isPossiblySensitive()) { //nsfw
                                for (MediaEntity mediaEntity : mediaEntities) {
                                    imageCount++;
                                    exchange.getIn()
                                            .setBody(new Tweet().withName(status.getUser().getScreenName())
                                                    .withText(status.getText()).withCount(tweetCount)
                                                    .withImageCount(imageCount)
                                                    .withTweetUrl(mediaEntity.getDisplayURL().toString())
                                                    .withImageUrl(mediaEntity.getMediaURLHttps().toString()));

                                    exchange.getIn().setHeader("UNIQUE_IMAGE_URL",
                                            mediaEntity.getMediaURL().toString());
                                    break; //grab only the first image
                                }
                            }
                        }
                    })

                    .filter(body().isInstanceOf(Tweet.class))

                    .idempotentConsumer(header("UNIQUE_IMAGE_URL"),
                            MemoryIdempotentRepository.memoryIdempotentRepository(10000))

                    .throttle(1).timePeriodMillis(500).asyncDelayed().executorServiceRef("throttlerPool")

                    .marshal().json(JsonLibrary.Jackson).convertBodyTo(String.class)

                    .to("websocket://0.0.0.0:8080/camelympics?sendToAll=true&staticResources=classpath:web/.");
        }
    });

    main.run();
}

From source file:com.oldterns.vilebot.handlers.user.UrlTweetAnnouncer.java

License:Open Source License

/**
 * Accesses the source of a HTML page and looks for a title element
 * /* w  w  w .j av  a2  s.c om*/
 * @param url http tweet String
 * @return String of text which represents the tweet.  Empty if error.
 */
private String scrapeURLHTMLTitle(String url) {
    String text = "";

    URL page;
    try {
        page = new URL(url);
    } catch (MalformedURLException x) {
        // System.err.format("scrapeURLHTMLTitle new URL error: %s%n", x);
        return text;
    }

    //split the url into pieces, change the request based on what we have
    String parts[] = url.split("/");
    int userPosition = 0;
    long tweetID = 0;
    for (int i = 0; i < parts.length; i++) {

        if (parts[i].toString().equals("twitter.com"))
            userPosition = i + 1;
        if (parts[i].toString().equals("status") || parts[i].toString().equals("statuses"))
            tweetID = Long.valueOf(parts[i + 1].toString()).longValue();
    }
    if (userPosition == 0)
        return text;
    else {
        try {
            String consumerKey = ""; //may be known as 'API key'
            String consumerSecret = ""; //may be known as 'API secret'
            String accessToken = ""; //may be known as 'Access token'
            String accessTokenSecret = ""; //may be known as 'Access token secret'
            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();
            if (tweetID != 0) //tweet of the twitter.com/USERID/status/TWEETID variety
            {
                Status status = twitter.showStatus(tweetID);
                return (status.getUser().getName() + ": " + status.getText());
            } else //just the user is given, ie, twitter.com/USERID 
            {
                User user = twitter.showUser(parts[userPosition].toString());
                if (!user.getDescription().isEmpty()) //the user has a description
                    return ("Name: " + user.getName() + " | " + user.getDescription() + "\'\nLast Tweet: \'"
                            + user.getStatus().getText());
                else //the user doesn't have a description, don't print it
                    return ("Name: " + user.getName() + "\'\nLast Tweet: \'" + user.getStatus().getText());

            }
        } catch (TwitterException x) {
            return text;
        }
    }
}

From source file:com.projectlaver.util.TwitterListingResponseHandler.java

License:Open Source License

public void processStatus(Status status) {

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("+processStatus() with status id: " + status.getId());
    }/*www.j a  va  2 s . co  m*/

    String twitterId = this.longToString(status.getId());
    User profile = status.getUser();

    // Convert twitterIds to Strings here because these fields are treated as varchars by the database
    String providerUserId = this.longToString(profile.getId());
    String inReplyToStatusId = this.longToString(status.getInReplyToStatusId());
    String tweetText = status.getText();
    Boolean isRetweet = (status.getRetweetedStatus() != null);

    // these two fields are required; without an @mention and a #hashtag we do not need to persist this tweet
    String mentionedProviderUserId = this.getMentionedProviderUserId(status.getUserMentionEntities());
    String hashtag = this.getMentionedHashtag(status.getHashtagEntities());

    if (StringUtils.isNoneBlank(mentionedProviderUserId, hashtag)) {

        ReplyMessageDTO dto = new ReplyMessageDTO(SocialProviders.TWITTER, providerUserId, twitterId,
                inReplyToStatusId, null, isRetweet, tweetText, hashtag, INITIAL_STATUS, status.getCreatedAt());

        // Use a try catch here to trap excptions
        try {
            super.processUserMessage(mentionedProviderUserId, dto, false);

            // Retry on deadlock
        } catch (DeadlockLoserDataAccessException e) {

            this.logger.error("Lost deadlock trying to insert tweet. Falling back on retry logic.");
            this.retryProcessAfterDeadlock(mentionedProviderUserId, dto);

            // Log on uncaught exception
        } catch (Exception e) {
            this.logger.error(String.format(
                    "Valid message with id: %s read by stream, but processing failed with an exception.",
                    twitterId), e);
            this.logger.error("UNINSERTED TWEET: " + ToStringBuilder.reflectionToString(dto));
        }
    }

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("-processStatus() with status id: " + status.getId());
    }
}

From source file:com.pulzitinc.flume.source.TwitterSource.java

License:Apache License

/**
 * Start processing events. This uses the Twitter Streaming API to sample
 * Twitter, and process tweets.//from   w w  w  .ja  v a 2s. c o  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.
    UserStreamListener listener = new UserStreamAdapter() {
        // 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() + " - "
                    + TwitterObjectFactory.getRawJSON(status));

            headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime()));
            Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers);

            channel.processEvent(event);
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    logger.debug("Setting up Twitter stream using consumer key {} and access token {}",
            new String[] { consumerKey, accessToken });

    // Set up the stream's listener (defined above),
    twitterStream.addListener(listener);

    logger.debug("Starting up Twitter consuming...");

    twitterStream.user();

    super.start();
}