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:br.shura.team.mpsbot.runtime.ConnectedBot.java

License:Open Source License

public void prepare(Function<URL, String> pinEvaluator)
        throws IllegalStateException, MalformedURLException, TwitterException {
    ApiKeys keys = getBot().getApiKeys();

    if (!isPrepared()) {
        Twitter handler = TwitterFactory.getSingleton();

        handler.setOAuthConsumer(keys.getConsumerKey(), keys.getConsumerSecret());

        RequestToken requestToken = handler.getOAuthRequestToken();
        URL url = new URL(requestToken.getAuthorizationURL());

        while (accessToken == null) {
            String pin = pinEvaluator.apply(url);

            try {
                if (pin != null && !pin.isEmpty()) {
                    this.accessToken = handler.getOAuthAccessToken(requestToken, pin);
                    this.handler = handler;
                } else {
                    return;
                }//from   w w  w . j  a  v  a 2s  .co  m
            } catch (TwitterException exception) {
                System.err.println("Could not evaluate OAuth access token:");
                System.err.println(exception);
            }
        }
    }

    getHandler().verifyCredentials();
}

From source file:cojoytuerto.TAuth.java

public TAuth() throws IOException, TwitterException { //Constructor de la clase
    File file = new File("auth_file.txt");
    if (!file.exists()) {

        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        configBuilder.setDebugEnabled(true).setOAuthConsumerKey("wCWSOW8xHlxfQq24kSxXuXNm9")
                .setOAuthConsumerSecret("5B1R4bxZv7TcO7Vmq3NvhM3Bo3YcO0qCIJP2vDD9HnOaPL63YD");
        configBuilder.setHttpProxyHost("127.0.0.1");
        configBuilder.setUseSSL(true);//from   w  w  w.java  2 s .c  om
        configBuilder.setHttpProxyPort(3128);
        Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
        RequestToken requestToken = null;
        AccessToken accessToken = null;
        String url = null;

        do {
            try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                System.out.println("Request Token obtenido con xito.");
                System.out.println("Request Token: " + requestToken.getToken());
                System.out.println("Request Token secret: " + requestToken.getTokenSecret());
                url = requestToken.getAuthorizationURL();
                url = url.replace("http://", "https://");
                System.out.println("URL:");
                System.out.println(url);
            } catch (TwitterException ex) {
                Logger.getLogger(TAuth.class.getName()).log(Level.SEVERE, null, ex);
            }
            BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in));
            //Abro el navegador. Firefox, en este caso.
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("firefox " + url);
            } catch (Exception e) {
            }
            //Nos avisa de que introduciremos el PIN a continuacin

            System.out.print("Introduce el PIN del navegador y pulsa intro.nn PIN: ");
            //Leemos el PIN
            //                String pin = lectorTeclado.readLine();
            String pin = JOptionPane.showInputDialog(null,
                    "Introduce el PIN del navegador y pulsa intro.nn PIN: ");
            if (pin.length() > 0) {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken);
            }
        } while (accessToken == null);

        System.out.println("nnAccess Tokens obtenidos con xito.");
        System.out.println("Access Token: " + accessToken.getToken());
        System.out.println("Access Token secret: " + accessToken.getTokenSecret());
        FileOutputStream fileOS = null;
        //            File file;
        String content = accessToken.getToken() + "\n" + accessToken.getTokenSecret();
        try {
            //                file = new File("auth_file.txt");
            fileOS = new FileOutputStream(file);
            //Si el archivo no existe, se crea
            if (!file.exists()) {
                file.createNewFile();
            }
            //Se obtiene el contenido en Bytes
            byte[] contentInBytes = content.getBytes();
            fileOS.write(contentInBytes);
            fileOS.flush();
            fileOS.close();
            System.out.println("Escritura realizada con xito.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOS != null) {
                    fileOS.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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;//from   w  ww. j  ava 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();
            }
        }
    }
    show((int) twitter.verifyCredentials().getId(), accessToken);
}

From source file:com.aldebaran.demo.picture.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/*from ww w .j a  va2  s  . com*/
 */
