Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

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

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file:org.jibble.simplewebserver.RequestThread.java

License:Open Source License

public void run() {
    InputStream reader = null;//from  w w w . jav  a2  s . c o m
    try {
        _socket.setSoTimeout(30000);
        BufferedReader in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
        BufferedOutputStream out = new BufferedOutputStream(_socket.getOutputStream());

        String request = in.readLine();
        if (request == null || !request.startsWith("GET ")
                || !(request.endsWith(" HTTP/1.0") || request.endsWith("HTTP/1.1"))) {
            // Invalid request type (no "GET")
            sendError(out, 500, "Invalid Method.");
            return;
        }
        String path = request.substring(4, request.length() - 9);

        if (path.indexOf("collection") > -1) {

            Twitter twitter = TF.getInstance();
            try {

                // Uncomment to send tweet and test credentials
                // Status status = twitter.updateStatus("Try this tweet.");

                String id = "custom-549647846786347008";
                int collectionIdIdx = path.indexOf("custom-");
                if (collectionIdIdx > 0) {
                    id = path.substring(collectionIdIdx);
                }
                List<Status> statuses = twitter.getCustomTimeline(id);

                sendHeader(out, 200, "text/html", -1, System.currentTimeMillis());

                String title = "Tweets for '" + id + "'";
                out.write(("<html><head><title>" + title + "</title></head><body><h3>" + title + "</h3><p>\n")
                        .getBytes());

                for (int i = 0; i < statuses.size(); i++) {
                    Status status = statuses.get(i);
                    User user = status.getUser();
                    String blockquote = "<blockquote class=\"twitter-tweet\" lang=\"en\"><p>" + status.getText()
                            + "</p>&mdash; " + user.getName() + " (" + user.getScreenName()
                            + ") <a href=\"https://twitter.com/" + user.getScreenName() + "/status/"
                            + status.getId() + "\">DATE5</a></blockquote>";
                    out.write((blockquote + "<br>\n").getBytes());

                }
                out.write(("</p><hr><p>" + SimpleWebServer.VERSION
                        + "</p><script async src=\"//platform.twitter.com/widgets.js\" charset=\"utf-8\"></script></body><html>")
                                .getBytes());

            } catch (TwitterException e) {
                sendError(out, 500, "Invalid Method.");
            }

            out.flush();
            out.close();

            return;

        }

        File file = new File(_rootDir, URLDecoder.decode(path, "UTF-8")).getCanonicalFile();

        if (file.isDirectory()) {
            // Check to see if there is an index file in the directory.
            File indexFile = new File(file, "index.html");
            if (indexFile.exists() && !indexFile.isDirectory()) {
                file = indexFile;
            }
        }

        if (!file.toString().startsWith(_rootDir.toString())) {
            // Uh-oh, it looks like some lamer is trying to take a peek
            // outside of our web root directory.
            sendError(out, 403, "Permission Denied.");
        } else if (!file.exists()) {
            // The file was not found.
            sendError(out, 404, "File Not Found.");
        } else if (file.isDirectory()) {
            // print directory listing
            if (!path.endsWith("/")) {
                path = path + "/";
            }
            File[] files = file.listFiles();
            sendHeader(out, 200, "text/html", -1, System.currentTimeMillis());
            String title = "Index of " + path;
            out.write(
                    ("<html><head><title>" + title + "</title></head><body><h3>Index of " + path + "</h3><p>\n")
                            .getBytes());
            for (int i = 0; i < files.length; i++) {
                file = files[i];
                String filename = file.getName();
                String description = "";
                if (file.isDirectory()) {
                    description = "&lt;DIR&gt;";
                }
                out.write(("<a href=\"" + path + filename + "\">" + filename + "</a> " + description + "<br>\n")
                        .getBytes());
            }
            out.write(("</p><hr><p>" + SimpleWebServer.VERSION + "</p></body><html>").getBytes());
        } else {
            reader = new BufferedInputStream(new FileInputStream(file));

            String contentType = (String) SimpleWebServer.MIME_TYPES.get(Utils.getExtension(file));
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            sendHeader(out, 200, contentType, file.length(), file.lastModified());

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = reader.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            reader.close();
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception anye) {
                // Do nothing.
            }
        }
    }
}

