Example usage for twitter4j Status getInReplyToUserId

List of usage examples for twitter4j Status getInReplyToUserId

Introduction

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

Prototype

long getInReplyToUserId();

Source Link

Document

Returns the in_reply_user_id

Usage

From source file:org.mariotaku.twidere.service.BackgroundOperationService.java

License:Open Source License

private List<SingleResponse<ParcelableStatus>> updateStatus(final Builder builder,
        final ParcelableStatusUpdate statusUpdate) {
    final ArrayList<ContentValues> hashTagValues = new ArrayList<>();
    final Collection<String> hashTags = extractor.extractHashtags(statusUpdate.text);
    for (final String hashTag : hashTags) {
        final ContentValues values = new ContentValues();
        values.put(CachedHashtags.NAME, hashTag);
        hashTagValues.add(values);//from   w w w  . j  a  va 2  s.  c o  m
    }
    final boolean hasEasterEggTriggerText = statusUpdate.text.contains(EASTER_EGG_TRIGGER_TEXT);
    final boolean hasEasterEggRestoreText = statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART1)
            && statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART2)
            && statusUpdate.text.contains(EASTER_EGG_RESTORE_TEXT_PART3);
    boolean mentionedHondaJOJO = false, notReplyToOther = false;
    mResolver.bulkInsert(CachedHashtags.CONTENT_URI,
            hashTagValues.toArray(new ContentValues[hashTagValues.size()]));

    final List<SingleResponse<ParcelableStatus>> results = new ArrayList<>();

    if (statusUpdate.accounts.length == 0)
        return Collections.emptyList();

    try {
        if (mUseUploader && mUploader == null)
            throw new UploaderNotFoundException(this);
        if (mUseShortener && mShortener == null)
            throw new ShortenerNotFoundException(this);

        final boolean hasMedia = statusUpdate.media != null && statusUpdate.media.length > 0;

        final String overrideStatusText;
        if (mUseUploader && mUploader != null && hasMedia) {
            final MediaUploadResult uploadResult;
            try {
                mUploader.waitForService();
                uploadResult = mUploader.upload(statusUpdate,
                        UploaderMediaItem.getFromStatusUpdate(this, statusUpdate));
            } catch (final Exception e) {
                throw new UploadException(this);
            } finally {
                mUploader.unbindService();
            }
            if (mUseUploader && hasMedia && uploadResult == null)
                throw new UploadException(this);
            if (uploadResult.error_code != 0)
                throw new UploadException(uploadResult.error_message);
            overrideStatusText = getImageUploadStatus(this, uploadResult.media_uris, statusUpdate.text);
        } else {
            overrideStatusText = null;
        }

        final String unShortenedText = isEmpty(overrideStatusText) ? statusUpdate.text : overrideStatusText;

        final boolean shouldShorten = mValidator.getTweetLength(unShortenedText) > mValidator
                .getMaxTweetLength();
        final String shortenedText;
        if (shouldShorten) {
            if (mUseShortener) {
                final StatusShortenResult shortenedResult;
                mShortener.waitForService();
                try {
                    shortenedResult = mShortener.shorten(statusUpdate, unShortenedText);
                } catch (final Exception e) {
                    throw new ShortenException(this);
                } finally {
                    mShortener.unbindService();
                }
                if (shortenedResult == null || shortenedResult.shortened == null)
                    throw new ShortenException(this);
                shortenedText = shortenedResult.shortened;
            } else
                throw new StatusTooLongException(this);
        } else {
            shortenedText = unShortenedText;
        }
        if (statusUpdate.media != null) {
            for (final ParcelableMediaUpdate media : statusUpdate.media) {
                final String path = getImagePathFromUri(this, Uri.parse(media.uri));
                final File file = path != null ? new File(path) : null;
                if (!mUseUploader && file != null && file.exists()) {
                    BitmapUtils.downscaleImageIfNeeded(file, 95);
                }
            }
        }
        for (final ParcelableAccount account : statusUpdate.accounts) {
            final Twitter twitter = getTwitterInstance(this, account.account_id, true, true);
            final StatusUpdate status = new StatusUpdate(shortenedText);
            status.setInReplyToStatusId(statusUpdate.in_reply_to_status_id);
            if (statusUpdate.location != null) {
                status.setLocation(ParcelableLocation.toGeoLocation(statusUpdate.location));
            }
            if (!mUseUploader && hasMedia) {
                final BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                final long[] mediaIds = new long[statusUpdate.media.length];
                ContentLengthInputStream is = null;
                try {
                    for (int i = 0, j = mediaIds.length; i < j; i++) {
                        final ParcelableMediaUpdate media = statusUpdate.media[i];
                        final String path = getImagePathFromUri(this, Uri.parse(media.uri));
                        if (path == null)
                            throw new FileNotFoundException();
                        BitmapFactory.decodeFile(path, o);
                        final File file = new File(path);
                        is = new ContentLengthInputStream(file);
                        is.setReadListener(new StatusMediaUploadListener(this, mNotificationManager, builder,
                                statusUpdate));
                        final MediaUploadResponse uploadResp = twitter.uploadMedia(file.getName(), is,
                                o.outMimeType);
                        mediaIds[i] = uploadResp.getId();
                    }
                } catch (final FileNotFoundException e) {
                    Log.w(LOGTAG, e);
                } catch (final TwitterException e) {
                    final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
                    results.add(response);
                    continue;
                } finally {
                    IoUtils.closeSilently(is);
                }
                status.mediaIds(mediaIds);
            }
            status.setPossiblySensitive(statusUpdate.is_possibly_sensitive);

            if (twitter == null) {
                results.add(new SingleResponse<ParcelableStatus>(null, new NullPointerException()));
                continue;
            }
            try {
                final Status resultStatus = twitter.updateStatus(status);
                if (!mentionedHondaJOJO) {
                    final UserMentionEntity[] entities = resultStatus.getUserMentionEntities();
                    if (entities == null || entities.length == 0) {
                        mentionedHondaJOJO = statusUpdate.text.contains("@" + HONDAJOJO_SCREEN_NAME);
                    } else if (entities.length == 1 && entities[0].getId() == HONDAJOJO_ID) {
                        mentionedHondaJOJO = true;
                    }
                    Utils.setLastSeen(this, entities, System.currentTimeMillis());
                }
                if (!notReplyToOther) {
                    final long inReplyToUserId = resultStatus.getInReplyToUserId();
                    if (inReplyToUserId <= 0 || inReplyToUserId == HONDAJOJO_ID) {
                        notReplyToOther = true;
                    }
                }
                final ParcelableStatus result = new ParcelableStatus(resultStatus, account.account_id, false);
                results.add(new SingleResponse<>(result, null));
            } catch (final TwitterException e) {
                final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
                results.add(response);
            }
        }
    } catch (final UpdateStatusException e) {
        final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
        results.add(response);
    }
    if (mentionedHondaJOJO) {
        triggerEasterEgg(notReplyToOther, hasEasterEggTriggerText, hasEasterEggRestoreText);
    }
    return results;
}

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

