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:com.mastfrog.acteur.twitter.TwitterSign.java

RemoteUserInfo getUserInfo(String oauth_nonce, TwitterOAuthPlugin.TwitterToken credential,
        AuthorizationResponse auth)//from w  ww  . j a v  a 2 s .  c  om
        throws UnsupportedEncodingException, GeneralSecurityException, InterruptedException, IOException {
    //        System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.StdOutLogger");
    System.setProperty("twitter4j.debug", "true");
    System.setProperty("twitter4j.http.useSSL", "false");

    Twitter twitter = TwitterFactory.getSingleton();
    try {
        // Idiotic 
        twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
    } catch (Exception e) {
        e.printStackTrace();
    }
    twitter.setOAuthAccessToken(new AccessToken(auth.accessToken, auth.accessTokenSecret));
    try {
        User user = twitter.verifyCredentials();

        RUI rui = new RUI();
        rui.put("displayName", user.getName());
        rui.put("name", user.getScreenName() + "@api.twitter.com");
        rui.put("screen_name", user.getScreenName());

        rui.put("picture", user.getProfileImageURLHttps());
        rui.put("pictureLarge", user.getBiggerProfileImageURLHttps());
        rui.put("id", user.getId());
        return rui;
    } catch (TwitterException ex) {
        throw new IOException(ex);
    } finally {
        twitter.shutdown();
    }
}

From source file:com.metadot.book.connectr.server.servlets.LoginTwitterCallbackServlet.java

License:Apache License

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Twitter twitter = new TwitterFactory().getInstance();
    String key = AuthenticationProvider.getProp("twitter-consumer-key");
    String secret = AuthenticationProvider.getProp("twitter-consumer-secret");

    RequestToken token = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    twitter.setOAuthConsumer(key, secret);

    try {/* w  w  w .  ja  va 2s.  c o  m*/
        twitter.getOAuthAccessToken(token, verifier);
        User user = twitter.verifyCredentials();
        log.info("Twitter user found:" + user.getName());
        request.getSession().removeAttribute("requestToken");
        String sid = ((Integer) user.getId()).toString();

        UserAccount u = new UserAccount(sid, AuthenticationProvider.TWITTER);
        // use screen name for uid
        u.setName(user.getScreenName());
        UserAccount connectr = new LoginHelper().loginStarts(request.getSession(), u);
        log.info("User id:" + connectr.getId().toString());

    } catch (TwitterException e) {
        e.printStackTrace();
    }

    response.sendRedirect(LoginHelper.getApplitionURL(request));
}

From source file:com.mothsoft.integration.twitter.TwitterServiceImpl.java

License:Apache License

public User login(final String oauthToken, final String oauthTokenSecret) {
    try {// w  ww . j  ava  2  s .  c  o m
        final Twitter twitter = this.factory.getInstance(new AccessToken(oauthToken, oauthTokenSecret));
        User user = twitter.verifyCredentials();
        return user;
    } catch (TwitterException e) {
        throw wrapException(e);
    }
}

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

License:Open Source License

public void setAccessToken(AccessToken accessToken) {
    this.access = accessToken;

    // fill out any info, like username and user id
    Twitter twitter = getConnection();
    try {//from w  w w  .j  ava 2 s .  c o  m
        this.user = twitter.verifyCredentials();
        this.access = twitter.getOAuthAccessToken();
        // Log.d(TAG, "Access after verify: " + this.access);
        // Log.d(TAG, "User after verify: " + user);
        downloadIcon();
    } catch (TwitterException e) {
        Log.e(TAG, "Access credentials did not verify: " + e.getMessage());
        this.access = null;
    }
}

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;/*w w w . ja v  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.tuncaysenturk.jira.plugins.compatibility.servlet.TwitterLoginServlet.java

private void twitterCallback(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> context) {
    if (null == req.getParameter("denied") && null != req.getParameter("oauth_verifier")) {
        String verifier = req.getParameter("oauth_verifier").toString();

        PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet();
        propSet.setString("accessTokenVerifier", verifier);

        Twitter twitter = new TwitterFactory().getInstance();

        twitter.setOAuthConsumer(propSet.getString("consumerKey"), propSet.getString("consumerSecret"));
        RequestToken requestToken = new RequestToken(propSet.getString("requestToken"),
                propSet.getString("requestTokenSecret"));

        propSet.remove("requestToken");
        propSet.remove("requestTokenSecret");

        try {/*from   w ww  .j  a v  a 2s  .co m*/
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            propSet.setString("accessToken", accessToken.getToken());
            propSet.setString("accessTokenSecret", accessToken.getTokenSecret());
            User user = twitter.verifyCredentials();
            logger.info(JTPConstants.LOG_PRE + "User :" + user.getScreenName() + " logged in successfully");
            restartListener(req, resp, context);
        } catch (TwitterException e) {
            logger.error(JTPConstants.LOG_PRE + "Error while streaming", e);
            ExceptionMessagesUtil.addExceptionMessage("Error while streaming : ", e);
        }
    } else {
        logger.warn(JTPConstants.LOG_PRE + "User denied Twitter authorization, plugin will not work properly");
        ExceptionMessagesUtil
                .addExceptionMessage("User denied Twitter authorization, plugin will not work properly");
    }

}

From source file:edu.allegheny.gatortweet.GetHomeTimeline.java

License:Apache License

