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:SwingAndTweetUI.java

private void jButtoNActionPerformed(java.awt.event.ActionEvent evt) {
    try {//from   ww  w. j a v  a 2 s  .  c o  m
        Twitter twitter = new Twitter("username", "password");
        twitter.verifyCredentials();
        JOptionPane.showMessageDialog(null, "You're logged in!");
        java.util.List<Status> statusList = twitter.getUserTimeline();
        String s = String.valueOf(statusList.get(0).getText());
        jTextField1.setText(s);
    } catch (TwitterException e) {

        JOptionPane.showMessageDialog(null, "Login failed");

    }
}

From source file:Demo.java

/**
 * Main method./*from w w w  . j ava  2 s  . c  o  m*/
 *
 * @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: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 {/*from   w  ww.  j a v  a  2 s. c  om*/
        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:au.edu.anu.portal.portlets.tweetal.logic.TwitterLogic.java

License:Apache License

/**
 * Get the screen name of the Twitter user (eg KRuddPM)
 * @param userToken/*from w  w w .j a  va  2 s . c  om*/
 * @param userSecret
 * @return the screen name, or null
 */
public String getScreenName(String userToken, String userSecret) {
    Twitter twitter = getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        return null;
    }

    try {
        return twitter.verifyCredentials().getScreenName();

    } catch (TwitterException e) {
        log.error("Error getting screen name: " + e.getClass() + ": " + e.getMessage());
    }
    return null;
}

From source file:au.edu.anu.portal.portlets.tweetal.logic.TwitterLogic.java

License:Apache License

public boolean verifyCredentials(String userToken, String userSecret) {
    Twitter twitter = getTwitterAuthForUser(userToken, userSecret);

    try {/*  ww w  .j a va2s . com*/
        twitter.verifyCredentials();
        return true;

    } catch (TwitterException e) {
        log.error("Error: Credentials are invalid.\n" + e.getClass() + ":\n" + e.getMessage());
    }
    return false;
}

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;//from   w w  w  .j  ava2s.  c  om
    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:ColourUs.OAuth.java

