Example usage for twitter4j TwitterException getMessage

List of usage examples for twitter4j TwitterException getMessage

Introduction

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

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:TwitterSend2.java

License:BEER-WARE LICENSE

public void tweet(String _tweetMessage) {
    try {//from  ww  w.  j  a  v a2  s.  c  o m
        StatusUpdate status = new StatusUpdate(tweetMessage);
        status.setMedia(
                new File("/Users/Fabax/Pro/Processing/Processing-snippets/Twitter/TwitterSend2/data/nbd.jpg"));// BY SPECIFYING FILE PATH
        //status.setMedia("File name", new FileInputStream("")); // By InputStream
        Status updateStatus = twitter.updateStatus(status);
        // Status status = twitter.updateStatus(_tweetMessage);
        // println("Status updated to [" + status.getText() + "].");
    } catch (TwitterException te) {
        System.out.println("Error: " + te.getMessage());
    }
}

From source file:TwitterSend2.java

License:BEER-WARE LICENSE

public void directMessage(String _reveiver, String _directMessage) {
    try {/* w  w  w . j a v  a 2  s. com*/
        twitter.sendDirectMessage(_reveiver, _directMessage);
        println("Direct message sent");
    } catch (TwitterException te) {
        System.out.println("Error: " + te.getMessage());
    }
}

From source file:TimeLine.java

private void btTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTwitActionPerformed
    // Tombol update status, show setelah update
    txtStatus.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();/* w  w w . ja  va2s  . c o m*/

    try {
        Status status = twitter.updateStatus(txStatus.getText());
        JOptionPane.showMessageDialog(rootPane, "Twit \n [ " + status.getText() + " ]\nTerkirim!");
    } catch (TwitterException ex) {
        JOptionPane.showMessageDialog(rootPane, "Tidak bisa mengirim : " + ex.getMessage());
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Status> statuses = null;
    try {
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:TimeLine.java

private void btTimelineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTimelineActionPerformed
    // TODO add your handling code here:
    txtTimeline.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();//from w w w .  j  ava2 s . c  o  m

    List<Status> statuses = null;
    try {
        statuses = twitter.getHomeTimeline();

        statuses.stream().forEach((status) -> {
            txtTimeline.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });
    } catch (TwitterException ex) {
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + ex.getMessage());
    }
}

From source file:TimeLine.java