License:Open Source License

@NonNull
public static ContentValues createStatus(final Status orig, final long accountId) {
    if (orig == null)
        throw new NullPointerException();
    final ContentValues values = new ContentValues();
    values.put(Statuses.ACCOUNT_ID, accountId);
    values.put(Statuses.STATUS_ID, orig.getId());
    values.put(Statuses.STATUS_TIMESTAMP, orig.getCreatedAt().getTime());
    final Status status;
    if (orig.isRetweet()) {
        final Status retweetedStatus = orig.getRetweetedStatus();
        final User retweetUser = orig.getUser();
        final long retweetedById = retweetUser.getId();
        values.put(Statuses.RETWEET_ID, retweetedStatus.getId());
        values.put(Statuses.RETWEET_TIMESTAMP, retweetedStatus.getCreatedAt().getTime());
        values.put(Statuses.RETWEETED_BY_USER_ID, retweetedById);
        values.put(Statuses.RETWEETED_BY_USER_NAME, retweetUser.getName());
        values.put(Statuses.RETWEETED_BY_USER_SCREEN_NAME, retweetUser.getScreenName());
        values.put(Statuses.RETWEETED_BY_USER_PROFILE_IMAGE, (retweetUser.getProfileImageUrlHttps()));
        values.put(Statuses.IS_RETWEET, true);
        if (retweetedById == accountId) {
            values.put(Statuses.MY_RETWEET_ID, orig.getId());
        } else {//from   w  w  w .j av a2 s  . c o  m
            values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet());
        }
        status = retweetedStatus;
    } else if (orig.isQuote()) {
        final Status quotedStatus = orig.getQuotedStatus();
        final User quoteUser = orig.getUser();
        final long quotedById = quoteUser.getId();
        values.put(Statuses.QUOTE_ID, quotedStatus.getId());
        final String textHtml = TwitterContentUtils.formatStatusText(orig);
        values.put(Statuses.QUOTE_TEXT_HTML, textHtml);
        values.put(Statuses.QUOTE_TEXT_PLAIN, orig.getText());
        values.put(Statuses.QUOTE_TEXT_UNESCAPED, toPlainText(textHtml));
        values.put(Statuses.QUOTE_TIMESTAMP, orig.getCreatedAt().getTime());
        values.put(Statuses.QUOTE_SOURCE, orig.getSource());
        final ParcelableMedia[] quoteMedia = ParcelableMedia.fromStatus(orig);
        if (quoteMedia != null && quoteMedia.length > 0) {
            try {
                values.put(Statuses.QUOTE_MEDIA_JSON,
                        LoganSquare.serialize(Arrays.asList(quoteMedia), ParcelableMedia.class));
            } catch (IOException ignored) {
            }
        }
        values.put(Statuses.QUOTED_BY_USER_ID, quotedById);
        values.put(Statuses.QUOTED_BY_USER_NAME, quoteUser.getName());
        values.put(Statuses.QUOTED_BY_USER_SCREEN_NAME, quoteUser.getScreenName());
        values.put(Statuses.QUOTED_BY_USER_PROFILE_IMAGE, quoteUser.getProfileImageUrlHttps());
        values.put(Statuses.QUOTED_BY_USER_IS_VERIFIED, quoteUser.isVerified());
        values.put(Statuses.QUOTED_BY_USER_IS_PROTECTED, quoteUser.isProtected());
        values.put(Statuses.IS_QUOTE, true);
        status = quotedStatus;
    } else {
        values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet());
        status = orig;
    }
    if (orig.isRetweet()) {
        values.put(Statuses.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
        values.put(Statuses.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
        values.put(Statuses.IN_REPLY_TO_USER_NAME, TwitterContentUtils.getInReplyToName(status));
        values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, status.getInReplyToScreenName());
    } else {
        values.put(Statuses.IN_REPLY_TO_STATUS_ID, orig.getInReplyToStatusId());
        values.put(Statuses.IN_REPLY_TO_USER_ID, orig.getInReplyToUserId());
        values.put(Statuses.IN_REPLY_TO_USER_NAME, TwitterContentUtils.getInReplyToName(orig));
        values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, orig.getInReplyToScreenName());
    }
    final User user = status.getUser();
    final long userId = user.getId();
    final String profileImageUrl = (user.getProfileImageUrlHttps());
    final String name = user.getName(), screenName = user.getScreenName();
    values.put(Statuses.USER_ID, userId);
    values.put(Statuses.USER_NAME, name);
    values.put(Statuses.USER_SCREEN_NAME, screenName);
    values.put(Statuses.IS_PROTECTED, user.isProtected());
    values.put(Statuses.IS_VERIFIED, user.isVerified());
    values.put(Statuses.USER_PROFILE_IMAGE_URL, profileImageUrl);
    values.put(CachedUsers.IS_FOLLOWING, user.isFollowing());
    final String textHtml = TwitterContentUtils.formatStatusText(status);
    values.put(Statuses.TEXT_HTML, textHtml);
    values.put(Statuses.TEXT_PLAIN, status.getText());
    values.put(Statuses.TEXT_UNESCAPED, toPlainText(textHtml));
    values.put(Statuses.RETWEET_COUNT, status.getRetweetCount());
    values.put(Statuses.REPLY_COUNT, status.getReplyCount());
    values.put(Statuses.FAVORITE_COUNT, status.getFavoriteCount());
    values.put(Statuses.DESCENDENT_REPLY_COUNT, status.getDescendentReplyCount());
    values.put(Statuses.SOURCE, status.getSource());
    values.put(Statuses.IS_POSSIBLY_SENSITIVE, status.isPossiblySensitive());
    final GeoLocation location = status.getGeoLocation();
    if (location != null) {
        values.put(Statuses.LOCATION,
                ParcelableLocation.toString(location.getLatitude(), location.getLongitude()));
    }
    final Place place = status.getPlace();
    if (place != null) {
        values.put(Statuses.PLACE_FULL_NAME, place.getFullName());
    }
    values.put(Statuses.IS_FAVORITE, status.isFavorited());
    final ParcelableMedia[] media = ParcelableMedia.fromStatus(status);
    if (media != null && media.length > 0) {
        try {
            values.put(Statuses.MEDIA_JSON, LoganSquare.serialize(Arrays.asList(media), ParcelableMedia.class));
        } catch (IOException ignored) {
        }
    }
    final ParcelableUserMention[] mentions = ParcelableUserMention.fromStatus(status);
    if (mentions != null && mentions.length > 0) {
        try {
            values.put(Statuses.MENTIONS_JSON,
                    LoganSquare.serialize(Arrays.asList(mentions), ParcelableUserMention.class));
        } catch (IOException ignored) {
        }
    }
    final ParcelableCardEntity card = ParcelableCardEntity.fromCardEntity(status.getCard(), accountId);
    if (card != null) {
        try {
            values.put(Statuses.CARD, LoganSquare.serialize(card));
            values.put(Statuses.CARD_NAME, card.name);
        } catch (IOException ignored) {
        }
    }
    return values;
}

