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:jp.xxxxxxxx.l3fish.twnyaan.service.UserService.java

License:Open Source License

/**
 * ????/*  w w  w. j  a  v  a  2s .c o m*/
 * ??????????????{@code null}?
 * 
 * @return ??????????{@code null}
 */
public User getUser() {
    Twitter twitter = TwitterFactory.getSingleton();

    User user = null;
    try {
        user = twitter.verifyCredentials();
    } catch (IllegalStateException e) {
        System.err.println(ErrorCode.MISSING_AUTHENTICATION_CREDENTIALS);
    } catch (TwitterException e) {
        if (e.getStatusCode() == 401) {
            System.err.println(ErrorCode.UNAUTHORIZED);
        } else {
            System.err.println(ErrorCode.TWITTER_SERVICE_UNAVAILABLE);
        }
    }

    return user;
}

From source file:Jums.SearchTweet.java

public void main(PrintWriter out) {
    try {//from w ww. ja  v  a  2  s .  com
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);
        cb.setOAuthConsumerKey(CONSUMERKEY);
        cb.setOAuthConsumerSecret(CONSUMERSECRET);
        cb.setOAuthAccessToken(TOKEN);
        cb.setOAuthAccessTokenSecret(TOKENSECRET);
        Twitter tw = new TwitterFactory(cb.build()).getInstance();
        User user = tw.verifyCredentials();
        List<Status> statuses = tw.getHomeTimeline();

        for (Status s : statuses) {

        }

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

From source file:net.wasdev.gameon.auth.twitter.TwitterCallback.java

License:Apache License

/**
 * Method that performs introspection on an AUTH string, and returns data as
 * a String->String hashmap.//from w  w  w .ja v  a2 s  .  c  om
 * 
 * @param auth
 *            the authstring to query, as built by an auth impl.
 * @return the data from the introspect, in a map.
 * @throws IOException
 *             if anything goes wrong.
 */
public Map<String, String> introspectAuth(String token, String tokensecret) throws IOException {
    Map<String, String> results = new HashMap<String, String>();

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret).setOAuthAccessToken(token)
            .setOAuthAccessTokenSecret(tokensecret);

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

    try {
        // ask twitter to verify the token & tokensecret from the auth
        // string
        // if invalid, it'll throw a TwitterException
        twitter.verifyCredentials();

        // if it's valid, lets grab a little more info about the user.
        long id = twitter.getId();
        ResponseList<User> users = twitter.lookupUsers(id);
        User u = users.get(0);
        String name = u.getName();
        String screenname = u.getScreenName();

        results.put("valid", "true");
        results.put("id", "twitter:" + id);
        results.put("name", name);
        results.put("screenname", screenname);

    } catch (TwitterException e) {
        results.put("valid", "false");
    }

    return results;
}

From source file:net.yorch.webocr.WebApp.java

License:Apache License

