Example usage for twitter4j Twitter setOAuthAccessToken

List of usage examples for twitter4j Twitter setOAuthAccessToken

Introduction

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

Prototype

void setOAuthAccessToken(AccessToken accessToken);

Source Link

Document

Sets the access token

Usage

From source file:RandomPicBot.java

License:Open Source License

public static void main(String[] args) {
    /*//from   w w  w  .j a v  a 2s. c om
     * initialize the yaml setup
     * reads from keys.yml in the classpath, or same directory as the program
     */
    Yaml yaml = new Yaml();
    InputStream fileInput = null;
    try {
        fileInput = new FileInputStream(new File("keys.yml"));
    } catch (FileNotFoundException e1) {
        System.out.println("keys.yml not found!");
        e1.printStackTrace();
        System.exit(0);
    }
    @SuppressWarnings("unchecked") //unchecked cast, who cares.
    Map<String, String> map = (Map<String, String>) yaml.load(fileInput);

    /*
     * extracts values from the map
     */

    String CONSUMER_KEY = map.get("CONSUMER_KEY");
    String CONSUMER_SECRET = map.get("CONSUMER_SECRET");
    String TOKEN = map.get("TOKEN");
    String TOKEN_SECRET = map.get("TOKEN_SECRET");
    long USER_ID = Long.parseLong(map.get("USER_ID"));

    /*
     * initialize Twitter using the keys we got from the yaml file
     */

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    twitter.setOAuthAccessToken(new AccessToken(TOKEN, TOKEN_SECRET, USER_ID));

    /*
     * set up our picture folder
     * gets the folder from the command line argument
     * may change this to yaml too in the future
     */
    File directory = new File(args[0]);
    File[] pictures = directory.listFiles(new FileFilter() {
        /*
         * check to make sure the file is under 3mb(with some wiggle room) and is an acceptable image(non-Javadoc)
         * @see java.io.FileFilter#accept(java.io.File)
         */
        public boolean accept(File pathname) {
            if (pathname.isFile() && pathname.length() < 3000000 && isImage(pathname)) {
                return true;
            } else
                return false;
        }
    });

    System.out.println(pictures.length + " usable files found.");

    Random rand = new Random();

    /*
     * convert our minute value into milliseconds since thats what Thread.sleep() uses
     */

    int WAIT_TIME = Integer.parseInt(args[1]) * 60 * 1000;

    String statusText = "";
    if (args[2] != null) {
        for (int i = 2; i < args.length; i++) {
            statusText += args[i] + " ";
        }
        statusText.trim();
    }

    if (statusText.length() > 117) {
        System.out.println("Your message is too long!");
        System.out.println("Only messages up to 117 characters are supported!");
        System.exit(5);
    }

    StatusUpdate status = new StatusUpdate(statusText);

    /*
     * main loop
     * generate a random number to choose our image with
     * then upload the image to twitter
     * then wait for the defined time(gotten from the command line in minutes)
     */

    while (true) {
        int index = rand.nextInt(pictures.length);
        status.setMedia(pictures[index]);

        try {
            System.out.print("uploading picture: " + pictures[index].getName());
            if (!statusText.equals(""))
                System.out.println(" with text: " + statusText);
            else
                System.out.println();
            twitter.updateStatus(status);
        } catch (TwitterException e) {
            System.out.println("Problem uploading the file!");
            e.printStackTrace();
        }
        try {
            Thread.sleep(WAIT_TIME);
        } catch (InterruptedException e) {
            System.out.println("Program was interrupted!");
            e.printStackTrace();
        }
    }
}

From source file:DumpRetrievedTweet.java