From source file:org.smarttechie.servlet.SimpleStream.java

public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out)
{

    listener = new StatusListener() {

        @Override//from w  w w  . jav  a2  s .c o m
        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) {
            Twitter twitter = new TwitterFactory().getInstance();
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();
            System.out.println("");
            String profileLocation = user.getLocation();
            System.out.println(profileLocation);
            long tweetId = status.getId();
            System.out.println(tweetId);
            String content = status.getText();
            System.out.println(content + "\n");

            JSONObject obj = new JSONObject();
            obj.put("User", status.getUser().getScreenName());
            obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''"));
            obj.put("Id", status.getId());
            obj.put("UserId", status.getUser().getId());
            //obj.put("User", status.getUser());
            obj.put("Message", status.getText().replaceAll("'", "''"));
            obj.put("CreatedAt", status.getCreatedAt().toString());
            obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId());
            //Get user retweeteed
            String otheruser;
            try {
                if (status.getCurrentUserRetweetId() != -1) {
                    User user2 = twitter.showUser(status.getCurrentUserRetweetId());
                    otheruser = user2.getScreenName();
                    System.out.println("Other user: " + otheruser);
                }
            } catch (Exception ex) {
                System.out.println("ERROR: " + ex.getMessage().toString());
            }
            obj.put("IsRetweet", status.isRetweet());
            obj.put("IsRetweeted", status.isRetweeted());
            obj.put("IsFavorited", status.isFavorited());

            obj.put("InReplyToUserId", status.getInReplyToUserId());
            //In reply to
            obj.put("InReplyToScreenName", status.getInReplyToScreenName());

            obj.put("RetweetCount", status.getRetweetCount());
            if (status.getGeoLocation() != null) {
                obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude());
                obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude());
            }

            JSONArray listHashtags = new JSONArray();
            String hashtags = "";
            for (HashtagEntity entity : status.getHashtagEntities()) {
                listHashtags.add(entity.getText());
                hashtags += entity.getText() + ",";
            }

            if (!hashtags.isEmpty())
                obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1));

            if (status.getPlace() != null) {
                obj.put("PlaceCountry", status.getPlace().getCountry());
                obj.put("PlaceFullName", status.getPlace().getFullName());
            }

            obj.put("Source", status.getSource());
            obj.put("IsPossiblySensitive", status.isPossiblySensitive());
            obj.put("IsTruncated", status.isTruncated());

            if (status.getScopes() != null) {
                JSONArray listScopes = new JSONArray();
                String scopes = "";
                for (String scope : status.getScopes().getPlaceIds()) {
                    listScopes.add(scope);
                    scopes += scope + ",";
                }

                if (!scopes.isEmpty())
                    obj.put("Scopes", scopes.substring(0, scopes.length() - 1));
            }

            obj.put("QuotedStatusId", status.getQuotedStatusId());

            JSONArray list = new JSONArray();
            String contributors = "";
            for (long id : status.getContributors()) {
                list.add(id);
                contributors += id + ",";
            }

            if (!contributors.isEmpty())
                obj.put("Contributors", contributors.substring(0, contributors.length() - 1));

            System.out.println("" + obj.toJSONString());

            insertNodeNeo4j(obj);

            //out.println(obj.toJSONString());
            String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';";
            executeQuery(session, statement);
        }

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

    fq.track(parametros);

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