public WebApp() {

    ConfigurationBuilder confBuilder = new ConfigurationBuilder();

    confBuilder.setDebugEnabled(true);/*from  ww  w .j a  va  2s . c  o m*/
    confBuilder.setOAuthAppId("709488202488871");
    confBuilder.setOAuthAppSecret("cf2a470921280967d91eecc0714058cc");
    confBuilder.setUseSSL(true);
    confBuilder.setJSONStoreEnabled(true);

    final Configuration configuration = confBuilder.build();

    final Facebook facebook = new FacebookFactory(configuration).getInstance();

    final String IP_ADDRESS = System.getenv("OPENSHIFT_DIY_IP") != null ? System.getenv("OPENSHIFT_DIY_IP")
            : "localhost";
    final int PORT = System.getenv("OPENSHIFT_DIY_PORT") != null
            ? Integer.parseInt(System.getenv("OPENSHIFT_DIY_PORT"))
            : 8080;

    setIpAddress(IP_ADDRESS);

    /**
      * Port Applicacion
      */
    setPort(PORT);

    /**
      * Public Files Path
      */
    Spark.staticFileLocation("/public");

    /**
      * Path /
      */
    get("/", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            /*Facebook facebook = new FacebookFactory().getInstance();
            facebook.setOAuthAppId("1621799478097585", "585fc241a31c74a350e9db01bc33ca3c");
            facebook.setOAuthCallbackURL("http://localhost:8080/fb");
            facebook.setOAuthPermissions("email");
                    
            AccessToken accessToken = null;
             try{
                 OAuthSupport oAuthSupport = new OAuthAuthorization(configuration );
                 accessToken = oAuthSupport.getOAuthAppAccessToken();
                         
                 facebook.setOAuthAccessToken(accessToken);
             }catch (FacebookException e) {
                 return e.getMessage();
             }
                     
            String strlogin = facebook.getOAuthAuthorizationURL("http://localhost:8080/fb");
                    
            request.session().attribute("facebook", facebook);
                    
             StringBuffer callbackURL = new StringBuffer(request.url());
                     
             int index = callbackURL.lastIndexOf("/");
             callbackURL.replace(index, callbackURL.length(), "").append("/callback");
                     
             //response.sendRedirect(facebook.getOAuthAuthorizationURL(callbackURL.toString()));
             String callback = facebook.getOAuthCallbackURL();
                    
             response.redirect(strlogin);
                     
             return strlogin;*/

            /*
             Twitter twitter = TwitterFactory.getSingleton();
             twitter.setOAuthConsumer("rj990vv20WAwBriRtirBhMSzp", "n2INiuJpV9uAioHKxTfANeJ4JDdq2ZIogH5FUwGocFVJsp0avn");
                     
             request.session().attribute("twitter", twitter);
                     
             try {
                RequestToken requestToken = twitter.getOAuthRequestToken("http://yorch.ngrok.com/tw");
                request.session().attribute("requestToken", requestToken);
                        
                String authUrl = requestToken.getAuthenticationURL();
                response.redirect(authUrl);
            } catch (TwitterException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            }*/

            return "WebOCR on Openshift !!!";
        }
    });

    get("/fb", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            //Facebook facebook = (Facebook) request.session().attribute("facebook");

            String oauthCode = request.queryParams("code");

            Facebook facebook = new FacebookFactory().getInstance();
            facebook.setOAuthAppId("1621799478097585", "585fc241a31c74a350e9db01bc33ca3c");
            facebook.setOAuthCallbackURL("http://localhost:8080/fb");

            try {
                AccessToken token = facebook.getOAuthAccessToken(oauthCode);
                facebook.setOAuthAccessToken(token);

                User me = facebook.getMe();

                String info = me.getEmail() + "-" + me.getName() + "-" + me.getId();

                return info;
            } catch (FacebookException e) {
                return e.getErrorMessage();
            }

        }
    });

    get("/tw", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            Twitter twitter = (Twitter) request.session().attribute("twitter");

            RequestToken requestToken = (RequestToken) request.session().attribute("requestToken");

            String verifier = request.queryParams("oauth_verifier");

            try {
                twitter.getOAuthAccessToken(requestToken, verifier);
                request.session().attribute("requestToken", null);

                twitter4j.User me = (twitter4j.User) twitter.verifyCredentials();

                String info = me.getScreenName() + "-" + me.getName() + "-" + me.getId();

                return info;

            } catch (TwitterException e) {
                return e.getErrorMessage();
            }
        }
    });

    /**
      * Subir Archivo
      * Example:  curl -F "webcam=@/home/yorch/tmp/mory.jpg" http://localhost:8080/upload
      */
    post("/upload", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/home/yorch/tmp/");

            request.raw().setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
            String retResponse = "";

            try {
                Part file = request.raw().getPart("webcam");
                //long fileSize = file.getSize();
                //String fileName = file.getName();

                file.write("yorch.jpg");

                retResponse = TessOcr.ocr("/home/yorch/tmp/yorch.jpg");

            } catch (IOException | ServletException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return retResponse;
        }
    });
}