public static void main(String[] args) {
    try {/* w  w w  .  j a va  2s.c  o m*/
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("rPtRCCRqdDyoxHS3E2UARA")
                .setOAuthConsumerSecret("hhDnR4NETStvN4F84km2xuBy3eXJ8l2FnjdL23YPs");
        // gets Twitter instance with default credentials
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        /* Twitter twitter = new TwitterFactory().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);
    }
}

From source file:h2weibo.controllers.CallbackServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:type");

    if (request.getParameter("denied") != null) {
        response.sendRedirect("/");
        return;/*from   ww w . ja v a2  s  .  com*/
    }

    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    String token = (String) session.getAttribute(Keys.SESSION_TOKEN);
    String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET);
    String oauthVerifier = request.getParameter("oauth_verifier");

    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);

    if (r.is(":type", "weibo")) {
        try {
            Weibo weibo = new Weibo();

            AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier);
            if (accessToken != null) {
                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getToken() == null) { // send for the first time
                    session.setAttribute(Keys.SESSION_PROMPT_TWEET,
                            "You are ready to go! Do you want to tweet about this service and share it with your friends?");
                }

                tid.setToken(accessToken.getToken());
                tid.setTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);
            } else {
                log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
            }
        } catch (WeiboException e) {
            log.error("Weibo Exception", e);
            throw new RuntimeException(e);
        }
    } else if (r.is(":type", "twitter")) {
        try {
            TwitterFactory factory = new TwitterFactory();
            Twitter t = factory.getInstance();

            twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN);
            twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier);
            session.removeAttribute(Keys.SESSION_REQUEST_TOKEN);

            if (accessToken != null) {
                t.setOAuthAccessToken(accessToken);
                User user = t.verifyCredentials();
                loginUser = user.getScreenName();

                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getTwitterToken() == null) {
                    // save latest id for the first time. sync from that tweet
                    ResponseList<Status> tl = t.getUserTimeline();
                    if (tl.size() > 0) {
                        Status s = tl.get(0);
                        tid.setLatestId(s.getId());
                    }
                }

                tid.setTwitterToken(accessToken.getToken());
                tid.setTwitterTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);

                session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser);
            }
        } catch (TwitterException e) {
            log.error("Twitter Exception", e);
            throw new RuntimeException(e);
        }
    }

    String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL);
    if (requestUrl != null) {
        session.removeAttribute(Keys.SESSION_REQUEST_URL);
        response.sendRedirect(requestUrl);
    } else {
        response.sendRedirect("/u/" + loginUser);
    }
}

From source file:h2weibo.controllers.UserServlet.java

License:Open Source License

@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:id");

    HttpSession session = request.getSession(false);

    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);

    // Service limit
    String uId = r.get(":id");
    if (!helper.isUser(uId) && helper.getUserCount() > 50) {
        return getTemplate("full.vm");
    }/*w  w  w . java2  s .c om*/

    T2WUser user = helper.findOneByUser(uId);
    if (r.has(":id")) {
        log.info("Displaying user info for @" + uId);

        ctx.put("user_id", uId);
        ctx.put("user", helper.findOneByUser(uId));

        try {
            weibo4j.User weiboUser = (weibo4j.User) session.getAttribute(Keys.SESSION_WEIBO_USER);
            if (weiboUser == null) {
                Weibo w = new Weibo();
                w.setToken(user.getToken(), user.getTokenSecret());
                weiboUser = w.verifyCredentials();

                session.setAttribute(Keys.SESSION_WEIBO_USER, weiboUser);
            }

            ctx.put("weibo_user", weiboUser.getScreenName());
            ctx.put("weibo_user_image", weiboUser.getProfileImageURL().toString());
            ctx.put("weibo_login", 1);

            // save weiboUser ID mapping
            helper.setWeiboId(user.getUserId(), weiboUser.getScreenName());
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof WeiboException && ((WeiboException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }

        try {
            twitter4j.User twitterUser = (twitter4j.User) session.getAttribute(Keys.SESSION_TWITTER_USER);
            if (twitterUser == null) {
                TwitterFactory factory = new TwitterFactory();
                Twitter t = factory.getInstance();
                t.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));

                twitterUser = t.verifyCredentials();
                session.setAttribute(Keys.SESSION_TWITTER_USER, twitterUser);
            }

            ctx.put("twitter_user", twitterUser.getScreenName());
            ctx.put("twitter_user_image", twitterUser.getProfileImageURL().toString());
            ctx.put("twitter_login", 1);
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof TwitterException && ((TwitterException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }
    }

    Object message = session.getAttribute(Keys.SESSION_MESSAGE);
    if (message != null) {
        ctx.put("message", message);
        session.removeAttribute(Keys.SESSION_MESSAGE);
    }

    Object prompt = session.getAttribute(Keys.SESSION_PROMPT_TWEET);
    if (prompt != null) {
        ctx.put("prompt", prompt);
        session.removeAttribute(Keys.SESSION_PROMPT_TWEET);
    }

    return getTemplate("user.vm");
}

From source file:jp.gihyo.wicket.AppSession.java

License:Apache License

public boolean login(String userName, String password) {
    Twitter client = new TwitterClient(userName, password);
    try {/* w w  w  . j  a v  a2 s  . co  m*/
        User user = client.verifyCredentials();
        if (user != null) {
            twitterUser = user;
            twitterSession = client;
            return true;
        }
    } catch (TwitterException ex) {
        if (ex.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {
            lastUnauthorizedMessage = ex.getMessage();
            return false;
        }
    }
    return false;
}