Example usage for twitter4j Twitter verifyCredentials

List of usage examples for twitter4j Twitter verifyCredentials

Introduction

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

Prototype

User verifyCredentials() throws TwitterException;

Source Link

Document

Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not.

Usage

From source file:tkwatch.GetAccessTokens.java

License:Open Source License

public static void main(String args[]) throws Exception {
    // The factory instance is re-usable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    // Assumes consumer key and consumer secret are already stored in
    // properties file.
    // twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
    // Constants.CONSUMER_SECRET);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;// w  w  w  . ja  v  a2 s  .co  m
    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();
            }
        }
    }
    // Print out the access tokens for future reference.
    System.out.println("Access tokens for " + twitter.verifyCredentials().getId());
    System.out.println("oauth.accessToken=" + accessToken.getToken());
    System.out.println("oauth.accessTokenSecret=" + accessToken.getTokenSecret());
}

From source file:tkwatch.Utilities.java

License:Open Source License

/**
 * The Twitter OAuth authorization process requires access tokens. Twitter4j
 * stores them in <code>twitter4j.properties</code>. Invoke this routine to
 * obtain them; then add the appropriate lines in the properties file. (You
 * will need to write your own <code>main()</code> to do this. This routine
 * isn't actually called from the <strong>TKWatch+</strong> routine.
 * Documentation for <code>twitter4j.properties</code> is available <a
 * href="http://twitter4j.org/en/configuration.html">here</a>.
 * <p>//  w ww  .ja va  2s  .c om
 * Adapted from Yusuke Yamamoto, <a
 * href="http://twitter4j.org/en/code-examples.html">OAuth support</a>,
 * April 18, 2011.
 */
@SuppressWarnings("null")
public static final void getAccessTokens() {
    // The factory instance is re-usable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    // Assumes consumer key and consumer secret are already stored in
    // properties file.
    // twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
    // Constants.CONSUMER_SECRET);
    RequestToken requestToken = null;
    try {
        requestToken = twitter.getOAuthRequestToken();
    } catch (TwitterException e1) {
        e1.printStackTrace();
    }
    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("Cut and paste the pin:");
        String pin = "";
        try {
            pin = br.readLine();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        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();
            }
        }
    }
    // Print out the access tokens for future reference. The ones we got are
    // in the
    // <code>twitter4j.properties</code> file.
    try {
        System.out.println("Access tokens for " + twitter.verifyCredentials().getId());
    } catch (TwitterException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Store in twitter4j.properties as oauth.accessToken=" + accessToken.getToken());
    System.out.println(
            "Store in twitter4j.properties as oauth.accessTokenSecret=" + accessToken.getTokenSecret());
}

From source file:twitter.crawler.TwitterCrawler.java

