Example usage for twitter4j Twitter getOAuthAccessToken

List of usage examples for twitter4j Twitter getOAuthAccessToken

Introduction

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

Prototype

AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException;

Source Link

Document

Retrieves an access token associated with the supplied request token and sets userId.

Usage

From source file:net.nitram509.controller.TwitterCallbackHttpController.java

License:Open Source License

public AccessToken validateAndRetrieveTwitterAccessToken(Twitter twitter, String requestTokenStr,
        String oauth_verifier) throws TwitterException {
    RequestToken requestToken = new RequestToken(requestTokenStr, "");
    assert requestToken.getToken() != null;
    assert requestToken.getTokenSecret() != null;
    return twitter.getOAuthAccessToken(requestToken, oauth_verifier);
}

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

License:Apache License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // twitter calls us back at this app when a user has finished authing
    // with them.
    // when it calls us back here, it passes an oauth_verifier token that we
    // can exchange
    // for a twitter access token.

    // we stashed our twitter & request token into the session, we'll need
    // those to do the exchange
    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");

    // grab the verifier token from the request parms.
    String verifier = request.getParameter("oauth_verifier");
    try {/*from w  w w .j  a v  a  2s.  c o m*/
        // clean up the session as we go (can leave twitter there if we need
        // it again).
        request.getSession().removeAttribute("requestToken");

        // swap the verifier token for an access token
        AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);

        Map<String, String> claims = introspectAuth(token.getToken(), token.getTokenSecret());

        // if auth key was no longer valid, we won't build a jwt. redirect
        // back to start.
        if (!"true".equals(claims.get("valid"))) {
            response.sendRedirect("http://game-on.org/#/game");
        } else {
            String newJwt = createJwt(claims);

            // debug.
            System.out.println("New User Authed: " + claims.get("id"));
            response.sendRedirect(callbackSuccess + "/" + newJwt);
        }

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

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

License:Apache License

public WebApp() {

    ConfigurationBuilder confBuilder = new ConfigurationBuilder();

    confBuilder.setDebugEnabled(true);/* w  w 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  va  2s.  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 {//from   w  ww.  j  ava 2  s. c om
        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.business.service.AbstractBaseService.java

License:Apache License

/**
 * Get Access Token./*from ww  w  . j  av a  2  s. c o m*/
 * @param token
 * @param tokenSecret
 * @param pin
 * @return
 * @throws TwitterException
 */
@SuppressWarnings("unused")
private AccessToken getAccessToken(final Twitter twitter, final String token, final String tokenSecret)
        throws TwitterException {

    final AccessToken accessToken = twitter.getOAuthAccessToken(token, tokenSecret);
    log.info(String.format("Auth Token {%s Token Secret {%s ", accessToken.getToken(),
            accessToken.getTokenSecret()));
    twitter.setOAuthAccessToken(accessToken);
    if (accessToken != null) {
        log.info(String.format("Got access token for user %s", accessToken.getScreenName()));
    }
    return accessToken;
}

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;//w ww  . j av  a 2  s . c o m

    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.exoplatform.extensions.twitter.services.TwitterService.java

License:Open Source License

public boolean validateTwitterAuthorization(String requestToken, String pin) {
    try {//from  w  w w .j  a va  2 s  .  c  o m
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, secretKey);
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterService.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}

From source file:org.fenixedu.bennu.social.ui.controller.SocialCallbackController.java

License:Open Source License

@RequestMapping(value = "/twitter/callback", method = RequestMethod.GET)
public String twitter(Model model, RedirectAttributes redirectAttrs,
        @RequestParam(value = "oauth_token", required = false) String oauthToken,
        @RequestParam(value = "oauth_verifier", required = false) String oauthVerifier,
        @RequestParam(value = "denied", required = false) String denied) {

    LOGGER.info("received invocation at twitter callback endpoint w/ params: oauth_token=" + oauthToken
            + ", oauth_verifier=" + oauthVerifier + ", denied=" + denied);

    TwitterAPI twitterAPI = twitterService.getInstance();

    if (!twitterAPI.isConfigured()) {
        LOGGER.error("Received invocation at Twitter callback endpoint, but service not yet configured");
        redirectAttrs.addFlashAttribute("errors", Arrays.asList("api.not.configured.twitter"));
    } else {/*  w  w  w  . j  a v  a2  s  . c  o  m*/

        if (denied != null) {
            String errorMessage = "Received error from Twitter server: " + denied;
            LOGGER.info(errorMessage);
            redirectAttrs.addFlashAttribute("errorMessage", errorMessage);
        } else {
            try {
                User user = Authenticate.getUser();
                TwitterUser twitterUser = twitterService.getAuthenticatedUser(user);

                Twitter instance = new TwitterFactory().getInstance();
                instance.setOAuthConsumer(twitterAPI.getClientId(), twitterAPI.getClientSecret());
                RequestToken requestToken = new RequestToken(twitterUser.getOauthToken(),
                        twitterUser.getOauthTokenSecret());
                AccessToken oAuthAccessToken = instance.getOAuthAccessToken(requestToken, oauthVerifier);

                twitterService.parseResponse(twitterUser, oAuthAccessToken);
            } catch (TwitterException | AccessTokenNotProvidedException e) {
                e.printStackTrace();
                redirectAttrs.addFlashAttribute("errors", Arrays.asList(e.getClass().getSimpleName()));
            }
        }
    }

    return "redirect:/bennu-social-admin";
}

From source file:org.gameontext.auth.twitter.TwitterCallback.java

License:Apache License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // twitter calls us back at this app when a user has finished authing
    // with them.
    // when it calls us back here, it passes an oauth_verifier token that we
    // can exchange
    // for a twitter access token.

    // we stashed our twitter & request token into the session, we'll need
    // those to do the exchange
    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");

    // grab the verifier token from the request parms.
    String verifier = request.getParameter("oauth_verifier");
    if (verifier == null) {
        //user elected to decline auth? redirect to fail url.
        response.sendRedirect(callbackFailure);
    } else {//from w  w  w  . j a  v  a2 s  .com
        try {
            // clean up the session as we go (can leave twitter there if we need
            // it again).
            request.getSession().removeAttribute("requestToken");

            // swap the verifier token for an access token
            AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);

            Map<String, String> claims = introspectAuth(token.getToken(), token.getTokenSecret());

            // if auth key was no longer valid, we won't build a jwt. redirect
            // to failure url.
            if (!"true".equals(claims.get("valid"))) {
                response.sendRedirect(callbackFailure);
            } else {
                String newJwt = createJwt(claims);

                // debug.
                System.out.println("New User Authed: " + claims.get("id"));
                response.sendRedirect(callbackSuccess + "/" + newJwt);
            }

        } catch (TwitterException e) {
            throw new ServletException(e);
        }
    }
}