Example usage for twitter4j StatusUpdate StatusUpdate

List of usage examples for twitter4j StatusUpdate StatusUpdate

Introduction

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

Prototype

public StatusUpdate(String status) 

Source Link

Usage

From source file:com.appspot.bitlyminous.handler.twitter.SendRelatedUrlsHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {/*www  . j  a  v a  2  s.  c om*/
        DeliciousGateway deliciousGateway = getDeliciousGateway(context.getVersion());
        DiggGateway diggGateway = getDiggGateway();
        List<Url> urls = context.getUrls();
        for (Url entity : urls) {
            WebSearchQuery googleQuery = getGoogleWebSearchQuery();
            googleQuery.withRelatedSite(entity.getUrl());
            List<Url> relatedUrls = new ArrayList<Url>();
            List<String> tags = entity.getTags();
            if (!tags.isEmpty()) {
                for (String tag : tags) {
                    try {
                        relatedUrls.addAll(deliciousGateway.getPopularUrls(tag));
                        relatedUrls.addAll(convertToUrls(diggGateway.getPopularStories(tag, 5)));
                    } catch (Exception e) {
                        logger.log(Level.WARNING, "Error while getting related urls.", e);
                    }
                }
                relatedUrls.addAll(convertToUrls(googleQuery.withQuery(createQuery(tags)).list()));
                relatedUrls = getBestMatches(entity, relatedUrls, 2);
            }

            if (!relatedUrls.isEmpty()) {
                StatusUpdate reply = new StatusUpdate(
                        "@" + tweet.getUser().getScreenName() + " " + buildStatus(relatedUrls));
                reply.setInReplyToStatusId(tweet.getId());
                return reply;
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while sending related urls.", e);
    }

    return null;
}

From source file:com.appspot.bitlyminous.handler.twitter.TweetForMeHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {//from   ww  w .j  a  v a  2 s .c om
        User user = context.getUser();
        if (user == null) {
            user = getUserByScreenName(tweet.getUser().getScreenName());
            context.setUser(user);
        }
        if (user == null || user.getTwitterToken() == null || user.getTwitterSecret() == null) {
            StatusUpdate reply = new StatusUpdate(
                    ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.notAuthenticated",
                            new String[] { "@" + tweet.getUser().getScreenName(), "Twitter",
                                    shortenUrl(ApplicationConstants.TWITTER_CALLBACK_URL) }));
            reply.setInReplyToStatusId(tweet.getId());
            return reply;
        } else {
            Twitter twitter = getTwitterClient(user.getTwitterToken().getValue(),
                    user.getTwitterSecret().getValue());
            String status = buildStatus(user.getUrls(), user.getTags());
            if (status != null) {
                StatusUpdate reply = new StatusUpdate(status);
                reply.setInReplyToStatusId(tweet.getId());
                twitter.updateStatus(reply);
            }
            return null;
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while tweeting on behalf of user.", e);
    }
    return null;
}

From source file:com.daiv.android.twitter.utils.api_helper.TwitLongerHelper.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.//from w ww  .  j a  v  a  2s.com
 *
 * @return id of the status that was posted to twitter
 */
public long createPost() {
    TwitLongerStatus status = postToTwitLonger();
    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();
        updateTwitlonger(status, statusId);
    } catch (Exception e) {
        e.printStackTrace();
        statusId = 0;
    }

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

From source file:com.daiv.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.//from www  .ja v  a  2  s. co m
 *
 * @return id of the status that was posted to twitter
 */
