Example usage for twitter4j Twitter getOAuthAccessToken

List of usage examples for twitter4j Twitter getOAuthAccessToken

Introduction

In this page you can find the example usage for twitter4j Twitter getOAuthAccessToken.

Prototype

AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;

Source Link

Document

Retrieves an access token associated with the supplied request token and sets userId.

Usage

From source file:Demo.java

/**
 * Main method.//w  w  w . java  2s.c om
 *
 * @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:GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message// w ww.j a v  a  2 s .  c o  m
 */
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);
    }
}

From source file:Register.java

License:Open Source License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 *
 * @param args message/*from w w w  .  j a v  a2 s .c o  m*/
 */
public static void main(String[] args) {
    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("wIb1qVNc0CNXQJxduYIXw")
                .setOAuthConsumerSecret("vTES3U9862wYaxFRdMyD1LRatkq2R42mDyOjXLHIdk");

        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        AccessToken accessToken = null;
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            RequestToken requestToken = twitter.getOAuthRequestToken();

            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("Access granted to Twitter.");
            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);
            }
        }
        twitter.updateStatus("Minecraft server successfully registered at " + (new Date()).toString());
        System.out.println("Successfully connected to Twitter.");

        // Write the properties file
        PrintWriter pw = new PrintWriter(new FileWriter("../TwitterEvents.properties"));
        pw.println("accessToken=" + accessToken.getToken());
        pw.println("accessTokenSecret=" + accessToken.getTokenSecret());
        pw.close();

        System.out.println("Your TwitterEvents.properties file has been created with your access tokens.");
        System.out.println("Start Minecraft server to load the remaining default values.");
        System.out.println("Then reload TwitterEvents if you make any changes.");
        System.exit(0);
    } catch (TwitterException te) {
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.out
                .println("Try revoking access to the hModEvents application from your Twitter settings page.");
        System.exit(-1);
    } catch (IOException ioe) {
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:NewJFrame.java

private void TweetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TweetButtonActionPerformed
    String message = TweetArea.getText();
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(API_KEY, API_SECRET);
    try {/*  w  w  w  . j a  va2s.c o  m*/
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == accessToken) {
            String pin = br.readLine();
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        }
        storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
    } catch (TwitterException | IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ac.simons.tweetarchive.Application.java

License:Apache License

static void createTwitterOauthTokens(final String consumerKey, final String consumerSecret) throws Exception {
    final Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    final RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//from   ww w .j a  va 2 s  .c o m
    final 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 {
                throw te;
            }
        }
    }

    final Properties properties = new Properties();
    properties.put("twitter4j.oauth.consumerKey", consumerKey);
    properties.put("twitter4j.oauth.consumerSecret", consumerSecret);
    properties.put("twitter4j.oauth.accessToken", accessToken.getToken());
    properties.put("twitter4j.oauth.accessTokenSecret", accessToken.getTokenSecret());

    try (final FileOutputStream out = new FileOutputStream("application.properties", true)) {
        properties.store(out, null);
    }
}

From source file:ar.com.zauber.commons.social.oauth.twitter.Twitter4JOAuthAccessManager.java

License:Apache License

/**
 * @param oauthToken/*from ww w .j a va 2  s.c o  m*/
 *            the oauthToken
 * @param oauthVerifier
 *            the oauthVerifier if exists, or <b>null</b>
 * @see OAuthAccessManager#getAccessToken(String, String)
 */
public final OAuthAccessToken getAccessToken(final String oauthToken, final String oauthVerifier) {
    Validate.notNull(oauthToken);
    OAuthRequestToken requestToken = repository.get(oauthToken);

    AccessToken accessToken = null;

    Twitter twitter = twitterFactory.getOAuthAuthorizedInstance(consumer.getKey(), consumer.getSecret());

    try {
        if (oauthVerifier == null) {
            accessToken = twitter.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret());
        } else {
            accessToken = twitter.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(),
                    oauthVerifier);
        }
    } catch (TwitterException e) {
        throw new OAuthAccessException("Exception when getting access token for RequestToken: " + requestToken,
                e);
    }

    return new Twitter4JOAuthAccessToken(accessToken);
}

