Example usage for twitter4j TwitterStream filter

List of usage examples for twitter4j TwitterStream filter

Introduction

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

Prototype

TwitterStream filter(final String... track);

Source Link

Document

Start consuming public statuses that match the filter predicate.

Usage

From source file:bditac.TwitterCaptura.java

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

    int criid, apiid, capid;

    if (args.length == 3) {
        criid = Integer.parseInt(args[0]);
        apiid = Integer.parseInt(args[1]);
        capid = Integer.parseInt(args[2]);
    } else {//w w  w.  j  a va 2 s  . c  o m
        criid = 1;
        apiid = 1;
        capid = 1;
    }

    CriseJpaController crijpa = new CriseJpaController(factory);

    Crise crise = crijpa.findCrise(criid);

    CriseApiJpaController criapijpa = new CriseApiJpaController(factory);

    CriseApi criapi = criapijpa.findCriseApi(capid);

    ApiJpaController apijpa = new ApiJpaController(factory);

    Api api = apijpa.findApi(apiid);

    CidadeJpaController cidjpa = new CidadeJpaController(factory);

    Cidade cidade = cidjpa.findCidade(crise.getCidId());

    String coords[] = crise.getCriRegiao().split(",");

    TwitterGeo geo = new TwitterGeo(coords, cidade.getCidNome(), crise.getCriGeotipo());

    Thread threadGeo = new Thread(geo);

    TwitterMens mens = new TwitterMens(crise.getCrtId());

    Thread threadMens = new Thread(mens);

    TwitterGravar gravar = new TwitterGravar();

    Thread threadGravar = new Thread(gravar);

    threadGeo.setName("ThreadGeo");
    threadGeo.start();

    threadMens.setName("ThreadMens");
    threadMens.start();

    threadGravar.setName("ThreadGravar");
    threadGravar.start();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(criapi.getCapKey())
            .setOAuthConsumerSecret(criapi.getCapSecret()).setOAuthAccessToken(criapi.getCapToken())
            .setOAuthAccessTokenSecret(criapi.getCapTokenSecret());

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

    String texto = "[\\xF0\\x9F]";

    StatusListener listener;
    listener = new StatusListener() {
        int cont = 0;

        @Override
        public void onStatus(Status status) {
            if (!(status.getText().contains(texto) || status.getText().isEmpty())) {
                Ocorrencia ocor = new Ocorrencia();
                ocor.setApiId(apiid);
                ocor.setCriId(criid);
                ocor.setCapId(capid);

                ocor.setOcrIdApi(status.getId());
                ocor.setOcrCriacao(status.getCreatedAt());
                ocor.setOcrTexto(status.getText());
                //                    System.out.println(ocor.getOcrTexto());
                ocor.setOcrUsuId(status.getUser().getId());
                ocor.setOcrUsuNome(status.getUser().getName());
                ocor.setOcrUsuScreenNome(status.getUser().getScreenName());
                ocor.setOcrFonte(status.getSource());
                ocor.setOcrLingua(status.getLang());
                ocor.setOcrFavorite(status.getFavoriteCount());
                ocor.setOcrRetweet(status.getRetweetCount());
                String coords = "";
                if (status.getPlace() == null) {
                    ocor.setOcrPaisCodigo("");
                    ocor.setOcrPais("");
                    ocor.setOcrLocal("");
                } else {
                    ocor.setOcrPaisCodigo(status.getPlace().getCountryCode());
                    ocor.setOcrPais(status.getPlace().getCountry());
                    ocor.setOcrLocal(status.getPlace().getFullName());
                    GeoLocation locs[][] = status.getPlace().getBoundingBoxCoordinates();
                    for (int x = 0; x < locs.length; x++) {
                        for (int y = 0; y < locs[x].length; y++) {
                            coords += "[" + locs[x][y].getLongitude() + "," + locs[x][y].getLatitude() + "]";
                            if (!(x == locs.length - 1 && y == locs[x].length - 1)) {
                                coords += ",";
                            }
                        }
                    }
                }

                ocor.setOcrCoordenadas(coords);
                ocor.setOcrGeo('0');
                ocor.setOcrIdentificacao('0');
                ocor.setOcrIdenper(0.0f);
                ocor.setOcrGravado('0');
                ocor.setOcrSentimento('0');
                ocor.setOcrTempo('0');

                boolean add = ocors.add(ocor);

                cont++;

                if (ocors.size() > 1000) {
                    Limpar();
                }

                //                    System.out.println(cont+" - "+status.getId() + " - " + status.getCreatedAt() + status.getPlace().getFullName());
            }
        }

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

        private void Limpar() {
            while (!threadGeo.isInterrupted()) {
                threadGeo.interrupt();
            }
            while (!threadMens.isInterrupted()) {
                threadMens.interrupt();
            }
            while (!threadGravar.isInterrupted()) {
                threadGravar.interrupt();
            }
            boolean achou = true;
            int x = 0;
            System.out.println("Removendo: " + ocors.size());
            while (x < ocors.size()) {
                if (ocors.get(x).getOcrGravado() != '0') {
                    ocors.remove(x);
                } else {
                    x++;
                }
            }
            System.out.println("Final: " + ocors.size());
            if (!threadGeo.isAlive()) {
                threadGeo.start();
            }
            if (!threadMens.isAlive()) {
                threadMens.start();
            }
            if (!threadGravar.isAlive()) {
                threadGravar.start();
            }
        }
    };

    FilterQuery filter = new FilterQuery();

    double[][] location = new double[2][2];

    location[0][0] = Double.parseDouble(coords[0]);
    location[0][1] = Double.parseDouble(coords[1]);
    location[1][0] = Double.parseDouble(coords[4]);
    location[1][1] = Double.parseDouble(coords[5]);

    filter.locations(location);

    twitterStream.addListener(listener);

    twitterStream.filter(filter);
}

