Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

In this page you can find the example usage for twitter4j.conf ConfigurationBuilder build.

Prototype

public Configuration build() 

Source Link

Usage

From source file:d3V.GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFollowersIDs [screen name]
 *
 * @param args message//  ww  w .j ava2 s.  co  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:datasite.DataSite.java

public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/*w  w w .  j  ava2s  .c o  m*/
    cb.setOAuthConsumerKey("ConsumerKey");
    cb.setOAuthConsumerSecret("ConsumerSecret");
    cb.setOAuthAccessToken("AccessToken");
    cb.setOAuthAccessTokenSecret("AccessTokenSecret");

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener;
    listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();

            try (PrintWriter out = new PrintWriter(
                    new BufferedWriter(new FileWriter("tweet_input\\tweets.txt", true))))

            {
                //out.println(username);

                String content = status.getText();
                out.println(content + "\n");
                //System.out.append( content +"\n");

            } catch (IOException ex) {
                Logger.getLogger(DataSite.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

    FilterQuery fq = new FilterQuery();

    String keywords[] = { "africa" };

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
    //twitterStream.();
}

From source file:datasite.SortedUnique.java

public static void main(String[] args) {
    ConfigurationBuilder confb = new ConfigurationBuilder();
    confb.setDebugEnabled(true);//from  w  w  w  . ja  v a  2s  .  c  om
    confb.setOAuthConsumerKey("Consumer Key");
    confb.setOAuthConsumerSecret("Consumer Secret");
    confb.setOAuthAccessToken("Access Token");
    confb.setOAuthAccessTokenSecret("Access Token Secret");

    TwitterStream twitterStream = new TwitterStreamFactory(confb.build()).getInstance();

    StatusListener listener;
    listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {

            PrintStream out = null;
            try {
                User user = status.getUser();
                // gets Username

                String username = status.getUser().getScreenName();
                String content = status.getText();
                Set<String> userWrds = new HashSet<String>(); // HashSet implements Set
                Scanner sc = new Scanner(content + user);
                while (sc.hasNext()) {
                    String word = sc.next();
                    userWrds.add(word);

                }
                out = new PrintStream(new FileOutputStream("tweet_output\\unique.txt", true));
                Iterator<String> iter = userWrds.iterator();
                for (int i = 1; i <= 1 && iter.hasNext(); i++)
                    //System.out.println(iter.next());
                    out.println(userWrds.size());
            } catch (FileNotFoundException ex) {
                Logger.getLogger(SortedUnique.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                out.close();
            }

        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "africa" };

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
    //twitterStream.();
}

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

License:Open Source License

/**
 * Gets the twitter instance.//from  ww  w  .  j  a va 2 s .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 . j a  v  a 2  s  .  c om
 */
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  ww w.  j  a  v 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.fhb.twitalyse.spout.TwitterStreamSpout.java

License:Open Source License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    this.collector = collector;

    // enable JSONStore
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);//ww  w .  j  a  va2  s  .c om

    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(cb.build());
    twitterStream = twitterStreamFactory.getInstance();

    AccessToken givenAccessToken = new AccessToken(TOKEN, TOKEN_SECRET);
    twitterStream.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECURE);
    twitterStream.setOAuthAccessToken(givenAccessToken);
    twitterStream.addListener(this);
    twitterStream.sample();
}

From source file:de.fhm.bigdata.projekt.dataimport.TwitterSource.java

License:Apache License

/**
 * The initialization method for the Source. The context contains all the
 * Flume configuration info, and can be used to retrieve any configuration
 * values necessary to set up the Source.
 *//*  ww  w.  j  a va  2  s.  c  om*/
@Override
public void configure(Context context) {
    consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY_KEY);
    consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET_KEY);
    accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN_KEY);
    accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET_KEY);

    proxyEnabled = context.getBoolean(TwitterSourceConstants.PROXY_ENABLED);
    proxyHost = context.getString(TwitterSourceConstants.PROXY_HOST);
    proxyPort = context.getInteger(TwitterSourceConstants.PROXY_PORT);

    String keywordString = context.getString(TwitterSourceConstants.KEYWORDS_KEY, "");
    if (keywordString.trim().length() == 0) {
        keywords = new String[0];
    } else {
        keywords = keywordString.split(",");
        for (int i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
        }
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    if (proxyEnabled) {
        cb.setHttpProxyHost(proxyHost);
        cb.setHttpProxyPort(proxyPort);//port
    }

    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
}

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

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 * // w w  w. j  av  a 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  www .  j  av  a2s .  c o  m*/
        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;
}