private void reauthorize() throws Exception {
    // In case we lose the A_SECRET
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(C_KEY, C_SECRET);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/* ww w. j  a  va  2  s  .  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();
            }
        }
    }
    show((int) twitter.verifyCredentials().getId(), accessToken);
}

From source file:com.allenzheng.twittersyn.controller.AccountServlet.java

License:Apache License

    public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException{
      String action = request.getParameter(PARAM_ACTION);
      //from w  w  w .jav a  2  s. c o  m
      HttpSession session = request.getSession();
      
      if(ACTION_TWITTER_SIGN_IN.equals(action)){
         logger.debug("Signing in with Twitter...");
         TwitterAPIImpl twitterapi = new TwitterAPIImpl();
         
         String id = null;
         Cookie[] cookies = request.getCookies();
         for (int i = 0; i < cookies.length; i++) {
            Cookie cookie;
            cookie = cookies[i];
            if (COOKIE_TWITTER_ID.equals(cookie.getName())) {
               id = cookie.getValue();
            }
         }
         
         AccessToken accessToken = null;
         if (id != null){
            
         }
         
         
      }
      
      String oauthToken = request.getParameter(PARAM_OAUTH_TOKEN);
      if(oauthToken != null){
         logger.debug(PARAM_OAUTH_TOKEN + " received from Twitter");
         try {
            Twitter twitter = (Twitter) session.getAttribute(ATTR_TWITTER);
            RequestToken requestToken = (RequestToken) session
                  .getAttribute(ATTR_REQUEST_TOKEN);
            AccessToken accessToken;
            if (callbackUrl == null) {
               accessToken = twitter.getOAuthAccessToken(requestToken);
            } else {
               String oauthVerifier = request
                     .getParameter(PARAM_OAUTH_VERIFIER);
               logger.debug(PARAM_OAUTH_VERIFIER
                     + " received from Twitter");
               accessToken = twitter.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(),
                     oauthVerifier);
            }
            twitter.setOAuthAccessToken(accessToken);
            session.removeAttribute(ATTR_REQUEST_TOKEN);
            session.setAttribute(ATTR_TWITTER, twitter);

            int id = twitter.verifyCredentials().getId();
            logger.debug("Access token retrieved for user " + id
                  + " from Twitter");
//            storeAccessToken(id, accessToken);
            Cookie cookie = new Cookie(COOKIE_TWITTER_ID, "" + id);
            cookie.setMaxAge(63072000); // Valid for 2 years
            response.addCookie(cookie);
            logger.debug("Cookie set for user " + id);

            // Get last status and friends' timelines
//            getMyLastStatusAndStoreInSession(session);
//            getFriendsTimelinesAndStoreInSession(session);

            // Go to the update status page
//            request.getRequestDispatcher(PAGE_UPDATE_STATUS).forward(
//                  request, response);
         } catch (TwitterException e) {
            logger.error("Failed to retrieve access token - "
                  + e.getMessage());
            throw new ServletException(e);
         }
      }
   }

From source file:com.anshul.HomeServlet.java

License:Open Source License

private void statusCheck(Twitter twitter, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, TwitterException {
    User user = twitter.verifyCredentials();

    String username = user.getName();
    String latestTweet = user.getStatus().getText();
    TweetWrapper tweetWrapper = TweetWrapper.feel(latestTweet);
    String emotion = tweetWrapper.getStrongestEmotion();

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("Station");
    query.setFilter(FilterOperator.EQUAL.of("mood", emotion));
    List<Entity> stations = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
    Entity station = stations.get(0);

    req.getSession().setAttribute("user", username);
    req.getSession().setAttribute("userId", user.getId());
    req.getSession().setAttribute("latestTweet", latestTweet);
    req.getSession().setAttribute("emotion", emotion);
    req.getSession().setAttribute("stationName", station.getProperty("name"));
    req.getSession().setAttribute("url", station.getProperty("url"));
    req.getSession().setAttribute("profileImage", user.getBiggerProfileImageURL());
    req.removeAttribute("oauth_token");
    req.removeAttribute("oauth_verifier");
    resp.sendRedirect("login.jsp");
}

From source file:com.daiv.android.twitter.services.CatchupPull.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    if (CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning
            || !MainActivity.canSwitch) {
        return;//from w  w  w  . j  a  v  a2s .c  o m
    }
    CatchupPull.isRunning = true;

    Log.v("Test_pull", "catchup pull started");

    sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    final Context context = getApplicationContext();

    int unreadNow = sharedPrefs.getInt("pull_unread", 0);

    // stop it just in case
    context.sendBroadcast(new Intent("com.daiv.android.twitter.STOP_PUSH_SERVICE"));

    AppSettings settings = AppSettings.getInstance(context);

    if (settings.liveStreaming) {
        Log.v("Test_pull", "into the try for catchup service");
        Twitter twitter = Utils.getTwitter(context, settings);

        HomeDataSource dataSource = HomeDataSource.getInstance(context);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        List<Status> statuses = new ArrayList<Status>();

        boolean foundStatus = false;

        Paging paging = new Paging(1, 200);

        long[] lastId;
        long id;

        try {
            lastId = dataSource.getLastIds(currentAccount);
            id = lastId[0];
        } catch (Exception e) {
            context.startService(new Intent(context, TestPullNotificationService.class));
            CatchupPull.isRunning = false;
            return;
        }

        try {
            paging.setSinceId(id);
        } catch (Exception e) {
            paging.setSinceId(1l);
        }

        for (int i = 0; i < settings.maxTweetsRefresh; i++) {
            try {
                if (!foundStatus) {
                    paging.setPage(i + 1);
                    List<Status> list = twitter.getHomeTimeline(paging);

                    statuses.addAll(list);

                    if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) {
                        Log.v("Test_inserting", "found status");
                        foundStatus = true;
                    } else {
                        Log.v("Test_inserting", "haven't found status");
                        foundStatus = false;
                    }

                }
            } catch (Exception e) {
                // the page doesn't exist
                foundStatus = true;
                e.printStackTrace();
            } catch (OutOfMemoryError o) {
                // don't know why...
                o.printStackTrace();
            }
        }

        Log.v("Test_pull", "got statuses, new = " + statuses.size());

        // hash set to remove duplicates I guess
        HashSet hs = new HashSet();
        hs.addAll(statuses);
        statuses.clear();
        statuses.addAll(hs);

        Log.v("Test_inserting", "tweets after hashset: " + statuses.size());

        lastId = dataSource.getLastIds(currentAccount);

        int inserted = dataSource.insertTweets(statuses, currentAccount, lastId);

        if (inserted > 0 && statuses.size() > 0) {
            sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId())
                    .commit();
            unreadNow += statuses.size();
        }

        if (settings.preCacheImages) {
            // delay it 15 seconds so that we can finish checking mentions first
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startService(new Intent(context, PreCacheService.class));
                }
            }, 15000);
        }

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
    }

    try {
        Twitter twitter = Utils.getTwitter(context, settings);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        User user = twitter.verifyCredentials();
        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);

        long[] lastId = dataSource.getLastIds(currentAccount);
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId[0] > 0) {
            paging.sinceId(lastId[0]);
        }

        List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging);

        int numNew = dataSource.insertTweets(statuses, currentAccount);

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();

        if (settings.notifications && settings.mentionsNot && numNew > 0) {
            NotificationUtils.refreshNotification(context);
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }

    sharedPrefs.edit().putInt("pull_unread", unreadNow).commit();
    context.startService(new Intent(context, TestPullNotificationService.class));

    context.sendBroadcast(new Intent("com.daiv.android.Test.UPDATE_WIDGET"));
    getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);

    Log.v("Test_pull", "finished with the catchup service");

    CatchupPull.isRunning = false;
}