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:ezbake.training.TweetIngestParser.java

License:Apache License

private Tweet convertToTweet(Status status) {
    Tweet tweet = new Tweet();
    tweet.setTimestamp(status.getCreatedAt().getTime());
    tweet.setId(status.getId());
    tweet.setText(status.getText());/*from  w w  w.ja va  2 s .c om*/
    tweet.setUserId(status.getUser().getId());
    tweet.setUserName(status.getUser().getName());
    tweet.setIsFavorite(status.isFavorited());
    tweet.setIsRetweet(status.isRetweet());
    if (status.getGeoLocation() != null) {
        tweet.setGeoLocation(
                new Coordinate(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
    }
    return tweet;
}

From source file:flight_ranker.Flight_colllector.java

public static void main(String[] args) throws FileNotFoundException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);//from ww  w  . j  ava 2 s  .c  o m
    cb.setOAuthConsumerKey("Oa6WAzH0j3sgVrP0CNGvxnWA2");
    cb.setOAuthConsumerSecret("sLdoFybvJvVFz7Lxbbv9KWQDFeKcVeZAkWDC4QMHnx5lV2OmGE");
    cb.setOAuthAccessToken("2691889945-5NOBWKUgT9FiAoyOQSCFg8CLlPRlDMbWcUrJBdK");
    cb.setOAuthAccessTokenSecret("J6tA8Sxrtz2JNSFdQwAonbGxNfLNuD9I54Zfvomku3p5t");

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();
            long followers = user.getFollowersCount();

            long retweets = status.getRetweetCount();

            long favs = status.getFavoriteCount();

            System.out.println("USERNAME--> " + username);
            System.out.println("FOLLOWERS--> " + followers);
            String profileLocation = user.getLocation();

            //                System.out.println("RETWEETS--> "+retweets);

            //                System.out.println("FAVOURITES--> "+favs);

            System.out.println("LOCATION--> " + profileLocation);
            long tweetId = status.getId();
            System.out.println("TWEET ID--> " + tweetId);
            String content = status.getText();
            System.out.println("TWEET--> " + content + "\n");

            BufferedWriter b1 = null, b2, b3, b4, b5, b6, b7 = null;

            try {
                //output_file = new BufferedReader(new FileReader("G:\\Sentiwords.txt"));

                FileWriter f1 = new FileWriter("G:\\flights_data.txt", true);
                b1 = new BufferedWriter(f1);
                b1.write("#USERNAME- " + username);
                b1.newLine();

                b1.write("#Followers- " + followers);

                b1.newLine();

                b1.write("#Location- " + profileLocation);

                b1.newLine();
                b1.write("#ID- " + tweetId);

                b1.newLine();
                b1.write("#Tweet- " + content);
                b1.newLine();
                b1.newLine();

                tweet_editor modified_tweet = new tweet_editor(content);
                //tweet_tagger tagged_tweet = new tweet_tagger(modified_tweet.edited_tweet);
                //System.out.println(tagged_tweet.tagged);

                sentiment_calculator senti_value = new sentiment_calculator(modified_tweet.edited_tweet);

                if (content.contains("Indigo")) {
                    System.out.println("indigo");
                    FileWriter f2 = new FileWriter("G:\\Indigo.txt", true);
                    b2 = new BufferedWriter(f2);
                    b2.write(Double.toString(senti_value.senti_rate));
                    b2.newLine();
                }

                if (content.contains("Jet")) {
                    System.out.println("jet");
                    FileWriter f3 = new FileWriter("G:\\jet.txt", true);
                    b3 = new BufferedWriter(f3);
                    b3.write(Double.toString(senti_value.senti_rate));
                    b3.newLine();
                }

                if (content.contains("Indian")) {
                    System.out.println("indian");
                    FileWriter f4 = new FileWriter("G:\\Indian.txt", true);
                    b4 = new BufferedWriter(f4);
                    b4.write(Double.toString(senti_value.senti_rate));
                    b4.newLine();
                }

                if (content.contains("Spicejet")) {
                    System.out.println("spicejet");
                    FileWriter f5 = new FileWriter("G:\\spicejet.txt", true);
                    b5 = new BufferedWriter(f5);
                    b5.write(Double.toString(senti_value.senti_rate));
                    b5.newLine();
                }

                if (content.contains("AirAsia")) {
                    System.out.println("airasia");
                    FileWriter f6 = new FileWriter("G:\\airasia.txt", true);
                    b6 = new BufferedWriter(f6);
                    b6.write(Double.toString(senti_value.senti_rate));
                    b6.newLine();
                }

                try {
                    //output_file = new BufferedReader(new FileReader("G:\\Sentiwords.txt"));

                    FileWriter f7 = new FileWriter("G:\\flight_senti.txt", true);
                    b7 = new BufferedWriter(f7);
                    b7.write(String.valueOf(senti_value.senti_rate));
                    b7.newLine();

                }

                catch (IOException e) {
                    e.printStackTrace();
                }

                finally {
                    try {
                        b7.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Flight_colllector.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }

            catch (IOException e) {
                e.printStackTrace();
            }

            finally {
                try {
                    b1.close();
                } catch (IOException ex) {
                    Logger.getLogger(Flight_colllector.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

    FilterQuery fq = new FilterQuery();

    String keywords[] = {
            "Indian Airlines, Indigo Airlines, Indigo Airline , Indian Airline , Spicejet , jetAirways , Jet Airways, Jet Airlines , airasia" }; //we will pass stock related keyword here

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);

}

From source file:gh.polyu.user.TrackUsers.java

License:Apache License

public void track(final int no, final int p) {
    final TwitterDBHandle handle = new TwitterDBHandle();
    handle.intialTwitterDBhandle();//  w  ww. j a va2  s  .  c  o  m

    while (alive) {
        alive = false;
        StatusListener listener = new StatusListener() {
            ArrayList<_TweetLink> listlink = new ArrayList<_TweetLink>();
            int cnt = 0;
            String oldmonth = "20138";
            String table = "UserTweet20138";
            String oldday = "";
            String currentday = "";
            String currentmonth = "";
            long lastinsert = 0l;
            long nowinsert = 0l;
            int newday = 0;
            String newtime = "";

            @Override

            public void onStatus(Status status) {
                if (status.getId() == 123 && status.getText().equals("YOU are WORNG!.")) {
                    System.out.println("Connection Need to be rebuilt!!");
                    alive = true;
                } else if (status.getLang().equals("en")) {
                    _TweetLink tweet = new _TweetLink();
                    String Test = status.getText();
                    tweet.setText(Test);
                    Date time = status.getCreatedAt();
                    tweet.setTime(time);
                    tweet.setUserName(status.getUser().getName());
                    HashtagEntity[] hashtagentity = status.getHashtagEntities();
                    StringBuffer hashen = new StringBuffer();
                    for (int i = 0; i < hashtagentity.length; i++) {
                        hashen.append(hashtagentity[i].getText());
                        hashen.append(";");

                    }
                    tweet.setHashtag(hashen.toString());

                    URLEntity[] URLEn = status.getURLEntities();
                    StringBuffer URL = new StringBuffer();
                    for (int i = 0; i < URLEn.length; i++) {
                        URL.append(URLEn[i].getURL());
                        URL.append(";");

                    }
                    tweet.setURL(URL.toString());

                    //user mention
                    UserMentionEntity[] userEn = status.getUserMentionEntities();
                    StringBuffer mentuser = new StringBuffer();
                    for (int i = 0; i < userEn.length; i++) {
                        mentuser.append(userEn[i].getId());
                        mentuser.append(";");
                    }
                    tweet.setUerMention(mentuser.toString());
                    //if(mentuser.length()!=0);
                    //System.out.println("mentuser: "+ mentuser);
                    //tweetID
                    tweet.setTweetID(status.getId());
                    //if(ID!=null)
                    // original twitterID
                    tweet.setOriginID(status.getInReplyToStatusId());
                    //original user ID
                    tweet.setOriginUser(status.getInReplyToUserId());

                    // user ID

                    User users = status.getUser();
                    tweet.setTweetUser(users.getId());

                    //places
                    Place Pl = status.getPlace();
                    String place = "";
                    if (Pl != null) {
                        place = Pl.getFullName();
                        //System.out.println("place "+place);
                    }
                    tweet.setPlace(place);
                    // Retweetcoun
                    long num = 0;
                    if (status.getRetweetedStatus() != null) {
                        num = status.getRetweetedStatus().getRetweetCount();
                        //System.out.println("retweetcount"+num);
                        tweet.setRetweetCount(num);
                        tweet.setRetweet(1);
                    } else {
                        tweet.setRetweetCount(0);
                        tweet.setRetweet(0);
                    }
                    //   if(Retweet!=null)

                    //System.out.println("Retweetcount: "+ Retweet);

                    //isfavourate
                    boolean favourate = status.isFavorited();
                    /*if(favourate)
                    {
                    fav = 1;
                    tweet.setFavourate(fav);
                    fav =0;
                    System.out.println("isf "+ fav);
                    }*/

                    // is retweet

                    //String other = status.toString();
                    // tweet.setOther(other);
                    listlink.add(tweet);
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH) + 1;
                    int day = cal.get(Calendar.DAY_OF_MONTH);
                    currentmonth = String.valueOf(year) + String.valueOf(month);
                    currentday = String.valueOf(day);
                    if (currentmonth.equals(oldmonth)) {
                        if (currentday.equals(oldday))
                            ;
                        else {
                            newday = 1;
                            SimpleDateFormat formatter = new SimpleDateFormat("MMddHH:mm:ss ");
                            Date curDate = new Date(System.currentTimeMillis());//     
                            newtime = formatter.format(curDate);
                        }
                    } else {
                        try {
                            handle.database_connection();
                            table = "UserTweet" + String.valueOf(year) + String.valueOf(month);
                            System.out.println("create new table " + table);
                            String CREATE_TABLE = "create table " + table
                                    + "(TweetID varchar(100), UserName varchar(200), TwitterUser varchar(145), OriginID varchar(100), OriginUser varchar(100), place varchar(100), RetweetCount varchar(100), isRetweet int(5), Text varchar(500), Time datetime,"
                                    + "Hashtag varchar(200), URL varchar(200), UerMention varchar(200))";
                            Statement st = handle.conn.createStatement();
                            st.execute(CREATE_TABLE);
                            String Create_Index = "alter table " + table + " add index time (Time)";
                            st.execute(Create_Index);
                            String Create_Index2 = "alter table " + table + " add index userID (TwitterUser)";
                            st.execute(Create_Index2);
                            String key = "ALTER TABLE " + table + " ADD PRIMARY KEY (TweetID)";
                            st.execute(key);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        handle.close_databasehandle();
                        try {
                            TwitterDBHandle handle2 = new TwitterDBHandle();
                            handle2.intialTwitterDBhandle2();
                            handle2.database_connection();
                            table = "UserTweet" + String.valueOf(year) + String.valueOf(month);
                            System.out.println("create new table " + table);
                            String CREATE_TABLE = "create table " + table
                                    + "(TweetID varchar(100), UserName varchar(200), TwitterUser varchar(145), OriginID varchar(100), OriginUser varchar(100), place varchar(100), RetweetCount varchar(100), isRetweet int(5), Text varchar(500), Time datetime,"
                                    + "Hashtag varchar(200), URL varchar(200), UerMention varchar(200))";
                            Statement st = handle2.conn.createStatement();
                            st.execute(CREATE_TABLE);
                            String Create_Index = "alter table " + table + " add index time (Time)";
                            st.execute(Create_Index);
                            String Create_Index2 = "alter table " + table + " add index userID (TwitterUser)";
                            st.execute(Create_Index2);
                            String key = "ALTER TABLE " + table + " ADD PRIMARY KEY (TweetID)";
                            st.execute(key);
                            handle2.close_databasehandle();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    //System.out.println("OTHER: "+ other);

                    if ((cnt++) % 1000 == 0) {

                        if (newday == 1) {
                            newday = 0;
                            oldday = currentday;
                            GmailSend gs = new GmailSend("cscchenyoyo@gmail.com", "910316ccy");
                            gs.send("THREAD" + p + " :" + "program no" + no + "message" + newtime,
                                    "I am still alive");
                            newtime = "";
                        }

                        try {
                            handle.database_connection();
                            handle.userTweet(table, listlink);
                            nowinsert = System.currentTimeMillis();
                            System.err.println(
                                    "No: " + no + "program " + "totally " + cnt + " tweets downloaded!\n"
                                            + new Date(nowinsert) + "  " + new Date(lastinsert));
                            lastinsert = nowinsert;
                            nowinsert = 0l;
                            handle.close_databasehandle();
                        } catch (SQLException e) {
                            handle.close_databasehandle();
                            e.printStackTrace();
                            // TODO Auto-generated catch block
                            TwitterDBHandle handle2 = new TwitterDBHandle();
                            handle2.intialTwitterDBhandle2();
                            handle2.database_connection();

                            try {
                                handle2.userTweet(table, listlink);
                                nowinsert = System.currentTimeMillis();
                                System.err.println("New Database No: " + no + "program " + "totally " + cnt
                                        + " tweets downloaded!\n" + new Date(nowinsert) + new Date(lastinsert));
                                lastinsert = nowinsert;
                                nowinsert = 0l;
                                handle2.close_databasehandle();
                            } catch (SQLException e1) {
                                // TODO Auto-generated catch block
                                GmailSend gs = new GmailSend("cscchenyoyo@gmail.com", "910316ccy");
                                try {
                                    gs.SendSSLMessage("cscchenyoyo@gmail.com", "program error",
                                            "both databases are down");
                                } catch (MessagingException ee) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            GmailSend gs = new GmailSend("cscchenyoyo@gmail.com", "910316ccy");
                            try {
                                gs.SendSSLMessage("cscchenyoyo@gmail.com", "program error",
                                        "change database to another one");
                            } catch (MessagingException ee) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        listlink.clear();
                    }
                }
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                //System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                //System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                //System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                //System.out.println("Got stall warning:" + warning);
            }

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

            }
        };
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
        twitterOAuth twtOauth = new twitterOAuth();
        twtOauth.AuthoritywithS(twitterStream, key);
        twitterStream.addListener(listener);
        twitterStream.filter(new FilterQuery(0, follow));

        /*  try {
           Thread.sleep(3000);
                   
        } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/
    }
}

From source file:gohai.simpletweet.SimpleTweet.java

License:Apache License

/**
 *  Send a tweet/*  w  ww . j a v a  2 s .  c  om*/
 *  @param message message to send
 *  @return partial URL of the tweet (e.g. "mrgohai/status/841086396194529280")
 */
public String tweet(String message) {
    try {
        StatusUpdate update = new StatusUpdate(message);
        Status status = twitter.updateStatus(update);

        User user = status.getUser();
        return user.getScreenName() + "/status/" + status.getId();
    } catch (TwitterException e) {
        System.err.println(e.getMessage());
        throw new RuntimeException("Error posting tweet");
    }
}

From source file:gohai.simpletweet.SimpleTweet.java

License:Apache License

/**
 *  Tweet an image/*from   ww  w  . j  a v a  2s  . c  om*/
 *  @param img PImage instance to attach
 *  @param update twitter4j StatusUpdate instance to use
 *  @return partial URL of the tweet (e.g. "mrgohai/status/841086396194529280")
 */
public String tweetImage(PImage img, StatusUpdate update) {
    File temp;

    // write image into temporary file that gets deleted when the VM exits
    try {
        // make sure one pixel is somewhat transparent
        // to prevent Twitter from recompressing the image
        // to JPEG
        PImage copy = new PImage(img.width, img.height, PImage.ARGB);
        copy.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
        copy.set(0, 0, 254 << 24 | (copy.get(0, 0) & 0xffffff));
        temp = File.createTempFile("out", ".png");
        temp.deleteOnExit();
        copy.save(temp.getCanonicalPath());
    } catch (IOException e) {
        throw new RuntimeException("Error exporting image to PNG");
    }

    try {
        update.setMedia(temp);
        Status status = twitter.updateStatus(update);
        temp.delete();

        User user = status.getUser();
        return user.getScreenName() + "/status/" + status.getId();
    } catch (TwitterException e) {
        System.err.println(e.getMessage());
        throw new RuntimeException("Error posting tweet");
    }
}

From source file:h2weibo.controllers.CallbackServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:type");

    if (request.getParameter("denied") != null) {
        response.sendRedirect("/");
        return;/*from   w ww .j  av  a 2 s. co  m*/
    }

    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    String token = (String) session.getAttribute(Keys.SESSION_TOKEN);
    String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET);
    String oauthVerifier = request.getParameter("oauth_verifier");

    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);

    if (r.is(":type", "weibo")) {
        try {
            Weibo weibo = new Weibo();

            AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier);
            if (accessToken != null) {
                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getToken() == null) { // send for the first time
                    session.setAttribute(Keys.SESSION_PROMPT_TWEET,
                            "You are ready to go! Do you want to tweet about this service and share it with your friends?");
                }

                tid.setToken(accessToken.getToken());
                tid.setTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);
            } else {
                log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
            }
        } catch (WeiboException e) {
            log.error("Weibo Exception", e);
            throw new RuntimeException(e);
        }
    } else if (r.is(":type", "twitter")) {
        try {
            TwitterFactory factory = new TwitterFactory();
            Twitter t = factory.getInstance();

            twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN);
            twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier);
            session.removeAttribute(Keys.SESSION_REQUEST_TOKEN);

            if (accessToken != null) {
                t.setOAuthAccessToken(accessToken);
                User user = t.verifyCredentials();
                loginUser = user.getScreenName();

                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getTwitterToken() == null) {
                    // save latest id for the first time. sync from that tweet
                    ResponseList<Status> tl = t.getUserTimeline();
                    if (tl.size() > 0) {
                        Status s = tl.get(0);
                        tid.setLatestId(s.getId());
                    }
                }

                tid.setTwitterToken(accessToken.getToken());
                tid.setTwitterTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);

                session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser);
            }
        } catch (TwitterException e) {
            log.error("Twitter Exception", e);
            throw new RuntimeException(e);
        }
    }

    String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL);
    if (requestUrl != null) {
        session.removeAttribute(Keys.SESSION_REQUEST_URL);
        response.sendRedirect(requestUrl);
    } else {
        response.sendRedirect("/u/" + loginUser);
    }
}