From source file:org.tweetalib.android.model.TwitterStatus.java

License:Apache License

public TwitterStatus(Status status) {
    User statusUser = status.getUser();/*  www  . j  av a  2s .  co m*/

    mCreatedAt = status.getCreatedAt();
    mId = status.getId();
    if (status.getInReplyToStatusId() != -1) {
        mInReplyToStatusId = status.getInReplyToStatusId();
    }
    if (status.getInReplyToUserId() != -1) {
        mInReplyToUserId = status.getInReplyToUserId();
    }
    mInReplyToUserScreenName = status.getInReplyToScreenName();
    mIsFavorited = status.isFavorited();
    mIsRetweet = status.isRetweet();
    mIsRetweetedByMe = status.isRetweetedByMe();

    mSource = TwitterUtil.stripMarkup(status.getSource());

    if (statusUser != null) {
        mUserId = statusUser.getId();
        mUserName = statusUser.getName();
        mUserScreenName = statusUser.getScreenName();
    }

    mMediaEntity = TwitterMediaEntity.createMediaEntity(status);

    boolean useDefaultAuthor = true;
    if (mIsRetweet) {
        if (status.getRetweetedStatus() != null && status.getRetweetedStatus().getUser() != null) {
            SetProfileImagesFromUser(new TwitterUser(status.getRetweetedStatus().getUser()));
        }
        mOriginalRetweetId = status.getRetweetedStatus().getId();

        // You'd think this check wasn't necessary, but apparently not...
        UserMentionEntity[] userMentions = status.getUserMentionEntities();
        if (userMentions != null && userMentions.length > 0) {
            useDefaultAuthor = false;
            UserMentionEntity authorMentionEntity = status.getUserMentionEntities()[0];
            mAuthorId = authorMentionEntity.getId();
            mAuthorName = authorMentionEntity.getName();
            mAuthorScreenName = authorMentionEntity.getScreenName();

            Status retweetedStatus = status.getRetweetedStatus();
            mStatus = retweetedStatus.getText();
            setStatusMarkup(retweetedStatus);
            mRetweetCount = retweetedStatus.getRetweetCount();
            mUserMentions = TwitterUtil.getUserMentions(retweetedStatus.getUserMentionEntities());
            mIsRetweetedByMe = retweetedStatus.isRetweetedByMe();
        }
    } else {
        if (statusUser != null) {
            SetProfileImagesFromUser(new TwitterUser(statusUser));
        }
    }

    if (useDefaultAuthor) {
        if (statusUser != null) {
            mAuthorId = statusUser.getId();
        }
        mStatus = status.getText();
        setStatusMarkup(status);
        mRetweetCount = status.getRetweetCount();
        mUserMentions = TwitterUtil.getUserMentions(status.getUserMentionEntities());
    }

    /*
     * if (status.getId() == 171546910249852928L) { mStatus =
     * "<a href=\"http://a.com\">@chrismlacy</a> You've been working on Tweet Lanes for ages. Is it done yet?"
     * ; mStatusMarkup =
     * "<a href=\"http://a.com\">@chrismlacy</a> You've been working on Tweet Lanes for ages. Is it done yet?"
     * ; mAuthorScreenName = "emmarclarke"; mStatusMarkup = mStatus; } else
     * if (status.getId() == 171444098698457089L) { mStatus =
     * "<a href=\"http://a.com\">@chrismlacy</a> How's that app of yours coming along?"
     * ; mStatusMarkup =
     * "<a href=\"http://a.com\">@chrismlacy</a> How's that app of yours coming along?"
     * ; mStatusMarkup = mStatus; }
     */
}

