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:com.producer.TwitterProducer.java

License:Apache License

public static void main(String[] args) {

    if (args.length == 0) {
        System.out.println(/* w w w . j  a va2 s.c o m*/
                "SimpleCounter {broker-list} {topic} {type old/new} {type sync/async} {delay (ms)} {count}");
        return;
    }

    /* get arguments */
    String brokerList = args[0];
    String topic = args[1];
    String age = args[2];
    String sync = args[3];
    /*
     * In order to create the spout, you need to get twitter credentials
     * If you need to use Twitter firehose/Tweet stream for your idea,
     * create a set of credentials by following the instructions at
     *
     * https://dev.twitter.com/discussions/631
     *
     */
    String custkey = "WXDgVgeJMwHEn0Z9VHDx5j93h";
    String custsecret = "DgP9CsaPtG87urpNU14fZySXOjNX4j4v2PqmeTndcjjYBgLldy";
    String accesstoken = "3243813491-ixCQ3HWWeMsthKQvj5MiBvNw3dSNAuAd3IfoDUw";
    String accesssecret = "aHOXUB4nbhZv2vbAeV15ZyTAD0lPPCptCr32N0PX7OaMe";

    producer = new DemoProducerOld(topic);

    /* start a producer */
    producer.configure(brokerList, sync);
    producer.start();

    //long startTime = System.currentTimeMillis();
    System.out.println("Starting...");
    producer.produce("Starting...");

    ConfigurationBuilder config = new ConfigurationBuilder().setOAuthConsumerKey(custkey)
            .setOAuthConsumerSecret(custsecret).setOAuthAccessToken(accesstoken)
            .setOAuthAccessTokenSecret(accesssecret);

    // create the twitter stream factory with the config
    TwitterStream twitterStream;
    TwitterStreamFactory fact = new TwitterStreamFactory(config.build());

    // get an instance of twitter stream
    twitterStream = fact.getInstance();
    // message to kafka
    Map<String, String> headers = new HashMap<String, String>();

    //filter non-english tweets
    FilterQuery tweetFilterQuery = new FilterQuery();
    tweetFilterQuery.language(new String[] { "en" });
    // tweetFilterQuery.locations(new double[][] { { -180, -90 }, { 180, 90 } });

    // provide the handler for twitter stream
    twitterStream.addListener(new TweetListener());

    twitterStream.filter(tweetFilterQuery);

    // start the sampling of tweets
    twitterStream.sample();

    // TODO ADD timestamp
    //long endTime = System.currentTimeMillis();
    //System.out.println("... and we are done. This took " + (endTime - startTime) + " ms.");
    //producer.produce("... and we are done. This took " + (endTime - startTime) + " ms.");

    /* close shop and leave */
    //producer.close();
    //System.exit(0);
}

From source file:com.pulzitinc.flume.source.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.
 *//*w w w  . ja v  a  2 s  . c o m*/
@Override
public void configure(Context context) {

    logger.info(context.toString());

    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);

    String accountIdsString = context.getString(TwitterSourceConstants.ACCOUNT_IDS_KEY, "");
    if (accountIdsString.trim().length() == 0) {
        throw new IllegalStateException("No accounts to follow provided");
    } else {
        String[] accountIds = accountIdsString.split(",");
        accountsToFollow = new long[accountIds.length];
        for (int i = 0; i < accountIds.length; i++) {
            accountsToFollow[i] = Long.valueOf(accountIds[i]);
        }
    }

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

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

From source file:com.redhat.middleware.jdg.TwitterDemoClient.java

License:Open Source License

public void startAsync() {

    ConfigurationBuilder cb = new ConfigurationBuilder();

    if (accessTokenSecret == null || accessToken == null) {
        try {/*w  w  w . j a  va 2s.c o  m*/
            this.authorize();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "error occured while authorizing", e);
        }
    }

    cb.setDebugEnabled(false).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    twitterStream.addListener(new DemoTwitterListener(twitterStream));
    twitterStream.sample();
}

