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.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(//  ww w . j  a  v  a  2  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.freedomotic.plugins.devices.twitter.gateways.OAuthSetup.java

License:Open Source License

/**
 * @param args/*from  ww w .jav a2s .  c o  m*/
 */
public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();

    //insert the appropriate consumer key and consumer secret here

    twitter.setOAuthConsumer("TLGtvoeABqf2tEG4itTUaw", "nUJPxYR1qJmhX9SnWTBT0MzO7dIqUtNyVPfhg10wf0");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    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 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()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    //persist to the accessToken for future reference.
    System.out.println(twitter.verifyCredentials().getId());
    System.out.println("token : " + accessToken.getToken());
    System.out.println("tokenSecret : " + accessToken.getTokenSecret());
    //storeAccessToken(twitter.verifyCredentials().getId() , accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:com.freshdigitable.udonroad.subscriber.StatusRequestWorker.java

License:Apache License

@StringRes
private static int findMessageByTwitterExeption(@NonNull Throwable throwable) {
    if (!(throwable instanceof TwitterException)) {
        return 0;
    }//from   w  ww  .ja v  a  2  s.  c o m
    final TwitterException te = (TwitterException) throwable;
    final int statusCode = te.getStatusCode();
    final int errorCode = te.getErrorCode();
    if (statusCode == 403 && errorCode == 139) {
        return R.string.msg_already_fav;
    } else if (statusCode == 403 && errorCode == 327) {
        return R.string.msg_already_rt;
    }
    Log.d(TAG, "not registered exception: ", throwable);
    return 0;
}

From source file:com.gloriouseggroll.TwitterAPI.java

License:Open Source License

public void CreateAccessToken(String pin) {
    //this.access_token = access_token;
    try {/* ww w.  j  a  v  a2s  .  c  o  m*/
        if (pin.length() > 0) {
            this.access_token = twitter.getOAuthAccessToken(requestToken, pin);
        } else {
            this.access_token = twitter.getOAuthAccessToken();
        }
    } catch (TwitterException te) {
        if (401 == te.getStatusCode()) {
            System.out.println("Unable to get the access token.");
        } else {
            te.printStackTrace();
        }
    }
}

From source file:com.google.minijoe.sys.Eval.java

License:Apache License

public void evalNative(int index, JsArray stack, int sp, int parCount) {
    switch (index) {
    case ID_HTTP_GET:
        try {/*from  w  w w.ja  va  2 s. c om*/
            String url = stack.getString(sp + 2);
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            stack.setObject(sp, response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        break;

    case ID_POST_JSON:
        try {
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                    stack.getString(sp + 3));
            Request request = new Request.Builder().url(stack.getString(sp + 2)).post(body).build();
            Response response = client.newCall(request).execute();
            stack.setObject(sp, response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        break;

    case ID_CRAWLER:
        try {
            Crawler.startCrawler(stack.getString(sp + 2));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        break;

    case ID_CURL:
        new Thread(new Curl()).start();
        break;

    case ID_EXTRACT_HTML:

        try {
            Readability readability = new Readability(new URL(stack.getString(sp + 2)), stack.getInt(sp + 3));
            readability.init();
            stack.setObject(sp, readability.outerHtml());
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        break;

    case ID_EVAL:
        try {
            stack.setObject(sp, eval(stack.getString(sp + 2),
                    stack.isNull(sp + 3) ? stack.getJsObject(sp) : stack.getJsObject(sp + 3)));
        } catch (Exception e) {
            throw new RuntimeException("" + e);
        }

        break;

    case ID_COMPILE:
        try {
            File file = new File(stack.getString(sp + 2));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            byte[] data = new byte[(int) file.length()];
            dis.readFully(data);
            String code = new String(data, "UTF-8");
            Eval.compile(code, System.out);
            dis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LOAD:
        try {
            File file = new File(stack.getString(sp + 2));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            byte[] data = new byte[(int) file.length()];
            dis.readFully(data);
            String code = new String(data, "UTF-8");
            //xxx.js
            Eval.eval(code, Eval.createGlobal());
            dis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_GEN_SITEMAP:

        try {
            // create web sitemap for web http://www.javavids.com
            WebSitemapGenerator webSitemapGenerator = new WebSitemapGenerator("http://www.javavids.com");
            // add some URLs
            webSitemapGenerator.addPage(new WebPage().setName("index.php").setPriority(1.0)
                    .setChangeFreq(ChangeFreq.NEVER).setLastMod(new Date()));
            webSitemapGenerator.addPage(new WebPage().setName("latest.php"));
            webSitemapGenerator.addPage(new WebPage().setName("contact.php"));
            // generate sitemap and save it to file /var/www/sitemap.xml
            File file = new File("/var/www/sitemap.xml");
            webSitemapGenerator.constructAndSaveSitemap(file);
            // inform Google that this sitemap has changed
            webSitemapGenerator.pingGoogle();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_WHOIS:
        try {
            stack.setObject(sp, Whois.getRawWhoisResults(stack.getString(sp + 2)));
        } catch (WhoisException e) {
            stack.setObject(sp, "Whois Exception " + e.getMessage());
        } catch (HostNameValidationException e) {
            stack.setObject(sp, "Whois host name invalid " + e.getMessage());
        }
        break;

    case ID_PAGERANK:
        stack.setObject(sp, PageRank.getPR(stack.getString(sp + 2)));
        break;

    case ID_SEND_TWITTER:
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            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(stack.getString(sp + 2));
            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);
        }
        break;

    case ID_EXTRACT_TEXT:
        try {
            String url = stack.getString(sp + 2);
            String selector = stack.getString(sp + 3);

            Document doc = Jsoup.connect(url).userAgent("okhttp").timeout(5 * 1000).get();

            HtmlToPlainText formatter = new HtmlToPlainText();

            if (selector != null) {
                Elements elements = doc.select(selector);
                StringBuffer sb = new StringBuffer();
                for (Element element : elements) {
                    String plainText = formatter.getPlainText(element);
                    sb.append(plainText);
                }
                stack.setObject(sp, sb.toString());
            } else {
                stack.setObject(sp, formatter.getPlainText(doc));

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LIST_LINKS:
        try {
            String url = stack.getString(sp + 2);
            print("Fetching %s...", url);

            Document doc = Jsoup.connect(url).get();
            Elements links = doc.select("a[href]");
            Elements media = doc.select("[src]");
            Elements imports = doc.select("link[href]");

            print("\nMedia: (%d)", media.size());
            for (Element src : media) {
                if (src.tagName().equals("img"))
                    print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"),
                            src.attr("height"), trim(src.attr("alt"), 20));
                else
                    print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
            }

            print("\nImports: (%d)", imports.size());
            for (Element link : imports) {
                print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel"));
            }

            print("\nLinks: (%d)", links.size());
            for (Element link : links) {
                print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LOG:
        log.info(stack.getString(sp + 2));
        break;

    case ID_SEND_MAIL:
        try {
            // put your e-mail address here
            final String yourAddress = "guilherme.@gmail.com";

            // configure programatically your mail server info
            EmailTransportConfiguration.configure("smtp.server.com", true, false, "username", "password");

            // and go!
            new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress)
                    .withSubject("Fluent Mail API").withAttachment("file_name").withBody("Demo message").send();

        } catch (Exception ex) {
            stack.setObject(sp, "[ERROR]" + ex.getMessage());
        }
        break;

    case ID_SNAPPY:
        try {
            String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of "
                    + "Snappy, a fast compresser/decompresser.";
            byte[] compressed = Snappy.compress(input.getBytes("UTF-8"));
            byte[] uncompressed = Snappy.uncompress(compressed, 0, compressed.length);

            String result = new String(uncompressed, "UTF-8");
            System.out.println(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_OPENBROWSER:
        new Thread(new Runnable() {
            public void run() {
                openBrowser();
            }
        }).start();
        break;

    case ID_HELP:
        Enumeration ex = this.keys();
        while (ex.hasMoreElements()) {
            String key = (String) ex.nextElement();
            Object val = this.getRawInPrototypeChain(key);
            if (val instanceof JsFunction) {
                System.out.println(key + "---" + ((JsFunction) val).description);
            } else {
                System.out.println(key + "---" + val);
            }
        }
        break;

    default:
        super.evalNative(index, stack, sp, parCount);
    }
}

From source file:com.ikungolf.java.javatwitter.twitterCmd.java

public void updateStatus(String msg) {
    if (msg == null) {
        System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
        System.exit(-1);//  www  .ja v a 2s  .  c o  m
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        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(msg);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    } 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:com.michaelfitzmaurice.clocktwerk.apps.TwitterPropertiesTool.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args/*w ww. j  ava2 s .  c o  m*/
 */
public static void main(String[] args) {

    File file = new File(TWITTER4J_PROPERTIES_FILE_NAME);
    Properties prop = new Properties();
    InputStream is = null;

    try {
        if (file.exists()) {
            System.out.println("Using existing twitter4j.properties file: " + file.getAbsolutePath());
            is = new FileInputStream(file);
            prop.load(is);
        }

        if (args.length < 2) {
            verifyOAuthProperties(prop);
        } else {
            createSkeletonPropertiesFile(args[0], args[1], prop);
        }
    } catch (IOException ioe) {
        printStackTraceAndExitSystem(ioe, null);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
    }

    try {
        Twitter twitter = new TwitterFactory().getInstance();
        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 in an authenticated " + "Twitter session as the target user:");
            System.out.println(requestToken.getAuthorizationURL());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            } catch (UnsupportedOperationException ignore) {
            }

            System.out.print("Enter the authorization PIN and hit enter:");
            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());

        OutputStream os = null;
        try {
            prop.setProperty(OAUTH_ACCESS_TOKEN_PROPERTY, accessToken.getToken());
            prop.setProperty(OAUTH_ACCESS_TOKEN_SECRET_PROPERTY, accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, TWITTER4J_PROPERTIES_FILE_NAME);
        } catch (IOException ioe) {
            printStackTraceAndExitSystem(ioe, null);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        System.exit(0);
    } catch (TwitterException te) {
        printStackTraceAndExitSystem(te, "Failed to get accessToken: " + te.getMessage());
    } catch (IOException ioe) {
        printStackTraceAndExitSystem(ioe, "Failed to read the system input.");
    }
}

From source file:com.nookdevs.twook.activities.SettingsActivity.java

License:Open Source License

/**
 * Helper method used for processing events recieved from the soft keyboard.
 * /* w ww. java  2s .c  om*/
 * @param keyCode
 *            the keyCode received from the soft keyboard
 * @see nookBaseSimpleActivity
 */
private void processCmd(int keyCode) {
    final String pin = txtPin.getText().toString();

    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    Settings settings = Settings.getSettings(this);

    switch (keyCode) {
    case nookBaseSimpleActivity.SOFT_KEYBOARD_SUBMIT:
        // if submit is pressed check if it is valid,
        // post a message if it is not or
        // set the settings and continue if it is
        // String auth = BasicAuthorization(username, password);
        TextView validation = (TextView) findViewById(R.id.validation);

        try {
            // we can specify the username and password here, but we'd need
            // to allow xauth
            // for this client, which requires an email to api@twitter.com.
            // Since we know
            // we have a browser available, launch that and let the user
            // authenticate there.
            AccessToken accessToken = mAuth.getOAuthAccessToken(pin);

            Log.d(TAG, "Auth result is: " + accessToken);

            // where do we set username/password?
            // accessToken includes username, userId, and auth tokens
            settings.setAccessToken(accessToken);

            settings.save();

            finish();

        } catch (TwitterException excep) {
            // TODO: resource-ize strings
            if (401 == excep.getStatusCode()) {
                validation.setText("Twitter rejected us: " + excep.getMessage());
            } else {
                // TODO: better validation here
                validation.setText("Unknown error: " + excep.getMessage());
            }
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } catch (IllegalStateException excep) {
            Log.e(TAG, "Internal error: " + excep.getMessage());
            validation.setText("Oops, something bad happened... Check the logs!");
        }

        break;
    case nookBaseSimpleActivity.SOFT_KEYBOARD_CANCEL:
        Log.d(TAG, "Token is: " + settings.getAccessToken());
        finish();
        break;
    case nookBaseSimpleActivity.NOOK_PAGE_DOWN_KEY_LEFT:
    case nookBaseSimpleActivity.NOOK_PAGE_DOWN_KEY_RIGHT:
    case nookBaseSimpleActivity.NOOK_PAGE_UP_KEY_LEFT:
    case nookBaseSimpleActivity.NOOK_PAGE_UP_KEY_RIGHT:
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        break;
    }

}

From source file:com.puestodequipe.mvc.testing.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/*  ww  w.  j  a  v  a  2  s  .co m*/
 */
public static void main(String[] args) {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        prop.setProperty("oauth.consumerKey", "mOpD2GQXUsc0tMKZHOvGJg");
        prop.setProperty("oauth.consumerSecret", "LnGRxSHrlzHDWC3R9aeTPDYmlr7LGXm7diNi6WZX3k");
        os = new FileOutputStream("twitter4j.properties");
        prop.store(os, "twitter4j.properties");

    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        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 (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 {
                    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 (null != os) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        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);
    }
}

From source file:com.redhat.middleware.jdg.TwitterDemoClient.java

License:Open Source License

protected void authorize() throws TwitterException, IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//from w w  w .java  2  s .  c  o m
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        logger.info("Open the following URL and grant access to your account:");
        logger.info(requestToken.getAuthorizationURL());
        logger.info("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();
            }

            this.accessToken = accessToken.getToken();
            this.accessTokenSecret = accessToken.getTokenSecret();
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                logger.info("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
}