Example usage for twitter4j FilterQuery FilterQuery

List of usage examples for twitter4j FilterQuery FilterQuery

Introduction

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

Prototype

public FilterQuery(int count, long[] follow, String[] track) 

Source Link

Document

Creates a new FilterQuery

Usage

From source file:twitterGateway_v2_06.java

License:Creative Commons License

public void SetupTwitter() {
    //twitterIn = new TwitterConnectStream();
    //accessToken = new AccessToken(TwitterAccessToken, TwitterAccessTokenSecret);
    //TwitterOAuthAuthorization.setOAuthAccessToken(accessToken);
    //TwitterOAuthAuthorization = new OAuthAuthorization(conf);
    //TwitterOAuthAuthorization.setOAuthConsumer(TwitterConsumerKey, TwitterConsumerSecret);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(TwitterConsumerKey)
            .setOAuthConsumerSecret(TwitterConsumerSecret).setOAuthAccessToken(TwitterAccessToken)
            .setOAuthAccessTokenSecret(TwitterAccessTokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitterOut = tf.getInstance();//w ww.  j a  v a 2 s.  c om
    //  try {
    //  twitterOut.updateStatus("Hello World!");
    //  }
    //  catch (TwitterException ex) {
    //    println(ex);
    //  }
    ActivityLogAddLine("twitter connector ready");
    output = createWriter("log.txt");

    StatusListener twitterIn = new StatusListener() {
        public void onStatus(Status status) {
            double Longitude;
            double Latitude;
            GeoLocation GeoLoc = status.getGeoLocation();
            if (GeoLoc != null) {
                //println("YES got a location");
                Longitude = GeoLoc.getLongitude();
                Latitude = GeoLoc.getLatitude();
            } else {
                Longitude = 0;
                Latitude = 0;
            }
            println(TimeStamp() + "\t" + Latitude + "\t" + Longitude + "\t" + status.getUser().getScreenName()
                    + "\t" + status.getText());
            output.println(TimeStamp() + "\t" + Latitude + "\t" + Longitude + "\t"
                    + status.getUser().getScreenName() + "\t" + status.getText());
            output.flush();
            TwitterToOsc(status.getUser().getScreenName(), status.getText());
        }

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

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

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

        public void onException(Exception ex) {
            println("CAUGHT in the ACT: " + ex);
        }
    };

    ConfigurationBuilder cbIn = new ConfigurationBuilder();
    cbIn.setDebugEnabled(true).setOAuthConsumerKey(TwitterConsumerKey)
            .setOAuthConsumerSecret(TwitterConsumerSecret).setOAuthAccessToken(TwitterAccessToken)
            .setOAuthAccessTokenSecret(TwitterAccessTokenSecret);

    TwitterStreamFactory ts = new TwitterStreamFactory(cbIn.build());
    TwitterStream twitterStream = ts.getInstance();
    twitterStream.addListener(twitterIn);

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

From source file:PrintFilterStream.java

License:Apache License

/**
 * Main entry of this application./*from   ww w.j  av  a 2s.  c  o m*/
 *
 * @param args follow(comma separated user ids) track(comma separated filter terms)
 * @throws TwitterException when Twitter service or network is unavailable
 */
public static void main(String[] args) throws TwitterException {
    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);
    }

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        @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);
    cb.setOAuthConsumerKey("");
    cb.setOAuthConsumerSecret("");
    cb.setOAuthAccessToken("");
    cb.setOAuthAccessTokenSecret("");

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

    twitterStream.addListener(listener);
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();
    for (String arg : args) {
        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));
}

From source file:ca.blackperl.WordFilterStreamBuilder.java

License:Apache License

public void main() {
    // create the twitter search listener
    PhraseListener listener = new PhraseListener(args);

    // Connect to twitter.
    final TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    // The listener to the twitter connection
    twitterStream.addListener(listener);

    // Build a search configuration
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();
    for (String arg : args) {
        if (isNumericalArgument(arg)) {
            for (String id : arg.split(",")) {
                follow.add(Long.parseLong(id));
            }//  www.  j  a  v a  2s. co m
        } 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 the listener methods continuously.

    // pass the search configuration to the twitter library to start the search
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));

    // Create a timer
    final Timer timer = new Timer();

    // Create a task to run every minute, starting in one minute.
    TimerTask summaryTask = new SummaryTask(listener, timer, twitterStream);
    timer.schedule(summaryTask, TimeToRunInSeconds * 1000, TimeToRunInSeconds * 1000);
}

