Example usage for twitter4j TwitterException getExceptionCode

List of usage examples for twitter4j TwitterException getExceptionCode

Introduction

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

Prototype

public String getExceptionCode() 

Source Link

Document

Returns a hexadecimal representation of this exception stacktrace.
An exception code is a hexadecimal representation of the stacktrace which enables it easier to Google known issues.
Format : XXXXXXXX:YYYYYYYY[ XX:YY]
Where XX is a hash code of stacktrace without line number
YY is a hash code of stacktrace excluding line number
[-XX:YY] will appear when this instance a root cause

Usage

From source file:Collector.TweetCollector.java

public static List<Status> getTweets(final String q) {
    Timer timer = new Timer();
    TimerTask hourlyTask = new TimerTask() {

        @Override//from   w w w .  java  2  s .  c  o m
        public void run() {

            long amountOfTweets = 0;

            try {

                long maxID = -1;

                Query query = new Query(q);
                //printTimeLine(query);
                Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
                RateLimitStatus searchLimit = rateLimitStatus.get("/search/tweets");
                for (int batchNumber = 0; MAX_QUERIES < 10; batchNumber++) {

                    System.out.printf("\n\n!!! batch %d\n\n", batchNumber);

                    if (searchLimit.getRemaining() == 0) {
                        // so as to not get blocked by twitter
                        Thread.sleep(searchLimit.getSecondsUntilReset() + 3 * 1001);
                    }

                    query.setCount(TWEETS_PER_QUERY);// constant value of 100
                    query.setResultType(Query.ResultType.recent);
                    query.setLang("en");// only english tweets

                    if (maxID != -1) {
                        query.setMaxId(maxID - 1);// so the first querys not set to previous max
                    }
                    QueryResult result = twitter.search(query);
                    if (result.getTweets().size() == 0) {
                        break;
                    }

                    for (Status s : result.getTweets()) {
                        amountOfTweets++;
                        if (maxID == -1 || s.getId() < maxID) {
                            maxID = s.getId();
                        }
                        storeTweet(s);// where stored in db

                        System.out.printf("At%s : %s\n", // debugging purposes
                                s.getCreatedAt().toString(), s.getText());
                        searchLimit = result.getRateLimitStatus(); //resets
                        System.out.printf("\n\nA total of %d tweet retrieved\n", amountOfTweets);

                    }

                }

            } catch (TwitterException te) {

                System.out.println("Error Code :" + te.getErrorCode());
                System.out.println("Exception Code " + te.getExceptionCode());
                System.out.println("Status Code " + te.getStatusCode());

                if (te.getStatusCode() == 401) {
                    System.out.println("Twitter Error :\nAuthentication "
                            + "credentials (https://dev.twitter.com/auth) "
                            + " are either missing of incorrect, " + "\nplease check consumer key /secret");
                }
            } catch (InterruptedException ex) {

            }

        }
    };

    // schedule the task to run starting now and then every hour...
    timer.schedule(hourlyTask, 0l, 1000 * 60 * 60);
    return statuses;

}

From source file:com.revolucion.secretwit.twitter.TwitterClient.java

License:Open Source License

private String findExceptionCause(TwitterException exception) {
    if (exception.exceededRateLimitation())
        return "Rate limitation exceeded.";

    if (exception.isCausedByNetworkIssue())
        return "Network issue.";

    if (exception.resourceNotFound())
        return "Resource not found.";

    return exception.getMessage() + " " + exception.getExceptionCode();
}

From source file:com.revolucion.secretwit.ui.SignupPane.java

License:Open Source License