From source file:org.junjun.twitter.GetUserTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]/*from ww w  . j a va2 s. c o m*/
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        List<Status> statuses;
        String user;
        Paging paging = new Paging(1);
        paging.setCount(100);
        if (args.length == 1) {
            user = args[0];
            /* statuses = twitter.getUserTimeline(Long.parseLong(user),paging);*/
            statuses = twitter.getUserTimeline(Long.parseLong(user));
        } else {
            user = twitter.verifyCredentials().getScreenName();
            statuses = twitter.getUserTimeline();
        }
        System.out.println("Showing @" + user + "'s user timeline.");
        int i = 0;

        for (Status status : statuses) {
            System.out.println(i++ + "@" + status.getUser().getName() + " - " + status + "  ");
        }

        System.out.println();
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

/**
 * Gets the Twitter timeline for a given user. If no user is given the user
 * registered for the app is used as default.
 *//*w ww. jav a 2s.c o m*/
private void getTimeline(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg;
    String lUsername = aToken.getString("username");

    try {
        if (mLog.isDebugEnabled()) {
            mLog.debug(
                    "Receiving timeline for user '" + (lUsername != null ? lUsername : "[not given]") + "'...");
        }
        if (!mCheckAuth(lResponse)) {
            mLog.error(lResponse.getString("msg"));
        } else {
            List<Status> lStatuses;
            // getting timelines is public so we can use the mTwitter object here
            if (lUsername != null && lUsername.length() > 0) {
                lStatuses = mTwitter.getUserTimeline(lUsername);
            } else {
                lStatuses = mTwitter.getUserTimeline();
            }
            // return the list of messages as an array of strings...
            List<String> lMessages = new FastList<String>();
            for (Status lStatus : lStatuses) {
                lMessages.add(lStatus.getUser().getName() + ": " + lStatus.getText());
                /*
                 * // If each status is supposed to be sent separately...
                 * Token lItem = TokenFactory.createToken(NS_TWITTER,
                 * BaseToken.TT_EVENT); lItem.setString("username",
                 * lStatus.getUser().getName()); lItem.setString("message",
                 * lStatus.getText()); lServer.sendToken(aConnector, lItem);
                 */
            }
            lResponse.setList("messages", lMessages);
            if (mLog.isInfoEnabled()) {
                mLog.info("Twitter timeline for user '" + (lUsername != null ? lUsername : "[not given]")
                        + "' successfully received");
            }
        }
    } catch (Exception lEx) {
        lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.kawalpemilukada.web.controller.SentimentAnalysis.java

private void cariText(JSONArray returnVals, Twitter twitter, String topic) throws ParseException {
    try {/*w  w  w.  java2 s. co  m*/
        Query query = new Query(topic);
        query.setCount(100);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                JSONObject returnVal = new JSONObject();
                returnVal.put("Text", tweet.getText());
                //returnVal.put("HashtagEntities", tweet.getHashtagEntities().toString());
                //returnVal.put("UserMentionEntities", tweet.getUserMentionEntities().toString());
                returnVal.put("FavoriteCount", tweet.getFavoriteCount());
                returnVal.put("RetweetCount", tweet.getRetweetCount());
                returnVal.put("UserImg", tweet.getUser().getBiggerProfileImageURLHttps().toString());
                returnVal.put("UserLink",
                        "https://twitter.com/" + CommonServices.getVal(tweet.getUser().getScreenName()));
                returnVal.put("CreatedAt", JakartaTime(tweet.getCreatedAt()).toString());
                returnVals.add(returnVal);
            }
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        te.printStackTrace();
    }
}

From source file:org.kie.io.Entry.java

License:Apache License

public Entry(final Status status) {
    this.title = "@" + status.getUser().getScreenName() + ": " + status.getText();
    this.link = "https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId();
    this.createdAt = new DateTime(status.getCreatedAt());
    this.type = EntryType.Twitter;
}

From source file:org.kuali.mobility.conference.controllers.ConferenceController.java

License:Open Source License

@RequestMapping(value = "twitter-search", method = RequestMethod.GET)
public ResponseEntity<String> twitterSearch(@RequestParam(value = "term", required = true) String searchParam,
        @RequestParam(value = "since", required = false) String sinceParam, HttpServletRequest request) {

    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query(searchParam.isEmpty() ? "#kualidays" : searchParam);
    QueryResult result = null;/*  w w  w. ja v a  2s. c  o  m*/
    query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01");
    query.setCount(100);
    query.setResultType(Query.MIXED);
    String json = "";
    List<String> tweetList = new ArrayList<String>();

    try {
        result = twitter.search(query);
    } catch (TwitterException e) {
        System.err.println("Caught 'twitterSearch' IOException: " + e.getMessage());
    }

    String tweetInfo = "";
    for (Status status : result.getTweets()) {
        tweetInfo = "{";
        tweetInfo += "\"id\" : \"" + status.getId() + "\", ";
        tweetInfo += "\"avatar\" : \"" + status.getUser().getProfileImageURL() + "\", ";
        tweetInfo += "\"tweetedOn\" : \"" + status.getCreatedAt() + "\", ";
        tweetInfo += "\"tweetedOnParsed\" : \"" + status.getCreatedAt().getTime() + "\", ";
        tweetInfo += "\"screenname\" : \"" + status.getUser().getScreenName() + "\", ";
        tweetInfo += "\"status\" : \""
                + StringEscapeUtils.escapeHtml(status.getText().replaceAll("(\\r|\\n)", "")) + "\", ";
        tweetInfo += "\"truncated\" : \"" + (status.isTruncated() ? "true" : "false") + "\",";
        tweetInfo += "\"retweeted\" : \"" + (status.isRetweet() ? "true" : "false") + "\"";
        tweetInfo += "}";

        tweetList.add(tweetInfo);
    }

    json = "[" + StringUtils.arrayToDelimitedString(tweetList.toArray(), ",") + "]";

    return new ResponseEntity<String>(json, HttpStatus.OK);
}

From source file:org.manalith.ircbot.plugin.tweetreader.TweetReader.java

License:Open Source License

private String getText(String twitterurl, UrlType type) {
    if (type == null)
        return null;

    // init twitter4j
    try {//from   ww  w  .  java2  s.c  om
        initTwitter4j();
    } catch (TwitterException e) {
        return e.getMessage();
    }

    if (StringUtils.isEmpty(config.getString("com.twitter.accessKey"))
            || StringUtils.isEmpty(config.getString("com.twitter.accessSecret"))) {
        try {
            authorizeTwitter();
        } catch (TwitterException e) {
            return "[twitter4j.TwitterException] " + e.getMessage();
        } catch (ConfigurationException e) {
            return "[org.apache.common.configuration.ConfigutaionException] " + e.getMessage();
        }
    } else {
        String accessToken = config.getString("com.twitter.accessKey");
        String accessSecret = config.getString("com.twitter.accessSecret");

        setAcecssToken(accessToken, accessSecret);
    }

    Status stat = null;
    try {
        stat = getStatus(twitterurl, type);
    } catch (TwitterException e) {
        return "[twitter4j.TwitterException] " + e.getMessage();
    }

    if (stat == null)
        return null;

    String author = stat.getUser().getName();
    String createdAt = DateFormatUtils.format(stat.getCreatedAt(), TARGET_DATE_PATTERN);
    String message = stat.getText();

    return String.format("?: %s, ?: %s, : %s", author, createdAt, message);
}

From source file:org.mariotaku.twidere.model.ParcelableStatus.java

License:Open Source License

public ParcelableStatus(final Status orig, final long account_id, final boolean is_gap) {
    this.is_gap = is_gap;
    this.account_id = account_id;
    id = orig.getId();/*from w w w  .  j av a  2s .  c o  m*/
    timestamp = getTime(orig.getCreatedAt());

    final Status retweeted = orig.getRetweetedStatus();
    final User retweet_user = retweeted != null ? orig.getUser() : null;
    is_retweet = orig.isRetweet();
    retweet_id = retweeted != null ? retweeted.getId() : -1;
    retweet_timestamp = retweeted != null ? getTime(retweeted.getCreatedAt()) : -1;
    retweeted_by_user_id = retweet_user != null ? retweet_user.getId() : -1;
    retweeted_by_user_name = retweet_user != null ? retweet_user.getName() : null;
    retweeted_by_user_screen_name = retweet_user != null ? retweet_user.getScreenName() : null;
    retweeted_by_user_profile_image = retweet_user != null ? retweet_user.getProfileImageUrlHttps() : null;

    final Status quoted = orig.getQuotedStatus();
    final User quote_user = quoted != null ? orig.getUser() : null;
    is_quote = orig.isQuote();
    quote_id = quoted != null ? quoted.getId() : -1;
    quote_text_html = TwitterContentUtils.formatStatusText(orig);
    quote_text_plain = orig.getText();
    quote_text_unescaped = HtmlEscapeHelper.toPlainText(quote_text_html);
    quote_timestamp = orig.getCreatedAt().getTime();
    quote_source = orig.getSource();

    quoted_by_user_id = quote_user != null ? quote_user.getId() : -1;
    quoted_by_user_name = quote_user != null ? quote_user.getName() : null;
    quoted_by_user_screen_name = quote_user != null ? quote_user.getScreenName() : null;
    quoted_by_user_profile_image = quote_user != null ? quote_user.getProfileImageUrlHttps() : null;
    quoted_by_user_is_protected = quote_user != null && quote_user.isProtected();
    quoted_by_user_is_verified = quote_user != null && quote_user.isVerified();

    final Status status;
    if (quoted != null) {
        status = quoted;
    } else if (retweeted != null) {
        status = retweeted;
    } else {
        status = orig;
    }
    final User user = status.getUser();
    user_id = user.getId();
    user_name = user.getName();
    user_screen_name = user.getScreenName();
    user_profile_image_url = user.getProfileImageUrlHttps();
    user_is_protected = user.isProtected();
    user_is_verified = user.isVerified();
    user_is_following = user.isFollowing();
    text_html = TwitterContentUtils.formatStatusText(status);
    media = ParcelableMedia.fromStatus(status);
    quote_media = quoted != null ? ParcelableMedia.fromStatus(orig) : null;
    text_plain = status.getText();
    retweet_count = status.getRetweetCount();
    favorite_count = status.getFavoriteCount();
    reply_count = status.getReplyCount();
    descendent_reply_count = status.getDescendentReplyCount();
    in_reply_to_name = TwitterContentUtils.getInReplyToName(retweeted != null ? retweeted : orig);
    in_reply_to_screen_name = (retweeted != null ? retweeted : orig).getInReplyToScreenName();
    in_reply_to_status_id = (retweeted != null ? retweeted : orig).getInReplyToStatusId();
    in_reply_to_user_id = (retweeted != null ? retweeted : orig).getInReplyToUserId();
    source = status.getSource();
    location = ParcelableLocation.fromGeoLocation(status.getGeoLocation());
    is_favorite = status.isFavorited();
    text_unescaped = HtmlEscapeHelper.toPlainText(text_html);
    my_retweet_id = retweeted_by_user_id == account_id ? id : status.getCurrentUserRetweet();
    is_possibly_sensitive = status.isPossiblySensitive();
    mentions = ParcelableUserMention.fromUserMentionEntities(status.getUserMentionEntities());
    card = ParcelableCardEntity.fromCardEntity(status.getCard(), account_id);
    place_full_name = getPlaceFullName(status.getPlace());
    card_name = card != null ? card.name : null;
}

From source file:org.mariotaku.twidere.task.CacheUsersStatusesTask.java

License:Open Source License

@SafeVarargs
@Override//from  w  ww . j a v  a 2  s  .  co  m
protected final Object doInBackground(final TwitterListResponse<twitter4j.Status>... args) {
    if (args == null || args.length == 0)
        return null;
    final ContentResolver resolver = context.getContentResolver();
    final Extractor extractor = new Extractor();

    for (final TwitterListResponse<twitter4j.Status> response : args) {
        if (response == null || response.list == null) {
            continue;
        }
        final List<twitter4j.Status> list = response.list;
        for (int bulkIdx = 0, totalSize = list.size(); bulkIdx < totalSize; bulkIdx += 100) {
            for (int idx = bulkIdx, end = Math.min(totalSize,
                    bulkIdx + ContentResolverUtils.MAX_BULK_COUNT); idx < end; idx++) {
                final twitter4j.Status status = list.get(idx);

                final Set<ContentValues> usersValues = new HashSet<>();
                final Set<ContentValues> statusesValues = new HashSet<>();
                final Set<ContentValues> hashTagValues = new HashSet<>();

                statusesValues.add(createStatus(status, response.accountId));
                for (final String hashtag : extractor.extractHashtags(status.getText())) {
                    final ContentValues values = new ContentValues();
                    values.put(CachedHashtags.NAME, hashtag);
                    hashTagValues.add(values);
                }
                usersValues.add(createCachedUser(status.getUser()));
                if (status.isRetweet()) {
                    usersValues.add(createCachedUser(status.getRetweetedStatus().getUser()));
                }

                bulkInsert(resolver, CachedStatuses.CONTENT_URI, statusesValues);
                bulkInsert(resolver, CachedHashtags.CONTENT_URI, hashTagValues);
                bulkInsert(resolver, CachedUsers.CONTENT_URI, usersValues);
            }
        }
    }

    return null;
}

From source file:org.mariotaku.twidere.util.CacheUsersStatusesTask.java

License:Open Source License

@Override
protected Void doInBackground(final Void... args) {
    if (all_statuses == null || all_statuses.length == 0)
        return null;
    final Extractor extractor = new Extractor();
    final Set<ContentValues> cached_users_values = new HashSet<ContentValues>();
    final Set<ContentValues> cached_statuses_values = new HashSet<ContentValues>();
    final Set<ContentValues> hashtag_values = new HashSet<ContentValues>();
    final Set<Long> user_ids = new HashSet<Long>();
    final Set<Long> status_ids = new HashSet<Long>();
    final Set<String> hashtags = new HashSet<String>();
    final Set<User> users = new HashSet<User>();
    final boolean large_preview_image = Utils
            .getImagePreviewDisplayOptionInt(context) == IMAGE_PREVIEW_DISPLAY_OPTION_CODE_LARGE;

    for (final TwitterListResponse<twitter4j.Status> values : all_statuses) {
        if (values == null || values.list == null) {
            continue;
        }//from  w  ww .ja va 2 s . co m
        final List<twitter4j.Status> list = values.list;
        for (final twitter4j.Status status : list) {
            if (status == null || status.getId() <= 0) {
                continue;
            }
            status_ids.add(status.getId());
            cached_statuses_values.add(makeStatusContentValues(status, values.account_id, large_profile_image,
                    large_preview_image));
            hashtags.addAll(extractor.extractHashtags(status.getText()));
            final User user = status.getUser();
            if (user != null && user.getId() > 0) {
                users.add(user);
            }
        }
    }

    bulkDelete(resolver, CachedStatuses.CONTENT_URI, CachedStatuses.STATUS_ID, status_ids, null, false);
    bulkInsert(resolver, CachedStatuses.CONTENT_URI, cached_statuses_values);

    for (final String hashtag : hashtags) {
        final ContentValues hashtag_value = new ContentValues();
        hashtag_value.put(CachedHashtags.NAME, hashtag);
        hashtag_values.add(hashtag_value);
    }
    bulkDelete(resolver, CachedHashtags.CONTENT_URI, CachedHashtags.NAME, hashtags, null, true);
    bulkInsert(resolver, CachedHashtags.CONTENT_URI, hashtag_values);

    for (final User user : users) {
        user_ids.add(user.getId());
        cached_users_values.add(makeCachedUserContentValues(user, large_profile_image));
    }
    bulkDelete(resolver, CachedUsers.CONTENT_URI, CachedUsers.USER_ID, user_ids, null, false);
    bulkInsert(resolver, CachedUsers.CONTENT_URI, cached_users_values);
    return null;
}