From source file:be.ugent.tiwi.sleroux.newsrec.twittertest.StreamReaderService.java

public void readTwitterFeed() {

    TwitterStream stream = TwitterStreamBuilderUtil.getStream();

    StatusListener listener = new StatusListener() {

        @Override/*from  w  ww .  ja  v a 2  s.  com*/
        public void onException(Exception e) {
        }

        @Override
        public void onTrackLimitationNotice(int n) {
        }

        @Override
        public void onStatus(Status status) {
            if (status.getLang().equals("en")) {
                System.out.println(status.getText());
            }
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
        }

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

    stream.addListener(listener);
    FilterQuery f = new FilterQuery();
    f.language(new String[] { "en" });
    f.follow(new long[] { 816653 });
    stream.filter(f);

    try {
        Thread.sleep(60000);
    } catch (InterruptedException ex) {
        Logger.getLogger(StreamReaderService.class.getName()).log(Level.SEVERE, null, ex);
    }
    stream.shutdown();
}

From source file:birdseye.Sample.java

License:Apache License

public List<TweetData> execute(String[] args) throws TwitterException {

    final List<TweetData> statuses = new ArrayList();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthAccessToken("14538839-3MX2UoCEUaA6u95iWoYweTKRbhBjqEVuK1SPbCjDV");
    cb.setOAuthAccessTokenSecret("nox7eYyOJpyiDiISHRDou90bGkHKasuw1IMqqJUZMaAbj");

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

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            String user = status.getUser().getScreenName();
            String content = status.getText();
            TweetData newTweet = new TweetData(user, content);

            statuses.add(newTweet);//from  w w w  .j a v  a2  s. c  om
            System.out.println(statuses.size() + ":" + status.getText());
            if (statuses.size() > 15) {
                synchronized (lock) {
                    lock.notify();
                }
                System.out.println("unlocked");
            }
        }

        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 sw) {
            System.out.println(sw.getMessage());

        }
    };

    FilterQuery fq = new FilterQuery();
    String[] keywords = args;

    fq.track(keywords);

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

    try {
        synchronized (lock) {
            lock.wait();
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("returning statuses");
    twitterStream.shutdown();
    return statuses;
}

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));
            }// w w  w  . j a v a2s  .c o  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:cc.twittertools.stream.GatherStatusStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    PatternLayout layoutStandard = new PatternLayout();
    layoutStandard.setConversionPattern("[%p] %d %c %M - %m%n");

    PatternLayout layoutSimple = new PatternLayout();
    layoutSimple.setConversionPattern("%m%n");

    // Filter for the statuses: we only want INFO messages
    LevelRangeFilter filter = new LevelRangeFilter();
    filter.setLevelMax(Level.INFO);
    filter.setLevelMin(Level.INFO);
    filter.setAcceptOnMatch(true);//  ww  w .j av  a2s. com
    filter.activateOptions();

    TimeBasedRollingPolicy statusesRollingPolicy = new TimeBasedRollingPolicy();
    statusesRollingPolicy.setFileNamePattern("statuses.log" + HOUR_ROLL);
    statusesRollingPolicy.activateOptions();

    RollingFileAppender statusesAppender = new RollingFileAppender();
    statusesAppender.setRollingPolicy(statusesRollingPolicy);
    statusesAppender.addFilter(filter);
    statusesAppender.setLayout(layoutSimple);
    statusesAppender.activateOptions();

    TimeBasedRollingPolicy warningsRollingPolicy = new TimeBasedRollingPolicy();
    warningsRollingPolicy.setFileNamePattern("warnings.log" + HOUR_ROLL);
    warningsRollingPolicy.activateOptions();

    RollingFileAppender warningsAppender = new RollingFileAppender();
    warningsAppender.setRollingPolicy(statusesRollingPolicy);
    warningsAppender.setThreshold(Level.WARN);
    warningsAppender.setLayout(layoutStandard);
    warningsAppender.activateOptions();

    ConsoleAppender consoleAppender = new ConsoleAppender();
    consoleAppender.setThreshold(Level.WARN);
    consoleAppender.setLayout(layoutStandard);
    consoleAppender.activateOptions();

    // configures the root logger
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.removeAllAppenders();
    rootLogger.addAppender(consoleAppender);
    rootLogger.addAppender(statusesAppender);
    rootLogger.addAppender(warningsAppender);

    // creates a custom logger and log messages
    final Logger logger = Logger.getLogger(GatherStatusStream.class);

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    RawStreamListener rawListener = new RawStreamListener() {

        @Override
        public void onMessage(String rawString) {
            cnt++;
            logger.info(rawString);
            if (cnt % 100 == 0) {
                System.out.println(cnt + " messages received.");
            }
        }

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

    };

    twitterStream.addListener(rawListener);
    FilterQuery fq = new FilterQuery();
    /* double locations[][]={{112.0,-44.0},{155.0,-10.5}}; 
     fq.locations(locations);*/
    long ids[] = { 87818409, 16675569 };
    fq.follow(ids);
    twitterStream.filter(fq);
    //twitterStream.sample();
}