From source file:h2weibo.Twitter2Weibo.java

License:Open Source License

public void syncTwitter(String userId) {
    T2WUser user = helper.findOneByUser(userId);

    weibo.setToken(user.getToken(), user.getTokenSecret());

    Twitter twitter = new TwitterFactory().getInstance();
    if (user.getTwitterToken() != null) {
        twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
        log.debug(String.format("Using OAuth for %s", user.getUserId()));
    }/*from w w  w.  j  a  va  2s .c  o  m*/

    StatusFilters filters = new StatusFilters();
    filters.use(new NoSyncFilter()); // should be used first
    filters.use(new TcoStatusFilter()).use(new URLStatusFilter()).use(new TagStatusFilter())
            .use(new FlickrImageFilter());

    NoMentionFilter mentionFilter = new NoMentionFilter();
    UserMappingFilter mappingFilter = new UserMappingFilter(helper);

    if (!user.ready()) {
        log.debug(String.format("Skipping @%s ...", user.getUserId()));
        return;
    }

    // gets Twitter instance with default credentials
    String screenName = user.getUserId();
    long latestId = user.getLatestId();

    log.debug(String.format("Checking @%s's timeline, latest ID = %d.", userId, latestId));

    try {
        if (latestId == 0) {
            List<Status> statuses = twitter.getUserTimeline(screenName);
            if (statuses.size() > 0) {
                user.setLatestId(statuses.get(0).getId()); // Record latestId, and sync next time
            }
            log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId));
        } else {
            Paging paging = new Paging(latestId);
            List<Status> statuses = twitter.getUserTimeline(screenName, paging);

            // sync from the oldest one
            for (int i = statuses.size() - 1; i >= 0; i--) {
                Status status = statuses.get(i);

                if (status.getId() < user.getLatestId())
                    continue; // safe keeper

                String name = status.getUser().getScreenName();
                String statusText = status.getText();
                log.info(String.format("%s - %s", name, statusText));
                try {
                    if (status.isRetweet()) {
                        if (user.isDropRetweets()) {
                            user.setLatestId(status.getId());
                            log.debug("Skipped " + statusText + " because status is a retweet.");
                            continue;
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    } else {
                        if (user.isDropMentions()) {
                            filters.remove(mappingFilter);
                            filters.use(mentionFilter);
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    }

                    statusText = filters.filter(statusText);
                    if (statusText == null) {
                        user.setLatestId(status.getId());
                        log.info(String.format("Skipped %s because of the filter.", statusText));
                        continue;
                    }

                    if (!user.isNoImage()) {
                        // add twitter images to status text
                        MediaEntity[] mediaEntities = status.getMediaEntities();
                        if (mediaEntities != null) {
                            for (MediaEntity entity : mediaEntities) {
                                statusText += " " + entity.getMediaURL();
                            }
                            log.info("with media url: " + statusText);
                        }

                        StatusImageExtractor ex = new StatusImageExtractor();
                        StringBuffer buf = new StringBuffer(statusText);
                        byte[] image = ex.extract(buf);
                        if (image != null) {
                            user.setLatestId(status.getId());
                            try {
                                statusText = buf.toString(); // with image urls removed
                                weibo.uploadStatus(statusText, new ImageItem(image));
                                log.info(String.format("@%s - %s sent with image.", name, statusText));
                            } catch (WeiboException e) {
                                log.error("Faile to update image.", e);
                            }
                            continue;
                        }
                    }

                    GeoLocation location = status.getGeoLocation();
                    if (user.isWithGeo() && location != null) {
                        weibo.updateStatus(statusText, location.getLatitude(), location.getLongitude());
                        log.info(String.format("@%s - %s sent with geo locations.", name, statusText));
                    } else {
                        weibo.updateStatus(statusText);
                        log.info(String.format("@%s - %s sent.", name, statusText));
                    }
                } catch (WeiboException e) {
                    if (e.getStatusCode() != 400) { // resending same tweet
                        log.error("Failed to update Weibo", e);
                        break;
                    } else {
                        log.error("Sending same message", e);
                    }
                }
                log.info(String.format("Sent: by %s - %s", name, statusText));
                user.setLatestId(status.getId());
            }
        }
        helper.saveUser(user);
    } catch (Exception e) {
        if (!(e instanceof TwitterException)) {
            log.error("Failed to update.", e);
        }
    }
}

