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:org.gatein.security.oauth.twitter.TwitterProcessorImpl.java

License:Open Source License

@Override
public TwitterAccessTokenContext validateTokenAndUpdateScopes(TwitterAccessTokenContext accessToken)
        throws OAuthException {
    try {//w w w.  ja  v a 2s  .c  om
        // Perform validation by obtaining some info about user
        Twitter twitter = getAuthorizedTwitterInstance(accessToken);
        twitter.verifyCredentials();
        return accessToken;
    } catch (TwitterException tw) {
        if (tw.getStatusCode() == 401) {
            throw new OAuthException(OAuthExceptionCode.ACCESS_TOKEN_ERROR,
                    "Error when verifying twitter access token: " + tw.getMessage(), tw);
        } else {
            throw new OAuthException(OAuthExceptionCode.IO_ERROR,
                    "IO Error when obtaining tokenInfo: " + tw.getClass() + ": " + tw.getMessage(), tw);
        }
    }
}

From source file:org.gatein.security.oauth.web.twitter.TwitterFilter.java

License:Open Source License

@Override
protected OAuthPrincipal<TwitterAccessTokenContext> getOAuthPrincipal(HttpServletRequest request,
        HttpServletResponse response, InteractionState<TwitterAccessTokenContext> interactionState) {
    TwitterAccessTokenContext accessTokenContext = interactionState.getAccessTokenContext();
    Twitter twitter = ((TwitterProcessor) getOauthProviderProcessor())
            .getAuthorizedTwitterInstance(accessTokenContext);

    User twitterUser;//from   w w w .j a v  a2 s  .co m
    try {
        twitterUser = twitter.verifyCredentials();
    } catch (TwitterException te) {
        throw new OAuthException(OAuthExceptionCode.TWITTER_ERROR, "Error when obtaining user", te);
    }

    OAuthPrincipal<TwitterAccessTokenContext> oauthPrincipal = OAuthUtils
            .convertTwitterUserToOAuthPrincipal(twitterUser, accessTokenContext, getOAuthProvider());
    return oauthPrincipal;
}

From source file:org.getlantern.firetweet.util.TwitterWrapper.java

License:Open Source License

@NonNull
public static User showUser(final Twitter twitter, final long id, final String screenName)
        throws TwitterException {
    if (twitter.getId() == id || twitter.getScreenName().equalsIgnoreCase(screenName)) {
        return twitter.verifyCredentials();
    } else if (id != -1) {
        return twitter.showUser(id);
    } else if (screenName != null) {
        return twitter.showUser(screenName);
    }/*from  ww  w  . j  av  a  2 s  .c  om*/
    throw new IllegalArgumentException();
}

From source file:org.junjun.twitter.GetUserTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]/*w w  w.j a v  a2s  . 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;
        Paging paging = new Paging(1);
        paging.setCount(100);
        if (args.length == 1) {
            user = args[0];
            /* statuses = twitter.getUserTimeline(Long.parseLong(user),paging);*/
            statuses = twitter.getUserTimeline(Long.parseLong(user));
        } else {
            user = twitter.verifyCredentials().getScreenName();
            statuses = twitter.getUserTimeline();
        }
        System.out.println("Showing @" + user + "'s user timeline.");
        int i = 0;

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

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

From source file:org.keycloak.social.twitter.TwitterProvider.java

License:Open Source License

@Override
public SocialUser processCallback(SocialProviderConfig config, AuthCallback callback)
        throws SocialProviderException {
    if (callback.getQueryParam("denied") != null) {
        throw new SocialAccessDeniedException();
    }// w ww  .j  a  v a  2  s . c  om

    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(config.getKey(), config.getSecret());

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

        RequestToken requestToken = new RequestToken((String) callback.getAttribute("token"),
                (String) callback.getAttribute("tokenSecret"));

        twitter.getOAuthAccessToken(requestToken, verifier);
        twitter4j.User twitterUser = twitter.verifyCredentials();

        SocialUser user = new SocialUser(Long.toString(twitterUser.getId()), twitterUser.getScreenName());
        user.setName(twitterUser.getName());

        return user;
    } catch (Exception e) {
        throw new SocialProviderException(e);
    }
}

From source file:org.nsoft.openbus.model.TwitterAccount.java

License:Open Source License

@Override
public URL processProfileImage() {
    Twitter twitter = TwitterUtils.getTwitter(new AccessToken(token, tokenSecret));
    try {/*from ww w  . j  a  va2s .  c  om*/
        return new URL(twitter.verifyCredentials().getOriginalProfileImageURL());
    } catch (TwitterException e) {
        return null;
    } catch (MalformedURLException e) {
        return null;
    }
}

From source file:org.picketlink.extensions.core.social.twitter.TwitterAuthenticationMechanism.java

License:Open Source License

