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.klinker.android.twitter.utils.api_helper.TwitPicHelper.java

License:Apache License

/**
 * posts the status onto Twitlonger, it then posts the shortened status (with link) to the user's twitter and updates the status on twitlonger
 * to include the posted status's id.//  w w  w .java  2  s.co  m
 *
 * @return id of the status that was posted to twitter
 */
public long createPost() {
    TwitPicStatus status = uploadToTwitPic();
    Log.v("talon_twitpic", "past upload");
    long statusId;
    try {
        Status postedStatus;
        StatusUpdate update = new StatusUpdate(status.getText());

        if (replyToStatusId != 0) {
            update.setInReplyToStatusId(replyToStatusId);
        }
        if (location != null) {
            update.setLocation(location);
        }

        postedStatus = twitter.updateStatus(update);

        statusId = postedStatus.getId();
    } catch (Exception e) {
        e.printStackTrace();
        statusId = 0;
    }

    // if zero, then it failed
    return statusId;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

License:Apache License

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {

    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {//from ww  w. j  a v a  2  s  .  co m
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        String responseBody = EntityUtils.toString(response2.getEntity());
        conn.close();

        JSONObject fullJson = new JSONObject(responseBody);
        JSONObject extendedEntities = fullJson.getJSONObject("extended_entities");
        JSONArray media = extendedEntities.getJSONArray("media");

        Log.v("talon_images", media.toString());

        for (int i = 0; i < media.length(); i++) {
            JSONObject entity = media.getJSONObject(i);
            try {
                // parse through the objects and get the media_url
                String url = entity.getString("media_url");
                String type = entity.getString("type");

                // want to check to make sure it doesn't have it already
                // this also checks to confirm that the entity is in fact a photo
                if (!images.contains(url) && type.equals("photo")) {
                    images.add(url);
                }
            } catch (Exception e) {

            }
        }

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

    return images;
}

From source file:com.krossovochkin.kwitter.activities.MainActivity.java

License:Apache License

@Override
public void sendReplyRequest(Status statusToReply, String tweet) {
    new SendReplyAsyncTask(mTwitter, tweet, statusToReply.getId(), this).execute();
}

From source file:com.marklogic.tweetdeck.SaveRawJSON.java

License:Apache License

/**
 * Usage: java twitter4j.examples.json.SaveRawJSON
 *
 * @param args//  ww w .  jav  a  2 s .  c om
 *            String[]
 */
public static void main(String[] args) {
    Twitter twitter = new TwitterFactory().getInstance();
    System.out.println("Saving public timeline.");
    try {
        new File("statuses").mkdir();
        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            String fileName = "statuses/" + status.getId() + ".json";
            storeJSON(rawJSON, fileName);
            System.out.println(fileName + " - " + status.getText());
        }
        System.out.print("\ndone.");
        System.exit(0);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to store tweets: " + ioe.getMessage());
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.marpies.ane.twitter.utils.StatusUtils.java

License:Apache License

public static JSONObject getJSON(Status status) throws JSONException {
    JSONObject statusJSON = new JSONObject();
    statusJSON.put("id", status.getId());
    statusJSON.put("idStr", String.valueOf(status.getId()));
    statusJSON.put("text", status.getText());
    statusJSON.put("replyToUserID", status.getInReplyToUserId());
    statusJSON.put("replyToStatusID", status.getInReplyToStatusId());
    statusJSON.put("likesCount", status.getFavoriteCount());
    statusJSON.put("retweetCount", status.getRetweetCount());
    statusJSON.put("isRetweet", status.isRetweet());
    statusJSON.put("isSensitive", status.isPossiblySensitive());
    statusJSON.put("createdAt", status.getCreatedAt());
    Status retweetedStatus = status.getRetweetedStatus();
    if (retweetedStatus != null) {
        statusJSON.put("retweetedStatus", getJSON(retweetedStatus));
    }/*from   w w w. j av a2  s . c o  m*/
    User user = status.getUser();
    if (user != null) {
        statusJSON.put("user", UserUtils.getJSON(user));
    }
    return statusJSON;
}

From source file:com.michaelfitzmaurice.clocktwerk.TweetResponder.java

License:Apache License

public Collection<Status> getNewMentions() throws TweetException {

    long sinceId = lastSeenMention();
    try {/*  www  .ja v  a  2  s.  c  om*/
        LOG.info("Checking for new Twitter mentions of {} since Tweet {}", myScreenName, sinceId);
        Paging paging = new Paging(sinceId);
        ResponseList<Status> mentions = twitterClient.getMentionsTimeline(paging);
        int numberOfMentions = mentions.size();
        LOG.info("Found {} new mentions", numberOfMentions);
        for (Status status : mentions) {
            User user = status.getUser();
            String mentionSummary = format("Date:%s, ID:%s, From:%s (%s), Text:'%s'", status.getCreatedAt(),
                    status.getId(), user.getScreenName(), user.getName(), status.getText());
            LOG.debug("New mention: [{}]", mentionSummary);
        }
        return mentions;
    } catch (TwitterException e) {
        throw new TweetException("Error getting Twitter mentions", e);
    }

    // TODO handle paging
}

From source file:com.michaelfitzmaurice.clocktwerk.TweetResponder.java

License:Apache License

public void respondToMentions(Collection<Status> mentions) {

    LOG.info("Responding to {} mentions on behalf of {}", mentions.size(), myScreenName);

    long latestMentionSeen = -1;
    for (Status mention : mentions) {
        String replyMessage = replyBody(myScreenName, mention, tweetDatabase.getNextTweet());
        StatusUpdate reply = new StatusUpdate(replyMessage);
        long mentionTweetId = mention.getId();
        reply.setInReplyToStatusId(mentionTweetId);
        LOG.debug("Replying to mention with ID {}", mentionTweetId);
        try {/* ww  w  .  j  a va  2 s  . c om*/
            twitterClient.updateStatus(reply);
            LOG.debug("Replied to mention with ID {}", mentionTweetId);
        } catch (TwitterException e) {
            LOG.error("Failed to reply to Tweet", e);
        }
        // even if we failed to reply, record the mention as seen
        if (mentionTweetId > latestMentionSeen) {
            latestMentionSeen = mentionTweetId;
        }
    }
    LOG.info("Finished replying to new mentions");
    updateLastMentionSeen(latestMentionSeen);
}

From source file:com.mothsoft.alexis.engine.retrieval.TwitterRetrievalTaskImpl.java

License:Apache License

private void handleSourceImpl(final TwitterSource twitterSource) {
    final SocialConnection socialConnection = twitterSource.getSocialConnection();
    final AccessToken accessToken = new AccessToken(socialConnection.getOauthToken(),
            socialConnection.getOauthTokenSecret());

    final List<Status> statuses = this.twitterService.getHomeTimeline(accessToken,
            twitterSource.getLastTweetId(), (short) 800);

    if (statuses != null && statuses.size() > 0) {
        logger.info("Twitter retrieval found " + statuses.size() + " Tweets for user: "
                + socialConnection.getRemoteUsername());

        // the newest tweet in the timeline will be our starting point for
        // the next fetch
        twitterSource.setLastTweetId(statuses.get(0).getId());

        // import these in reverse order to ensure newest ones have the
        // highest document IDs
        Collections.reverse(statuses);

        final Long userId = twitterSource.getUserId();
        final User user = this.userDao.get(userId);

        for (final Status status : statuses) {
            final Long tweetId = status.getId();

            Tweet tweet = this.tweetDao.getTweetByRemoteTweetId(tweetId);
            final boolean isAdd = (tweet == null);

            if (isAdd) {
                // TODO - is this right?
                // Twitter allows 2 different styles of retweets. The
                // ones that are actually retweets show as tweeted by the
                // original user. Others may show
                // "RT @original thing original said" tweeted
                // by the new person
                final boolean retweet = status.isRetweet();

                final twitter4j.User tweeter;
                final String text;
                twitter4j.User retweeter = null;

                final List<TweetLink> links;
                final List<TweetMention> mentions;
                final List<TweetHashtag> hashtags;

                if (retweet) {
                    tweeter = status.getRetweetedStatus().getUser();
                    text = status.getRetweetedStatus().getText();
                    retweeter = status.getUser();
                    links = readLinks(status.getRetweetedStatus());
                    mentions = readMentions(status.getRetweetedStatus());
                    hashtags = readHashtags(status.getRetweetedStatus());
                } else {
                    tweeter = status.getUser();
                    text = status.getText();
                    links = readLinks(status);
                    mentions = readMentions(status);
                    hashtags = readHashtags(status);
                }/*from   ww  w . j ava2 s .  c om*/

                final URL profileImageUrl = tweeter.getProfileImageUrlHttps();
                final Date createdAt = status.getCreatedAt();

                tweet = new Tweet(tweetId, createdAt, tweeter.getScreenName(), tweeter.getName(),
                        profileImageUrl, text, links, mentions, hashtags, retweet,
                        retweet ? retweeter.getScreenName() : null);
                this.documentDao.add(tweet);
            }

            final DocumentUser documentUser = new DocumentUser(tweet, user);

            if (isAdd || !tweet.getDocumentUsers().contains(documentUser)) {
                tweet.getDocumentUsers().add(new DocumentUser(tweet, user));
                this.documentDao.update(tweet);
            }
        }
    } else {
        logger.info("Twitter retrieval found no Tweets for user: " + socialConnection.getRemoteUsername());
    }

    twitterSource.setRetrievalDate(new Date());
    this.sourceDao.update(twitterSource);
}

From source file:com.mycompany.omnomtweets.RetweetersOfCandidate.java

/**
 * Method to get the 200 most recent tweets from a candidate.
 * @return List of 200 most recent tweet ids.
 *///  w ww .  j  ava 2 s . c  om
public List<String> getCandidateTweetIds() {
    List<String> candidateTweetIds = new ArrayList<>();

    //First try to read in unprocessed tweets
    List<String> processedIds = new ArrayList<>();
    String tempFileName = (candidate.name + "Tweets.txt").replace(" ", "");
    File f1 = new File(tempFileName);
    FileReader fr;
    try {
        fr = new FileReader(f1);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains("Processed")) {
                processedIds.add(line.split(",")[0]);
            } else {
                candidateTweetIds.add(line);
            }
        }
        fr.close();
        br.close();
    } catch (Exception ex) {
        System.out.println("Something went wrong with file IO");
    }

    //If there weren't any unproccessed ones, get some new ones.
    if (candidateTweetIds.isEmpty()) {
        try {
            List<Status> statuses;

            Paging paging = new Paging(1, 200);
            statuses = twitter.getUserTimeline(candidate.account, paging);
            //System.out.println("Gathered: " + statuses.size() + " tweet ids");
            for (Status status : statuses) {
                candidateTweetIds.add(String.valueOf(status.getId()));
            }

            //File to store tweetIds in as an intermediary.
            FileWriter writeCandidateTweets = new FileWriter(new File(tempFileName), true);
            for (String tweetId : candidateTweetIds) {
                writeCandidateTweets.write(tweetId + "\n");
            }
            writeCandidateTweets.close();

        } catch (TwitterException te) {
            System.out.println("Failed to get timeline: " + te.getMessage());
        } catch (IOException ex) {
            Logger.getLogger("FileWriting sucks");
        }
    }
    return candidateTweetIds;
}

From source file:com.mycompany.omnomtweets.Search.java

public static boolean writeToStdErr(Status tweet) {
    //System.out.println("Writing " + tweets.size() + " tweets");
    boolean success = true;
    if (tweet != null) {
        String tweetText;/*from   ww w. j  av a 2 s .  c o m*/
        String idOfRetweetee = "";
        if (tweet.getRetweetedStatus() != null) {
            tweetText = "RT " + tweet.getRetweetedStatus().getText();
            idOfRetweetee = "" + tweet.getRetweetedStatus().getUser().getScreenName();
            //System.out.println("retweeted" + tweetText);
        } else {
            tweetText = tweet.getText();
        }
        String urlText = "";
        if (tweet.getURLEntities().length > 0) {
            for (URLEntity url : tweet.getURLEntities()) {
                if (url.getExpandedURL() != null) {
                    urlText += url.getExpandedURL() + " ";
                    tweetText = tweetText.replace(url.getURL(), url.getExpandedURL());
                    //System.out.println("Expanded URL " + url.getExpandedURL());
                } else {
                    urlText += url.getURL() + " ";
                    //System.out.println("URL " + url.getURL());
                }
            }
        }
        if (tweet.getMediaEntities().length > 0) {
            for (MediaEntity media : tweet.getMediaEntities()) {
                if (media.getExpandedURL() != null) {
                    urlText += media.getExpandedURL() + " ";
                    tweetText = tweetText.replace(media.getMediaURL(), media.getExpandedURL());
                    //System.out.println("Expanded URL " + media.getExpandedURL());
                } else {
                    urlText += media.getMediaURL() + " ";
                    //System.out.println("URL " + media.getMediaURL());
                }
            }
        }
        String encodedText = tweetText.replaceAll("\"", "\"\"");
        encodedText = encodedText.replaceAll("\\s", " ");
        String writeMe = "\"" + encodedText + "\"," + urlText + "," + tweet.getUser().getId() + ","
                + tweet.getId() + "," + candidate.name + "," + sdf.format(tweet.getCreatedAt()) + ","
                + idOfRetweetee + "\n";
        System.err.print(writeMe);
        //writeTweets.write(writeMe);
    }
    return success;
}