Example usage for twitter4j TwitterException getStatusCode

List of usage examples for twitter4j TwitterException getStatusCode

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Usage

From source file:com.rhymestore.twitter.util.TwitterUtils.java

License:Open Source License

/**
 * Checks if the exception cause is a duplicate tweet.
 * /*from   ww w  .  j av  a  2 s  .c om*/
 * @param ex The exception to check.
 * @return Boolean indicating if the exception cause is a duplicate tweet.
 */
public static boolean isDuplicateTweetError(final TwitterException ex) {
    return ex.getStatusCode() == HttpResponseCode.FORBIDDEN && ex.getMessage().contains(DUPLICATE_TWEET_ERROR);
}

From source file:com.temenos.interaction.example.mashup.twitter.OAuthRequestor.java

License:Open Source License

public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;// ww w  .j av a  2 s .  c  om
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Open the following URL and grant access to your account:");
            LOGGER.debug(requestToken.getAuthorizationURL());
            LOGGER.debug("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        }

        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode() && LOGGER.isInfoEnabled()) {
                LOGGER.info("Unable to get the access token.");
            } else {
                LOGGER.error("Error writing the object.", te);
            }
        }
    }
    // persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId(), accessToken);

    // Tweet!      
    //      Status status = twitter.updateStatus(args[0]);
    //      System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:com.twitstreet.twitter.TwitterProxyImpl.java

License:Open Source License

private void handleError(TwitterException e, ArrayList<Object> params) {

    String paramsStr = "";

    if (params != null) {

        for (Object obj : params) {
            paramsStr = paramsStr + obj.toString() + ", ";
        }/*from ww w. j  av  a  2  s  .  c o m*/

    }

    if (e.getStatusCode() == NOT_FOUND) {
        logger.debug("Twitter: User not found. Params: " + paramsStr);
    } else if (e.getStatusCode() == USER_SUSPENDED) {
        logger.info("Twitter: User suspended. Params: " + paramsStr);
    } else if (e.getStatusCode() == TWITTER_SERVERS_OVERLOADED) {
        logger.info("Twitter: The Twitter servers are up, but overloaded with requests. Try again later.");
    } else if (e.getStatusCode() == RATE_LIMIT_EXCEEDED) {
        logger.error("Twitter: Rate limit exceeded.");
    } else if (e.getStatusCode() == UNAUTHORIZED) {

        logger.error("Twitter: Authentication credentials were missing or incorrect. Token: " + oToken
                + ", Secret: " + oSecret);

        com.twitstreet.db.data.User user = userMgr.getUserByTokenAndSecret(oToken, oSecret);

        userMgr.deleteUser(user.getId());

    } else if (e.getStatusCode() == INVALID_REQUEST) {

        logger.error(
                "Twitter: The request was invalid. Possible reason: Query string may be including empty character. ");

    } else {
        logger.error("Twitter: Unhandled twitter exception.", e);

    }

}

From source file:com.twitstreet.twitter.TwitterProxyImpl.java

License:Open Source License

@Override
public boolean verifyUser() {

    try {//  w w  w.  jav  a  2  s  .c  o  m
        User user = twitter.verifyCredentials();
        if (user == null)
            return false;
    } catch (TwitterException e) {
        if (e.getStatusCode() == UNAUTHORIZED) {
            return false;
        }
    }
    return true;
}

From source file:com.wimbli.serverevents.Register.java

License:Open Source License

public static boolean tryPin(String pin) {
    if (pin == null)
        pin = "";

    try {/*from w  w w .j  a  va 2 s.  c o  m*/
        if (pin.length() > 0)
            accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        else
            accessToken = twitter.getOAuthAccessToken(requestToken);
    } catch (TwitterException te) {
        if (te.getStatusCode() == 401)
            msg("Unable to get the access token. 401: Unauthorized.");
        else {
            msg("Unable to get the access token. Stack trace output to log.");
            te.printStackTrace();
        }
        return false;
    }

    msg("Successfully connected to Twitter.");

    msg("******************* IMPORTANT ********************");
    msg("Place these values in your server_events.xml file:");
    msg("accessToken=\"" + accessToken.getToken() + "\"");
    msg("accessTokenSecret=\"" + accessToken.getTokenSecret() + "\"");
    msg("*************************************************");

    outputToFile("<twitter enabled=\"true\" accessToken=\"" + accessToken.getToken() + "\" accessTokenSecret=\""
            + accessToken.getTokenSecret()
            + "\" rate_limit=\"350\" add_timestamp=\"true\" timestamp_hour_offset=\"0\" />");
    msg("For convenience, a completed entry (which can be copied to server_events.xml) is output to the file: "
            + outFile);

    if (cmdLine)
        msg("Access granted to Twitter. After updating server_event.xml with the info above, you can start the server up.");
    else
        msg("After editing server_events.xml, you can use \"" + (isPlayer ? "/" : "")
                + "serverevents reload\" to reload it without needing to restart the server.");

    return true;
}

From source file:de.fhb.twitalyse.spout.TwitterStreamSpout.java

License:Open Source License