From source file:au.com.tyo.services.sn.twitter.SNTwitter.java

License:Apache License

@Override
public void retrieveAccessToken() throws TwitterException {
    Twitter t = this.getTwitter();

    assert (requestToken != null);

    String token = callback.getQueryParameter("oauth_token");
    String verifier = callback.getQueryParameter("oauth_verifier");

    AccessToken accessToken = t.getOAuthAccessToken(this.requestToken, verifier);

    secretOAuth.getId().setToken(String.valueOf(accessToken.getUserId()));

    secretOAuth.getToken().setToken(accessToken.getToken());
    secretOAuth.getToken().setSecret(accessToken.getTokenSecret());

    secrets.save(secretOAuth.getId());/*w  ww.  j  a v  a2s .c  o  m*/
    secrets.save(secretOAuth.getToken());
}

From source file:au.com.tyo.sn.twitter.SNTwitter.java

License:Apache License

@Override
public void retrieveAccessToken(Uri uri) throws TwitterException {
    Twitter t = this.getTwitter();

    assert (requestToken != null);

    String token = uri.getQueryParameter("oauth_token");
    String verifier = uri.getQueryParameter("oauth_verifier");

    AccessToken accessToken = t.getOAuthAccessToken(this.requestToken, verifier);

    secretOAuth.getId().setToken(String.valueOf(accessToken.getUserId()));

    secretOAuth.getToken().setToken(accessToken.getToken());
    secretOAuth.getToken().setSecret(accessToken.getTokenSecret());

    secrets.save(secretOAuth.getId());/* w  ww  . ja  v a  2  s .c  o m*/
    secrets.save(secretOAuth.getToken());
}

From source file:be.ugent.tiwi.sleroux.newsrec.twittertest.GrantAccess.java

public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("tQjT8XvB7OPNTl8qdhchDo3J2", "FXWVS3OEW7omiUDSLpET0aRInoUumGPWRxOVyk7GrhiwcfLBnV");

    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//w w w . j  a va2s.  com
    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();
            }
        }
    }
    storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
}

From source file:bluevia.OAuth.java

License:Apache License

private String oAuthTwitter(HttpServletRequest req, String step) {
    String oAuthUrl = "/index.jsp";
    Properties prop = new Properties();

    prop.setProperty("oauth.consumerKey", TwitterOAuth.consumer_key);
    prop.setProperty("oauth.consumerSecret", TwitterOAuth.consumer_secret);

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(TwitterOAuth.consumer_key, TwitterOAuth.consumer_secret);
    try {/*from  w  w  w  . j a va 2s . com*/

        if (step.compareTo("1") == 0) {

            RequestToken requestToken = twitter
                    .getOAuthRequestToken(Util.getCallbackDomain() + "/oauth?network=twitter&step=2");

            req.getSession().setAttribute("request_key", requestToken.getToken());
            req.getSession().setAttribute("request_secret", requestToken.getTokenSecret());

            oAuthUrl = requestToken.getAuthenticationURL();

        } else {

            String request_key = (String) req.getSession().getAttribute("request_key");
            String request_secret = (String) req.getSession().getAttribute("request_secret");

            String oauth_verifier = req.getParameter("oauth_verifier");

            RequestToken requestToken = new RequestToken(request_key, request_secret);
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);

            UserService userService = UserServiceFactory.getUserService();
            User user = userService.getCurrentUser();

            Util.addNetworkAccount(user.getEmail(), "TwitterAccount", Util.TwitterOAuth.consumer_key,
                    Util.TwitterOAuth.consumer_secret, accessToken.getToken(), accessToken.getTokenSecret());

            req.getSession().removeAttribute("request_key");
            req.getSession().removeAttribute("request_secret");

            oAuthUrl = "/settings.jsp";
        }
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.severe(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        logger.severe(e.getMessage());
    }

    return oAuthUrl;
}