From source file:org.xmlsh.twitter.util.TwitterWriter.java

License:BSD License

public void write(Status t) throws XMLStreamException {
    startElement("tweet");
    attribute("id", t.getId());

    // write("annotations",t.getAnnotations());
    write("created-at", t.getCreatedAt());
    write("from-user", sanitizeID(t.getUser().getId()), sanitizeUser(t.getUser().getName()));
    write("geo-location", t.getGeoLocation());
    write("hash-tags", t.getHashtagEntities());
    write("iso-language-code", t.getUser().getLang());
    write("location", t.getUser().getLocation());
    write("media", t.getMediaEntities());
    write("place", t.getPlace());
    write("profile-image-url", sanitizeUser(t.getUser().getProfileImageURL()));
    write("source", t.getSource());
    write("text", t.getText());
    write("to-user", sanitizeID(t.getInReplyToUserId()), sanitizeUser(t.getInReplyToScreenName()));
    write("url-entities", t.getURLEntities());
    write("user-mention-entities", t.getUserMentionEntities());

    endElement();//from  w ww  .jav  a2  s . c  o m

}

From source file:testtweet.TweetUsingTwitter4jExample.java

/**
 * @param args the command line arguments
 *///from  w  ww. ja va 2  s .c om
public static void main(String[] args) throws IOException, TwitterException {

    //Instantiate a re-usable and thread-safe factory
    TwitterFactory twitterFactory = new TwitterFactory(Data.getConf().build());

    //Instantiate a new Twitter instance
    Twitter twitter = twitterFactory.getInstance();

    /*
    //setup OAuth Consumer Credentials
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
            
    //setup OAuth Access Token
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    */

    //Instantiate and initialize a new twitter status update
    StatusUpdate statusUpdate = new StatusUpdate(
            //your tweet or status message
            "Twitter API #Hacked");
    //attach any media, if you want to
    /*
    statusUpdate.setMedia(
    //title of media
    "http://h1b-work-visa-usa.blogspot.com"
    , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream());
    */
    //tweet or update status
    Status status = twitter.updateStatus(statusUpdate);

    //response from twitter server
    System.out.println("status.toString() = " + status.toString());
    System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
    System.out.println("status.getSource() = " + status.getSource());
    System.out.println("status.getText() = " + status.getText());
    System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
    System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
    System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
    System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
    System.out.println("status.getId() = " + status.getId());
    System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
    System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
    System.out.println("status.getPlace() = " + status.getPlace());
    System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
    System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
    System.out.println("status.getUser() = " + status.getUser());
    System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
    System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
    System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
    if (status.getRateLimitStatus() != null) {
        System.out
                .println("status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
        System.out.println(
                "status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining());
        System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                + status.getRateLimitStatus().getResetTimeInSeconds());
        System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                + status.getRateLimitStatus().getSecondsUntilReset());
        System.out.println("status.getRateLimitStatus().getRemainingHits() = "
                + status.getRateLimitStatus().getRemaining());
    }
    System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
    System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
}