From source file:cloudcomputebot.CloudComputeBot.java

License:Open Source License

public static void main(String[] args) {
    TwitterLib.init();//w  w  w .j a va  2  s .c om
    t = TwitterLib.t;
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 4741197613L });
    twitterStream.addListener(new MentionListener());
    twitterStream.filter(filterQuery);
}

From source file:com.babatunde.twittergoogle.Utility.java

public void postToGoogle(PlusDomains s, String id, String hashtag) {
    try {/*  w  ww  .j  a  va  2  s  .  c o m*/
        final PlusDomains serve = s;
        final String circleID = id;
        listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                String msg = status.getUser().getName() + " - " + "@" + status.getUser().getScreenName() + " - "
                        + status.getText();
                System.out.println(msg);
                //Create a list of ACL entries
                if (serve != null && (!circleID.isEmpty() || (circleID != null))) {
                    PlusDomainsAclentryResource resource = new PlusDomainsAclentryResource();
                    resource.setType("domain").setType("circle").setId(circleID);

                    //Get Emails of people in the circle.
                    List<PlusDomainsAclentryResource> aclEntries = new ArrayList<PlusDomainsAclentryResource>();
                    aclEntries.add(resource);

                    Acl acl = new Acl();

                    acl.setItems(aclEntries);
                    acl.setDomainRestricted(true); // Required, this does the domain restriction

                    // Create a new activity object
                    Activity activity = new Activity()
                            .setObject(new Activity.PlusDomainsObject().setOriginalContent(msg)).setAccess(acl);
                    try {
                        // Execute the API request, which calls `activities.insert` for the logged in user
                        activity = serve.activities().insert("me", activity).execute();
                    } catch (IOException ex) {
                        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

            }

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

        };
    } catch (Exception e) {
    }

    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    twitterStream.addListener(listener);
    String str[] = { hashtag };
    twitterStream.shutdown();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
    }
    twitterStream.filter(new FilterQuery().track(str));

}