private void GetTweetData() throws TwitterException, IOException {
    System.out.println("Seting up twitter");
    Twitter twitter = new TwitterFactory().getInstance();
    //        String CONSUMER_KEY = "9zVRlQTXlTKf4QeYMiucyXqg9";
    //        String CONSUMER_SECRET = "xH0H2SfcXj914z1DGB7HgZZ012ntSqRbfnLFw5A6v1TB94Y2O1";
    //        String TWITTER_TOKEN = "753222147695259648-QnzInB98PtwpFb75dqlP1J7SSOQMcMX";
    //        String TWITTER_TOKEN_SECRET = "uxJHGE1e2kFBJYoNRRFfy5gBLXYaRrzCUycRncSkoLsle";

    //        String CONSUMER_KEY = "nNV9KxWFVmdI0a2shhJImcEGk";
    //        String CONSUMER_SECRET = "I4AvaGOZRFtLFTqAkpKrfFOnV13Ej2seiwnNQ47z0qE9ORoBhW";
    //        String TWITTER_TOKEN = "753222147695259648-kY3Gq1O6FqHw6LQViuTQAhLbEQLZRZX";
    //        String TWITTER_TOKEN_SECRET = "a6hsmYipeGvqJcrIUUZah4ZhH7B8wbY77hqNWwojQysiO";

    //        String CONSUMER_KEY = "PBMKK9P2YD9MFgDfdANQt2Zzc";
    //        String CONSUMER_SECRET = "ldB0FybCQIjfYLzuYE4CeGtvcevaSkFxPENGbFd19Yn2crXa5R";
    //        String TWITTER_TOKEN = "753222147695259648-ZWqj3CvdQAXeVl9zfa71BCRcxeD2yAi";
    //        String TWITTER_TOKEN_SECRET = "1bypYSL1D1t1Gt6nQLwEbyRg5rniOUHfJhTYuVWYWvAvP";

    //        String CONSUMER_KEY = "tf0Cbp3ZQcJh9vwkQ9vInw6WS";
    //        String CONSUMER_SECRET = "gRmcjuqrSH40K47CkRFEO5OVthUtExEW7xrZU2oWiRcpPmzRz9";
    //        String TWITTER_TOKEN = "126239739-qaXgO4urp91PXLT2RgkxlyONwAQyXnq236dhqtTe";
    //        String TWITTER_TOKEN_SECRET = "AIykIeAKGFHRucTPgNYZd9bqdbZEJQhMsF5cGiyBLUII7";

    String CONSUMER_KEY = "EmmSsTEML5XrB3SYBUOOKxqn6";
    String CONSUMER_SECRET = "J1TrjmcqhBd1cURBTjUCwNqcf5IxCfdInAs74TVT9axvSwLnlJ";
    String TWITTER_TOKEN = "126239739-ktoaE8NhM4S9CjFhrktTdpuvY7fkbqj1nYxfaQsD";
    String TWITTER_TOKEN_SECRET = "a5fFQbKO9meoqnY31wwlZF0nqDHtqfxlwUla1uaAT8Y0p";

    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    AccessToken accesstoken = new AccessToken(TWITTER_TOKEN, TWITTER_TOKEN_SECRET);
    twitter.setOAuthAccessToken(accesstoken);
    writer.write("\n");
    for (int i = 0; i < tweet_ids.size(); i++) {
        Long tweet_id = tweet_ids.get(i);
        System.out.println("[" + i + "] Getting Tweet id " + tweet_id);
        Status status = twitter.showStatus((long) tweet_ids.get(i));
        if (status == null) {
            System.out.println("[FAILED] Doesnot exist twitter with tweet id : " + tweet_id);
        } else {//  ww w. j  a v a2 s .  c  o m
            System.out.println("status asli : " + status.getText());
            writer.write(tweet_id + "\t" + status.getText().replaceAll("\n", " "));
            writer.write("\n");
            updateIsLabelledAnotator3(tweet_id);
        }
    }
}

From source file:GetTweetsAndSaveToFile.java

License:Apache License

