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:net.lacolaco.smileessence.view.adapter.PostState.java

License:Open Source License

/**
 * Convert to StatusUpdate for tweet./*w w w. java2  s  .  c  o  m*/
 *
 * @return StatusUpdate
 */
public StatusUpdate toStatusUpdate() {
    return new StatusUpdate(getText()).inReplyToStatusId(getInReplyToStatusID());
}

From source file:net.nitram509.twitter.TwitterService.java

License:Open Source License

public void postMessage(UserId userId, Tweet tweet) throws TwitterException {
    AccessToken accessToken = createAccessTokenFor(userId);
    Twitter twitter = twitterClientToolbox.getTwitterFor(accessToken);
    String message = twitterTextHelper.appendDefaultHashtag(tweet.getText(), tweet.getSuffix());
    System.out.println(message);//  w ww.  j  a va  2s .c  om
    twitter.updateStatus(new StatusUpdate(formatMessage(message)));
}

From source file:noki.preciousshot.helper.TwitterHelper.java

License:Apache License

public static void tweetMedia(String text, File file) {

    Thread thread = new Thread() {
        private String text;
        private File file;

        public Thread setArgs(String text, File file) {
            this.text = text;
            this.file = file;
            return this;
        }// w w w  . j av  a  2s  .c  om

        @Override
        public void run() {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey(PreciousShotData.twitterKeys[0])
                    .setOAuthConsumerSecret(PreciousShotData.twitterKeys[1])
                    .setOAuthAccessToken(PreciousShotData.twitterKeys[2])
                    .setOAuthAccessTokenSecret(PreciousShotData.twitterKeys[3]);
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();

            try {
                Status status = twitter.updateStatus(new StatusUpdate(this.text).media(this.file));
                if (status != null && status.getId() != 0) {
                    String url = String.format("https://twitter.com/%s/status/%s", twitter.getScreenName(),
                            status.getId());
                    PreciousShotCore.log("the url is %s.", url);
                    LangHelper.sendChatWithUrl(LangKey.TWITTER_SUCCESS, LangKey.TWITTER_URL, url);
                } else {
                    LangHelper.sendChat(LangKey.TWITTER_FAILED);
                }
            } catch (TwitterException e) {
                LangHelper.sendChat(LangKey.TWITTER_FAILED);
            }
        }
    }.setArgs(text, file);

    thread.start();

}

From source file:org.addhen.smssync.data.twitter.TwitterClient.java

License:Open Source License

@Nullable
public Status tweet(@NonNull String update) {
    if (mTwitterSessionManager != null && mTwitterSessionManager.getActiveSession() != null) {
        TwitterAuthToken authToken = mTwitterSessionManager.getActiveSession().getAuthToken();
        AccessToken accessToken = new AccessToken(authToken.token, authToken.secret);
        Twitter twitter = mTwitterFactory.getInstance(accessToken);
        StatusUpdate latestStatus = new StatusUpdate(update);
        try {// ww  w.j  a  v a 2 s .  c o m
            return twitter.updateStatus(latestStatus);
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:org.botlibre.sense.twitter.Twitter.java

License:Open Source License

/**
 * Tweet.//from   w  ww .j  a va  2  s . com
 */
public void tweet(String html, Long reply) {
    String text = format(html);
    if (text.length() > 140) {
        int index = text.indexOf("http://");
        if (index == -1) {
            text = text.substring(0, 140);
        } else if (index > 120) {
            text = text.substring(0, 120) + " " + text.substring(index, text.length());
        }
    }
    this.tweets++;
    log("Tweeting:", Level.INFO, text);
    try {
        if (getConnection() == null) {
            connect();
        }
        StatusUpdate update = new StatusUpdate(text);
        if (reply != null) {
            update.setInReplyToStatusId(reply);
        }

        // Check for linked media.
        if ((html.indexOf('<') != -1) && (html.indexOf('>') != -1)) {
            String media = null;
            Element root = getBot().awareness().getSense(Http.class).parseHTML(html);
            NodeList nodes = root.getElementsByTagName("img");
            if (nodes.getLength() > 0) {
                String src = ((Element) nodes.item(0)).getAttribute("src");
                if (src != null && !src.isEmpty()) {
                    media = src;
                }
            }
            if (media == null) {
                nodes = root.getElementsByTagName("video");
                if (nodes.getLength() > 0) {
                    String src = ((Element) nodes.item(0)).getAttribute("src");
                    if (src != null && !src.isEmpty()) {
                        media = src;
                    }
                }
            }
            if (media == null) {
                nodes = root.getElementsByTagName("audio");
                if (nodes.getLength() > 0) {
                    String src = ((Element) nodes.item(0)).getAttribute("src");
                    if (src != null && !src.isEmpty()) {
                        media = src;
                    }
                }
            }
            if (media != null) {
                try {
                    URL url = new URL(media);
                    URLConnection urlConnection = url.openConnection();
                    InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
                    update.setMedia("image.png", stream);
                } catch (Exception exception) {
                    log(exception);
                }
            }
        }

        getConnection().updateStatus(update);
    } catch (Exception exception) {
        this.errors++;
        log(exception.getMessage(), Level.WARNING, text);
    }
}

From source file:org.examproject.tweet.service.SimpleTweetService.java

License:Apache License

private Status replyStatus(String content, long statusId) {
    Status status = null;/*w w w .ja va2s . co  m*/
    StatusUpdate statusUpdate = new StatusUpdate(content);
    statusUpdate.setInReplyToStatusId(statusId);
    try {
        Twitter twitter = getTwitter();
        status = twitter.updateStatus(statusUpdate);
    } catch (TwitterException te) {
        LOG.error("an error occurred: " + te.getMessage());
        throw new RuntimeException(te);
    }
    return status;
}

From source file:org.fossasia.phimpme.share.twitter.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final String imageUrl, final String message,
        final String token, final String secret, final TwitterCallback postResponse) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
    configurationBuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
    configurationBuilder.setOAuthAccessToken(token);
    configurationBuilder.setOAuthAccessTokenSecret(secret);
    Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    final File file = new File(imageUrl);
    boolean success = true;
    if (file.exists()) {
        try {//from  w w w.  j  ava  2 s  . co  m
            StatusUpdate status = new StatusUpdate(message);
            status.setMedia(file);
            twitter.updateStatus(status);
        } catch (TwitterException e) {
            e.printStackTrace();
            success = false;
        }
    } else {
        Log.d(TAG, "----- Invalid File ----------");
        success = false;
    }
    postResponse.onFinsihed(success);

}

From source file:org.getlantern.firetweet.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 .ja  v  a2  s.c  om*/
    }
    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 && hasMedia) {
            final MediaUploadResult uploadResult;
            try {
                if (mUploader != null) {
                    mUploader.waitForService();
                }
                uploadResult = mUploader.upload(statusUpdate,
                        UploaderMediaItem.getFromStatusUpdate(this, statusUpdate));
            } catch (final Exception e) {
                Crashlytics.logException(e);
                throw new UploadException(this);
            }
            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) {
                    Crashlytics.logException(e);
                    throw new ShortenException(this);
                }
                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) {
                    Crashlytics.logException(e);
                    Log.w(LOGTAG, e);
                } catch (final TwitterException e) {
                    Crashlytics.logException(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);
                Crashlytics.logException(e);
            }
        }
    } catch (final UpdateStatusException e) {
        final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
        results.add(response);
        Crashlytics.logException(e);
    }
    if (mentionedHondaJOJO) {
        triggerEasterEgg(notReplyToOther, hasEasterEggTriggerText, hasEasterEggRestoreText);
    }
    return results;
}