private void btReloadTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReloadTwitActionPerformed
    // Tombol reload twit saya
    txtStatus.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();/*from w  w w.ja v a2 s .c  om*/

    List<Status> statuses = null;
    try {
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:TweetMapManager.java

public static void main(String[] args) {

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();//w  w w.  j  a  va 2 s  . c  o  m
    String searchStr = "#ParkandGoUNL";
    Query query = new Query(searchStr);

    GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");
    List<Marker> markers = new LinkedList<>();
    StreetExtractor se = new StreetExtractor();
    LocalTime now = LocalTime.now();

    while (true) {
        DayOfWeek today = LocalDate.now().getDayOfWeek();
        if (today.getValue() < WEEKEND) {
            if (now.isAfter(STARTTIME) && now.isBefore(ENDTIME)) {

                // Send API request to execute a search with the given query.
                QueryResult results = null;
                try {
                    results = twitter.search(query);
                } catch (TwitterException ex) {
                    LOGGER.warn(ex.getMessage());
                }

                // Display search results.
                if (results != null) {
                    results.getTweets().stream().forEach((Status status) -> {
                        try {

                            Date created = status.getCreatedAt();
                            String text = status.getText();
                            LOGGER.info(status.getText());
                            LatLng location;
                            if (status.getGeoLocation() != null) {
                                location = new LatLng(status.getGeoLocation().getLatitude(),
                                        status.getGeoLocation().getLongitude());
                            } else {
                                String modified = text.replace("#ParkAndGoUNL", "");
                                List<Address> address = se.find(modified);

                                location = GeocodingApi.geocode(context, address.get(0).getAddress())
                                        .await()[0].geometry.location;
                            }
                            String id = UUID.randomUUID().toString().substring(0, 8);
                            Marker m = new Marker(location, "m" + id, text, created);
                            markers.add(m);
                        } catch (Exception ex) {
                            LOGGER.warn(ex.getMessage());
                        }

                    });
                }
                if (!markers.isEmpty()) {
                    Marker m = markers.get(markers.size() - 1);

                    if (m.getTimestamp().getTime() < Time.valueOf(now.minusMinutes(30)).getTime()) {
                        DailyLogs.addMarkerToLog(m, today);
                        markers.remove(m);
                    }
                }
                Map map = new Map(markers);
                map.create();
            } else {
                //wait 5 hours
                try {
                    LOGGER.info("Sleeping 5 hours");
                    Thread.sleep((long) 1.8e+7);
                } catch (InterruptedException ex) {
                    LOGGER.warn(ex.getMessage());
                }
            }

            now = LocalTime.now();
        } else {
            try {
                //Wait a day
                LOGGER.info("Sleeping 1 day");
                Thread.sleep((long) 8.64e+7);
            } catch (InterruptedException ex) {
                LOGGER.warn(ex.getMessage());
            }
        }
        try {
            LOGGER.info("Successful Loop, Resting");
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            LOGGER.warn(ex.getMessage());
        }
    }
}

From source file:Pencarian.java

private void btSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSearchActionPerformed
    // TODO add your handling code here:
    txtSearchTimeline.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();/*from  w  w w  .j a v a 2  s . c om*/

    Query query = new Query(txSearch.getText());
    QueryResult result = null;

    try {
        result = twitter.search(query);

        result.getTweets().stream().forEach((status) -> {
            txtSearchTimeline.append("@" + status.getUser().getScreenName() + ":" + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });
    } catch (TwitterException ex) {
        Logger.getLogger(Pencarian.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(rootPane, "Failed !! " + ex.getMessage());
    }
}

From source file:Demo.java

/**
 * Main method.//from  www  .  j a  va 2s. co  m
 *
 * @param args
 * @throws TwitterException
 */
public static void main(String[] args) throws TwitterException, IOException {

    // The TwitterFactory object provides an instance of a Twitter object
    // via the getInstance() method. The Twitter object is the API consumer.
    // It has the methods for interacting with the Twitter API.
    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();

    boolean keepItGoinFullSteam = true;
    do {
        // Main menu
        Scanner input = new Scanner(System.in);
        System.out.print("\n--------------------" + "\nH. Home Timeline\nS. Search\nT. Tweet"
                + "\n--------------------" + "\nA. Get Access Token\nQ. Quit" + "\n--------------------\n> ");
        String choice = input.nextLine();

        try {

            // Home Timeline
            if (choice.equalsIgnoreCase("H")) {

                // Display the user's screen name.
                User user = twitter.verifyCredentials();
                System.out.println("\n@" + user.getScreenName() + "'s timeline:");

                // Display recent tweets from the Home Timeline.
                for (Status status : twitter.getHomeTimeline()) {
                    System.out.println("\n@" + status.getUser().getScreenName() + ": " + status.getText());
                }

            } // Search
            else if (choice.equalsIgnoreCase("S")) {

                // Ask the user for a search string.
                System.out.print("\nSearch: ");
                String searchStr = input.nextLine();

                // Create a Query object.
                Query query = new Query(searchStr);

                // Send API request to execute a search with the given query.
                QueryResult result = twitter.search(query);

                // Display search results.
                result.getTweets().stream().forEach((Status status) -> {
                    System.out.println("\n@" + status.getUser().getName() + ": " + status.getText());
                });

            } // Tweet
            else if (choice.equalsIgnoreCase("T")) {

                boolean isOkayLength = true;
                String tweet;
                do {
                    // Ask the user for a tweet.
                    System.out.print("\nTweet: ");
                    tweet = input.nextLine();

                    // Ensure the tweet length is okay.
                    if (tweet.length() > 140) {
                        System.out.println("Too long! Keep it under 140.");
                        isOkayLength = false;
                    }
                } while (isOkayLength == false);

                // Send API request to create a new tweet.
                Status status = twitter.updateStatus(tweet);
                System.out.println("Just tweeted: \"" + status.getText() + "\"");

            } // Get Access Token
            else if (choice.equalsIgnoreCase("A")) {

                // First, we ask Twitter for a request token.
                RequestToken reqToken = twitter.getOAuthRequestToken();
                System.out.println("\nRequest token: " + reqToken.getToken() + "\nRequest token secret: "
                        + reqToken.getTokenSecret());

                AccessToken accessToken = null;
                while (accessToken == null) {

                    // The authorization URL sends the request token to Twitter in order
                    // to request an access token. At this point, Twitter asks the user
                    // to authorize the request. If the user authorizes, then Twitter
                    // provides a PIN.
                    System.out
                            .print("\nOpen this URL in a browser: " + "\n    " + reqToken.getAuthorizationURL()
                                    + "\n" + "\nAuthorize the app, then enter the PIN here: ");
                    String pin = input.nextLine();
                    try {
                        // We use the provided PIN to get the access token. The access
                        // token allows this app to access the user's account without
                        // knowing his/her password.
                        accessToken = twitter.getOAuthAccessToken(reqToken, pin);
                    } catch (TwitterException te) {
                        System.out.println(te.getMessage());
                    }
                }
                System.out.println("\nAccess token: " + accessToken.getToken() + "\nAccess token secret: "
                        + accessToken.getTokenSecret() + "\nSuccess!");

            } // Quit
            else if (choice.equalsIgnoreCase("Q")) {

                keepItGoinFullSteam = false;
                GeoApiContext context = new GeoApiContext()
                        .setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");

                System.out.println(GeocodingApi.geocode(context, "Sigma Phi Epsilon, Lincoln, Nebraska, USA")
                        .await()[0].geometry.location.toString());
                System.out.println(GeocodingApi.geocode(context, "16th and R, Lincoln, Nebraska, USA")
                        .await()[0].geometry.location.toString());
                File htmlFile = new File("map.html");
                Desktop.getDesktop().browse(htmlFile.toURI());
            } // Bad choice
            else {

                System.out.println("Invalid option.");
            }

        } catch (IllegalStateException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

    } while (keepItGoinFullSteam == true);
}

From source file:TwitterPull.java

public void retrieveTweets() {
    try {//from w  w w . j  a va  2  s . c o m
        Query query = new Query(this.queryString);
        query.setLang("en");
        query.setCount(100);
        QueryResult result;
        int i = 0;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            //                int i = 0;
            for (Status tweet : tweets) {
                System.out.println(tweet.getText().replaceAll("\n", "").replaceAll("\r", ""));
                //                    appendTweetDocument(tweet.getText());
            }
            i++;
        } while ((query = result.nextQuery()) != null && i < 10);
        //            setTwitterFeed(tweets);

        //            System.exit(0);
    } catch (TwitterException te) {
        Logger.getLogger(TwitterPull.class.getName()).log(Level.SEVERE, null, te);
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message//w w w  .  j av  a2  s  .  c  om
 */
public void getToken() throws TwitterException, IOException {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    MainActivity m = new MainActivity();
    Twitter twitter = new TwitterFactory().getInstance();
    try {

        try {
            if (file.exists()) {
                is = new FileInputStream(file);
                prop.load(is);
            }
            if (true) {
                if (null == prop.getProperty("oauth.consumerKey")
                        && null == prop.getProperty("oauth.consumerSecret")) {
                    // consumer key/secret are not set in twitter4j.properties
                    System.out.println(
                            "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                    // System.exit(-1);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            //System.exit(-1);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignore) {
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        try {

            RequestToken requestToken = twitter.getOAuthRequestToken();
            System.out.println("Got request token.");
            System.out.println("Request token: " + requestToken.getToken());
            System.out.println("Request token secret: " + requestToken.getTokenSecret());
            AccessToken accessToken = null;

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (null == accessToken) {
                System.out.println("Open the following URL and grant access to your account:");
                System.out.println(requestToken.getAuthorizationURL());
                try {
                    Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
                } catch (UnsupportedOperationException ignore) {
                } catch (IOException ignore) {
                } catch (URISyntaxException e) {
                    throw new AssertionError(e);
                }
                System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
                String pin = br.readLine();
                try {
                    if (pin.length() > 0) {
                        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                    } else {
                        accessToken = twitter.getOAuthAccessToken(requestToken);
                    }
                } catch (TwitterException te) {
                    if (401 == te.getStatusCode()) {
                        System.out.println("Unable to get the access token.");
                    } else {
                        System.out.println("fdfgghd");
                        te.printStackTrace();
                    }
                }
            }
            System.out.println("Got access token.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());

            try {
                prop.setProperty("oauth.accessToken", accessToken.getToken());
                prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
                os = new FileOutputStream(file);
                prop.store(os, "twitter4j.properties");
                os.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
                // System.exit(-1);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException ignore) {
                    }
                }
            }
            System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
            m.setTwitter(twitter);
            m.setVisible(true);

            //System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get accessToken: " + te.getMessage());
            //System.exit(-1);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println("Failed to read the system input.");
            // System.exit(-1);
        }

    } catch (java.lang.IllegalStateException jli) {

        System.out.println("Already registered");
        m.setTwitter(twitter);
        m.setVisible(true);
    }
}