@Override
public void onException(Exception ex) {
    LOGGER.log(Level.SEVERE, null, ex);
    TwitterException tex = (TwitterException) ex;
    if (400 == tex.getStatusCode()) {
        close();//w  ww .  j  av  a  2s .  c o m
        LOGGER.log(Level.SEVERE,
                "Rate limit texceeded. Clients may not make more than {0} requests per hour. \nThe ntext reset is {1}",
                new Object[] { tex.getRateLimitStatus().getHourlyLimit(),
                        tex.getRateLimitStatus().getResetTime() });
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (401 == tex.getStatusCode()) {
        close();
        LOGGER.log(Level.SEVERE, "Authentication credentials were missing or incorrect.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (403 == tex.getStatusCode()) {
        LOGGER.log(Level.SEVERE, "Duplicated status.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (404 == tex.getStatusCode()) {
        LOGGER.log(Level.SEVERE,
                "The URI requested is invalid or the resource requested, such as a user, does not exists.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (406 == tex.getStatusCode()) {
        LOGGER.log(Level.SEVERE, "Request returned - invalid format is specified in the request.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (420 == tex.getStatusCode()) {
        close();
        LOGGER.log(Level.SEVERE, "Too many logins with your account in a short time.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (500 == tex.getStatusCode()) {
        LOGGER.log(Level.SEVERE,
                "Something is broken. Please post to the group so the Twitter team can investigate.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (502 == tex.getStatusCode()) {
        close();
        LOGGER.log(Level.SEVERE, "Twitter is down or being upgraded.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (503 == tex.getStatusCode()) {
        close();
        LOGGER.log(Level.SEVERE, "The Twitter servers are up, but overloaded with requests. Try again later.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else if (-1 == tex.getStatusCode()) {
        close();
        LOGGER.log(Level.SEVERE, "Can not connect to the internet or the host is down.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    } else {
        close();
        LOGGER.log(Level.SEVERE, "Unknown twitter-error occured.");
        LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}",
                new Object[] { tex, tex.getMessage(), tex.getCause() });
    }
}

From source file:de.hikinggrass.eiwomisarc.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 * //from w ww .  ja v a2 s.c o  m
 * @param args
 *            message
 */
public UpdateStatus() {
    try {
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        //use https for oauth 
        confBuilder.setUseSSL(true);

        Configuration conf = confBuilder.build();
        Twitter twitter = new TwitterFactory(conf).getInstance();
        twitter.setOAuthConsumer("HaBxuZMHygmtcuPeCbOLg", "zg6bV26ksBrgKHdhmiLlubTtV9MaDhoIRZC1ODUKw");
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            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());
                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 {
                        te.printStackTrace();
                    }
                }
            }
            System.out.println("Got access token.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                System.out.println("OAuth consumer key/secret is not set.");
                System.exit(-1);
            }
        }
        Status status = twitter.updateStatus("test from eiwomisarc");
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:de.hoesel.dav.buv.twitter.preferences.TwitterPreferencePage.java

License:Open Source License

protected Control createContents(Composite parent) {
    noDefaultAndApplyButton();/*  w w  w  . j a v a2 s.c  o m*/
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    composite.setLayout(layout);

    try {
        user = twitter.verifyCredentials();
        invalidateTwitterAuthentication(composite, user);
    } catch (TwitterException e) {
        if (401 == e.getStatusCode()) {
            // (noch) kein oauth token
        } else {
            Activator.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getErrorMessage()));
        }

        createNewTwitterAuthentication(composite);

    } catch (Exception e2) {
        createNewTwitterAuthentication(composite);
    }

    return composite;
}

From source file:de.vanita5.twittnuker.util.imageloader.TwidereImageDownloader.java

License:Open Source License

@Override
protected InputStream getStreamFromNetwork(final String uriString, final Object extras) throws IOException {
    if (uriString == null)
        return null;
    final ParcelableMedia media = MediaPreviewUtils.getAllAvailableImage(uriString, mFullImage,
            mFullImage || !mFastImageLoading ? mClient : null);
    try {//from   w w  w .  ja v  a  2 s .  co m
        final String mediaUrl = media != null ? media.media_url : uriString;
        if (isTwitterProfileImage(uriString)) {
            final String replaced = getTwitterProfileImageOfSize(mediaUrl, mTwitterProfileImageSize);
            return getStreamFromNetworkInternal(replaced, extras);
        } else
            return getStreamFromNetworkInternal(mediaUrl, extras);
    } catch (final TwitterException e) {
        final int statusCode = e.getStatusCode();
        if (statusCode != -1 && isTwitterProfileImage(uriString) && !uriString.contains("_normal.")) {
            try {
                return getStreamFromNetworkInternal(getNormalTwitterProfileImage(uriString), extras);
            } catch (final TwitterException e2) {

            }
        }
        throw new IOException(
                String.format(Locale.US, "Error downloading image %s, error code: %d", uriString, statusCode));
    }
}

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

License:Open Source License

public static HttpResponse getRedirectedHttpResponse(final HttpClientWrapper client, final String url,
        final String signUrl, final Authorization auth) throws TwitterException {
    if (url == null)
        return null;
    final ArrayList<String> urls = new ArrayList<String>();
    urls.add(url);// ww w .  ja v a  2s .  c om
    HttpResponse resp;
    try {
        resp = client.get(url, signUrl, auth);
    } catch (final TwitterException te) {
        if (isRedirected(te.getStatusCode())) {
            resp = te.getHttpResponse();
        } else
            throw te;
    }
    while (resp != null && isRedirected(resp.getStatusCode())) {
        final String request_url = resp.getResponseHeader("Location");
        if (request_url == null)
            return null;
        if (urls.contains(request_url))
            throw new TwitterException("Too many redirects");
        urls.add(request_url);
        try {
            resp = client.get(request_url, request_url);
        } catch (final TwitterException te) {
            if (isRedirected(te.getStatusCode())) {
                resp = te.getHttpResponse();
            } else
                throw te;
        }
    }
    return resp;
}