From source file:com.isdp.twitterposter.TwitterManager.java

License:Open Source License

public void startTwitterStream() {
    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    StatusListener listener = new StatusListener() {
        @Override//w  ww  .  j  av  a  2 s . c o m
        public void onStatus(Status status) {
            try {
                System.out.println("Text recieved: @" + status.getUser().getScreenName() + " - "
                        + status.getText() + "\n");

                StringTokenizer st = new StringTokenizer(status.getText(), " ");

                //first token indicates search engine
                String searchEngine = st.nextToken();

                //burn the next random token
                String randToken = st.nextToken();

                //next token indicates max number of results to return
                int maxResults = Integer.parseInt(st.nextToken());

                String searchString = "";
                while (st.hasMoreTokens()) {
                    searchString += st.nextToken() + " ";
                }

                if (searchEngine.equals(GoogleManager.TAG_YELP)) {
                    String[] results = GoogleManager.getInstance().trySearch(searchString,
                            GoogleManager.SEARCH_YELP);

                    if (results != null) {
                        for (int i = 0; i < results.length && i < maxResults; ++i) {
                            String tweetMsg = Util.truncateString(results[i], TWITTER_CHARACTER_LIMIT);

                            System.out.println("Tweeting" + tweetMsg);

                            tweet(tweetMsg);
                        }
                    } else if (results == null || results.length == 0) {
                        tweet(Util.generateRandomString(7) + "\n" + "No results found!");
                    }
                } else if (searchEngine.equals(GoogleManager.TAG_WIKI)) {
                    String[] results = GoogleManager.getInstance().trySearch(searchString,
                            GoogleManager.SEARCH_WIKI);

                    if (results != null) {
                        for (int i = 0; i < results.length && i < maxResults; ++i) {
                            String tweetMsg = Util.generateRandomString(3) + "\n"
                                    + Util.shortenText(results[i]);
                            tweetMsg = Util.truncateString(tweetMsg, TWITTER_CHARACTER_LIMIT);

                            System.out.println("Tweeting " + tweetMsg);

                            tweet(tweetMsg);
                        }
                    } else if (results == null || results.length == 0) {
                        tweet(Util.generateRandomString(7) + "\n" + "No results found!");
                    }
                }
            } catch (Exception e) {
            }
        }

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

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

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

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

        @Override
        public void onException(Exception ex) {
            System.out.println("onException" + ex.toString());
        }
    };

    twitterStream.addListener(listener);

    FilterQuery tweetFilterQuery = new FilterQuery();

    tweetFilterQuery.follow(new long[] { FOLLOW_ID });

    twitterStream.filter(tweetFilterQuery);
}

From source file:com.isdp.twitterposterandroid.TwitterManager.java

License:Open Source License