/**
 * Usage: java twitter4j.examples.user.ShowUser [screen name]
 *
 * @param args message/*from   w w w  . j a  v a 2 s .  co m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer("men2JyLEaAsxcbfmgzOAwUnTp",
                "2AGN0ie9TfCDJyWeH8qhTLtMhqRvRlNBtQU3lAP2M8k3Xk1KWl");
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Authorization URL: \n" + requestToken.getAuthorizationURL());

        AccessToken accessToken = new AccessToken("2811255124-zigkuv8MwDQbr5s9HdjLRSbg8aCOyxeD2gYGMfH",
                "D7jFABWHQa8QkTWwgYj1ISUbWP8twdfbzNgYkXI3jwySR");

        twitter.setOAuthAccessToken(accessToken);
        /*
        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) 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());

        User user = twitter.showUser(args[0]);
        if (user.getStatus() != null) {
            System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText());
        } else {
            // the user is protected
            System.out.println("@" + user.getScreenName());
        }

        FileWriter file = new FileWriter("./" + user.getScreenName() + "_Tweets.txt");
        List<Status> list = twitter.getHomeTimeline();
        for (Status each : list) {
            file.write("Sent by: @" + each.getUser().getScreenName() + " - " + each.getUser().getName() + "---"
                    + each.getText() + "\n");
        }

        file.close();
        System.exit(0);
    } catch (Exception te) {
        te.printStackTrace();
        System.exit(-1);
    }
}

From source file:MyUpdateTweetTimeToDB.java

public void GetTweetTime() {
    Twitter twitter = new TwitterFactory().getInstance();
    String CONSUMER_KEY = "4enxNevEGWMqBuKzcJoQ";
    String CONSUMER_SECRET = "UUDCNSvkFoZRaRUV4b8eHBcgR2N1LSrHXX7IELxdIk";
    String TWITTER_TOKEN = "470084145-qwjAlIxq7GFB1I62TO5ebyoO10tXgUuZJfgTLu7G";
    String TWITTER_TOKEN_SECRET = "9y47ww1xk0Nc5DhL9ZW0HOC6Qoig2wP101tOjsERnqNNv";
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    AccessToken accesstoken = new AccessToken(TWITTER_TOKEN, TWITTER_TOKEN_SECRET);
    twitter.setOAuthAccessToken(accesstoken);

    Iterator iterator = tweet_id_to_time.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry pair = (Map.Entry) iterator.next();
        try {//from w  ww.j a v  a  2  s  .c o m
            Status status = twitter.showStatus((long) pair.getKey());
            if (status == null) {
                System.out.println("Doesnot exist twitter with tweet id : " + pair.getKey());
            } else {
                tweet_id_to_time.put((Long) pair.getKey(), status.getCreatedAt().getTime());
            }
        } catch (TwitterException e) {
            tweet_id_to_time.put((Long) pair.getKey(), 1L);
            e.printStackTrace();
        }
        System.out.println("Id : " + pair.getKey() + "value " + pair.getValue());
    }
}

From source file:au.com.infiniterecursion.hashqanda.MainActivity.java

private void showTweetDialog() {

    app.setShowing_tweet_dialog(true);/*  www  . ja  va2  s  .c  o  m*/

    // Launch Tweet Edit View
    LayoutInflater inflater = (LayoutInflater) getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final View tweet_dialog_view = inflater.inflate(R.layout.tweet_dialog, null);

    final EditText tweet_edittext = (EditText) tweet_dialog_view.findViewById(R.id.EditTextTweet);

    final Dialog d = new Dialog(this);
    Window w = d.getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    d.setTitle(R.string.tweet_dialog_title);
    // the edit layout defined in an xml file (in res/layout)
    d.setContentView(tweet_dialog_view);
    // Cancel
    Button cbutton = (Button) d.findViewById(R.id.button2Cancel);
    cbutton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            app.setShowing_tweet_dialog(false);
            d.dismiss();
        }
    });
    // Edit
    Button ebutton = (Button) d.findViewById(R.id.button1Edit);
    ebutton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // save title and description to DB.
            String tweet = tweet_edittext.getText().toString();

            int end = (tweet.length() > 133) ? 133 : tweet.length();
            String real_tweet = "#qanda " + tweet.substring(0, end);
            Log.d(TAG, "New tweet is " + tweet);
            Log.d(TAG, "real tweet is " + real_tweet);

            String twitterToken, twitterTokenSecret;
            String[] toks = twitterTokens();
            twitterToken = toks[0];
            twitterTokenSecret = toks[1];

            if (twitterToken != null && twitterTokenSecret != null) {

                // Ok, now we can tweet this URL
                AccessToken a = new AccessToken(twitterToken, twitterTokenSecret);
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(TwitterOAuthActivity.consumerKey, TwitterOAuthActivity.consumerSecret);
                twitter.setOAuthAccessToken(a);

                try {
                    twitter.updateStatus(real_tweet);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(MainActivity.this, R.string.tweet_posted, Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (TwitterException e) {
                    // 
                    e.printStackTrace();
                    Log.e(TAG, " twittering failed " + e.getMessage());
                }
            } else {

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MainActivity.this, R.string.tweet_not_posted, Toast.LENGTH_LONG).show();
                    }
                });

            }

            app.setShowing_tweet_dialog(false);
            d.dismiss();
        }
    });
    d.show();
}