public static void main(String[] args) {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        if (args.length < 2) {
            if (null == prop.getProperty("oauth.consumerKey")
                    && null == prop.getProperty("oauth.consumerSecret")) {
                // consumer key/secret are not set in twitter4j.properties
                System.out.println(
                        "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                System.exit(-1);
            }
        } else {
            prop.setProperty("oauth.consumerKey", args[0]);
            prop.setProperty("oauth.consumerSecret", args[1]);
            os = new FileOutputStream("twitter4j.properties");
            prop.store(os, "twitter4j.properties");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        AccessToken accessToken = null;

        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());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (UnsupportedOperationException ignore) {
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            }
            System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
            try {
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                }
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());

        try {
            prop.setProperty("oauth.accessToken", accessToken.getToken());
            prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, "twitter4j.properties");
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.exit(-1);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get accessToken: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java

License:Open Source License

@Command(name = "twitpin", desc = "Second stage of adding your twitter account")
@Usage(".twitpin <pin>")
public CommandResult twitpin(CommandSource source, CommandContext context) {
    if (source.getSource() != CommandSource.Source.USER) {
        return get(ReturnType.MESSAGE, "Muse be done from IRC.", source, context);
    }/*from  ww  w. jav  a 2  s . c om*/

    if (context.getPrefix() == null || !context.getPrefix().equals(".")) {
        return null;
    }

    if (context.getArgs() == null || context.getArgs().length < 1) {
        return get(ReturnType.MESSAGE, "Correct usage is .twitpin <pin>", source, context);
    }

    String pin = context.getArgs()[0];
    CyborgUser permsAccount = getUser(source.getUser());

    if (getUser(source.getUser()) == null) {
        return get(ReturnType.NOTICE,
                "You have not registered with me! You need to register to add a twitter account! Type .register for help!",
                source, context);
    }

    TwitterUser twitterUser = getDatabase().select(TwitterUser.class).where()
            .equal("permUser", permsAccount.getName()).execute().findOne();
    if (twitterUser != null) {
        return get(ReturnType.NOTICE, "You already have an twitter user associated with your account!", source,
                context);
    }

    RequestToken requestToken = tokenMap.get(permsAccount.getName());
    if (requestToken == null) {
        return get(ReturnType.NOTICE, "You haven't started the process! To start type .twituser <user>", source,
                context);
    }

    Twitter twitter = defaultTwitterFactory.getInstance();

    try {
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        twitterUser = new TwitterUser();
        twitterUser.setAccessTokenObject(accessToken);
        twitterUser.setPermUser(permsAccount.getName());
        getDatabase().save(TwitterUser.class, twitterUser);
        tokenMap.remove(permsAccount.getName());
        return get(ReturnType.NOTICE, "Twitter account created! You can now use the tweet command!", source,
                context);
    } catch (TwitterException e) {
        tokenMap.remove(permsAccount.getName());
        e.printStackTrace();
        return get(ReturnType.MESSAGE, "Internal Twitter Exception http code:" + e.getStatusCode(), source,
                context);
    }
}

From source file:com.appspot.bitlyminous.command.authentication.AbstractAuthenticationCommand.java

License:Apache License

/**
 * Execute twitter o auth.// www. ja v a  2  s . co  m
 * 
 * @param req the req
 * @param resp the resp
 * @param callbackUrl the callback url
 * 
 * @return true, if successful
 * 
 * @throws Exception the exception
 */
protected boolean executeTwitterOAuth(HttpServletRequest req, HttpServletResponse resp, String callbackUrl)
        throws Exception {
    HttpSession session = req.getSession(true);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ApplicationConstants.TWITTER_CONSUMER_KEY,
            ApplicationConstants.TWITTER_CONSUMER_SECRET);
    if (session.getAttribute(ParameterNames.REQUEST_TOKEN_PARAM) == null
            || session.getAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM) == null) {
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
        session.setAttribute(ParameterNames.REQUEST_TOKEN_PARAM, requestToken.getToken());
        session.setAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM, requestToken.getTokenSecret());
        resp.sendRedirect(requestToken.getAuthenticationURL());
        return false;
    } else {
        AccessToken accessToken = twitter.getOAuthAccessToken(
                new RequestToken((String) session.getAttribute(ParameterNames.REQUEST_TOKEN_PARAM),
                        (String) session.getAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM)),
                req.getParameter(ParameterNames.OAUTH_VERIFIER));
        session.removeAttribute(ParameterNames.REQUEST_TOKEN_PARAM);
        session.removeAttribute(ParameterNames.REQUEST_TOKEN_SECRET_PARAM);
        User user = userService.getUserByScreenName(accessToken.getScreenName());
        if (user == null) {
            user = new User();
            user.setScreenName(accessToken.getScreenName());
        }
        user.setTwitterToken(new Text(accessToken.getToken()));
        user.setTwitterSecret(new Text(accessToken.getTokenSecret()));
        session.setAttribute(ParameterNames.SESSION_USER, user);
        return true;
    }
}

From source file:com.appspot.bitlyminous.standalone.TwitterExample.java

License:Apache License

