Example usage for twitter4j StatusUpdate setMedia

List of usage examples for twitter4j StatusUpdate setMedia

Introduction

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

Prototype

public void setMedia(String name, InputStream body) 

Source Link

Usage

From source file:com.amandine.twitterpostforcoucou.Tweet.java

private void publishStatusUpdateWithMedia(String message) throws MalformedURLException, IOException {
    Status status = null;//from  ww w  . ja  v  a 2s  .c om
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            RequestToken requestToken = twitter.getOAuthRequestToken();
            AccessToken accessToken = null;
            while (null == accessToken) {
                logger.fine("Open the following URL and grant access to your account:");
                logger.fine(requestToken.getAuthorizationURL());
                try {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                } catch (TwitterException te) {
                    if (401 == te.getStatusCode()) {
                        logger.severe("Unable to get the access token.");
                    } else {
                        te.printStackTrace();
                    }
                }
            }
            logger.log(Level.INFO, "Got access token.");
            logger.log(Level.INFO, "Access token: {0}", accessToken.getToken());
            logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                logger.severe("OAuth consumer key/secret is not set.");
                return;
            }
        }
        //Instantiate and initialize a new twitter status update
        StatusUpdate statusUpdate = new StatusUpdate(message);
        //attach any media, if you want to
        statusUpdate.setMedia(
                //title of media
                "Amandine Leforestier Spring Summer 2015 white",
                new URL("https://issuu.com/kadiemurphy/docs/volume_xxi_issuu/52?e=0").openStream());
        //tweet or update status
        status = twitter.updateStatus(statusUpdate);

        //Status status = twitter.updateStatus(message);
        logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText());
    } catch (TwitterException te) {
        te.printStackTrace();
        logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage());
    }
}

From source file:com.amandine.twitterpostforcoucou.Tweet.java

public void tweetMessageToUser(String username, String hashtags, String imageUrl, String targetUrl,
        String twitterid) {//from   w  w  w  .j  av  a2  s. com
    Twitter twitterHandle = this.getTwitter();
    //Instantiate and initialize a new twitter status update
    String message = username + " " + targetUrl + " " + hashtags + " #amandineleforestier";
    StatusUpdate statusUpdate = new StatusUpdate(message);
    try {
        //attach any media, if you want to
        statusUpdate.setMedia(//title of media
                "Amandine Leforestier Athleasure Sport-Chic Autumn Winter 2015 http://shop.amandineleforestier.fr",
                new URL(imageUrl).openStream());
    } catch (MalformedURLException ex) {
        logger.log(Level.SEVERE, "Bad image Url {0}", ex.getMessage());
    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Cannot open Url {0}", ex.getMessage());
    }
    //tweet or update status
    Status status = null;
    try {
        status = twitterHandle.updateStatus(statusUpdate);
        logTheStatusUpdate(twitterid, message, imageUrl, targetUrl);
    } catch (TwitterException te) {
        logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage());
    }
    //Status status = twitter.updateStatus(message);
    if (status != null) {
        logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText());
    } else {
        logger.log(Level.SEVERE, "Status update failed [{0}].", status);
    }
}

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

License:Open Source License

/**
 * "Post" button and "Home" buttonhandler.
 *///  w  w w  .ja va  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 ww . 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")) {
            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();
        }
    }
}

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

License:Open Source License

/**
 * Post button and home button handler./*from w  w w . j  a  v  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 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, com.ibuildapp.romanblack.FanWallPlugin.data.Statics.APP_ID);

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

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

                        message_text += "\n" + contentPath;

                        boolean res = FacebookAuthorizationActivity.sharing(Authorization
                                .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken(),
                                message_text, image_url);
                        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 (com.ibuildapp.romanblack.FanWallPlugin.data.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();
        }
    }
}

From source file:com.learnncode.demotwitterimagepost.HelperMethods.java

License:Apache License

public static void postToTwitterWithInputStream(Context context, final Activity callingActivity,
        final InputStream inputStream, final String message, final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);//from   ww w .java 2  s .  c o m
        return;
    }

    final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken(context));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    final Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    new Thread(new Runnable() {

        private double x;

        @Override
        public void run() {
            boolean success = true;
            try {
                x = Math.random();
                if (inputStream != null) {
                    final StatusUpdate status = new StatusUpdate(message);
                    status.setMedia("GIF image", inputStream);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (final Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:net.bluemix.droneselfie.TwitterUtilities.java

License:Open Source License

private String tweet(String pictureId, String message) {
    String output = null;/*from w  w  w  .  ja  va  2s.  c o m*/
    if (message == null)
        return null;
    if (message.equalsIgnoreCase(""))
        return null;

    try {
        String consumerKey = ConfigUtilities.getSingleton().getTwitterConsumerKey();
        String consumerSecret = ConfigUtilities.getSingleton().getTwitterConsumerSecret();
        String accessToken = ConfigUtilities.getSingleton().getTwitterAccessToken();
        String accessTokenSecret = ConfigUtilities.getSingleton().getTwitterAccessTokenSecret();

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

        StatusUpdate statusUpdate = new StatusUpdate(message);

        AttachmentInputStream data = DatabaseUtilities.getSingleton().getDB().getAttachment(pictureId,
                pictureId);
        statusUpdate.setMedia("picture", data);

        Status status = twitter.updateStatus(statusUpdate);
        if (status == null)
            return null;
        output = "https://twitter.com/bluedroneselfie/status/" + String.valueOf(status.getId());

        return output;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return output;
}

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

