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(String configTreePath) 

Source Link

Document

Creates a TwitterFactory with a specified config tree

Usage

From source file:cz.mgn.collabdesktop.utils.apis.twitter.CollabTwitter.java

License:Open Source License

public static void tweet(String roomName, String text, BufferedImage roomImage, String accessToken,
        String accessTokenSecret) {
    try {/*from w  w w  .  java2  s  . c  om*/
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true) //
                .setOAuthConsumerKey("PLFCUaLARG3rW66MbME1Kg") // twitter app: MG Collab desktop
                .setOAuthConsumerSecret("Rf5G5htymWOVnC4KGT5lSzaAzlgW6mUwXNIPnywI8") //
                .setOAuthAccessToken(accessToken) //
                .setOAuthAccessTokenSecret(accessTokenSecret);
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        StatusUpdate su = new StatusUpdate(text);
        su.media(roomName, makeInputStreamFromImage(roomImage));
        twitter.updateStatus(su);
    } catch (IOException ex) {
        Logger.getLogger(CollabTwitter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TwitterException ex) {
        Logger.getLogger(CollabTwitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:d3V.GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFollowersIDs [screen name]
 *
 * @param args message/*from   w  w  w . j  a v a 2s . c o  m*/
 */
public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Em3WTI7jc90HcvKzPkTLQ")
            .setOAuthConsumerSecret("vg4p6rOF32bmffqRR8m0jAUClrxvtGiMB5PrSr3Zsw")
            .setOAuthAccessToken("1681973072-1q0zI0VPjHD3ttNuaBOL94frzCI9sXInxAcDK0w")
            .setOAuthAccessTokenSecret("ZRLkOyjmhHBkU1iNyEVNyIgIBsKrl0DUDKOcOMneYFYEM");
    cb.setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    try {
        String core_user = "nytimes";
        FileWriter writer = new FileWriter(core_user + "_friends.txt", true);
        Twitter twitter = tf.getInstance();

        long cursor = -1;
        ArrayList<String> directFriends = new ArrayList<String>();
        PagableResponseList<User> tempFriends = null;

        System.out.println("Listing " + core_user + " friends's ScreenNames.");
        int count = 0;
        //boolean first = true;
        //getFriends(writer, twitter, cursor, count, core_user);
        do {
            tempFriends = twitter.getFriendsList(core_user, cursor);

            for (User user : tempFriends) {
                directFriends.add(user.getScreenName());
                writer.write(core_user + "\t" + user.getScreenName() + "\n");
            }

            count += tempFriends.size();
            System.out.println(core_user + ": " + count);
            if (count >= 100)
                break;

            Thread.sleep(300 * MILLISECOND);

        } while ((cursor = tempFriends.getNextCursor()) != 0);

        System.out.println("Size of DFs: " + directFriends.size());

        //            for (String user : directFriends){
        for (int i = 0; i < directFriends.size(); i++) {
            //                PagableResponseList<User> idrfriends = null;
            long _cursor = -1;
            int _count = 0;
            String _username = directFriends.get(i);
            System.out.println("\nFriends of Direct friend: " + _username + "(" + (i + 1) + ")");
            try {
                getFriends(writer, twitter, _cursor, _count, _username);
            } catch (TwitterException e) {
                e.printStackTrace();
                System.out.println("Failed to get friends' ids: " + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        writer.close();
        System.out.println(count);
        System.exit(0);
    } catch (TwitterException e) {
        e.printStackTrace();
        System.out.println("Failed to get friends' ids: " + e.getMessage());
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:de.binfalse.jatter.JatterTools.java

License:Open Source License

/**
 * Gets the twitter instance./*from w w w  .j  a  va 2s.c  o  m*/
 *
 * @param conf
 *          the conf
 * @return the twitter instance
 */
public static Twitter getTwitterInstance(Config conf) {
    if (twitter == null) {
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        confBuilder.setOAuthConsumerKey(conf.getTwitterConsumerKey());
        confBuilder.setOAuthConsumerSecret(conf.getTwitterConsumerSecret());
        confBuilder.setOAuthAccessToken(conf.getTwitterAccesstoken());
        confBuilder.setOAuthAccessTokenSecret(conf.getTwitterAccesstokenSecret());
        twitter = new TwitterFactory(confBuilder.build()).getInstance();
    }
    return twitter;
}

From source file:de.dev.eth0.retweeter.AbstractTwitterClient.java

License:BEER-WARE LICENSE

/**
 * Builds a twitter object to access twitter, including all configs
 *
 * @return twitter/*from  www . jav a 2  s  . c o m*/
 */
protected Twitter getTwitter() {
    if (twitter == null) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthAccessToken(config.getAccessToken());
        cb.setOAuthAccessTokenSecret(config.getAccessSecret());
        cb.setOAuthConsumerKey(config.getConsumerKey());
        cb.setOAuthConsumerSecret(config.getConsumerSecret());
        twitter = new TwitterFactory(cb.build()).getInstance();
    }
    return twitter;
}

From source file:de.ecw.ant.twitter.AntTwitterTask.java

License:Apache License

/**
 * Executes Ant task://from w w w . j av a 2s. c o m
 * <ul>
 * <li>establish a connection to Twitter via twitter4j</li>
 * <li>if enabled, execute URL shortening via bitly</li>
 * <li>check the input message and split it into chunks if message is larger
 * than 140 characters</li>
 * <li>update status of every message</li>
 * </ul>
 */
public void execute() throws BuildException {
    String useMessage = getMessage();

    // validate Twitter parameters
    if ((getConsumerKey() == null) || ((getConsumerKey() != null) && (getConsumerKey().length() == 0))
            || (getConsumerSecret() == null)
            || ((getConsumerSecret() != null) && (getConsumerSecret().length() == 0))) {
        log("You have to enter a valid Twitter username/password combination, missing arguments!",
                Project.MSG_ERR);
        return;
    }

    // should URLs be shortened?
    if ((getEnableBitly() != null) && (getEnableBitly().toLowerCase().equals(TRUE))) {
        // validate bit.ly parameters
        if ((getBitlyUsername() == null) || ((getBitlyUsername() != null) && (getBitlyUsername().length() == 0))
                || (getBitlyApiKey() == null)
                || ((getBitlyApiKey() != null) && (getBitlyApiKey().length() == 0))) {
            log("You have enabled bit.ly support, but bit.ly username or API key is missing - bit.ly support is disabled",
                    Project.MSG_WARN);
        } else {
            useMessage = shortenUrls(message);
        }
    }

    // new Twitter client
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(getConsumerKey()).setOAuthConsumerSecret(getConsumerSecret())
            .setOAuthAccessToken(getAccessToken()).setOAuthAccessTokenSecret(getAccessTokenSecret());
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    // assume that all messages are longer than 140 chars
    List<String> messages = AntTwitterTask.splitMessage(useMessage);

    log("Twittering update (" + messages.size() + " tweets)", Project.MSG_INFO);

    int iTotalPosts = messages.size();
    int iSuccededUpdates = 0;

    try {
        // post every tweet
        for (int i = 0; i < iTotalPosts; i++) {
            String msg = messages.get(i);
            log(msg.length() + " chars: " + msg, Project.MSG_INFO);
            twitter.updateStatus(msg);
            iSuccededUpdates++;
        }
    } catch (TwitterException e) {
        log("Failed to update Twitter status", e, Project.MSG_ERR);
    }

    log("Tweets posted: " + iSuccededUpdates + "/" + iTotalPosts, Project.MSG_INFO);
}

From source file:de.hikinggrass.eiwomisarc.UpdateStatus.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 * //  w w w  . j ava 2 s .  c  o m
 * @param args
 *            message
 */
public UpdateStatus() {
    try {
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        //use https for oauth 
        confBuilder.setUseSSL(true);

        Configuration conf = confBuilder.build();
        Twitter twitter = new TwitterFactory(conf).getInstance();
        twitter.setOAuthConsumer("HaBxuZMHygmtcuPeCbOLg", "zg6bV26ksBrgKHdhmiLlubTtV9MaDhoIRZC1ODUKw");
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            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());
                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());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                System.out.println("OAuth consumer key/secret is not set.");
                System.exit(-1);
            }
        }
        Status status = twitter.updateStatus("test from eiwomisarc");
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + 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:de.hoesel.dav.buv.twitter.internal.RahmenwerkService.java

License:Open Source License

public Twitter getTwitter() {
    if (twitter == null) {
        loadProperties();/*from   ww w  .j ava 2s  . c om*/
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(oAuthConsumerKey);
        builder.setOAuthConsumerSecret(oAuthConsumerSecret);

        IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
        String accessToken = preferenceStore.getString(PreferenceConstants.OAUTH_ACCESS_TOKEN);
        String secretToken = preferenceStore.getString(PreferenceConstants.OAUTH_ACCESS_SECRET_TOKEN);
        if (!accessToken.isEmpty() && !secretToken.isEmpty()) {
            builder.setOAuthAccessToken(accessToken);
            builder.setOAuthAccessTokenSecret(secretToken);
        }
        Configuration configuration = builder.build();
        twitterFactory = new TwitterFactory(configuration);
        twitter = twitterFactory.getInstance();

    }
    return twitter;
}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

/**
 * Connect with twitter to get a new personalized twitter4j instance.
 *
 * @throws RuntimeException if verification or connecting failed
 *//* w w w .jav a  2  s .  c o m*/
public TwitterSearch initTwitter4JInstance(String token, String tokenSecret, boolean verify) {
    if (consumerKey == null)
        throw new NullPointerException("Please use init consumer settings!");

    setupProperties();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(token).setOAuthAccessTokenSecret(tokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
    try {
        //            RequestToken requestToken = t.getOAuthRequestToken();
        //            System.out.println("TW-URL:" + requestToken.getAuthorizationURL());
        if (verify)
            twitter.verifyCredentials();

        String str = twitter.getScreenName();
        logger.info("create new TwitterSearch for " + str + " with verifification:" + verify);
    } catch (TwitterException ex) {
        //            if (checkAndWaitIfRateLimited("initTwitter", ex))
        //                return this;

        throw new RuntimeException(ex);
    }
    return this;
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Twitter getTwitterInstance(final Context context, final long accountId,
        final boolean includeEntities, final boolean includeRetweets, final boolean apacheHttp,
        final String mediaProvider, final String mediaProviderAPIKey) {
    if (context == null)
        return null;
    final TwittnukerApplication app = TwittnukerApplication.getInstance(context);
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int connection_timeout = prefs.getInt(KEY_CONNECTION_TIMEOUT, 10) * 1000;
    final boolean enableGzip = prefs.getBoolean(KEY_GZIP_COMPRESSING, true);
    final boolean ignoreSSLError = prefs.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enableProxy = prefs.getBoolean(KEY_ENABLE_PROXY, false);
    // Here I use old consumer key/secret because it's default key for older
    // versions/*w w w . jav  a2 s.c  om*/
    final String where = Where.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL();
    final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI,
            Accounts.COLUMNS, where, null, null);
    if (c == null)
        return null;
    try {
        if (!c.moveToFirst())
            return null;
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(app));
        if (apacheHttp) {
            cb.setHttpClientFactory(new TwidereHttpClientFactory(app));
        }
        cb.setHttpConnectionTimeout(connection_timeout);
        cb.setGZIPEnabled(enableGzip);
        cb.setIgnoreSSLError(ignoreSSLError);
        if (enableProxy) {
            final String proxy_host = prefs.getString(KEY_PROXY_HOST, null);
            final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1"));
            if (!isEmpty(proxy_host) && proxy_port > 0) {
                cb.setHttpProxyHost(proxy_host);
                cb.setHttpProxyPort(proxy_port);
            }
        }
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY_2);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
        final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT));
        final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY)));
        final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET)));
        final boolean sameOAuthSigningUrl = c.getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1;
        final boolean noVersionSuffix = c.getInt(c.getColumnIndex(Accounts.NO_VERSION_SUFFIX)) == 1;
        if (!isEmpty(apiUrlFormat)) {
            final String versionSuffix = noVersionSuffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix));
            if (!sameOAuthSigningUrl) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }
        }
        if (isOfficialConsumerKeySecret(context, consumerKey, consumerSecret)) {
            setMockOfficialUserAgent(context, cb);
        } else {
            setUserAgent(context, cb);
        }

        if (!isEmpty(mediaProvider)) {
            cb.setMediaProvider(mediaProvider);
        }
        if (!isEmpty(mediaProviderAPIKey)) {
            cb.setMediaProviderAPIKey(mediaProviderAPIKey);
        }
        cb.setIncludeEntitiesEnabled(includeEntities);
        cb.setIncludeRTsEnabled(includeRetweets);
        cb.setIncludeReplyCountEnabled(true);
        cb.setIncludeDescendentReplyCountEnabled(true);
        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
        case Accounts.AUTH_TYPE_OAUTH:
        case Accounts.AUTH_TYPE_XAUTH: {
            if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
                cb.setOAuthConsumerKey(consumerKey);
                cb.setOAuthConsumerSecret(consumerSecret);
            } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
                cb.setOAuthConsumerKey(prefConsumerKey);
                cb.setOAuthConsumerSecret(prefConsumerSecret);
            } else {
                cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
                cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
            }
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            if (isEmpty(token) || isEmpty(tokenSecret))
                return null;
            cb.setOAuthAccessToken(token);
            cb.setOAuthAccessTokenSecret(tokenSecret);
            return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret));
        }
        case Accounts.AUTH_TYPE_BASIC: {
            final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME));
            final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME));
            final String loginName = username != null ? username : screenName;
            final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD));
            if (isEmpty(loginName) || isEmpty(password))
                return null;
            return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password));
        }
        case Accounts.AUTH_TYPE_TWIP_O_MODE: {
            return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization());
        }
        default: {
            return null;
        }
        }
    } finally {
        c.close();
    }
}

From source file:demo.UserFollowers.java

License:Apache License

public static void main(String[] args) throws TwitterException, IOException {
    //?/* w ww.j av  a 2  s.  co  m*/
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter tw = new TwitterFactory(configuration).getInstance();
    //String screenName = "masason";
    String screenName = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print(
            "??ScreenName???????!! ex)masason : ");
    screenName = br.readLine();

    //?
    List<Long> followersList = followers(tw, screenName);
    for (int i = 0; i < followersList.size(); i++) {
        //???idscreenName?
        User user = tw.showUser(followersList.get(i));
        System.out.println("[" + (i + 1) + "]" + "ScreenName : " + "[" + user.getScreenName() + "]  "
                + "UserIds : " + followersList.get(i));
    }
}