Example usage for twitter4j StatusUpdate setInReplyToStatusId

List of usage examples for twitter4j StatusUpdate setInReplyToStatusId

Introduction

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

Prototype

public void setInReplyToStatusId(long inReplyToStatusId) 

Source Link

Usage

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

License:Open Source License

/**
 * This method is called when invoke <b>execute()</b>.<br />
 * Do not invoke manually. Use: <i>new TwitterListener().execute("");</i>
 *
 * @param params/*from w w  w  .ja  v a  2 s  .  c  o  m*/
 */
@Override
protected List<String> doInBackground(String... params) {

    Intelligence ai = new Intelligence();

    try {

        User user = twitter.verifyCredentials();
        Paging paging;
        if (idLastTwit != 0)
            paging = new Paging(idLastTwit + 1);
        else
            paging = new Paging();
        paging.count(100);
        statuses = twitter.getMentionsTimeline(paging);

        if (statuses.size() != 0 && statuses != null) {

            Log.d(TAG, "Showing @" + user.getScreenName() + "'s mentions:");
            Log.d(TAG, statuses.get(0).getText() + "-- ID: " + statuses.get(0).getId());

            if (!"".equals(statuses.get(0).getText()) && licenses.size() == 0) {

                extractCommand(ai, statuses);
                Log.d(TAG, "Non ho licenze attive!");

            } else if (!"".equals(statuses.get(0).getText()) && licenses.size() > 0
                    && f.boolContainsIgnoreCase(licenses, String.valueOf(statuses.get(0).getUser().getId()))) {

                extractCommand(ai, statuses);
                Log.i(TAG, "Seguo la lista delle licenze: " + licenses.toString());

            } else {
                publishProgress(false);
            }

            if (deviceController != null) {

                Random r = new Random();
                Interpreter interp = new Interpreter(deviceController);

                for (int i = 0; i < execute.size(); i++) {
                    Log.d(TAG, "Seguenza istruzioni rilevate: " + execute.toString());

                    if (execute.size() >= 1 && "EXECUTE".equals(execute.get(i))
                            && f.getUrls(statuses.get(0).getText()).size() != 0) {

                        String url = statuses.get(0).getURLEntities()[0].getExpandedURL();
                        // String url = f.getUrls(statuses.get(0).getText()).get(0);
                        File folder = new File(Constants.DIR_ROBOT);
                        Log.d(TAG, "URL Expanded: " + url);

                        if (downloadFileUrl(url, folder)) {
                            FileFilter ff = new FileFilter();
                            File[] list = folder.listFiles(ff);
                            Log.e(TAG, "Lista file: " + list.length);
                            if (list != null && list.length >= 1) {

                                if (list[0].getName().endsWith(".csv") || list[0].getName().endsWith(".txt")) {
                                    String commandsList = "";
                                    try {
                                        commandsList = f.getStringFromFile(list[0].getPath());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    Log.d(TAG, "Lista comandi: " + commandsList);
                                    interp.doListCommands(commandsList);
                                    list[0].delete();

                                    if (i == execute.size() - 1) {
                                        try {
                                            StatusUpdate reply = new StatusUpdate(
                                                    ai.actionAnswer(execute.get(i)).get(
                                                            r.nextInt(ai.actionAnswer(execute.get(i)).size()))
                                                            + "@" + statuses.get(0).getUser().getScreenName());
                                            reply.setInReplyToStatusId(statuses.get(0).getId());
                                            twitter.updateStatus(reply);
                                        } catch (TwitterException te) {
                                            Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                        }
                                    }
                                }

                            }

                        }

                    } else if (execute.size() >= 1 && "PHOTO".equals(execute.get(i))) {
                        // Download immagine e post nel tweet
                        if (interp.doCommand(execute.get(i)) == 0) {

                            String result = FTPDownloadFile(ip_host, 21, "anonymous", "", context);

                            if (i == execute.size() - 1 && !"".equals(result)) {
                                try {
                                    StatusUpdate reply = new StatusUpdate(ai.actionAnswer(execute.get(i))
                                            .get(r.nextInt(ai.actionAnswer(execute.get(i)).size())) + "@"
                                            + statuses.get(0).getUser().getScreenName());
                                    reply.setInReplyToStatusId(statuses.get(0).getId());
                                    File image = new File(Constants.DIR_ROBOT_IMG + "/" + result);
                                    Log.d(TAG, "Nome File immagine: " + image.getPath());
                                    reply.media(image);
                                    twitter.updateStatus(reply);
                                    image.delete();
                                } catch (TwitterException te) {
                                    Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                }
                            }
                        }
                    } else if (execute.size() >= 1 && !"PHOTO".equals(execute.get(i))
                            && !"EXECUTE".equals(execute.get(i))) {

                        if (interp.doCommand(execute.get(i)) == 0) {

                            if (i == execute.size() - 1) {
                                try {
                                    StatusUpdate reply = new StatusUpdate(ai.actionAnswer(execute.get(i))
                                            .get(r.nextInt(ai.actionAnswer(execute.get(i)).size())) + "@"
                                            + statuses.get(0).getUser().getScreenName());
                                    reply.setInReplyToStatusId(statuses.get(0).getId());
                                    twitter.updateStatus(reply);
                                } catch (TwitterException te) {
                                    Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                }
                            }
                        }
                    }
                }

            }
        }

        Log.d(TAG, "ready exit");

    } catch (TwitterException te) {
        te.printStackTrace();
        Log.e(TAG, "Failed to get timeline: " + te.getMessage());
    }

    return execute;
}

From source file:it.baywaylabs.jumpersumo.utility.Finder.java

License:Open Source License

public int executePQ(PriorityQueue pq, ARDeviceController deviceController, List<twitter4j.Status> statuses,
        Twitter twitter) {//from ww  w. j a v  a 2  s .c  o  m

    if (pq != null && !pq.isEmpty() && deviceController != null) {

        Interpreter interpreter = new Interpreter(deviceController);
        Intelligence ai = new Intelligence();
        Random r = new Random();
        int indexExecutedFile = 0;

        while (pq.isEmpty()) {
            Command c = (Command) pq.peek();
            Log.d(TAG, "Command Object: " + c.getPriority() + " -- " + c.getCmd());

            if ("EXECUTE".equals(c.getCmd())) {
                if (statuses != null && twitter != null
                        && this.getUrls(statuses.get(0).getText()).size() != 0) {

                    String url = statuses.get(0).getURLEntities()[indexExecutedFile].getExpandedURL();
                    // String url = f.getUrls(statuses.get(0).getText()).get(0);
                    File folder = new File(Constants.DIR_ROBOT);
                    Log.d(TAG, "URL Expanded: " + url);

                    if (downloadFileUrl(url, folder)) {
                        FileFilter ff = new FileFilter();
                        File[] list = folder.listFiles(ff);
                        if (list != null && list.length >= 1) {

                            if (list[0].getName().endsWith(".csv") || list[0].getName().endsWith(".txt")) {
                                String commandsList = "";
                                try {
                                    commandsList = this.getStringFromFile(list[0].getPath());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Log.d(TAG, "Lista comandi: " + commandsList);
                                interpreter.doListCommands(commandsList);
                                list[0].delete();

                                if (pq.size() == 1) {
                                    try {
                                        StatusUpdate reply = new StatusUpdate(ai
                                                .actionAnswer(
                                                        commandsList.split(";")[commandsList.length() - 1])
                                                .get(r.nextInt(ai.actionAnswer(
                                                        commandsList.split(";")[commandsList.length() - 1])
                                                        .size()))
                                                + "@" + statuses.get(0).getUser().getScreenName());
                                        reply.setInReplyToStatusId(statuses.get(0).getId());
                                        twitter.updateStatus(reply);
                                    } catch (TwitterException te) {
                                        Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                    }
                                }
                            }

                        }

                    }

                    pq.remove();
                    indexExecutedFile++;
                }
            } else {

                interpreter.doCommand(c.getCmd());
                pq.remove();
            }
        }
        return 0;
    } else if (pq.isEmpty()) {
        return 2;
    } else {
        return 1;
    }
}

From source file:net.lacolaco.smileessence.twitter.TweetBuilder.java

License:Open Source License

public StatusUpdate build() {
    StatusUpdate statusUpdate = new StatusUpdate(buildText());
    if (inReplyToStatusID >= 0) {
        statusUpdate.setInReplyToStatusId(inReplyToStatusID);
    }/*w w  w . j  a v  a  2  s  .  com*/
    if (!TextUtils.isEmpty(mediaPath)) {
        File media = new File(mediaPath);
        if (media.exists()) {
            statusUpdate.setMedia(media);
        }
    }
    return statusUpdate;
}

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

License:Open Source License

/**
 * Tweet./*from w  w  w . j  av a  2  s.  c  o m*/
 */
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;/*  www.ja  v  a 2  s. com*/
    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.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);//  www .j av a 2s .co 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 && 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  w w  . j  a v a 2  s . com*/

    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.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 av  a2  s  .co  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.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 . ja  v a2  s  .  c om
 * {@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 {/*from w  w  w .  java 2s  .  c  om*/
            TwitterUtils.getTwitter(new AccessToken(twitterAcc.getToken(), twitterAcc.getTokenSecret()))
                    .updateStatus(update);

        } catch (TwitterException e) {

        }
    } else
        twitterAcc.updateStatus(message);

    messageSent = true;

}