Example usage for twitter4j TwitterStreamFactory TwitterStreamFactory

List of usage examples for twitter4j TwitterStreamFactory TwitterStreamFactory

Introduction

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

Prototype

public TwitterStreamFactory(String configTreePath) 

Source Link

Document

Creates a TwitterStreamFactory with a specified config tree.

Usage

From source file:au.net.moon.tUtils.twitterAuthorise.java

License:Open Source License

/**
 * @param streamConnection/*from   w  ww .jav  a  2s. com*/
 *            <CODE>True</CODE> if connection is to streamAPI,
 *            <CODE>False</CODE> otherwise
 */
public twitterAuthorise(Boolean streamConnection) {
    if (!streamConnection) {
        if (twitter == null) {
            System.out.println("TwitterAuthorise: Connecting to Twitter with OAuth");
            twitter = new TwitterFactory().getInstance();
            try {
                System.out.println("TwitterAuthorise: rate limit status: " + twitter.getRateLimitStatus());
            } catch (TwitterException e) {
                System.out.println("TwitterAuthorise: Failed to get rate limit status");
                e.printStackTrace();
            }
        }
    } else {
        if (twitterStream == null) {
            System.out.println("TwitterAuthorise: Connecting to Twitter Stream with OAuth");
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setUseSSL(true);
            Configuration conf = builder.build();
            twitterStream = new TwitterStreamFactory(conf).getInstance();
            System.out.println(
                    "TwitterAuthorise: Stream authorisation status: " + twitterStream.getAuthorization());

        }
    }
}

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 {/*from  w ww  .j  av a 2s  .  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:benche.me.TwitterParser.Main.java

License:Open Source License

    /**
   * Configure twitter API connection for tweet streaming
   * @return TwitterStream instance/*from   ww w.  jav  a2s.  com*/
   */
  private static TwitterStream configureStream() {
       ConfigurationBuilder cb = new ConfigurationBuilder();
       cb.setOAuthConsumerKey(Constants.CONSUMER_KEY_KEY);
       cb.setOAuthConsumerSecret(Constants.CONSUMER_SECRET_KEY);
       cb.setOAuthAccessToken(Constants.ACCESS_TOKEN_KEY);
       cb.setOAuthAccessTokenSecret(Constants.ACCESS_TOKEN_SECRET_KEY);
       cb.setJSONStoreEnabled(true);
       cb.setIncludeEntitiesEnabled(true);
       return new TwitterStreamFactory(cb.build()).getInstance();
}

From source file:beproject.myTwitter.java

License:Open Source License

myTwitter(JLabel ret) {

    ts = new TwitterStreamFactory(conf).getInstance();
    try {/*from ww  w  .  java2  s .  c om*/
        stmt = inConn.createStatement();
    } catch (SQLException e) {
        ExceptionManager.handleException(e, "Serious Error at myTwitter.java method myTwitter()");
    }
    polarityAnalyzer = new PolarityAnalyzer();
    this.ret = ret;
}

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  va 2s.  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: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 av a2  s .  co m
            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   w  w  w .  j  a  v a  2s  .  c  om
            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 {/*w w  w .j  av  a2  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:br.shura.team.mpsbot.runtime.ConnectedBot.java

License:Open Source License

public void connect() {
    ApiKeys keys = getBot().getApiKeys();

    if (!isConnected()) {
        Configuration configuration = new ConfigurationBuilder().setOAuthAccessToken(keys.getAccessToken())
                .setOAuthAccessTokenSecret(keys.getAccessTokenSecret())
                .setOAuthConsumerKey(keys.getConsumerKey()).setOAuthConsumerSecret(keys.getConsumerSecret())
                .build();//w w  w.  j  a  v a2  s.c  o m
        OAuthAuthorization auth = new OAuthAuthorization(configuration);
        TwitterStreamFactory streamFactory = new TwitterStreamFactory(configuration);
        ImageUploadFactory uploadFactory = new ImageUploadFactory(configuration);

        this.streamer = streamFactory.getInstance(auth);
        this.uploader = uploadFactory.getInstance(auth);
    }
}

From source file:cats.twitter.collect.Collect.java

@Override
public boolean runCollect() {

    dateEnd = Calendar.getInstance();
    dateEnd.add(Calendar.DAY_OF_YEAR, duree);
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);//w  w w .j  a  v  a 2s. com
    cb.setOAuthConsumerKey(user.getConsumerKey());
    System.out.println("CONSUMER KEY " + user.getConsumerKey());
    cb.setOAuthConsumerSecret(user.getConsumerSecret());
    System.out.printf("CONSUMER SECRET " + user.getConsumerSecret());
    cb.setOAuthAccessToken(user.getToken());
    System.out.printf("TOKEN" + user.getToken());
    cb.setOAuthAccessTokenSecret(user.getTokenSecret());
    System.out.printf("TOKEN SECRET " + user.getTokenSecret());

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

    setStatus(State.WAITING_FOR_CONNECTION);

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {

            if (!corpus.getState().equals(State.INPROGRESS)) {
                setStatus(State.INPROGRESS);
            }
            if (status.getCreatedAt().after(dateEnd.getTime())) {
                shutdown();

            } else if (corpus.getLang() == null || corpus.getLang().equals(status.getLang())) {
                Tweet t = new Tweet();
                t.setText(status.getText().replace("\r", "\n"));
                t.setAuthor(status.getUser().getId());
                t.setId(status.getId());
                t.setDate(status.getCreatedAt());
                if (status.getGeoLocation() != null)
                    t.setLocation(status.getGeoLocation().toString());
                t.setName(status.getUser().getName());
                t.setDescriptionAuthor(status.getUser().getDescription());
                t.setLang(status.getLang());
                t.setCorpus(corpus);
                if (tweetRepository != null)
                    tweetRepository.save(t);
            }

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
            System.out.println(sdn);
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            corpus.setLimitationNotice(i);
            corpus = corpusRepository.save(corpus);

        }

        @Override
        public void onScrubGeo(long l, long l1) {
            System.out.println(l + "" + l1);
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            System.out.println(sw);
        }

        @Override
        public void onException(Exception excptn) {
            corpus.setErrorMessage(excptn.getMessage());
            setStatus(State.ERROR);
            excptn.printStackTrace();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.filter(filter);

    return false;
}