From source file:twitbak.MentionBak.java

License:Open Source License

public void statusToJson(Status status) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    User poster = status.getUser();//w  w  w .  ja v a 2 s  .  c  o  m
    result.put("Poster ID", poster.getId());
    result.put("Poster", poster.getScreenName());
    result.put("Poster Name", poster.getName());
    result.put("Created At", status.getCreatedAt().toString());
    result.put("ID", status.getId());
    result.put("Text", status.getText());
    long inReplyToStatusId = status.getInReplyToStatusId();
    if (inReplyToStatusId != -1) {
        result.put("In Reply To Status ID", status.getInReplyToStatusId());
    }
    long inReplyToUserID = status.getInReplyToUserId();
    result.put("In Reply To User ID", inReplyToUserID);
    if (inReplyToUserID != -1) {
        result.put("In Reply To Screen Name", status.getInReplyToScreenName());
    }
    boolean isFavorited = status.isFavorited();
    if (isFavorited) {
        result.put("Favorited", status.isFavorited());
    }
    statusArray().put(result);
}

From source file:twitbak.StatusBak.java

License:Open Source License

/**
 * Adds a Status to statusArray as a JSONObject.
 * /*from  w ww .  j  a  va 2 s.c o  m*/
 * @param status
 * @throws TwitterException
 * @throws JSONException
 */