From source file:au.com.infiniterecursion.vidiom.activity.MainActivity.java

public void finishedUploading(boolean success) {
    // not uploading anymore.

    // Auto twittering.
    ///*  w ww.  jav  a2  s. c om*/
    if (twitterPreference && success) {

        new Thread(new Runnable() {
            public void run() {

                // Check there is a hosted URL for a start..

                // XXX get which URL from user if more than one!!

                String[] hosted_urls_to_tweet = db_utils
                        .getHostedURLsFromID(new String[] { Long.toString(latestsdrecord_id) });

                Log.d(TAG, " checking " + hosted_urls_to_tweet[0] + " in auto twitter publishing");

                if (hosted_urls_to_tweet != null && hosted_urls_to_tweet[0] != null
                        && hosted_urls_to_tweet[0].length() > 0) {

                    // Check there is a valid twitter OAuth tokens.
                    String twitterToken = prefs.getString("twitterToken", null);
                    String twitterTokenSecret = prefs.getString("twitterTokenSecret", null);

                    if (twitterToken != null && twitterTokenSecret != null) {

                        // Ok, now we can tweet this URL
                        AccessToken a = new AccessToken(twitterToken, twitterTokenSecret);
                        Twitter twitter = new TwitterFactory().getInstance();
                        twitter.setOAuthConsumer(TwitterOAuthActivity.consumerKey,
                                TwitterOAuthActivity.consumerSecret);
                        twitter.setOAuthAccessToken(a);

                        String status = "New video:" + hosted_urls_to_tweet[0];
                        try {
                            twitter.updateStatus(status);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(MainActivity.this, R.string.tweeted_ok, Toast.LENGTH_LONG)
                                            .show();
                                }
                            });
                        } catch (TwitterException e) {
                            //
                            e.printStackTrace();
                            Log.e(TAG, "Auto twittering failed " + e.getMessage());
                        }
                    }

                }

            }
        }).start();

    }

    mainapp.setNotUploading();
}

From source file:be.ugent.tiwi.sleroux.newsrec.twittertest.App.java

public static void main(String[] args) throws TwitterException {
    Twitter twitter = TwitterFactory.getSingleton();
    AccessToken accessToken = new AccessToken("2369203675-1Pk99eotzhCznmIgr3iXb670DpsEVQCANuoBHRs",
            "6ua72cabIzcFsBgE15RVzULeKT44TnIrOIaf9chY9dlWe");
    twitter.setOAuthConsumer("tQjT8XvB7OPNTl8qdhchDo3J2", "FXWVS3OEW7omiUDSLpET0aRInoUumGPWRxOVyk7GrhiwcfLBnV");
    twitter.setOAuthAccessToken(accessToken);

    User user = twitter.showUser("billclinton");
    System.out.println("id=" + user.getId());
    StreamReaderService srs = new StreamReaderService();
    srs.readTwitterFeed();/*w  w w . j av a  2 s  . c  om*/
}

From source file:bluevia.SendSMS.java

