Example usage for twitter4j Status getCreatedAt

List of usage examples for twitter4j Status getCreatedAt

Introduction

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

Prototype

Date getCreatedAt();

Source Link

Document

Return the created_at

Usage

From source file:com.spec.CityTwitterSource.java

License:Apache License

/**
 * Start processing events. This uses the Twitter Streaming API to sample
 * Twitter, and process tweets./*  w  ww.j a v a2s.  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.
    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

            flag = false;
            for (int i = 0; i < cities.length; i++) {
                if (status.getUser().getLocation().toLowerCase().contains(cities[i].toLowerCase()))
                    flag = true;
            }
            if (flag) {

                logger.debug(status.getUser().getLocation() + " : " + flag);
                headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime()));
                Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status.getUser()).getBytes(),
                        headers);

                channel.processEvent(event);
            }
        }

        // 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 sw) {
        }
    };

    //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), and set any necessary
    // security information.
    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    // 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.sstrato.flume.source.TwitterSource.java

License:Apache License

/**
 * Start processing events. This uses the Twitter Streaming API to sample
 * Twitter, and process tweets./*from  www .  j av  a  2  s .  co  m*/
 */
@Override
public void start() {

    // ? ?
    final ChannelProcessor channel = getChannelProcessor();

    final Map<String, String> headers = new HashMap<String, String>();

    // ?  twitter4j? StatusListener   ?   ?. 

    StatusListener listener = new StatusListener() {
        // The onStatus method is executed every time a new tweet comes in.
        public void onStatus(Status status) {
            // header raw json ?  ? .

            logger.debug(status.getUser().getScreenName() + ": " + status.getText());

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

            channel.processEvent(event);
        }

        // 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) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { this.consumerKey, this.accessToken });
    // Set up the stream's listener (defined above), and set any necessary
    // security information.
    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(this.consumerKey, this.consumerSecret);
    AccessToken token = new AccessToken(this.accessToken, this.accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    // 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.TweetExtractor.java

/**
 * *// w w w.  j a  v  a2s  . c  om
 *
 */
public ArrayList<Tweet> retrieveTweets(String searchWord) {

    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;
    userToSearch = searchWord;

    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) {

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

                // 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) {
                return tweetList;
                // break;
            }

        } catch (TwitterException e) {
            e.printStackTrace();
            break;
        } catch (Exception e) {
            e.printStackTrace();
            break;
        }
    }
    return tweetList;

}

From source file:com.twitt4droid.data.dao.impl.sqlite.ListSQLiteDAO.java

License:Apache License

/** {@inheritDoc} */
@Override//from  w  w w .  jav a2 s  .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 w w  .j  a va  2  s . 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.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 a v  a 2 s .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.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;
    }//  w  w  w.  j a  v a 2 s . com

    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  w w. ja  v  a  2  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.j  a v a  2  s  . co 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;
}

From source file:com.wso2.stream.connector.protocol.TweetContent.java

License:Open Source License

public OMElement createBodyContent(OMFactory omFactory, Status status) {
    OMElement tweet = omFactory.createOMElement(qTweet);

    OMElement text = omFactory.createOMElement(qText);
    tweet.addChild(text);/*w  w  w.  j  a v  a 2 s .  com*/
    text.addChild(omFactory.createOMText(status.getText()));

    OMElement createdAt = omFactory.createOMElement(qCreatedAt);
    tweet.addChild(createdAt);
    createdAt.addChild(omFactory.createOMText(status.getCreatedAt().toString()));

    OMElement latitude = omFactory.createOMElement(qLatitude);
    tweet.addChild(latitude);
    OMElement longitude = omFactory.createOMElement(qLongitude);
    tweet.addChild(longitude);
    if (status.getGeoLocation() != null) {
        latitude.addChild(omFactory.createOMText(String.valueOf(status.getGeoLocation().getLatitude())));
        longitude.addChild(omFactory.createOMText(String.valueOf(status.getGeoLocation().getLongitude())));
    }

    OMElement country = omFactory.createOMElement(qCountry);
    tweet.addChild(country);
    OMElement countryCode = omFactory.createOMElement(qCountryCode);
    tweet.addChild(countryCode);

    if (status.getPlace() != null) {
        country.addChild(omFactory.createOMText(status.getPlace().getCountry()));
        countryCode.addChild(omFactory.createOMText(status.getPlace().getCountryCode()));
    }

    OMElement location = omFactory.createOMElement(qLocation);
    tweet.addChild(location);
    if (status.getUser() != null) {
        location.addChild(omFactory.createOMText(status.getUser().getLocation()));
    }

    OMElement hashTags = omFactory.createOMElement(qHasTags);
    tweet.addChild(hashTags);

    if (status.getHashtagEntities().length > 0) {
        String tags = "";
        for (HashtagEntity h : status.getHashtagEntities()) {
            tags += h.getText() + ";";
        }
        tags = tags.substring(0, tags.length() - 1);
        hashTags.addChild(omFactory.createOMText(tags));
    }

    return tweet;

}