public long createPost() {
    TwitPicStatus status = uploadToTwitPic();
    Log.v("Test_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.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Sets access token, sends tweet.//  w  ww .  j  a  v a  2 s .c o m
 * @category Helpers
 * @return result code
 */
private int sendTweet(String text, String imagePath, AccessToken accessToken) {
    int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;

    // check to make sure we have data and access before tweeting
    if (text == null && imagePath == null) {
        return MSTwitter.MST_RESULT_NO_DATA_TO_SEND;
    }
    if (accessToken == null) {
        return MSTwitter.MST_RESULT_NOT_AUTHORIZED;
    }

    // get twitter4j object
    Twitter twitter4j = null;
    try {
        twitter4j = new TwitterFactory().getInstance();
        twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
    } catch (IllegalStateException e) {
        // No network access or token already available
        resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
        Log.e(MSTwitter.TAG, e.toString());
        return resultCode;
    }

    // Create and set twitter access credentials from token and or secret
    twitter4j.setOAuthAccessToken(accessToken);
    try {
        // finally update the status (send the tweet)
        StatusUpdate status = new StatusUpdate(text);
        if (imagePath != null) {
            status.setMedia(new File(imagePath));
        }
        twitter4j.updateStatus(status);
    } catch (TwitterException e) {
        return MSTwitter.getTwitterErrorNum(e, this);
    }

    return resultCode;
}

From source file:com.freshdigitable.udonroad.TweetInputFragment.java

License:Apache License

private Observable<Status> createSendObservable() {
    final String sendingText = binding.mainTweetInputView.getText().toString();
    if (!isStatusUpdateNeeded()) {
        return twitterApi.updateStatus(sendingText);
    }/*from www . ja v a  2s  . c o  m*/
    String s = sendingText;
    for (long q : quoteStatusIds) {
        final Status status = statusCache.find(q);
        if (status == null) {
            continue;
        }
        s += " https://twitter.com/" + status.getUser().getScreenName() + "/status/" + q;
    }
    final StatusUpdate statusUpdate = new StatusUpdate(s);
    if (replyEntity != null) {
        statusUpdate.setInReplyToStatusId(replyEntity.inReplyToStatusId);
    }
    return twitterApi.updateStatus(statusUpdate);
}

From source file:com.github.moko256.twitlatte.model.impl.twitter.PostTweetModelImpl.java

License:Apache License

@Override
public Completable postTweet() {
    return Completable.create(subscriber -> {
        try {/*from w  w w  . j  a  v  a2  s .c om*/
            StatusUpdate statusUpdate = new StatusUpdate(tweetText);
            if (uriList.size() > 0) {
                long ids[] = new long[uriList.size()];
                for (int i = 0; i < uriList.size(); i++) {
                    Uri uri = uriList.get(i);
                    InputStream image = contentResolver.openInputStream(uri);
                    ids[i] = twitter.uploadMedia(uri.getLastPathSegment(), image).getMediaId();
                }
                statusUpdate.setMediaIds(ids);
                statusUpdate.setPossiblySensitive(possiblySensitive);
            }
            if (isReply()) {
                statusUpdate.setInReplyToStatusId(inReplyToStatusId);
            }
            if (location != null) {
                statusUpdate.setLocation(location);
            }
            twitter.updateStatus(statusUpdate);
            subscriber.onComplete();
        } catch (FileNotFoundException | TwitterException e) {
            subscriber.tryOnError(e);
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Tweet with Image, Uploaded to Twitter
 *///from   w w w .ja  v a  2s  . c o m
@SimpleFunction(description = "This sends a tweet as the logged-in user with the "
        + "specified Text and a path to the image to be uploaded, which will be trimmed if it " + "exceeds "
        + MAX_CHARACTERS + " characters. "
        + "If an image is not found or invalid, only the text will be tweeted."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void TweetWithImage(final String status, final String imagePath) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "TweetWithImage", ErrorMessages.ERROR_TWITTER_SET_STATUS_FAILED,
                "Need to login?");
        return;
    }

    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() {
            try {
                String cleanImagePath = imagePath;
                // Clean up the file path if necessary
                if (cleanImagePath.startsWith("file://")) {
                    cleanImagePath = imagePath.replace("file://", "");
                }
                File imageFilePath = new File(cleanImagePath);
                if (imageFilePath.exists()) {
                    StatusUpdate theTweet = new StatusUpdate(status);
                    theTweet.setMedia(imageFilePath);
                    twitter.updateStatus(theTweet);
                } else {
                    form.dispatchErrorOccurredEvent(Twitter.this, "TweetWithImage",
                            ErrorMessages.ERROR_TWITTER_INVALID_IMAGE_PATH);
                }
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "TweetWithImage",
                        ErrorMessages.ERROR_TWITTER_SET_STATUS_FAILED, e.getMessage());
            }
        }
    });

}

From source file:com.ibuildapp.romanblack.CameraPlugin.SharingActivity.java

License:Open Source License

/**
 * "Post" button and "Home" buttonhandler.
 *//*from  ww w  .jav  a  2  s . co  m*/
public void onClick(View arg0) {
    final String edittext = mainEditText.getText().toString();

    if (arg0 == homeImageView) {
        finish();
    } else if (arg0 == postImageView) {

        if (!Utils.networkAvailable(SharingActivity.this)) {
            handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
            return;
        }

        if (sharingType.equalsIgnoreCase("facebook")) {
            handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String message_text = edittext;
                        if (hasAd == true) {
                            message_text += "\nPosted via http://ibuildapp.com.";
                        }

                        boolean res = FacebookAuthorizationActivity.sharing(Authorization
                                .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken(),
                                message_text, image);
                        if (res)
                            handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_SUCCESS);
                        else
                            handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    } catch (Exception e) {
                        Log.e("", "");
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    }
                }
            }).start();

        } else if (sharingType.equalsIgnoreCase("twitter")) {
            handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        twitter = reInitTwitter();
                        String message_text = edittext;
                        if (hasAd == true) {
                            message_text += "\nPosted via http://ibuildapp.com.";
                        }

                        if (message_text.length() > 140) {
                            message_text = message_text.substring(0, 140);
                        }
                        StatusUpdate su = new StatusUpdate(message_text);

                        if (image != null && image.length() > 0) {
                            InputStream input = new FileInputStream(image);
                            su.setMedia(image, input);
                        }
                        twitter.updateStatus(su);
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_SUCCESS);
                    } catch (Exception e) {
                        Log.d("", "");
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    }
                }
            }).start();
        }
    }

}

