Example usage for twitter4j TwitterException isCausedByNetworkIssue

List of usage examples for twitter4j TwitterException isCausedByNetworkIssue

Introduction

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

Prototype

public boolean isCausedByNetworkIssue() 

Source Link

Document

Tests if the exception is caused by network issue

Usage

From source file:com.eventattend.portal.bl.TwitterBL.java

License:Open Source License

public void processTwitterException(TwitterException e) throws BaseAppException {

    if (e.getStatusCode() == 400) {
        System.out.println("Limit exceeded");
        throw new TwitterRateLimitException();
    } else if (e.getStatusCode() == 401) {
        System.out.println("Authentication credentials were missing or incorrect.");
        throw new TwitterUnauthorizedException();
    } else if (e.getStatusCode() == 403) {
        System.out.println(/*  w  ww.  ja v a2  s .c  o  m*/
                "The request is understood, but it has been refused.  An accompanying error message will explain why. This code is used when requests are being denied due to update limits.");
        throw new TwitterForbiddenException();
    } else if (e.getStatusCode() == 404) {
        System.out.println(
                " The URI requested is invalid or the resource requested, such as a user, does not exists. ");
    } else if (e.getStatusCode() == 503) {
        System.out.println(
                "Service Unavailable: The Twitter servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.");
        throw new TwitterServiceUnavailableException(
                "Service Unavailable: The Twitter servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.");
    } else if (e.getStatusCode() == 500) {
        System.out
                .println("Something is broken.  Please post to the group so the Twitter team can investigate.");
        throw new TwitterServiceUnavailableException(
                "Something is broken.  Please post to the group so the Twitter team can investigate.");
    } else if (e.getStatusCode() == -1) {
        if (e.isCausedByNetworkIssue()) {
            System.out.println("Unable to connect to Twitter. Host Not found. Check for Internet Connection.");
        } else {
            System.out.println("Unknown Twitter problem.");
        }

    } else {
        e.printStackTrace();
    }
}

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:de.jetsli.twitter.TwitterSearch.java

License:Apache License

/**
 * @return a message describing the problem with twitter or an empty string
 * if nothing related to twitter!//from  w  ww .  j a  v  a  2 s.co m
 */