From source file:com.rsinghal.cep.sample.facebook.StreamCollector1.java

License:Apache License

public void start() {

    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    long[] userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {//www  .  j a va 2s.  co m
            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.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    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()])));

    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.rsinghal.cep.sample.twitter.StreamCollector1.java

License:Apache License

public void start() {

    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    long[] userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {//from ww w .  ja  v  a 2s. c o  m
            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()])));

    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.rsinghal.cep.sample.twitter.TwitterBot.java

License:Apache License

public void start() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);/*from  w w w  . j a v a  2  s .  c o  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:crawling.PrintFilterStreamByFile.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamByFile ID_File ");
        System.exit(-1);//from  ww  w  .j a v  a2 s.  c om
    }

    idFile = args[0];
    tweetFile = idFile.split("\\.")[0] + "-tweets.txt";

    try {
        FileWriter outFile = new FileWriter(tweetFile, true);
        out = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            storeTweet(status.getUser().getId() + "::" + status.getText());
        }

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

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

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

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

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);

    // String users = "700896487,701053075,636744543";
    // String[] split = users.split(",");

    buildFollowList();

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

From source file:de.botshield.CaptureFilterStream.java

License:Apache License

public void execute(long[] followArray, String[] trackArray) {
    // try to set up new stream, when the listener fails due to HTTP timeout
    // for example

    this.initializeStreamListener();

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    try {/*from w  ww  .  java 2 s. c o  m*/
        // filter() method internally creates a thread which manipulates
        // TwitterStream and calls these adequate listener methods
        // continuously.
        twitterStream.filter(new FilterQuery(0, followArray, trackArray));
    } catch (Exception ex) {
        twitterStream.removeListener(listener);
        twitterStream.cleanUp();
    }
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public TwitterStream streamingTwitter(Collection<String> track, final Queue<JTweet> queue)
        throws TwitterException {
    String[] trackArray = track.toArray(new String[track.size()]);
    TwitterStream stream = new TwitterStreamFactory().getInstance(twitter.getAuthorization());
    stream.addListener(new StatusListener() {

        @Override// ww  w .  j  a  v  a 2s .com
        public void onStatus(Status status) {
            // ugly twitter ...
            if (Helper.isEmpty(status.getUser().getScreenName()))
                return;

            if (!queue.offer(new JTweet(toTweet(status), new JUser(status.getUser()))))
                logger.error("Cannot add tweet as input queue for streaming is full:" + queue.size());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            logger.error("We do not support onDeletionNotice at the moment! Tweet id: "
                    + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            logger.warn("onTrackLimitationNotice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onException(Exception ex) {
            logger.error("onException", ex);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }
    });
    stream.filter(new FilterQuery(0, new long[0], trackArray));
    return stream;
}

From source file:foo.bar.twitter.sample01.Sample01Activity.java

License:Apache License

/**
 * start button clicked/* w ww . j a v a  2 s .c o  m*/
 * @param v
 */
public void onClickStartButton(View v) {
    Log.d("DEBUG", "Start button clicked!");

    if (!isAuthorized) {
        Log.d("DEBUG", "not authorized");
        return;
    }

    bt_start.setEnabled(false); //start button disabled
    bt_cancel.setEnabled(true); //cancel button enabled

    if (isAuthorized) {
        twitterStream = new TwitterStreamFactory().getInstance();
        twitterStream.setOAuthConsumer(ConstantValue.CONSUMER_KEY, ConstantValue.CONSUMER_SECRET);
        twitterStream.setOAuthAccessToken(new AccessToken(token, tokenSecret));
        StatusListener listener = new StatusListener() {
            @Override
            public void onException(Exception arg0) {
                ;//no process
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice arg0) {
                ;//no process
            }

            @Override
            public void onScrubGeo(long arg0, long arg1) {
                ;//no process
            }

            @Override
            public void onStatus(Status status) {
                String tweet = status.getText();
                Log.d("DEBUG", "tweet: " + tweet);
            }

            @Override
            public void onTrackLimitationNotice(int arg0) {
                ;//no process
            }
        };
        twitterStream.addListener(listener);
        String[] trackArray = { ConstantValue.HASH_TAG };
        twitterStream.filter(new FilterQuery(0, null, trackArray));
    }
}