Example usage for twitter4j TwitterStreamFactory getInstance

List of usage examples for twitter4j TwitterStreamFactory getInstance

Introduction

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

Prototype

public TwitterStream getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:streamflow.spout.twitter.TwitterSampleSpout.java

License:Apache License

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

    logger.info(//from  w ww  .j a va 2 s .  c  om
            "Twitter Sampler Started: Consumer Key = " + consumerKey + ", Consumer Secret = " + consumerSecret
                    + ", Access Token = " + accessToken + ", Access Token Secret = " + accessTokenSecret);

    if (StringUtils.isNotBlank(consumerKey) && StringUtils.isNotBlank(consumerSecret)
            && StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(accessTokenSecret)) {
        // Build the twitter config to authenticate the requests
        ConfigurationBuilder twitterConfig = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey)
                .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
                .setOAuthAccessTokenSecret(accessTokenSecret).setJSONStoreEnabled(true)
                .setIncludeEntitiesEnabled(true).setIncludeEntitiesEnabled(true);

        // Add the proxy settings to the Twitter config if they were specified
        if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
            try {
                twitterConfig.setHttpProxyPort(proxyPort).setHttpProxyHost(proxyHost);
            } catch (Exception ex) {
            }
        }

        // Status listener which handle the status events and add them to the queue
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                queue.offer(status);
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                logger.debug("Twitter Deletion Notice: " + statusDeletionNotice.getUserId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                logger.debug("Twitter On Track Limitation Notice: Number Of Limited Statuses"
                        + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                logger.debug("Twitter Scrub Geo: UserID = " + userId + ", UpToStatusId = " + upToStatusId);
            }

            @Override
            public void onException(Exception exception) {
                logger.debug("Twitter Exception: " + exception.getMessage());
            }

            @Override
            public void onStallWarning(StallWarning stallWarning) {
                logger.debug("Twitter Stall Warning: " + stallWarning.toString());
            }
        };

        TwitterStreamFactory twitterFactory = new TwitterStreamFactory(twitterConfig.build());
        twitterStream = twitterFactory.getInstance();
        twitterStream.addListener(listener);
        twitterStream.sample();

        logger.info("Twitter Sample Stream Initialized");

    } else {
        logger.info("Twitter Sampler missing required OAuth properties. "
                + "Pleast check your settings and try again.");
    }
}

From source file:toninbot.ToninBot.java

/**
 * @param args the command line arguments
 *///from w w  w  . j  av a 2 s.  c o  m
public static void main(String[] args) {

    AccessToken accessToken = new AccessToken(Credenciales.token, Credenciales.tokenSecret);
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(Credenciales.consumerKey);
    builder.setOAuthConsumerSecret(Credenciales.consumerSecret);

    Configuration configuration = builder.build();
    TwitterStreamFactory twStreamFactory = new TwitterStreamFactory(configuration);
    TwitterStream twitterStream = twStreamFactory.getInstance();
    twitterStream.setOAuthAccessToken(accessToken);

    ToninStatusListener listener = new ToninStatusListener();
    twitterStream.addListener(listener);

    FilterQuery filtre = new FilterQuery();
    filtre.follow(184742273L, 2841338087L);//Allegue y proyectoPSIa1
    //filtre.follow(2841338087L);//proyectoPSIa1

    twitterStream.filter(filtre);
}

From source file:Twitter.FilterStream.java

License:Apache License

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

    System.getProperties().put("http.proxyHost", "127.0.0.1");
    System.getProperties().put("http.proxyPort", "8580");

    /* if (args.length < 1) {
    System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
    System.exit(-1);/*  w  w  w .  j av  a2 s  .c om*/
     }*/

    final FilterStream fs = new FilterStream();

    try {
        fs.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            String str = DataObjectFactory.getRawJSON(status);
            try {
                //JSONObject nnstr = new JSONObject(newstr);  
                DBObject dbObject = (DBObject) JSON.parse(str);
                fs.collection.insert(dbObject);
                //System.out.println(dbObject);  
                fs.count++;
                if (fs.count > 900000000) {
                    fs.mongo.close();
                    System.exit(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("7ZVgfKiOvBDcDFpytRWSA")
            .setOAuthConsumerSecret("JmeJVeym78arzmGthrDUshQyhkq6nWA9tWLUKxc")
            .setOAuthAccessToken("321341780-Zy7LptVYBZBVvAeQ5GFJ4aKFw8sdqhWBnvA3pDuO")
            .setOAuthAccessTokenSecret("foi8FnQCeN0J5cdwad05Q6d7dbytFayQn1ZOvmhF6Qc");
    cb.setJSONStoreEnabled(true);

    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());

    TwitterStream twitterStream = tf.getInstance();
    twitterStream.addListener(listener);
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();

    //String[] keywords = {"RT @justinbieber"};
    String[] keywords = { "27260086" }; // user_id(justinbieber)
    for (String arg : keywords) {
        if (isNumericalArgument(arg)) {
            for (String id : arg.split(",")) {
                follow.add(Long.parseLong(id));
            }
        } else {
            track.addAll(Arrays.asList(arg.split(",")));
        }
    }
    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }
    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    //twitterStream.filter(new FilterQuery(0, followArray, trackArray));
    twitterStream.filter(new FilterQuery(followArray));
}

From source file:twitter_app_p1.Twitter_app_p1.java

public static void initialize_stuff() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("T9Gl1DWeRjeBazUInktTNtEtD")
            .setOAuthConsumerSecret("3NXrL1qGpF3WPVyJQ7ytInlhNjIsMgT6s7bJOIDhD1uotzZ958")
            .setOAuthAccessToken("2428771880-4e3LHhOzmiYx4lChlAEYtJ6sB2oetARYbXcqfyU")
            .setOAuthAccessTokenSecret("7HLOf3dafjJEGoioWOMHfgiNrhBDb66YJZgSzrDkTNA9x")
            .setJSONStoreEnabled(true);/*from w w w.  ja v  a2  s .c o  m*/

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

From source file:uk.co.flax.ukmp.twitter.ManagedTwitterClient.java

License:Apache License

@Override
public void start() throws Exception {
    Configuration authConfig = buildConfiguration();

    TwitterStreamFactory tsf = new TwitterStreamFactory(authConfig);
    stream = tsf.getInstance();

    StatusListener statusListener = new UKMPStatusListener(statusQueue, deletionQueue);
    stream.addListener(statusListener);//from   w  ww . j  a va 2s .com

    // Start the update and delete threads
    deletionThread.start();
    updateThread.start();
}

From source file:wordgame.WordGame.java

public static void initGame(String file) throws FileNotFoundException {
    Scanner s = new Scanner(new File(file)); //open the file
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true) //populate the twitter details with the proper API informatin
            .setOAuthConsumerKey(s.nextLine()).setOAuthConsumerSecret(s.nextLine())
            .setOAuthAccessToken(s.nextLine()).setOAuthAccessTokenSecret(s.nextLine());
    TwitterFactory tf = new TwitterFactory(cb.build());
    t = tf.getInstance();//w  w  w.ja v  a 2 s .c o m
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 731852008030916608L }); //Track our tweets
    twitterStream.addListener(new MentionListener()); //Set the listener to our MentionListener class
    twitterStream.filter(filterQuery); //begin listening
}