public static void main(String[] args) {
    try {//ww  w .  j a  v  a  2  s  . co m
        // Authorise the library
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("AhoydO8uSe4v8NEq7j2ISGFlq");
        cb.setOAuthConsumerSecret("ptKEYwq3G9vpFkqAhvwFLSWFcBW8U1SfqycECwK4cH6wThVba6");
        cb.setOAuthAccessToken("778240255577194496-taafqDIHebrg972oxT5kTqcNd3Uojod");
        cb.setOAuthAccessTokenSecret("DMRmeRahnLJRvCBIGQGTaTzE6Pr3PAZMgMsfWIT5ue3PD");
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        User user = twitter.verifyCredentials(); // Get main user

        long cursor = -1;

        // Print user profile
        System.out.println("@" + user.getScreenName());
        System.out.println(user.getId());
        System.out.println(user.getProfileImageURL());
        System.out.println(user.getFriendsCount() + " friends.");
        System.out.println("-------");

        // Print Home Timeline
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");

        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        //Print followers
        System.out.println("-------");
        System.out.println("Showing Follwers:");

        PagableResponseList<User> followers;

        //do
        //{
        followers = twitter.getFollowersList(user.getScreenName(), cursor);

        for (User follower : followers) {
            System.out.println("@" + follower.getScreenName());
        }
        //}
        //while ((cursor = followers.getNextCursor())!=-1);

        //Print follwees

        System.out.println("-------");
        System.out.println("Showing Followees:");

        PagableResponseList<User> followees;

        do {
            followees = twitter.getFriendsList(user.getScreenName(), cursor);

            for (User followee : followees) {
                System.out.println("@" + followee.getScreenName());
            }
        } while ((cursor = followees.getNextCursor()) != -1);
    }

    catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitter4j.examples.account.VerifyCredentials.java

License:Apache License

/**
 * Usage: java twitter4j.examples.account.VerifyCredentials
 *
 * @param args message/*from  w w  w.j  a  va  2  s  . c o  m*/
 */
public static void main(String[] args) {
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        User user = twitter.verifyCredentials();
        System.out.println("Successfully verified credentials of " + user.getScreenName());
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to verify credentials: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitter4j.examples.timeline.GetUserTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]//from   w ww . ja v a 2s . c om
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        List<Status> statuses;
        String user;
        if (args.length == 1) {
            user = args[0];
            statuses = twitter.getUserTimeline(user);
        } else {
            user = twitter.verifyCredentials().getScreenName();
            statuses = twitter.getUserTimeline();
        }
        System.out.println("Showing @" + user + "'s user timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitterplugin.TwitterLoginDialog.java

License:Open Source License

/**
 * Create Gui/*from  w  w w .  j  ava 2  s.c  o m*/
 */
private void createGui() {
    setTitle(mLocalizer.msg("login", "Login"));

    UiUtilities.registerForClosing(this);

    PanelBuilder content = new PanelBuilder(
            new FormLayout("5dlu, pref:grow(0.5), 3dlu, 100dlu, fill:pref:grow(0.5), 5dlu"));

    CellConstraints cc = new CellConstraints();

    final Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret());
    try {
        mRequestToken = twitter.getOAuthRequestToken();
        mAuthorizationUrl = mRequestToken.getAuthorizationURL();
    } catch (TwitterException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    content.appendRow("3dlu");
    content.appendRow("pref");
    mLabelBrowser = new JLabel("1. " + mLocalizer.msg("step1", "Open authentication page on Twitter"));
    content.add(mLabelBrowser, cc.xy(2, content.getRowCount()));
    mUrlButton = new JButton(mLocalizer.msg("openBrowser", "Open browser"));
    mUrlButton.setToolTipText(mAuthorizationUrl);
    content.add(mUrlButton, cc.xy(4, content.getRowCount()));
    mUrlButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Launch.openURL(mAuthorizationUrl);
        }
    });

    content.appendRow("3dlu");
    content.appendRow("pref");
    mLabelPin = new JLabel("2. " + mLocalizer.msg("step2", "Enter PIN from web page"));
    content.add(mLabelPin, cc.xy(2, content.getRowCount()));
    mPIN = new JTextField();
    content.add(mPIN, cc.xy(4, content.getRowCount()));

    ButtonBarBuilder builder = new ButtonBarBuilder();
    builder.addGlue();

    JButton ok = new JButton(Localizer.getLocalization(Localizer.I18N_OK));

    ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            mReturnValue = JOptionPane.OK_OPTION;
            AccessToken accessToken = null;
            try {
                String pin = mPIN.getText().trim();
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(mRequestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken();
                }
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
            try {
                twitter.verifyCredentials().getId();
                mSettings.setAccessToken(accessToken);
            } catch (TwitterException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            setVisible(false);
        }
    });

    getRootPane().setDefaultButton(ok);

    JButton cancel = new JButton(Localizer.getLocalization(Localizer.I18N_CANCEL));

    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            close();
        }
    });

    builder.addGriddedButtons(new JButton[] { ok, cancel });

    content.appendRow("fill:pref:grow");
    content.appendRow("pref");
    content.add(builder.getPanel(), cc.xyw(1, content.getRowCount(), 4));

    content.appendRow("5dlu");
    content.setBorder(Borders.DIALOG_BORDER);
    getContentPane().add(content.getPanel());

    UiUtilities.setSize(this, Sizes.dialogUnitXAsPixel(200, this), Sizes.dialogUnitYAsPixel(140, this));
}

From source file:twitterrest.GetHomeTimeline.java

License:Apache License

public static void main(String[] args) {
    try {/*w  ww.  jav a2  s  .com*/
        // ?
        Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
                .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
                .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
        Twitter twitter = new TwitterFactory(configuration).getInstance();
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}