public void statusToJson(Status status) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    result.put("Created At", status.getCreatedAt().toString());
    result.put("ID", status.getId());
    result.put("Text", status.getText());
    long inReplyToStatusId = status.getInReplyToStatusId();
    if (inReplyToStatusId != -1) {
        result.put("In Reply To Status ID", status.getInReplyToStatusId());
    }
    long inReplyToUserID = status.getInReplyToUserId();
    result.put("In Reply To User ID", inReplyToUserID);
    if (inReplyToUserID != -1) {
        result.put("In Reply To Screen Name", status.getInReplyToScreenName());
    }
    boolean isFavorited = status.isFavorited();
    if (isFavorited) {
        result.put("Favorited", status.isFavorited());
    }
    statusArray.put(result);
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

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

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(/*from  w w w  .  j a v a2s . c o m*/
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twittermarkovchain.Main.java

public static void main(String[] args) throws TwitterException, IOException {
    Args.parseOrExit(Main.class, args);
    Twitter twitter = TwitterFactory.getSingleton();

    List<String> tweets = new ArrayList<>();
    File file = new File(user + ".txt");
    if (file.exists()) {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        String line;//from  w w w  .  j  a  v a  2 s  .c  o  m
        while ((line = br.readLine()) != null) {
            tweets.add(line);
        }
    } else {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        int total = 0;
        int page = 1;
        int size;
        do {
            ResponseList<Status> statuses = twitter.timelines().getUserTimeline(user, new Paging(page++, 200));
            size = statuses.size();
            total += size;

            for (Status status : statuses) {
                if (status.getInReplyToUserId() == -1 && status.getRetweetedStatus() == null) {
                    String text = status.getText().replaceAll("\n", " ");
                    bw.write(text);
                    bw.newLine();
                    tweets.add(text);
                }
            }
        } while (size > 0);
        bw.close();
    }

    // We need to generate a map of pair frequencies indexed by the first in the pair
    Map<String, Map<String, Integer>> frequencyMap = tweets.stream().flatMap((String s) -> {
        Stream.Builder<Pair> builder = Stream.builder();
        String last = null;
        for (String current : s.toLowerCase().replaceAll("https?://.+\\b", "").replaceAll("[^a-z@# ]", "")
                .split(" ")) {
            if (current.equals(""))
                continue;
            if (last == null) {
                builder.add(new Pair("", current));
            } else {
                builder.add(new Pair(last, current));
            }
            last = current;
        }
        if (last != null) {
            builder.add(new Pair(last, ""));
        }
        return builder.build();
    }).collect(Collectors.toMap(p -> p.s1, p -> ImmutableMap.of(p.s2, 1), (m1, m2) -> {
        HashMap<String, Integer> newmap = new HashMap<>(m1);
        for (Map.Entry<String, Integer> e : m2.entrySet()) {
            String key = e.getKey();
            Integer integer = newmap.get(key);
            if (integer == null) {
                newmap.put(key, 1);
            } else {
                newmap.put(key, integer + e.getValue());
            }
        }
        return newmap;
    }));

    // Random!
    Random random = new SecureRandom();

    // Check using language
    JLanguageTool language = new JLanguageTool(Language.ENGLISH);

    for (int i = 0; i < 1000; i++) {
        StringBuilder sb = new StringBuilder();
        // Now that we have the frequency map we can generate a message.
        String word = "";
        do {
            Map<String, Integer> distribution = frequencyMap.get(word);
            int total = 0;
            for (Map.Entry<String, Integer> e : distribution.entrySet()) {
                total += e.getValue();
            }
            int which = random.nextInt(total);
            int current = 0;
            for (Map.Entry<String, Integer> e : distribution.entrySet()) {
                Integer value = e.getValue();
                if (which >= current && which < current + value) {
                    word = e.getKey();
                }
                current += value;
            }
            if (sb.length() > 0) {
                if (word.length() > 0) {
                    sb.append(" ");
                    sb.append(word);
                }
            } else {
                sb.append(word.substring(0, 1).toUpperCase());
                if (word.length() > 1)
                    sb.append(word.substring(1));
            }
        } while (!word.equals(""));
        sb.append(".");
        List<RuleMatch> check = language.check(sb.toString());
        if (check.isEmpty()) {
            System.out.println(sb);
        }
    }
}