private void init() {
    labelInfo = new MultilineLabel(
            "SecreTwit uses OAuth authentication for safe access to your Twitter account.");

    numberAuthorize = new NumberRenderer(1);
    labelAuthorize = new JLabel("Please first authorize this application on Twitter.com");
    buttonAuthorize = new JButton("Sign in to Twitter in browser");
    buttonAuthorize.addActionListener(new ActionListener() {
        @Override//from  w w  w  .  j  a  va  2s.  c om
        public void actionPerformed(ActionEvent e) {
            String authorizationUrl = TwitterClient.getInstance().getAuthorizationUrl();
            logger.info("Authorization url: {}", authorizationUrl);

            SystemUtils.openWebSite(authorizationUrl);

            /*
            int option = JOptionPane.showOptionDialog(SignupPane.this, "Please use following link to authorize this application.", "Authorization", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Open in browser", "Copy link" }, "Open in browser");
            if (option == 0) {
               // Open url in default browser
               SystemUtils.openWebSite(authorizationUrl);
            }
            else if (option == 1) {
               // Copy url to clipboard
               StringSelection contents = new StringSelection(authorizationUrl);
               Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, contents);
            }
            */

            fieldPin.setEnabled(true);
        }
    });

    numberPin = new NumberRenderer(2);
    labelPin = new JLabel("Then enter the PIN provided to you by Twitter.com");
    fieldPin = new JTextField(10);
    fieldPin.setEnabled(false);
    fieldPin.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            buttonSignIn.setEnabled(e.getLength() != 0);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            buttonSignIn.setEnabled(e.getLength() != 0);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            buttonSignIn.setEnabled(e.getLength() != 0);
        }
    });
    buttonSignIn = new JButton("Sign in");
    buttonSignIn.setEnabled(false);
    buttonSignIn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String pin = fieldPin.getText();
            if (pin != null && !pin.isEmpty()) {
                try {
                    User authorizedUser = TwitterClient.getInstance().authorize(pin);
                    if (authorizedUser != null) {
                        HeaderPane.getInstance().setPlace("@home");
                        HeaderPane.getInstance().setUserStatus(authorizedUser.getScreenName(), true);
                        ViewManager.getInstance().showTimelineView();
                        TimelinePane.getInstance().reload();
                        MessagePane.getInstance().setEnabled(true);
                    }
                } catch (TwitterException te) {
                    logger.error("Authorization error. {} - {}", te.getExceptionCode(), te.getMessage());
                    JOptionPane.showMessageDialog(SignupPane.this,
                            "<html><b>Authorization failed.</b><br>" + te.getMessage(), "Authorization Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    });

    buttonCancel = new JButton("Cancel");
    buttonCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            HeaderPane.getInstance().setPlace("@public");
            HeaderPane.getInstance().setUserStatus(null, false);
            ViewManager.getInstance().showTimelineView();
        }
    });

    add(labelInfo, "span, growx, wrap");
    add(numberAuthorize, "spany 2");
    add(labelAuthorize, "wrap");
    add(buttonAuthorize, "growx, wrap");
    add(numberPin, "spany 2");
    add(labelPin, "wrap");
    add(fieldPin, "split 2");
    add(buttonSignIn, "growx, wrap");
    add(buttonCancel, "span, tag cancel");
}

From source file:org.apache.streams.twitter.provider.TwitterErrorHandler.java

License:Apache License

public static int handleTwitterError(Twitter twitter, Exception exception) {
    if (exception instanceof TwitterException) {
        TwitterException e = (TwitterException) exception;
        if (e.exceededRateLimitation()) {
            LOGGER.warn("Rate Limit Exceeded");
            try {
                Thread.sleep(retry);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }/*from w w  w  . j  av  a 2 s. com*/
            return 1;
        } else if (e.isCausedByNetworkIssue()) {
            LOGGER.info("Twitter Network Issues Detected. Backing off...");
            LOGGER.info("{} - {}", e.getExceptionCode(), e.getLocalizedMessage());
            try {
                Thread.sleep(retry);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }
            return 1;
        } else if (e.isErrorMessageAvailable()) {
            if (e.getMessage().toLowerCase().contains("does not exist")) {
                LOGGER.warn("User does not exist...");
                return 100;
            } else {
                return 1;
            }
        } else {
            if (e.getExceptionCode().equals("ced778ef-0c669ac0")) {
                // This is a known weird issue, not exactly sure the cause, but you'll never be able to get the data.
                return 5;
            } else {
                LOGGER.warn("Unknown Twitter Exception...");
                LOGGER.warn("  Account: {}", twitter);
                LOGGER.warn("   Access: {}", e.getAccessLevel());
                LOGGER.warn("     Code: {}", e.getExceptionCode());
                LOGGER.warn("  Message: {}", e.getLocalizedMessage());
                return 1;
            }
        }
    } else if (exception instanceof RuntimeException) {
        LOGGER.warn("TwitterGrabber: Unknown Runtime Error", exception.getMessage());
        return 1;
    } else {
        LOGGER.info("Completely Unknown Exception: {}", exception);
        return 1;
    }
}

From source file:org.onebusaway.admin.service.impl.TwitterServiceImpl.java

License:Apache License

public String updateStatus(String statusMessage) throws IOException {
    if (statusMessage == null) {
        _log.info("nothing to tweet!  Exiting");
        return null;
    }//from   w  w  w  . ja va 2  s  . c  o  m

    Map<String, String> params = new HashMap<>();
    _log.info("tweeting: " + statusMessage);
    params.put("status", statusMessage);

    if (_twitter == null) {
        throw new IOException("Invalid Configuration:  Missing consumer / access keys in spring configuration");
    }

    String response = null;
    try {
        Status status = _twitter.updateStatus(statusMessage);
        if (status != null) {
            response = "Successfully tweeted \"" + status.getText() + "\" at " + status.getCreatedAt();
        }
    } catch (TwitterException te) {
        _log.error(te.getExceptionCode() + ":" + ":" + te.getStatusCode() + te.getErrorMessage());
        throw new IOException(te);
    }
    return response;
}