Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory() 

Source Link

Document

Creates a TwitterFactory with the root configuration.

Usage

From source file:com.michaelfitzmaurice.clocktwerk.apps.Clocktwerk.java

License:Apache License

public static void main(String[] args) throws Exception {

    // TODO - make tweet file location a sys prop/command line arg
    LOG.info("Looking for tweets file...");
    URL tweetFileUrl = new Object().getClass().getResource("/tweets.txt");
    if (tweetFileUrl == null) {
        throw new IOException("No tweets.txt file found on the classpath");
    }/*from   ww  w.  j av a2 s. c o  m*/
    LOG.info("Found tweets file at {}", tweetFileUrl);
    File tweetFile = new File(tweetFileUrl.getPath());

    // TODO - make prevayler dir a sys prop/command line arg
    Prevayler prevayler = PrevaylerFactory.createPrevayler(new HashMap<String, Integer>());
    TweetIndex tweetIndex = new PrevaylentTweetIndex(prevayler);
    TweetDatabase tweetDatabase = new TweetDatabase(tweetFile, tweetIndex);

    LOG.info("Setting up Twitter client...");
    // TODO - make twitter4j.properties location a sys prop
    Twitter twitter = new TwitterFactory().getInstance();
    if (twitter.getAuthorization().isEnabled() == false) {
        String msg = "Not authenticated to twitter - check OAuth consumer "
                + "key/secret in twitter4j.properties file";
        LOG.error(msg);
        throw new IOException(msg);
    }
    LOG.info("Twitter client connected and authenticated");

    boolean singleTweetMode = Boolean.getBoolean(SINGLE_TWEET_MODE_PROPERTY);

    TweetDaemon tweetDaemon = null;
    if (singleTweetMode) {
        LOG.info("Using single tweet mode....");
        tweetDaemon = new TweetDaemon(tweetDatabase, null, twitter);
        tweetDaemon.sendNextTweet();
        LOG.info("Sent next tweet - exiting...");
    } else {
        tweetDaemon = new TweetDaemon(tweetDatabase, Executors.newSingleThreadScheduledExecutor(), twitter);
        LOG.info("Starting tweet daemon....");
        tweetDaemon.start();
        LOG.info("Started tweet daemon");
    }
}

From source file:com.michaelfitzmaurice.clocktwerk.apps.FollowChecker.java

License:Apache License

public static void main(String[] args) throws Exception {

    String source = args[0];/*w  ww . java2  s  .c  o m*/
    String target = args[1];

    LOG.info("Setting up Twitter client...");
    Twitter twitter = new TwitterFactory().getInstance();
    LOG.info("Twitter client connected");

    LOG.info("Inspecting Twitter relationship between {} and {} ", source, target);
    Relationship relationship = twitter.showFriendship(source, target);
    boolean targetFollowsSource = relationship.isSourceFollowedByTarget();
    boolean sourceFollowsTarget = relationship.isSourceFollowingTarget();

    LOG.info("{} follows {}: {}", new Object[] { target, source, targetFollowsSource });
    LOG.info("{} follows {}: {}", new Object[] { source, target, sourceFollowsTarget });
}

From source file:com.michaelfitzmaurice.clocktwerk.apps.FollowerCounter.java

License:Apache License

public static void main(String[] args) throws Exception {

    File outputDir = new File(args[0]);
    String[] users = new String[args.length - 1];
    System.arraycopy(args, 1, users, 0, users.length);

    LOG.info("Setting up Twitter client...");
    Twitter twitter = new TwitterFactory().getInstance();
    LOG.info("Twitter client connected");

    LOG.info("Getting followers for users " + Arrays.asList(users));
    ResponseList<User> foundUsers = twitter.lookupUsers(users);
    for (User user : foundUsers) {
        LOG.info("\t'{}' has {} followers", user.getName(), user.getFollowersCount());
        recordFollowersToCsv(outputDir, user.getScreenName(), user.getFollowersCount());
    }// ww  w.  j  a v a2 s . c om
}

From source file:com.michaelfitzmaurice.clocktwerk.apps.TwitterPropertiesTool.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args//from   w  w w.  j a va 2  s  . co  m
 */
