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:org.jetbrains.webdemo.servlet.TwitterServlet.java

License:Apache License

private void tweet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/* w ww  .  j av a 2  s  .  c om*/
        Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
        RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
        String verifier = request.getParameter("oauth_verifier");
        twitter.getOAuthAccessToken(requestToken, verifier);

        String status = (String) request.getSession().getAttribute("tweetText");
        request.getSession().removeAttribute("tweetText");
        StatusUpdate statusUpdate = new StatusUpdate(status);

        String level = (String) request.getSession().getAttribute("kotlin-level");
        request.getSession().removeAttribute("level");
        statusUpdate.setMedia(
                new File(CommonSettings.WEBAPP_ROOT_DIRECTORY + "static/images/" + level + "level.gif"));

        twitter.updateStatus(statusUpdate);
        request.getSession().removeAttribute("requestToken");
        response.sendRedirect(request.getContextPath() + "/");
    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:org.komusubi.feeder.sns.twitter.Twitter4j.java

License:Apache License

/**
 * tweet./*from  ww w  . j  a v  a 2  s.c o m*/
 * @param message
 */
public void tweet(Message message) {
    Script current = new ScriptLine("");
    try {
        Status result = null;
        for (Script script : message) {
            current = script; // mark current script for when exception occurred.
            if (outputConsole) {
                System.out.printf("tweet(length:%d): %s%n", TweetScript.lengthAfterTweeted(script.trimedLine()),
                        script.trimedLine());
            } else {
                StatusUpdate status = new StatusUpdate(script.trimedLine());
                if (result != null) {
                    status.inReplyToStatusId(result.getId());
                }
                logger.info("tweet(length:{}): {}", TweetScript.lengthAfterTweeted(status.getStatus()),
                        status.getStatus());
                result = twitter.updateStatus(status);
            }
        }
    } catch (TwitterException e) {
        throw new Twitter4jException(String.format("tweet(length:%d): %s",
                TweetScript.lengthAfterTweeted(current.trimedLine()), current.trimedLine()), e);
    }
}

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 ww  .  j  ava2  s  .com*/
    }
    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.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Updates the authenticating user's status. A status update with text identical
 * to the authenticating user's text identical to the authenticating user's
 * current status will be ignored to prevent duplicates. <br>
 * This method calls http://api.twitter.com/1.1/statuses/update
 * <p/>//from   w w w  .  j a va2 s. c o  m
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:updateStatus}
 *
 * @param status    the text of your status update
 * @param inReplyTo The ID of an existing status that the update is in reply to.
 * @param latitude  The latitude of the location this tweet refers to. This parameter will be ignored unless it is
 *                  inside the range -90.0 to +90.0 (North is positive) inclusive.
 * @param longitude he longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to
 *                  +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range or if there not a
 *                  corresponding lat parameter.
 * @return the latest {@link Status}
 * @throws TwitterException when Twitter service or network is unavailable
 * @see <a href="http://dev.twitter.com/doc/post/statuses/update">POST
 *      statuses/update | dev.twitter.com</a>
 */
@Processor
public Status updateStatus(String status, @Default(value = "-1") @Optional long inReplyTo,
        @Placement(group = "Coordinates") @Optional Double latitude,
        @Placement(group = "Coordinates") @Optional Double longitude) throws TwitterException {
    StatusUpdate update = new StatusUpdate(status);
    if (inReplyTo > 0) {
        update.setInReplyToStatusId(inReplyTo);
    }
    if (latitude != null && longitude != null) {
        update.setLocation(new GeoLocation(latitude, longitude));
    }
    Status response = twitter.updateStatus(update);

    //Twitter4j doesn't throw exception when json reponse has 'error: Could not authenticate with OAuth'
    if (response.getId() == -1) {
        throw new TwitterException("Could not authenticate with OAuth\n");
    }

    return response;
}

From source file:org.nsoft.openbus.action.SendTwitteAction.java

License:Open Source License

@Override
public void execute(Activity a, String message, Bundle b) {

    TwitterAccount twitterAcc = Account.getTwitterAccount(a);
    long idReplyStatus = -1;
    if (b != null)
        idReplyStatus = b.getLong("inReply");

    if (idReplyStatus != -1) {
        inReplyId = "" + inReplyId;
        StatusUpdate update = new StatusUpdate(message);
        update.setInReplyToStatusId(idReplyStatus);

        try {//w ww. ja  v  a2s  . c o  m
            TwitterUtils.getTwitter(new AccessToken(twitterAcc.getToken(), twitterAcc.getTokenSecret()))
                    .updateStatus(update);

        } catch (TwitterException e) {

        }
    } else
        twitterAcc.updateStatus(message);

    messageSent = true;

}