@Override
protected Principal doAuthenticate(UserCredential credential, AuthenticationResult result)
        throws AuthenticationException {
    TwitterCredential oAuthCredential = (TwitterCredential) credential;

    HttpServletRequest request = oAuthCredential.getRequest();
    HttpServletResponse response = oAuthCredential.getResponse();
    HttpSession session = request.getSession();

    Principal principal = null;//ww w  .ja v  a 2  s.  c  om
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(clientID, clientSecret);

    //See if we are a callback
    RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    if (requestToken != null) {
        String verifier = request.getParameter("oauth_verifier");
        try {
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            session.setAttribute("accessToken", accessToken);
            session.removeAttribute("requestToken");
        } catch (TwitterException e) {
            throw new AuthenticationException(e);
        }

        try {
            principal = new TwitterPrincipal(twitter.verifyCredentials());
            checkUserInStore((TwitterPrincipal) principal);
        } catch (TwitterException e) {
            throw new AuthenticationException(e);
        }
        return principal;
    }
    try {
        requestToken = twitter.getOAuthRequestToken(returnURL);
        session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (Exception e) {
        throw new AuthenticationException(e);
    }
    return principal;
}

From source file:org.picketlink.social.auth.TwitterAuthenticator.java

License:Apache License

@Override
public void authenticate() {
    if (httpServletRequest == null) {
        throw new IllegalStateException("http request not available");
    }/*  www.j  a v a  2s.  c o  m*/
    if (httpServletResponse == null) {
        throw new IllegalStateException("http response not available");
    }
    if (configuration == null) {
        throw new IllegalStateException("configuration not available");
    }
    HttpSession session = httpServletRequest.getSession();

    ServletContext servletContext = httpServletRequest.getServletContext();

    String clientID = configuration.getClientID();
    String clientSecret = configuration.getClientSecret();
    String returnURL = configuration.getReturnURL();

    Principal principal = null;
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(clientID, clientSecret);

    //See if we are a callback
    String verifier = httpServletRequest.getParameter("oauth_verifier");
    RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    if (verifier != null && requestToken == null) {
        //Let us fall back
        String twitterSentRequestToken = httpServletRequest.getParameter("oauth_token");
        if (twitterSentRequestToken != null) {
            requestToken = (RequestToken) servletContext.getAttribute(twitterSentRequestToken);
        }
        if (requestToken == null) {
            throw new IllegalStateException("Verifier present but request token null");
        }
        //Discard the stored request tokens
        servletContext.removeAttribute(twitterSentRequestToken);
        session.removeAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE);
    }
    if (requestToken != null && verifier != null) {
        try {
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            session.setAttribute("accessToken", accessToken);
            session.removeAttribute("requestToken");
        } catch (TwitterException e) {
            throw new AuthenticationException("Twitter Login:", e);
        }

        try {
            principal = new TwitterPrincipal(twitter.verifyCredentials());

            setStatus(AuthenticationStatus.SUCCESS);
            setAccount(new User(principal.getName()));
            return;
        } catch (TwitterException e) {
            throw new AuthenticationException("Twitter Login:", e);
        }
    }
    try {
        requestToken = twitter.getOAuthRequestToken(returnURL);
        session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken);

        //back up in the case the browser provides a new session to the user on twitter callback
        servletContext.setAttribute(requestToken.getToken(), requestToken);

        httpServletResponse.sendRedirect(requestToken.getAuthenticationURL());

    } catch (Exception e) {
        throw new AuthenticationException("Twitter Login:", e);
    }
    if (principal != null) {
        setStatus(AuthenticationStatus.SUCCESS);
        setAccount(new User(principal.getName()));
    }
}

From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java

License:Educational Community License

/**
  * {@inheritDoc}// w w  w .j a va2s.  co  m
  */
public String getTwitterName(ExternalIntegrationInfo info) {

    if (info == null) {
        return null;
    }

    //get values
    String token = info.getTwitterToken();
    String secret = info.getTwitterSecret();

    if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(secret)) {

        //global config
        Map<String, String> config = getTwitterOAuthConsumerDetails();

        //token for user
        AccessToken accessToken = new AccessToken(token, secret);

        //setup
        TwitterFactory factory = new TwitterFactory();
        Twitter twitter = factory.getInstance();
        twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
        twitter.setOAuthAccessToken(accessToken);

        //check
        try {
            return twitter.verifyCredentials().getScreenName();
        } catch (TwitterException e) {
            log.error("Error retrieving Twitter credentials: " + e.getClass() + ": " + e.getMessage());
        }
    }
    return null;
}

From source file:org.socialnetlib.android.TwitterApi.java

License:Apache License

@Override
/*/*from w w w  .  j a  v a 2s  .c o  m*/
 * Warning: SYNCHRONOUS call. This exists just so we can get the screename
 * after a sign in
 */
public TwitterUser verifyCredentialsSync(String token, String secret) {

    TwitterUser twitterUser = null;

    clearApiInstance();

    try {
        setOAuthTokenWithSecret(token, secret, true);
        Twitter twitter = getAndConfigureApiInstance();
        twitterUser = new TwitterUser(twitter.verifyCredentials());

    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return twitterUser;
}