From source file:ikemen.Main.java

License:Apache License

public static void main(String[] args) {
    final Twitter twitter = TwitterFactory.getSingleton();
    final TwitterStream stream = TwitterStreamFactory.getSingleton();
    stream.addListener(new UserStreamAdapter() {
        public void onStatus(Status status) {
            if (yonda(status.getText())) {
                try {
                    twitter.createFavorite(status.getId());
                } catch (TwitterException ignore) {
                }/*from   w  w w  .j av  a 2 s . c o m*/
                try {
                    twitter.sendDirectMessage("yusuke", "http://twitter.com/yusuke/status/" + status.getId());
                } catch (TwitterException ignore) {
                }
            }
        }
    });
    stream.user();
}

From source file:info.maslowis.twitterripper.command.impl.twitter.TweetDeleteAll.java

License:Open Source License

@Override
public void execute() throws ExecuteCmdException {
    try {/*from   www .j a va  2  s.  com*/
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.RED)
                .a("This command delete all yours statuses! You want to continue? [yes/no]").reset());
        String input = Application.INSTANCE.getReader().readLine();
        if (input.trim().equalsIgnoreCase("yes")) {
            try {
                int page = 1;
                final int count = 200;
                Paging paging = new Paging(page, count);
                ResponseList<Status> statuses = twitter.getUserTimeline(twitter.getId(), paging);
                while (!statuses.isEmpty()) {
                    for (Status status : statuses) {
                        twitter.destroyStatus(status.getId());
                        out.println("You now deleted " + Util.toString(status));
                    }
                    page++;
                    paging = new Paging(page, count);
                    statuses = twitter.getUserTimeline(twitter.getId(), paging);
                }
            } catch (TwitterException e) {
                throw new ExecuteCmdException(e);
            }
        } else {
            out.println("Command was cancelled");
        }
    } catch (IOException e) {
        logger.error("Error reading input", e);
        exit(-1);
    }
}

From source file:info.maslowis.twitterripper.util.Util.java

License:Open Source License

/**
 * Returns a representation the status (tweet) as string
 *
 * @return a representation the status as string in format <em>Status{id=, text='', lang='', createdAt=, geoLocation=, isFavorited=, isRetweeted=, retweetCount=, isTruncated=}</em>
 *//*from  w w  w .  j a va2s. co m*/
public static String toString(final Status status) {
    return "Status{id=" + status.getId() + ", text='" + status.getText() + "', lang='" + status.getLang()
            + "', createdAt=" + status.getCreatedAt() + ", geoLocation=" + status.getGeoLocation()
            + ", isFavorited=" + status.isFavorited() + ", isRetweeted=" + status.isRetweeted()
            + ", retweetCount=" + status.getRetweetCount() + ", isTruncated=" + status.isTruncated() + "}";
}