From source file:org.hornetq.integration.twitter.impl.OutgoingTweetsHandler.java

License:Apache License

public HandleStatus handle(final MessageReference ref) throws Exception {
    if (filter != null && !filter.match(ref.getMessage())) {
        return HandleStatus.NO_MATCH;
    }//  w ww .ja  va2  s  .c om

    synchronized (this) {
        ref.handled();

        ServerMessage message = ref.getMessage();

        StatusUpdate status = new StatusUpdate(message.getBodyBuffer().readString());

        // set optional property

        if (message.containsProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID)) {
            status.setInReplyToStatusId(message.getLongProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID));
        }

        if (message.containsProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE)) {
            double geolat = message.getDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE);
            double geolong = message.getDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LONGITUDE);
            status.setLocation(new GeoLocation(geolat, geolong));
        }

        if (message.containsProperty(TwitterConstants.KEY_PLACE_ID)) {
            status.setPlaceId(message.getStringProperty(TwitterConstants.KEY_PLACE_ID));
        }

        if (message.containsProperty(TwitterConstants.KEY_DISPLAY_COODINATES)) {
            status.setDisplayCoordinates(message.getBooleanProperty(TwitterConstants.KEY_DISPLAY_COODINATES));
        }

        // send to Twitter
        try {
            this.twitter.updateStatus(status);
        } catch (TwitterException e) {
            if (e.getStatusCode() == 403) {
                // duplicated message
                HornetQTwitterLogger.LOGGER.error403(connectorName);
                queue.acknowledge(ref);

                return HandleStatus.HANDLED;
            } else {
                throw e;
            }
        }

        queue.acknowledge(ref);
        HornetQTwitterLogger.LOGGER.debug(connectorName + ": forwarded to twitter: " + message.getMessageID());
        return HandleStatus.HANDLED;
    }
}

From source file:org.hubiquitus.hubotsdk.adapters.HTwitterAdapterOutbox.java

License:Open Source License

private StatusUpdate transformTweet(HMessage message) {
    StatusUpdate result = null;/*from  ww w. j  ava  2 s  .co  m*/
    if ("htweet".equalsIgnoreCase(message.getType())) {
        try {
            HTweet hTweet = new HTweet(message.getPayloadAsJSONObject());
            String status = hTweet.getText();
            String screenNameDest = "@" + message.getActor().split("@")[0];
            if ((!actor.equals(message.getActor())) && (!status.startsWith(screenNameDest))) {
                // in this case, the tweet must be send in public mode to the current actor
                //If the hMessage doesnt begin with the @screenName?,
                //   the outbox adapter will add it automatically.
                status = screenNameDest + " " + status;
            }
            // check the limit;
            if (status.length() > 140) {
                status = status.substring(0, 136) + "...";
            }
            result = new StatusUpdate(status);
        } catch (JSONException e) {
            log.error("Can not transform a hTweet in a status format: ", e);
        }
    }

    if (result == null) {
        log.warn("Strange, I receive an hMessage of type='" + message.getType() + "' instead of an 'hTweet'");
    }
    return result;
}