From source file:com.reyk.socialmedia.implementations.TwitterSB.java

@Override
public String connectToSocialMedia(String username) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("a7QcplYaabjAy7Qw6WsyNAkwy")
            .setOAuthConsumerSecret("1xHSPlDU6eUp7YkkZL9oQioeQGuKiZHtwNuUCmTbARD2MoJLwV");
    twitter = new TwitterFactory(cb.build()).getInstance();
    try {/*from   w w w.jav a  2  s  . c  o  m*/
        token = twitter.getOAuthRequestToken();
    } catch (TwitterException ex) {
        return "Impossible to connect with Twitter";
    }
    return token.getAuthorizationURL();
}

From source file:com.reyk.socialmedia.implementations.TwitterSB.java

@Override
public void postComment(String username, String post) throws EJBException {
    try {//from   ww w  . j  a  v a 2s  .c o  m
        String fileName = "twitter-" + username + ".properties";
        File file = new File(fileName);
        OutputStream outputStream = null;
        Properties prop = new Properties();
        InputStream inputStream = null;

        try {
            if (file.exists()) {
                inputStream = new FileInputStream(file);
                prop.load(inputStream);
            } else {
                throw new EJBException("There is no configuration int Twitter for " + username);
            }

        } catch (IOException ioEx) {
            ioEx.printStackTrace();
            System.exit(-1);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignore) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ignore) {
                }
            }
        }
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("a7QcplYaabjAy7Qw6WsyNAkwy")
                .setOAuthConsumerSecret("1xHSPlDU6eUp7YkkZL9oQioeQGuKiZHtwNuUCmTbARD2MoJLwV")
                .setOAuthAccessToken(prop.getProperty("oauth.accessToken"))
                .setOAuthAccessTokenSecret(prop.getProperty("oauth.accessTokenSecret"));
        twitter = new TwitterFactory(cb.build()).getInstance();
        twitter.updateStatus(post);
    } catch (TwitterException e) {
        throw new EJBException("Error en el twitter sb al twittear", e);
    }
}

From source file:com.richardstansbury.tweetfollow.TwitterHelper.java

License:Open Source License

/**
 * Creates an authentication configuration for accessing the _twitter streaming
 * API./*w w  w . j av  a2 s .  c o m*/
 *
 * See readme.txt in root folder for location and format of twitter4j.txt.
 *
 * @param c - context to access the asset's folder
 * @return configuration object based upon keys read from asset's folder
 */
private Configuration readConfiguration(Context c) {

    //Create a Configuration Builder
    ConfigurationBuilder cb = new ConfigurationBuilder();
    try {

        //Create an input stream for the properties file
        BufferedReader in = new BufferedReader(new InputStreamReader(c.getAssets().open("twitter4j.txt")));

        //Set up the configuration
        cb.setDebugEnabled(true).setOAuthConsumerKey(in.readLine()).setOAuthConsumerSecret(in.readLine())
                .setOAuthAccessToken(in.readLine()).setOAuthAccessTokenSecret(in.readLine());

    } catch (IOException io) {
        Log.e("TwitterHelper", "Error opening input file");
        System.exit(-1);
    }

    //Build the configuration and return the object
    return cb.build();
}

From source file:com.rowland.hashtrace.utility.Utility.java

License:Apache License

public static Twitter getTwitter() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
    cb.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
    cb.setOAuthAccessToken(Constants.TWITTER_ACCESS_TOKEN);
    cb.setOAuthAccessTokenSecret(Constants.TWITTER_TOKEN_SECRET).setHttpConnectionTimeout(100000);
    //cb.setUseSSL(true);

    /*/*w  ww  .  j av  a2s  .  c  o  m*/
     * if() { cb.setHttpProxyHost(httpProxyHost);
     * cb.setHttpProxyPort(httpProxyPort);
     * cb.setHttpProxyUser(httpProxyUser);
     * cb.setHttpProxyPassword(httpProxyPassword);
     *
     * }
     */

    return new TwitterFactory(cb.build()).getInstance();
}