From source file:onl.area51.a51li.twitter.TwitterAuth.java

License:Apache License

public static void main(String args[]) throws Exception {
    final String consumerKey = args[0];
    final String consumerSecret = args[1];

    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//from w  w  w . j a v a2 s  . c  o  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();
            }
        }
    }
    //persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:org.celstec.arlearn2.oauth.OauthTwitterWorker.java

License:Open Source License

public String afterSuccesfullAuthentication(HttpServletRequest request) {
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken token = (RequestToken) request.getSession().getAttribute("requestToken");
    String verifier = request.getParameter("oauth_verifier");
    twitter.setOAuthConsumer(client_id, client_secret);
    try {//w w w.ja v  a2s.  c  o m
        AccessToken accessToken = twitter.getOAuthAccessToken(token, verifier);
        User user = twitter.verifyCredentials();
        AccountJDO account = AccountManager.addAccount("" + user.getId(), AccountJDO.TWITTERCLIENT, "", "", "",
                user.getName(), user.getProfileImageURL(), false);
        UserLoggedInManager.submitOauthUser(account.getUniqueId(), accessToken.getToken());
        return accessToken.getToken();
    } catch (TwitterException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}

From source file:org.encuestame.social.api.templates.TwitterAPITemplate.java

License:Apache License

/**
 * Verify Credentials./* w  w  w.j  av a 2s  .  co m*/
 * @param socialAccount
 * @return
 */
public Boolean verifyCredentials() {
    final Twitter twitter = this.getTwitterInstance();
    User user;
    try {
        user = twitter.verifyCredentials();
    } catch (TwitterException e) {
        user = null;
        log.error(e);
    }
    return user == null ? false : true;
}

From source file:org.eventjuggler.services.security.authc.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;//from w w w .  ja  v a2 s . com

    provideSecrets(oAuthCredential);
    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);
    String verifier = request.getParameter("oauth_verifier");
    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(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.gameontext.auth.twitter.TwitterCallback.java

License:Apache License

/**
 * Method that performs introspection on an AUTH string, and returns data as
 * a String->String hashmap.//from w  ww  .  j a v  a2 s . co m
 *
 * @param auth
 *            the authstring to query, as built by an auth impl.
 * @return the data from the introspect, in a map.
 * @throws IOException
 *             if anything goes wrong.
 */
public Map<String, String> introspectAuth(String token, String tokensecret) throws IOException {
    Map<String, String> results = new HashMap<String, String>();

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret).setOAuthAccessToken(token)
            .setOAuthAccessTokenSecret(tokensecret).setIncludeEmailEnabled(true).setJSONStoreEnabled(true);

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

    try {
        // ask twitter to verify the token & tokensecret from the auth
        // string
        // if invalid, it'll throw a TwitterException
        User verified = twitter.verifyCredentials();

        // if it's valid, lets grab a little more info about the user.
        String name = verified.getName();
        String email = verified.getEmail();

        results.put("valid", "true");
        results.put("id", "twitter:" + twitter.getId());
        results.put("name", name);
        results.put("email", email);

    } catch (TwitterException e) {
        results.put("valid", "false");
    }

    return results;
}

From source file:org.gatein.security.oauth.portlet.twitter.TwitterPortlet.java

License:Apache License

@Override
protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    AccessToken accessToken = getAccessToken();
    final Twitter twitter = getOAuthProvider().getAuthorizedSocialApiObject(accessToken, Twitter.class);

    User twitterUser = new TwitterPortletRequest<User>(request, response, getPortletContext(),
            getOAuthProvider()) {/*from  w w  w. java  2s.  c o m*/

        @Override
        protected User invokeRequest() throws TwitterException {
            return twitter.verifyCredentials();
        }

    }.executeRequest();

    if (twitterUser != null) {
        request.setAttribute("twitterUserInfo", twitterUser);
        PortletRequestDispatcher prd = getPortletContext().getRequestDispatcher("/jsp/twitter/userinfo.jsp");
        prd.include(request, response);
    }
}