From source file:org.springframework.integration.twitter.StatusUpdateSupport.java

License:Apache License

/**
 * {@link StatusUpdate} instances are used to drive status updates.
 *
 * @param message the inbound messages/*from  w  ww. j ava  2  s  .  c om*/
 * @return a {@link StatusUpdate}  that's been materialized from the inbound message
 * @throws Throwable thrown if something goes wrong
 */
public StatusUpdate fromMessage(Message<?> message) throws Throwable {
    Object payload = message.getPayload();
    StatusUpdate statusUpdate = null;

    if (payload instanceof String) {
        statusUpdate = new StatusUpdate((String) payload);

        if (message.getHeaders().containsKey(TwitterHeaders.TWITTER_IN_REPLY_TO_STATUS_ID)) {
            Long replyId = (Long) message.getHeaders().get(TwitterHeaders.TWITTER_IN_REPLY_TO_STATUS_ID);

            if ((replyId != null) && (replyId > 0)) {
                statusUpdate.inReplyToStatusId(replyId);
            }
        }

        if (message.getHeaders().containsKey(TwitterHeaders.TWITTER_PLACE_ID)) {
            String placeId = (String) message.getHeaders().get(TwitterHeaders.TWITTER_PLACE_ID);

            if (StringUtils.hasText(placeId)) {
                statusUpdate.placeId(placeId);
            }
        }

        if (message.getHeaders().containsKey(TwitterHeaders.TWITTER_GEOLOCATION)) {
            GeoLocation geoLocation = (GeoLocation) message.getHeaders()
                    .get(TwitterHeaders.TWITTER_GEOLOCATION);

            if (null != geoLocation) {
                statusUpdate.location(geoLocation);
            }
        }

        if (message.getHeaders().containsKey(TwitterHeaders.TWITTER_DISPLAY_COORDINATES)) {
            Boolean displayCoords = (Boolean) message.getHeaders()
                    .get(TwitterHeaders.TWITTER_DISPLAY_COORDINATES);

            if (displayCoords != null) {
                statusUpdate.displayCoordinates(displayCoords);
            }
        }
    }

    if (payload instanceof StatusUpdate) {
        statusUpdate = (StatusUpdate) payload;
    }

    return statusUpdate;
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

private void replyTo(final Status status, final String reply, final boolean prefix) throws TwitterException {
    final String message;

    if (prefix) {
        message = "@" + status.getUser().getScreenName() + " " + reply;
    } else {/*  w w w  .j  av a2s.c o  m*/
        message = reply;
    }

    final StatusUpdate statusUpdate = new StatusUpdate(message);
    statusUpdate.setInReplyToStatusId(status.getId());
    twitter.updateStatus(statusUpdate);
}

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

License:Apache License

public StatusUpdate getT4JStatusUpdate() {
    StatusUpdate statusUpdate = new StatusUpdate(mStatus);

    if (mInReplyToStatusId != null) {
        statusUpdate.setInReplyToStatusId(mInReplyToStatusId);
    }/*from  w w  w . ja  v a2 s  . co  m*/

    if (mMediaFilePath != null) {
        try {
            statusUpdate.setMedia(getMediaFile(mMediaFilePath));
        } catch (IOException error) {
            error.printStackTrace();
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        }
    }

    return statusUpdate;
}

From source file:Servlet.TwitterShareServlet.java

License:Apache License

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/* w  w w  .j a v a 2s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String share = request.getParameter("share");

    if (share.equalsIgnoreCase("post")) {
        int threadID;
        int page;

        try {
            threadID = Integer.parseInt(request.getParameter("tid"));
        } catch (NumberFormatException ex) {
            threadID = 0;
            Logger.getLogger(TwitterShareServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            page = Integer.parseInt(request.getParameter("page"));
        } catch (NumberFormatException ex) {
            page = 1;
            Logger.getLogger(TwitterShareServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
        StatusUpdate su = new StatusUpdate(
                DirectoryAdmin.getURLContextPath(request) + "/thread?tid=" + threadID + "&page=" + page);

        try {
            twitter.updateStatus(su);
        } catch (TwitterException ex) {
            Logger.getLogger(TwitterShareServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (share.equalsIgnoreCase("module")) {
        int moduleID;

        try {
            moduleID = Integer.parseInt(request.getParameter("mid"));
        } catch (NumberFormatException ex) {
            moduleID = 0;
            Logger.getLogger(TwitterShareServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
        StatusUpdate su = new StatusUpdate(
                DirectoryAdmin.getURLContextPath(request) + "/module?mid=" + moduleID);

        try {
            twitter.updateStatus(su);
        } catch (TwitterException ex) {
            Logger.getLogger(TwitterShareServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:social.controller.PostToSocial.java

@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    boolean face = false;
    boolean twit = false;
    try {//from  w  w  w  .  j av  a2  s.c om
        getSqlMethodsInstance().session = request.getSession();
        Integer user_id = (Integer) getSqlMethodsInstance().session.getAttribute("UID");
        String htmlString = (String) getSqlMethodsInstance().session.getAttribute("htmlString");
        String isFacebook = request.getParameter("isFacebook");
        String isTwitter = request.getParameter("isTwitter");
        String getImageFile = request.getParameter("imageToPost");
        String getFile = request.getParameter("imagePost");
        String url = request.getParameter("url");

        String file_image_path = AppConstants.LAYOUT_IMAGES_HOME + File.separator + getImageFile;

        //            String file_image_path = getServletContext().getRealPath("") + "/temp/"+getImageFile;
        String imagePostURL = ServletUtil.getServerName(request.getServletContext());
        //String imagePostURL = AppConstants.LAYOUT_IMAGES_HOME + getImageFile;
        if (isFacebook.equalsIgnoreCase("true")) {

            String accessToken = request.getParameter("accesstoken");
            String posttext = request.getParameter("postText");
            String title = request.getParameter("title");
            String description = request.getParameter("description");
            String url1 = request.getParameter("url");

            facebook = new FacebookFactory().getInstance();
            facebook.setOAuthAppId("592852577521569", "a87cc0c30d792fa5dd0aaef6b43994ef");
            facebook.setOAuthPermissions("publish_actions, publish_pages,manage_pages");
            //            File file = new File(file_image_path);
            facebook.setOAuthAccessToken(new AccessToken(accessToken));

            if (title == "") {

                Media media = new Media(new File(file_image_path));
                PhotoUpdate update = new PhotoUpdate(media);
                update.message(posttext);
                facebook.postPhoto(update);
            } else {
                logger.info(title);
                PostUpdate post = new PostUpdate(posttext).picture(new URL(
                        imagePostURL + "DownloadImage?image_type=LAYOUT_IMAGES&image_name=" + getImageFile))
                        .name(title).link(new URL(url1)).description(description);
                facebook.postFeed(post);
            }
            try {

                getSqlMethodsInstance().setSocialPostHistory(user_id, htmlString, false, true, getImageFile);
            } catch (Exception ex) {
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getCause());
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getMessage());
            }
        }
        if (isTwitter.equalsIgnoreCase("true")) {

            try {

                AccessToken accTok = null;
                String shortUrl = "";
                ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
                twitterConfigBuilder.setDebugEnabled(true);
                twitterConfigBuilder.setOAuthConsumerKey("K7TJ3va8cyAeh6oN3Hia91S2o");
                twitterConfigBuilder
                        .setOAuthConsumerSecret("IWUt2aDVTHgUc8N0qI0cF1Z1dTAEQ7CSgnBymZNr3BPSmtkNHL");
                twitterConfigBuilder.setOAuthAccessToken(request.getParameter("twittweraccestoken"));
                twitterConfigBuilder.setOAuthAccessTokenSecret(request.getParameter("twitterTokenSecret"));

                Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
                String statusMessage = request.getParameter("text").replace("bit.ly/1XOkJo", "");
                shortUrl = request.getParameter("shorturl");
                if (shortUrl.length() > 0) {
                    String StatusMessageWithoutUrl = statusMessage.substring(0, statusMessage.length());
                    if (StatusMessageWithoutUrl.length() + shortUrl.length() < 140) {
                        statusMessage = StatusMessageWithoutUrl + " " + shortUrl;
                    } else {
                        int urlLength = shortUrl.length() + 1;
                        int statusLength = 115 - urlLength;
                        statusMessage = StatusMessageWithoutUrl.substring(0, statusLength);
                        statusMessage = statusMessage + " " + shortUrl;
                    }
                }
                File file = new File(file_image_path);
                int count = statusMessage.length();
                StatusUpdate status = new StatusUpdate(statusMessage);
                // set the image to be uploaded here.

                status.setMedia(file);
                twitter.updateStatus(status);
                try {
                    getSqlMethodsInstance().setSocialPostHistory(user_id, htmlString, false, true,
                            getImageFile);
                } catch (Exception ex) {
                    Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getCause());
                    Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getMessage());
                }

            } catch (TwitterException te) {

                PrintWriter out1 = response.getWriter();
                out1.println("Twitter Exception: " + te.getMessage());
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, te.getCause());
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, te.getMessage());

            } catch (Exception e) {
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e);
                Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getMessage());
            }

        }
    } catch (FacebookException e) {
        Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getCause());
        Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getMessage());
    }
}