/**
 * The main method./*from   w  w w .  j  a  va  2s .  co m*/
 * 
 * @param args the arguments
 * 
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer("671O1zUicFBCYHHYVp0XA", "cP7WvfAtxXGSaf1Sz0ksZtWGcENosFcRr46WR7a9jU");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;
    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 available) 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.
    System.out.println("Screen name:" + accessToken.getScreenName());
    System.out.println("Token:" + accessToken.getToken());
    System.out.println("Secret:" + accessToken.getTokenSecret());

    IDs friendsIDs = twitter.getFriendsIDs("gapinginfinity");
    System.out.println(Arrays.toString(friendsIDs.getIDs()));

    ResponseList<Status> favorites = twitter.getFavorites("gapinginfinity");
    System.out.println(favorites.size());
    System.exit(0);
}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/callback.arihant15")
public void doCallback(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {/*from  w  w  w .j a va  2s. c o m*/
        AccessToken accessToken;
        Twitter twitter = (Twitter) req.getSession().getAttribute("t");
        RequestToken requestToken = (RequestToken) req.getSession().getAttribute("rToken");
        String verifier = req.getParameter("oauth_verifier");
        accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
        req.getSession().removeAttribute("rToken");
    } catch (Exception e) {
        (res.getWriter()).println(e);
    }
    res.sendRedirect(req.getContextPath() + "/");
}

From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java

License:Apache License

public static AccessToken getAccessToken(String username) {
    AccessToken accessToken = null;//www.  java  2 s.c o  m
    if (Prefs.get(username + "/accessToken").isEmpty()) {
        Twitter twitter = factory.getInstance();
        twitter.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret"));
        RequestToken requestToken;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            requestToken = twitter.getOAuthRequestToken();
            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 ex) {
                    if (401 == ex.getStatusCode()) {
                        System.out.println("Unable to get the access token.");
                    } else {
                        logger.log(Level.SEVERE, "Unable to get the Access Token", ex);
                    }
                }
            }
        } catch (IOException | TwitterException ex) {
            logger.log(Level.SEVERE, "Unable to get the Access Token", ex);
        }
        Prefs.put(username + "/accessToken", accessToken.getToken());
        Prefs.put(username + "/accessTokenSecret", accessToken.getTokenSecret());
    }
    logger.finest("Token&Secret: " + Prefs.get(username + "/accessToken") + " "
            + Prefs.get(username + "/accessTokenSecret"));
    logger.finest("OauthConsum&Secret: " + Prefs.get("OAuthConsumerKey") + " " + Prefs.get("consumerSecret"));

    accessToken = new AccessToken(Prefs.get(username + "/accessToken"),
            Prefs.get(username + "/accessTokenSecret"));
    return accessToken;
}

From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Make the token and save using SharedPreferences. Then send back a sticky broadcast
 * @param extras Bundle containing the oauth verifier string
 *//*from  w ww  .  j  a va 2  s .c o m*/
private void processMakeToken(Bundle extras) {
    AccessToken accessToken = null;
    int resultCode = MSTwitter.MST_RESULT_NO_PASSED_OAUTH;
    // get the oAuth verifier string from the bundle
    String oAuthVerifier = extras.getString(MST_KEY_AUTH_OAUTH_VERIFIER);
    if (oAuthVerifier != null) {
        // first setup the twitter4j object
        resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;
        Twitter twitter4j = null;
        try {
            twitter4j = new TwitterFactory().getInstance();
            twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
        } catch (IllegalStateException e) {
            // No network access or token already available
            resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
            Log.e(MSTwitter.TAG, e.toString());
        }

        // now get the access token
        if (resultCode == MSTwitter.MST_RESULT_SUCCESSFUL) {
            try {
                accessToken = twitter4j.getOAuthAccessToken(MSTwitter.smReqToken, oAuthVerifier);
            } catch (NullPointerException e) {
                resultCode = MSTwitter.MST_RESULT_BAD_RESPONSE_FROM_TWITTER;
                Log.e(MSTwitter.TAG, e.toString());
            } catch (UnsupportedOperationException e) {
                resultCode = MSTwitter.MST_RESULT_BAD_RESPONSE_FROM_TWITTER;
                Log.e(MSTwitter.TAG, e.toString());
            } catch (TwitterException e) {
                resultCode = MSTwitter.getTwitterErrorNum(e, this);
                Log.e(MSTwitter.TAG, e.getLocalizedMessage());
            }
        }
    }

    if (accessToken != null) {
        // save the access token parts
        String token = accessToken.getToken();
        String secret = accessToken.getTokenSecret();

        // Create shared preference object to remember if the user has already given us permission
        SharedPreferences refs = this.getSharedPreferences(MSTwitter.PERF_FILENAME, Context.MODE_PRIVATE);
        Editor editor = refs.edit();
        editor.putString(MSTwitter.PREF_ACCESS_TOKEN, token);
        editor.putString(MSTwitter.PREF_ACCESS_TOKEN_SECRET, secret);
        editor.commit();
        resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;
    }

    // broadcast the results
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MSTwitter.INTENT_BROADCAST_MSTWITTER);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_SERVICE_TASK,
            MSTwitterService.MST_SERVICE_TASK_MAKE_TOKEN);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_MAKE_TOKEN_RESULT, resultCode);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_TEXT, mText);
    broadcastIntent.putExtra(MSTwitterService.MST_KEY_TWEET_IMAGE_PATH, mImagePath);
    sendStickyBroadcast(broadcastIntent);
}