License:Apache License

public static void setTwitterStatus(String userEmail, String tweet) {
    if (tweet != null) {
        try {/*from  www.j  a v a2s.  c o m*/
            Properties twitterAccount = Util.getNetworkAccount(userEmail, "TwitterAccount");

            if (twitterAccount != null) {
                String consumer_key = twitterAccount.getProperty("TwitterAccount.consumer_key");
                String consumer_secret = twitterAccount.getProperty("TwitterAccount.consumer_secret");
                String access_key = twitterAccount.getProperty("TwitterAccount.access_key");
                String access_secret = twitterAccount.getProperty("TwitterAccount.access_secret");

                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(consumer_key, consumer_secret);
                twitter.setOAuthAccessToken(new AccessToken(access_key, access_secret));

                StatusUpdate status = new StatusUpdate(tweet);
                twitter.updateStatus(status);
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            log.severe(te.getMessage());
        } catch (Exception e) {
            log.severe(String.format("Error sending SMS: %s", e.getMessage()));
        }
    }
}

From source file:br.ufba.dcc.tagcloud.util.TwitterProvider.java

public void start(String user, int max) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
    AccessToken oathAccessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    twitter.setOAuthAccessToken(oathAccessToken);
    this.getTweets(twitter, user, max);
}

From source file:com.allenzheng.twittersyn.controller.AccountServlet.java

License:Apache License

    public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException{
      String action = request.getParameter(PARAM_ACTION);
      //from   w  w  w .j a va2s.c  o  m
      HttpSession session = request.getSession();
      
      if(ACTION_TWITTER_SIGN_IN.equals(action)){
         logger.debug("Signing in with Twitter...");
         TwitterAPIImpl twitterapi = new TwitterAPIImpl();
         
         String id = null;
         Cookie[] cookies = request.getCookies();
         for (int i = 0; i < cookies.length; i++) {
            Cookie cookie;
            cookie = cookies[i];
            if (COOKIE_TWITTER_ID.equals(cookie.getName())) {
               id = cookie.getValue();
            }
         }
         
         AccessToken accessToken = null;
         if (id != null){
            
         }
         
         
      }
      
      String oauthToken = request.getParameter(PARAM_OAUTH_TOKEN);
      if(oauthToken != null){
         logger.debug(PARAM_OAUTH_TOKEN + " received from Twitter");
         try {
            Twitter twitter = (Twitter) session.getAttribute(ATTR_TWITTER);
            RequestToken requestToken = (RequestToken) session
                  .getAttribute(ATTR_REQUEST_TOKEN);
            AccessToken accessToken;
            if (callbackUrl == null) {
               accessToken = twitter.getOAuthAccessToken(requestToken);
            } else {
               String oauthVerifier = request
                     .getParameter(PARAM_OAUTH_VERIFIER);
               logger.debug(PARAM_OAUTH_VERIFIER
                     + " received from Twitter");
               accessToken = twitter.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(),
                     oauthVerifier);
            }
            twitter.setOAuthAccessToken(accessToken);
            session.removeAttribute(ATTR_REQUEST_TOKEN);
            session.setAttribute(ATTR_TWITTER, twitter);

            int id = twitter.verifyCredentials().getId();
            logger.debug("Access token retrieved for user " + id
                  + " from Twitter");
//            storeAccessToken(id, accessToken);
            Cookie cookie = new Cookie(COOKIE_TWITTER_ID, "" + id);
            cookie.setMaxAge(63072000); // Valid for 2 years
            response.addCookie(cookie);
            logger.debug("Cookie set for user " + id);

            // Get last status and friends' timelines
//            getMyLastStatusAndStoreInSession(session);
//            getFriendsTimelinesAndStoreInSession(session);

            // Go to the update status page
//            request.getRequestDispatcher(PAGE_UPDATE_STATUS).forward(
//                  request, response);
         } catch (TwitterException e) {
            logger.error("Failed to retrieve access token - "
                  + e.getMessage());
            throw new ServletException(e);
         }
      }
   }