From source file:com.ibuildapp.romanblack.CataloguePlugin.SharingActivity.java

License:Open Source License

/**
 * Post button and home button handler./*from  w  w  w  .j a  v  a 2  s.c  o  m*/
 */
public void onClick(View arg0) {
    final String edittext = mainEditText.getText().toString();

    if (arg0 == homeImageView) {
        finish();
    } else if (arg0 == postImageView) {
        if (!Utils.networkAvailable(SharingActivity.this)) {
            handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
            return;
        }

        if (sharingType.equalsIgnoreCase("facebook")) {
            final FacebookClient fbClient = new DefaultFacebookClient(Authorization
                    .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken());
            handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                        String photo_name = "IMG_IBUILDAPP_" + timeStamp + ".jpg";

                        String message_text = edittext;

                        // *************************************************************************************************
                        // preparing sharing message
                        String downloadThe = getString(R.string.directoryplugin_email_download_this);
                        String androidIphoneApp = getString(R.string.directoryplugin_email_android_iphone_app);
                        String postedVia = getString(R.string.directoryplugin_email_posted_via);
                        String foundThis = getString(R.string.directoryplugin_email_found_this);

                        // prepare content
                        String downloadAppUrl = String.format("http://%s/projects.php?action=info&projectid=%s",
                                Statics.BASE_DOMEN, Statics.appId);

                        String adPart = String.format(downloadThe + " %s " + androidIphoneApp + ": %s\n%s",
                                Statics.appName, downloadAppUrl, postedVia + " http://ibuildapp.com");

                        // content part
                        String contentPath = String.format(foundThis + " %s: %s \n%s", Statics.appName,
                                image_url,
                                com.ibuildapp.romanblack.CataloguePlugin.Statics.hasAd ? adPart : "");

                        //without prefilled                            message_text += "\n" + contentPath;

                        if (!TextUtils.isEmpty(image_url)) {
                            InputStream input = new URL(image_url).openStream();
                            fbClient.publish("me/photos", FacebookType.class,
                                    BinaryAttachment.with(photo_name, input),
                                    Parameter.with("description", message_text),
                                    Parameter.with("message", message_text));
                        } else {
                            fbClient.publish("me/feed", FacebookType.class,
                                    Parameter.with("message", message_text));
                        }
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_SUCCESS);
                    } catch (Exception e) {
                        Log.e("", "");
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    }
                }
            }).start();

        } else if (sharingType.equalsIgnoreCase("twitter")) {
            handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        twitter = reInitTwitter();
                        String message_text = edittext;
                        if (com.ibuildapp.romanblack.CataloguePlugin.Statics.hasAd == true) {
                            message_text += getString(R.string.directoryplugin_email_posted_via)
                                    + " http://ibuildapp.com.";
                        }

                        if (message_text.length() > 140) {
                            if (TextUtils.isEmpty(image_url))
                                message_text = message_text.substring(0, 110);
                            else
                                message_text = message_text.substring(0, 140 - image_url.length());
                        }

                        StatusUpdate su = new StatusUpdate(message_text);
                        if (!TextUtils.isEmpty(image_url)) {
                            InputStream input = new URL(image_url).openStream();
                            su.setMedia(image_url, input);
                        }
                        twitter.updateStatus(su);
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_SUCCESS);
                    } catch (Exception e) {
                        Log.d("", "");
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG_FAILURE);
                    }
                }
            }).start();
        }
    }
}