Example usage for twitter4j TwitterStream addListener

List of usage examples for twitter4j TwitterStream addListener

Introduction

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

Prototype

TwitterStream addListener(StreamListener listener);

Source Link

Usage

From source file:at.storm.spout.TwitterStreamSpout.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*from   ww  w  .  j a  v  a2 s.  c  o  m*/
public void open(Map config, TopologyContext context, SpoutOutputCollector collector) {
    m_collector = collector;
    m_tweetsQueue = new LinkedBlockingQueue<Status>(1000);

    // Optional startup sleep to finish bolt preparation
    // before spout starts emitting
    if (config.get(CONF_STARTUP_SLEEP_MS) != null) {
        long startupSleepMillis = (Long) config.get(CONF_STARTUP_SLEEP_MS);
        TimeUtils.sleepMillis(startupSleepMillis);
    }

    TwitterStream twitterStream = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance();

    // Set Listener
    twitterStream.addListener(new StatusListener() {
        @Override
        public void onStatus(Status status) {
            m_tweetsQueue.offer(status); // add tweet into queue
        }

        @Override
        public void onException(Exception arg0) {
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
        }

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

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
        }
    });

    // Set credentials
    twitterStream.setOAuthConsumer(m_consumerKey, m_consumerSecret);
    AccessToken token = new AccessToken(m_accessToken, m_accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    // Filter twitter stream
    FilterQuery tweetFilterQuery = new FilterQuery();
    if (m_keyWords != null) {
        tweetFilterQuery.track(m_keyWords);
    }

    // Filter location
    // https://dev.twitter.com/docs/streaming-apis/parameters#locations
    tweetFilterQuery.locations(new double[][] { new double[] { -180, -90, }, new double[] { 180, 90 } }); // any
    // geotagged
    // tweet

    // Filter language
    tweetFilterQuery.language(new String[] { m_filterLanguage });

    twitterStream.filter(tweetFilterQuery);
}

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  . ja  v  a2 s  .  c om*/
        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 .  j  a  v a2 s. c om
        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  a 2s  .  co m
            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:br.com.porcelli.hornetq.integration.twitter.stream.StreamHandler.java

License:Apache License

private <U extends AbstractUserBaseStreamListener> UserStreamHandler buildUserStreamHandler(
        final String[] listeners) {
    final Set<U> result = new HashSet<U>();
    for (final String listener : listeners) {
        try {//from   w  w  w  .j a v  a2  s .c om
            final Class<?> clazz = Class.forName(listener);
            if (AbstractUserBaseStreamListener.class.isAssignableFrom(clazz)) {
                result.add(ReflectionSupport.buildInstance((Class<U>) clazz, streamListenersConstructorArgs,
                        streamListenersInsanceArgs));
            }
        } catch (final ClassNotFoundException e) {
            mbean.notifyException(e);
            log.error("Twitter Stream '" + listener + "' not found");
        }
    }
    if (result.size() > 0) {
        final TwitterStream twitterStream = new TwitterStreamFactory(data.getConf()).getInstance();
        for (final U activeUserListener : result) {
            twitterStream.addListener(activeUserListener);
        }
        return new UserStreamHandler(data, twitterStream);
    }
    return null;
}

From source file:br.com.porcelli.hornetq.integration.twitter.stream.StreamHandler.java

License:Apache License

private <S extends AbstractSiteBaseStreamListener> SiteStreamHandler buildSiteStreamHandler(
        final String[] listeners) {
    final Set<S> result = new HashSet<S>();
    for (final String listener : listeners) {
        try {/*from ww  w  . j  av  a 2s .co m*/
            final Class<?> clazz = Class.forName(listener);
            if (AbstractSiteBaseStreamListener.class.isAssignableFrom(clazz)) {
                result.add(ReflectionSupport.buildInstance((Class<S>) clazz, streamListenersConstructorArgs,
                        streamListenersInsanceArgs));
            }
        } catch (final ClassNotFoundException e) {
            mbean.notifyException(e);
            log.error("Twitter Stream '" + listener + "' not found");
        }
    }
    if (result.size() > 0) {
        final TwitterStream twitterStream = new TwitterStreamFactory(data.getConf()).getInstance();
        for (final S activeUserListener : result) {
            twitterStream.addListener(activeUserListener);
        }
        return new SiteStreamHandler(data, twitterStream);
    }
    return null;
}

From source file:br.com.porcelli.hornetq.integration.twitter.stream.StreamHandler.java

License:Apache License

private <ST extends AbstractStatusBaseStreamListener> StatusStreamHandler buildStatusStreamHandler(
        final String[] listeners) {
    final Set<ST> result = new HashSet<ST>();
    for (final String listener : listeners) {
        try {//from  w  ww  .j a va  2 s  . c o  m
            final Class<?> clazz = Class.forName(listener);
            if (AbstractStatusBaseStreamListener.class.isAssignableFrom(clazz)) {
                result.add(ReflectionSupport.buildInstance((Class<ST>) clazz, streamListenersConstructorArgs,
                        streamListenersInsanceArgs));
            }
        } catch (final ClassNotFoundException e) {
            mbean.notifyException(e);
            log.error("Twitter Stream '" + listener + "' not found");
        }
    }
    if (result.size() > 0) {
        final TwitterStream twitterStream = new TwitterStreamFactory(data.getConf()).getInstance();
        for (final ST activeUserListener : result) {
            twitterStream.addListener(activeUserListener);
        }
        return new StatusStreamHandler(data, twitterStream);
    }
    return null;
}

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  va  2  s .  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: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);/*from  ww w .ja  v  a 2 s  .c o  m*/
    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();/*from ww  w  . j a v  a2  s  .  c o m*/
    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);
}