Example usage for twitter4j Status getId

List of usage examples for twitter4j Status getId

Introduction

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

Prototype

long getId();

Source Link

Document

Returns the id of the status

Usage

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

License:Apache License

/** {@inheritDoc} */
@Override//from w  w  w .j  a  v a  2s.c  om
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 .j  av  a2s .  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  ww  . j  av  a 2s. c o m
    }

    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.varaneckas.hawkscope.plugins.twitter.TwitterPlugin.java

License:Open Source License

/**
 * Lists twitter messages in a menu/*from w w w  . j a  v  a  2s  .  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;
    }/*from   w  ww . j  a va2 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/*from  www  .  j  a  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// www  .jav  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.yfiton.notifiers.twitter.TwitterNotifier.java

License:Apache License

@Override
protected void notify(Parameters parameters) throws NotificationException {
    try {//from w w w. j av  a 2 s. co m
        StatusUpdate statusUpdate = new StatusUpdate(status);
        Status status = twitter.updateStatus(statusUpdate);

        log.info("https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId());
    } catch (TwitterException e) {
        throw new NotificationException(new String[] { e.getErrorMessage(),
                "Error code " + e.getErrorCode() + ": https://dev.twitter.com/overview/api/response-codes" },
                e);
    }
}

From source file:crawler.DataStorage.java

License:Apache License

private static void sqlStore(Status status) throws SQLException {
    long sql_pid = Settings.pid;
    Settings.pid++;/* ww w . ja v a  2  s .  c  om*/

    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss, z");
    String sqlCreateAt = tempDate.format(new java.util.Date(status.getCreatedAt().getTime()));

    double sqlGeoLocationLat = 0;
    double sqlGeoLocationLong = 0;

    if (status.getGeoLocation() != null) {
        sqlGeoLocationLat = status.getGeoLocation().getLatitude();
        sqlGeoLocationLong = status.getGeoLocation().getLongitude();
    }

    String sqlPlace = (status.getPlace() != null ? status.getPlace().getFullName() : "");
    long sqlId = status.getId();
    String sqlTweet = status.getText().replace("'", "''");
    String sqlSource = status.getSource().replace("'", "''");
    sqlSource = sqlSource.replace("\\", "\\\\");
    String sqlLang = status.getUser().getLang();
    String sqlScreenName = status.getUser().getScreenName();
    String sqlReplyTo = status.getInReplyToScreenName();
    long sqlRtCount = status.getRetweetCount();

    HashtagEntity[] hashs = status.getHashtagEntities();
    String sqlHashtags = "";
    for (HashtagEntity hash : hashs)
        sqlHashtags += hash.getText() + " ";

    pstm.setLong(1, sql_pid);
    pstm.setString(2, sqlCreateAt);
    pstm.setDouble(3, sqlGeoLocationLat);
    pstm.setDouble(4, sqlGeoLocationLong);
    pstm.setString(5, sqlPlace);
    pstm.setLong(6, sqlId);
    pstm.setString(7, sqlTweet);
    pstm.setString(8, sqlSource);
    pstm.setString(9, sqlLang);
    pstm.setString(10, sqlScreenName);
    pstm.setString(11, sqlReplyTo);
    pstm.setLong(12, sqlRtCount);
    pstm.setString(13, sqlHashtags);

    pstm.addBatch();
}

From source file:crawler.TwitterFeed.java

/**
 *
 *//* w  ww.j ava  2s  .  com*/
public void get_tweets() throws SQLException {
    CSVReader cr = new CSVReader();
    ArrayList<String> names = new ArrayList<>();
    Map<String, String> name_ticker;
    names = cr.get_company_names(tickers);
    System.out.println(names);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("WNSycI2GS33ZAwHJ9Fb4A");
    cb.setOAuthConsumerSecret("BBWeSThT3ZV2g9c5BDuUduDyNAWyzouMI0XjQy7KUc");
    cb.setOAuthAccessToken("1852271029-SLfE061bImfcRxWQZpy1pAgpEkfFhg3757Q9JRf");
    cb.setOAuthAccessTokenSecret("1uPSfYPbaENtXFYWsryBIAHnUsmG3pT6lGH0NzxTCGW7O");
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    for (String s : names) {
        String[] temp;
        if (s.contains(",")) {
            temp = s.split(",");
        } else {
            temp = s.split(" ");
        }

        System.out.println(
                "--------------------------------------------------------------------------------------"
                        + temp[0]);
        Query query = new Query("#" + temp[0]);
        query.lang("en");
        int numberOfTweets = 500;
        long lastID = Long.MAX_VALUE;
        ArrayList<Status> tweets = new ArrayList<>();
        while (tweets.size() < numberOfTweets) {
            if (numberOfTweets - tweets.size() > 100) {
                query.setCount(100);
            } else {
                query.setCount(numberOfTweets - tweets.size());
            }
            try {
                QueryResult result = twitter.search(query);
                tweets.addAll(result.getTweets());
                System.out.println("Gathered " + tweets.size() + " tweets");
                for (Status t : tweets) {
                    if (t.getId() < lastID) {
                        lastID = t.getId();
                    }
                }

            } catch (TwitterException te) {
                System.out.println("Couldn't connect: " + te);
            }
            query.setMaxId(lastID - 1);
        }
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CrawledData", "root", "");
        for (int i = 0; i < tweets.size(); i++) {
            Status t = (Status) tweets.get(i);

            //GeoLocation loc = t.getGeoLocation();
            String user = t.getUser().getScreenName();
            String msg = t.getText();
            String time = t.getCreatedAt().toString();
            //if (loc!=null) {
            //    Double lat = t.getGeoLocation().getLatitude();
            //    Double lon = t.getGeoLocation().getLongitude();
            //    System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);
            //} 
            //else{ 
            System.out.println(i + " USER: " + user + " wrote: " + msg + " at: " + time);
            //}
            try {
                Class.forName("com.mysql.jdbc.Driver");

                PreparedStatement ps = con
                        .prepareStatement("INSERT IGNORE INTO TwitterFeed VALUES (?,?,?,?,?)");
                ps.setString(1, s);
                ps.setString(2, cr.get_ticker_from_company(s));
                ps.setString(3, user);
                ps.setString(4, msg);
                ps.setString(5, time);

                int k = ps.executeUpdate();
                if (k <= 0) {
                    System.out.println("Entry Unsuccessful");
                } else {
                    System.out.println("Entry Successful");
                }

            } catch (ClassNotFoundException | SQLException e) {
                System.out.println(e);
            }

        }
        con.close();
    }
}