public static String getMessage(Exception ex) {
    String msg = ex.getMessage() == null ? "" : ex.getMessage();
    if (msg.length() > 100)
        msg = msg.substring(0, 100);
    if (ex instanceof TwitterException) {
        TwitterException twExc = (TwitterException) ex;
        if (twExc.exceededRateLimitation())
            return "Couldn't process your request. You don't have enough twitter API points!" + " Please wait: "
                    + twExc.getRetryAfter() + " seconds and try again! " + msg;
        else if (twExc.isCausedByNetworkIssue())
            return "Couldn't process your request. Network issue." + msg;

        return "Couldn't process your request. Something went wrong while communicating with Twitter :-/ "
                + msg;
    } else if (ex != null)
        return msg;

    return "";
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

/**
 * @return a message describing the problem with twitter or an empty string
 * if nothing related to twitter!/*from  ww w .  ja va2s  .  com*/
 */
public static String getMessage(Exception ex) {
    if (ex instanceof TwitterException) {
        TwitterException twExc = (TwitterException) ex;
        if (twExc.exceededRateLimitation())
            return ("Couldn't process your request. You don't have enough twitter API points!"
                    + " Please wait: " + twExc.getRetryAfter() + " seconds and try again!");
        else if (twExc.isCausedByNetworkIssue())
            return ("Couldn't process your request. Network issue.");
        else
            return ("Couldn't process your request. Something went wrong while communicating with Twitter :-/");
    }

    return "";
}

From source file:de.vanita5.twittnuker.util.OAuthPasswordAuthenticator.java

License:Open Source License

public AccessToken getOAuthAccessToken(final String username, final String password)
        throws AuthenticationException {
    if (twitter == null)
        return null;
    final RequestToken requestToken;
    try {//www  . j  a va2 s .  co  m
        requestToken = twitter.getOAuthRequestToken(OAUTH_CALLBACK_OOB);
    } catch (final TwitterException e) {
        if (e.isCausedByNetworkIssue())
            throw new AuthenticationException(e);
        throw new AuthenticityTokenException();
    }
    try {
        final String oauthToken = requestToken.getToken();
        final String authorizationUrl = requestToken.getAuthorizationURL().toString();
        final String authenticityToken = readAuthenticityTokenFromHtml(
                client.get(authorizationUrl, authorizationUrl, null, null).asReader());
        if (authenticityToken == null)
            throw new AuthenticityTokenException();
        final Configuration conf = twitter.getConfiguration();
        final HttpParameter[] params = new HttpParameter[4];
        params[0] = new HttpParameter("authenticity_token", authenticityToken);
        params[1] = new HttpParameter("oauth_token", oauthToken);
        params[2] = new HttpParameter("session[username_or_email]", username);
        params[3] = new HttpParameter("session[password]", password);
        final String oAuthAuthorizationUrl = conf.getOAuthAuthorizationURL().toString();
        final String oauthPin = readOAuthPINFromHtml(
                client.post(oAuthAuthorizationUrl, oAuthAuthorizationUrl, params).asReader());
        if (isEmpty(oauthPin))
            throw new WrongUserPassException();
        return twitter.getOAuthAccessToken(requestToken, oauthPin);
    } catch (final IOException e) {
        throw new AuthenticationException(e);
    } catch (final TwitterException e) {
        throw new AuthenticationException(e);
    } catch (final NullPointerException e) {
        throw new AuthenticationException(e);
    } catch (final XmlPullParserException e) {
        throw new AuthenticationException(e);
    }
}

From source file:edu.uml.TwitterDataMining.TwitterConsumer.java

/**
 * Search twitter with the given search term Results will be saved in a file
 * with the same name as the query/*from  ww  w . j  a  v a  2  s.c  o m*/
 *
 * @param searchTerm The search term to be queried
 * @return a list of tweets
 */
public static List<Status> queryTwitter(String searchTerm) {
    Query query = new Query(searchTerm);
    query.setLang("en"); // we only want english tweets
    // get and format date to get tweets no more than a year old
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String date = sdf.format(new Date(System.currentTimeMillis() - (long) (365 * 24 * 60 * 60 * 1000)));
    query.setSince(date);
    QueryResult result;
    List<Status> tweets = null;

    try {
        //ONLY GETTING FIRST SET OF RESULTS
        result = twitter.search(query);
        tweets = result.getTweets();
        //         for (Status tweet : tweets) {
        //            System.out.println("@" + tweet.getUser().getScreenName() + "\t" + tweet.getText());
        //         }

        // Wait loop for reset
    } catch (TwitterException te) {
        try { // try block for sleep thread
            if (!te.isCausedByNetworkIssue()) {
                // Not really checking for anything else but it is likely that we are out of requests
                int resetTime = te.getRateLimitStatus().getSecondsUntilReset();

                while (resetTime > 0) {
                    Thread.sleep(1000); // 1 second stop
                    System.out.println("seconds till reset: " + resetTime);
                    --resetTime;
                }
            } else {
                te.printStackTrace();
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
            System.exit(-1);
        }

    }
    return tweets;
}

From source file:edu.uml.TwitterDataMining.TwitterConsumer.java

/**
 * Search a specific user name and get their most recent tweets. DO NOT
 * INCLUDE THE @ SYMBOL BEFORE USERNAME/*from w  ww.  j  a  v  a2s.com*/
 *
 * @param Username
 * @return a list of tweets
 */
public static List<Status> queryTwitterUser(String Username) {
    List<Status> tweets = null;

    try {

        tweets = twitter.getUserTimeline(Username);
        //         for (Status tweet : tweets) {
        //            System.out.println("@" + tweet.getUser().getScreenName() + "\t" + tweet.getText());
        //         }

        // Wait loop for reset
    } catch (TwitterException te) {
        try { // try block for sleep thread
            if (!te.isCausedByNetworkIssue()) {
                // Not really checking for anything else but it is likely that we are out of requests
                int resetTime = te.getRateLimitStatus().getSecondsUntilReset();

                while (resetTime > 0) {
                    Thread.sleep(1000); // 1 second stop
                    System.out.println("seconds till reset: " + resetTime);
                    --resetTime;
                }
            } else {
                te.printStackTrace();
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
            System.exit(-1);
        }

    }
    return tweets;
}

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();
            }/* w  w  w. ja v a2 s .c o m*/
            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.getlantern.firetweet.util.OAuthPasswordAuthenticator.java

License:Open Source License

public AccessToken getOAuthAccessToken(final String username, final String password)
        throws AuthenticationException {
    final RequestToken requestToken;
    try {/*w ww  . j  av  a2  s  . c o m*/
        requestToken = twitter.getOAuthRequestToken(OAUTH_CALLBACK_OOB);
    } catch (final TwitterException e) {
        if (e.isCausedByNetworkIssue())
            throw new AuthenticationException(e);
        throw new AuthenticityTokenException();
    }
    try {
        final String oauthToken = requestToken.getToken();
        final String authorizationUrl = requestToken.getAuthorizationURL();
        final HashMap<String, String> inputMap = new HashMap<>();
        final HttpResponse authorizePage = client.get(authorizationUrl, authorizationUrl, null, null, null);
        final List<String> cookieHeaders = authorizePage.getResponseHeaders("Set-Cookie");
        readInputFromHtml(authorizePage.asReader(), inputMap, INPUT_AUTHENTICITY_TOKEN,
                INPUT_REDIRECT_AFTER_LOGIN);
        final Configuration conf = twitter.getConfiguration();
        final List<HttpParameter> params = new ArrayList<>();
        params.add(new HttpParameter("oauth_token", oauthToken));
        params.add(new HttpParameter(INPUT_AUTHENTICITY_TOKEN, inputMap.get(INPUT_AUTHENTICITY_TOKEN)));
        if (inputMap.containsKey(INPUT_REDIRECT_AFTER_LOGIN)) {
            params.add(new HttpParameter(INPUT_REDIRECT_AFTER_LOGIN, inputMap.get(INPUT_REDIRECT_AFTER_LOGIN)));
        }
        params.add(new HttpParameter("session[username_or_email]", username));
        params.add(new HttpParameter("session[password]", password));
        final HeaderMap requestHeaders = new HeaderMap();
        requestHeaders.addHeader("Origin", "https://twitter.com");
        requestHeaders.addHeader("Referer",
                "https://twitter.com/oauth/authorize?oauth_token=" + requestToken.getToken());
        requestHeaders.put("Cookie", cookieHeaders);
        final String oAuthAuthorizationUrl = conf.getOAuthAuthorizationURL();
        final String oauthPin = readOAuthPINFromHtml(client.post(oAuthAuthorizationUrl, oAuthAuthorizationUrl,
                params.toArray(new HttpParameter[params.size()]), requestHeaders).asReader());
        if (isEmpty(oauthPin))
            throw new WrongUserPassException();
        return twitter.getOAuthAccessToken(requestToken, oauthPin);
    } catch (final IOException | TwitterException | NullPointerException | XmlPullParserException e) {
        throw new AuthenticationException(e);
    }
}

From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java

License:Open Source License

public AccessToken getOAuthAccessToken(final String username, final String password)
        throws AuthenticationException {
    final RequestToken requestToken;
    try {//from  w w w .  j av  a 2s. c om
        requestToken = twitter.getOAuthRequestToken(OAUTH_CALLBACK_OOB);
    } catch (final TwitterException e) {
        if (e.isCausedByNetworkIssue())
            throw new AuthenticationException(e);
        throw new AuthenticityTokenException();
    }
    HttpResponse authorizePage = null, authorizeResult = null;
    try {
        final String oauthToken = requestToken.getToken();
        final String authorizationUrl = requestToken.getAuthorizationURL();
        final HashMap<String, String> inputMap = new HashMap<>();
        authorizePage = client.get(authorizationUrl, authorizationUrl, null, null, null);
        final List<String> cookieHeaders = authorizePage.getResponseHeaders("Set-Cookie");
        readInputFromHtml(authorizePage.asReader(), inputMap, INPUT_AUTHENTICITY_TOKEN,
                INPUT_REDIRECT_AFTER_LOGIN);
        final Configuration conf = twitter.getConfiguration();
        final List<HttpParameter> params = new ArrayList<>();
        params.add(new HttpParameter("oauth_token", oauthToken));
        params.add(new HttpParameter(INPUT_AUTHENTICITY_TOKEN, inputMap.get(INPUT_AUTHENTICITY_TOKEN)));
        if (inputMap.containsKey(INPUT_REDIRECT_AFTER_LOGIN)) {
            params.add(new HttpParameter(INPUT_REDIRECT_AFTER_LOGIN, inputMap.get(INPUT_REDIRECT_AFTER_LOGIN)));
        }
        params.add(new HttpParameter("session[username_or_email]", username));
        params.add(new HttpParameter("session[password]", password));
        final HeaderMap requestHeaders = new HeaderMap();
        requestHeaders.addHeader("Origin", "https://twitter.com");
        requestHeaders.addHeader("Referer",
                "https://twitter.com/oauth/authorize?oauth_token=" + requestToken.getToken());
        final List<String> modifiedCookieHeaders = new ArrayList<>();
        final String oAuthAuthorizationUrl = conf.getOAuthAuthorizationURL();

        final String host = parseUrlHost(oAuthAuthorizationUrl);
        for (String cookieHeader : cookieHeaders) {
            for (HttpCookie cookie : HttpCookie.parse(cookieHeader)) {
                if (HttpCookie.domainMatches(cookie.getDomain(), host)) {
                    cookie.setVersion(1);
                    cookie.setDomain("twitter.com");
                }
                modifiedCookieHeaders.add(cookie.toString());
            }
        }
        requestHeaders.put("Cookie", modifiedCookieHeaders);
        authorizeResult = client.post(oAuthAuthorizationUrl, oAuthAuthorizationUrl,
                params.toArray(new HttpParameter[params.size()]), requestHeaders);
        final String oauthPin = readOAuthPINFromHtml(authorizeResult.asReader());
        if (isEmpty(oauthPin))
            throw new WrongUserPassException();
        return twitter.getOAuthAccessToken(requestToken, oauthPin);
    } catch (final IOException | TwitterException | NullPointerException | XmlPullParserException e) {
        throw new AuthenticationException(e);
    } finally {
        if (authorizePage != null) {
            try {
                authorizePage.disconnect();
            } catch (IOException ignore) {
            }
        }
        if (authorizeResult != null) {
            try {
                authorizeResult.disconnect();
            } catch (IOException ignore) {
            }
        }
    }
}