public void startTwitterStream() {
    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    StatusListener listener = new StatusListener() {
        @Override//  w w  w .  ja v  a 2 s  . c  om
        public void onStatus(Status status) {
            try {
                Log.d("Text recieved",
                        "@" + status.getUser().getScreenName() + " - " + status.getText() + "\n");

                StringTokenizer st = new StringTokenizer(status.getText(), " ");

                //first token indicates search engine
                String searchEngine = st.nextToken();

                //burn the next random token
                String randToken = st.nextToken();

                //next token indicates max number of results to return
                int maxResults = Integer.parseInt(st.nextToken());

                String searchString = "";
                while (st.hasMoreTokens()) {
                    searchString += st.nextToken() + " ";
                }

                if (searchEngine.equals(GoogleManager.TAG_YELP)) {
                    String[] results = GoogleManager.getInstance().trySearch(searchString,
                            GoogleManager.SEARCH_YELP);

                    if (results != null) {
                        for (int i = 0; i < results.length && i < maxResults; ++i) {
                            String tweetMsg = Util.truncateString(results[i], TWITTER_CHARACTER_LIMIT);

                            Log.d("Tweeting", tweetMsg);

                            tweet(tweetMsg);
                        }
                    } else if (results == null || results.length == 0) {
                        tweet(Util.generateRandomString(7) + "\n" + "No results found!");
                    }
                } else if (searchEngine.equals(GoogleManager.TAG_WIKI)) {
                    String[] results = GoogleManager.getInstance().trySearch(searchString,
                            GoogleManager.SEARCH_WIKI);

                    if (results != null) {
                        for (int i = 0; i < results.length && i < maxResults; ++i) {
                            String tweetMsg = Util.generateRandomString(3) + "\n"
                                    + Util.shortenText(results[i]);
                            tweetMsg = Util.truncateString(tweetMsg, TWITTER_CHARACTER_LIMIT);

                            Log.d("Tweeting", tweetMsg);

                            tweet(tweetMsg);
                        }
                    } else if (results == null || results.length == 0) {
                        tweet(Util.generateRandomString(7) + "\n" + "No results found!");
                    }
                }
            } catch (Exception e) {
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            Log.d("onDeletionNotice", "Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            Log.d("onTrackLimitationNotice", "Got track limitation notice:" + numberOfLimitedStatuses);
        }

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

        @Override
        public void onStallWarning(StallWarning warning) {
            Log.d("onStallWarning", "Got stall warning:" + warning);
        }

        @Override
        public void onException(Exception ex) {
            Log.d("onException", ex.toString());
        }
    };

    twitterStream.addListener(listener);

    FilterQuery tweetFilterQuery = new FilterQuery();

    tweetFilterQuery.follow(new long[] { FOLLOW_ID });

    twitterStream.filter(tweetFilterQuery);
}

From source file:com.left8.evs.utilities.dsretriever.TweetsRetriever.java

License:Open Source License

/**
 * Method that handles the Twitter streaming API. <br>
 * <b>WARNING:</b> Method does not terminate by itself, due to the fact that
 * the streamer runs in a different thread.
 * @param keywords The keywords for which the streamer searches for tweets.
 * @param mongoDB A handler for the MongoDB database.
 * @param config A configuration object.
 *//*w w w. j  a  va  2s . c  o m*/
public final void retrieveTweetsWithStreamingAPI(String[] keywords, MongoHandler mongoDB, Config config) {

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

    final StatusListener listener;
    listener = new StatusListener() {

        @Override
        public final void onStatus(Status status) {
            //Insert tweet to MongoDB
            mongoDB.insertSingleTweetIntoMongoDB(status, "NULL");
        }

        @Override
        public final void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            Utilities.printMessageln("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public final void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            Utilities.printMessageln("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public final void onScrubGeo(long userId, long upToStatusId) {
            Utilities.printMessageln("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public final void onStallWarning(StallWarning warning) {
            Utilities.printMessageln("Got stall warning:" + warning);
        }

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

    FilterQuery fq = new FilterQuery();
    fq.language("en"); //Set language of tweets to "English"
    fq.track(keywords); //Load the search terms

    twitterStream.addListener(listener); //Start listening to the stream
    twitterStream.filter(fq); //Apply the search filters
}