public static void main(String[] args) {

    File file = new File(TWITTER4J_PROPERTIES_FILE_NAME);
    Properties prop = new Properties();
    InputStream is = null;

    try {
        if (file.exists()) {
            System.out.println("Using existing twitter4j.properties file: " + file.getAbsolutePath());
            is = new FileInputStream(file);
            prop.load(is);
        }

        if (args.length < 2) {
            verifyOAuthProperties(prop);
        } else {
            createSkeletonPropertiesFile(args[0], args[1], prop);
        }
    } catch (IOException ioe) {
        printStackTraceAndExitSystem(ioe, null);
    } finally {
        if (is != null) {
            try {
                is.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 in an authenticated " + "Twitter session as the target user:");
            System.out.println(requestToken.getAuthorizationURL());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            } catch (UnsupportedOperationException ignore) {
            }

            System.out.print("Enter the authorization PIN and hit enter:");
            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());

        OutputStream os = null;
        try {
            prop.setProperty(OAUTH_ACCESS_TOKEN_PROPERTY, accessToken.getToken());
            prop.setProperty(OAUTH_ACCESS_TOKEN_SECRET_PROPERTY, accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, TWITTER4J_PROPERTIES_FILE_NAME);
        } catch (IOException ioe) {
            printStackTraceAndExitSystem(ioe, null);
        } 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) {
        printStackTraceAndExitSystem(te, "Failed to get accessToken: " + te.getMessage());
    } catch (IOException ioe) {
        printStackTraceAndExitSystem(ioe, "Failed to read the system input.");
    }
}

From source file:com.mycompany.twitterdemo.SignIn.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request// ww  w  .jav  a2 s  .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    request.getSession().setAttribute("twitter", twitter);
    System.out.println("key:" + twitter.getConfiguration().getOAuthConsumerKey());
    System.out.println("secret: " + twitter.getConfiguration().getOAuthConsumerSecret());
    try {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }
    processRequest(request, response);
}

From source file:com.nookdevs.twook.activities.Settings.java

License:Open Source License

public Twitter getConnection() {
    Configuration conf = getConfiguration().build();
    OAuthAuthorization auth = new OAuthAuthorization(conf);
    if (access != null) {
        // already authorized
        auth.setOAuthAccessToken(access);
    }//from  ww w.ja va2s. c  o m
    Twitter twitter = new TwitterFactory().getInstance(auth);
    return twitter;
}

From source file:com.playcez.twitter.android.TwitterApp.java

License:Apache License

/**
 * Instantiates a new twitter app./*  ww  w .j ava2  s  .c o m*/
 *
 * @param context the context
 * @param consumerKey the consumer key
 * @param secretKey the secret key
 */
public TwitterApp(Activity context, String consumerKey, String secretKey) {
    this.context = context;

    mTwitter = new TwitterFactory().getInstance();
    mSession = new TwitterSession(context);
    mProgressDlg = new ProgressDialog(context);

    mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);

    mConsumerKey = consumerKey;
    mSecretKey = secretKey;

    mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);

    String request_url = TWITTER_REQUEST_URL;
    String access_token_url = TWITTER_ACCESS_TOKEN_URL;
    String authorize_url = TWITTER_AUTHORZE_URL;

    mHttpOauthprovider = new DefaultOAuthProvider(request_url, access_token_url, authorize_url);
    mAccessToken = mSession.getAccessToken();

    configureToken();
}

From source file:com.practicando.controllers.adapters.LoginTwitterAdapter.java

@Override
public String login(HttpServletRequest request) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer("t2UVo2VHdoQx4QoP9GdysJzoA", "9D7wrEtAr2ffPJisbd68iUPQZohp0KW6Xh3fIUhPs2RGq3K477");
    request.getSession().setAttribute("twitter", twitter);
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/login-twitter-callback");
    RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
    request.getSession().setAttribute("requestToken", requestToken);
    return requestToken.getAuthenticationURL();

}

From source file:com.puestodequipe.mvc.testing.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/* w ww . j  a  va 2  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);
        }
        prop.setProperty("oauth.consumerKey", "mOpD2GQXUsc0tMKZHOvGJg");
        prop.setProperty("oauth.consumerSecret", "LnGRxSHrlzHDWC3R9aeTPDYmlr7LGXm7diNi6WZX3k");
        os = new FileOutputStream("twitter4j.properties");
        prop.store(os, "twitter4j.properties");

    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (null != os) {
            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 (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 (null != os) {
                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.quicklookbusy.twending.TwendsRequest.java

License:Apache License

/**
 * Makes the request and calls the callback with the acquired data
 *//*from w  w w.  j  a  v  a  2  s  . co m*/
public void run() {
    ArrayList<String> topics = new ArrayList<String>();
    Twitter twitter = new TwitterFactory().getInstance();
    Trends usTrends;
    try {
        usTrends = twitter.getLocationTrends(23424977);

        for (int i = 0; i < usTrends.getTrends().length; i++) {
            topics.add(usTrends.getTrends()[i].getName());
        }

        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss d MMM");
        Calendar cal = Calendar.getInstance();
        topics.add("Last updated at " + dateFormat.format(cal.getTime()));

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

    callback.doOnResult(topics);
}