From source file:com.rsinghal.cep.sample.twitter.TwitterBot.java

License:Apache License

public void start() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);// w  w  w.  j a va2s  .  co m
    twitter = new TwitterFactory(cb.build()).getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {
            String screenName = StringUtils.substringAfter(trackTerms.get(i), "@");
            logger.info("Fetching user ID for - " + screenName);
            userIdsToTrack[i] = twitter.showUser(screenName).getId();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //   twitter = null;
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    twitterStream.addListener(listener2);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, userIdsToTrack, trackTerms.toArray(new String[trackTerms.size()])));

    jedis = new Jedis(redisHostname, redisPort, 1800);
    jedis.connect();
    System.out.println("start() ...");
    /*   // Create an appropriately sized blocking queue
       BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
               
       // create the endpoint
       DefaultStreamingEndpoint endpoint = createEndpoint();
       System.out.println("endpoint created ...");
            
       endpoint.stallWarnings(false);
            
       // create an authentication
       Authentication auth = new OAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            
       // Create a new BasicClient. By default gzip is enabled.
       client = new ClientBuilder().name("sampleExampleClient")
    .hosts(Constants.STREAM_HOST).endpoint(endpoint)
    .authentication(auth)
    .processor(new StringDelimitedProcessor(queue)).build();
       System.out.println("client created ...");
            
       // Create an executor service which will spawn threads to do the actual
       // work of parsing the incoming messages and
       // calling the listeners on each message
       ExecutorService service = Executors
    .newFixedThreadPool(this.numberOfProcessingThreads);
            
       // Wrap our BasicClient with the twitter4j client
       Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(client,
    queue, Lists.newArrayList(listener2), service);
            
       // Establish a connection
       t4jClient.connect();
               
       System.out.println("connection established ...");
            
       for (int threads = 0; threads < this.numberOfProcessingThreads; threads++) {
          // This must be called once per processing thread
          t4jClient.process();
          System.out.println("thread " + threads + " started ...");
            
       }*/
}

From source file:com.sinfonier.drains.TweetIt.java

License:Apache License

@Override
public void userexecute() {

    ConfigurationBuilder config = new ConfigurationBuilder();
    config.setOAuthConsumerKey(this.CONSUMER_KEY);
    config.setOAuthConsumerSecret(this.CONSUMER_SECRET);
    config.setOAuthAccessToken(this.ACCESS_TOKEN);
    config.setOAuthAccessTokenSecret(this.ACCESS_TOKEN_SECRET);
    config.setJSONStoreEnabled(true);/* w  w w.  ja  v a2s . c o m*/
    config.setIncludeEntitiesEnabled(true);
    try {
        TwitterFactory tf = new TwitterFactory(config.build());
        Twitter twitter = tf.getInstance();
        Status status = twitter.updateStatus(this.customText + " " + this.getField(this.fieldToTweet));
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    } catch (TwitterException te) {
        te.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sinfonier.spouts.Twitter.java

License:Apache License

/**
 * Create a TwitterStream. Requires Twitter API keys.
 * /* w w  w  .ja  v  a2  s .c  o  m*/
 * @return {@link twitter4j.TwitterStream}
 */
private TwitterStream createTwitterStream() {

    ConfigurationBuilder config = new ConfigurationBuilder();
    config.setOAuthConsumerKey(xml.get(CONSUMER_KEY, true));
    config.setOAuthConsumerSecret(xml.get(CONSUMER_SECRET, true));
    config.setOAuthAccessToken(xml.get(ACCESS_TOKEN, true));
    config.setOAuthAccessTokenSecret(xml.get(ACCESS_TOKEN_SECRET, true));
    config.setJSONStoreEnabled(true);
    config.setIncludeEntitiesEnabled(true);

    return new TwitterStreamFactory(config.build()).getInstance();
}