License:Open Source License

/**
 * Tweet.// ww  w. j  a v  a  2 s. co  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:twitterswingclient.TwitterClient.java

private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed
    // TODO add your handling code here:
    String consKey = "Your key";
    String consSecret = "Your secret";
    String accToken = "Your key";
    String accSecret = "Your secret";
    try {/*from w w  w  . j a  va  2s  . c  o m*/

        TwitterFactory twitterFactory = new TwitterFactory();

        Twitter twitter = twitterFactory.getInstance();

        twitter.setOAuthConsumer(consKey, consSecret);

        twitter.setOAuthAccessToken(new AccessToken(accToken, accSecret));

        StatusUpdate statusUpdate = new StatusUpdate(status.getText());

        statusUpdate.setMedia("Feeling great",
                new URL("http://media3.giphy.com/media/el1tH0BzEWm4w/giphy.gif").openStream());

        Status stat = twitter.updateStatus(statusUpdate);

        textArea.append("status.toString() = " + stat.toString());
        textArea.append("status.getInReplyToScreenName() = " + stat.getInReplyToScreenName());
        textArea.append("status.getSource() = " + stat.getSource());
        textArea.append("status.getText() = " + stat.getText());
        textArea.append("status.getContributors() = " + Arrays.toString(stat.getContributors()));
        textArea.append("status.getCreatedAt() = " + stat.getCreatedAt());
        textArea.append("status.getCurrentUserRetweetId() = " + stat.getCurrentUserRetweetId());
        textArea.append("status.getGeoLocation() = " + stat.getGeoLocation());
        textArea.append("status.getId() = " + stat.getId());
        textArea.append("status.getInReplyToStatusId() = " + stat.getInReplyToStatusId());
        textArea.append("status.getInReplyToUserId() = " + stat.getInReplyToUserId());
        textArea.append("status.getPlace() = " + stat.getPlace());
        textArea.append("status.getRetweetCount() = " + stat.getRetweetCount());
        textArea.append("status.getRetweetedStatus() = " + stat.getRetweetedStatus());
        textArea.append("status.getUser() = " + stat.getUser());
        textArea.append("status.getAccessLevel() = " + stat.getAccessLevel());
        textArea.append("status.getHashtagEntities() = " + Arrays.toString(stat.getHashtagEntities()));
        textArea.append("status.getMediaEntities() = " + Arrays.toString(stat.getMediaEntities()));

        if (stat.getRateLimitStatus() != null) {
            textArea.append("status.getRateLimitStatus().getLimit() = " + stat.getRateLimitStatus().getLimit());
            textArea.append(
                    "status.getRateLimitStatus().getRemaining() = " + stat.getRateLimitStatus().getRemaining());
            textArea.append("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + stat.getRateLimitStatus().getResetTimeInSeconds());
            textArea.append("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + stat.getRateLimitStatus().getSecondsUntilReset());
            textArea.append("status.getRateLimitStatus().getRemainingHits() = "
                    + stat.getRateLimitStatus().getRemaining());
        }
        textArea.append("status.getURLEntities() = " + Arrays.toString(stat.getURLEntities()));
        textArea.append("status.getUserMentionEntities() = " + Arrays.toString(stat.getUserMentionEntities()));

    } catch (IOException ex) {
        textArea.append("IO Exception");
    } catch (TwitterException tw) {
        textArea.append("Twitter Exception");
    }
}