Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

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

License:Open Source License

/**
 * @param streamConnection/*ww w  .jav  a  2s .c om*/
 *            <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 w w.  j  a  v  a  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:Beans.Crawler.java

/**
 * Retrieve the "bearer" token from Twitter in order to make application-authenticated calls.
 *
 * This is the first step in doing application authentication, as described in Twitter's documentation at
 * https://dev.twitter.com/docs/auth/application-only-auth
 *
 * Note that if there's an error in this process, we just print a message and quit.  That's a pretty
 * dramatic side effect, and a better implementation would pass an error back up the line...
 *
 * @return   The oAuth2 bearer token/*  w w  w. ja va 2 s . c  o m*/
 */
public static OAuth2Token getOAuth2Token() {
    OAuth2Token token = null;
    ConfigurationBuilder cb;

    cb = new ConfigurationBuilder();
    cb.setApplicationOnlyAuthEnabled(true);

    cb.setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET);

    try {
        token = new TwitterFactory(cb.build()).getInstance().getOAuth2Token();
    } catch (Exception e) {
        System.out.println("Could not get OAuth2 token");
        e.printStackTrace();
        System.exit(0);
    }

    return token;
}

From source file:Beans.Crawler.java

/**
 * Get a fully application-authenticated Twitter object useful for making subsequent calls.
 *
 * @return   Twitter4J Twitter object that's ready for API calls
 *//*from w w w.j a  v a2s  .  c  o m*/
public static Twitter getTwitter() {
    OAuth2Token token;

    //   First step, get a "bearer" token that can be used for our requests
    token = getOAuth2Token();

    //   Now, configure our new Twitter object to use application authentication and provide it with
    //   our CONSUMER key and secret and the bearer token we got back from Twitter
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setApplicationOnlyAuthEnabled(true);

    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);

    cb.setOAuth2TokenType(token.getTokenType());
    cb.setOAuth2AccessToken(token.getAccessToken());

    //   And create the Twitter object!
    return new TwitterFactory(cb.build()).getInstance();

}

From source file:benche.me.TwitterParser.Main.java

License:Open Source License

/**
     * Configure twitter API connection for historical search
     * @return Twitter connection instance
     *///from  ww  w .j  a va2  s . c  o m
    private static Twitter configureSearch() {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.CONSUMER_KEY_KEY)
                .setOAuthConsumerSecret(Constants.CONSUMER_SECRET_KEY)
                .setOAuthAccessToken(Constants.ACCESS_TOKEN_KEY)
                .setOAuthAccessTokenSecret(Constants.ACCESS_TOKEN_SECRET_KEY);
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        return twitter;
    }

From source file:benche.me.TwitterParser.Main.java

License:Open Source License

    /**
   * Configure twitter API connection for tweet streaming
   * @return TwitterStream instance/*from w  w  w.j  a va2  s  . 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: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 .  jav  a2s  . c  o  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.controller.TweetController.java

public static OAuth2Token getOAuth2Token() {
    OAuth2Token token = null;//from  w  w  w. j av  a2  s.  c  om
    ConfigurationBuilder cb;

    cb = new ConfigurationBuilder();
    cb.setApplicationOnlyAuthEnabled(true);

    cb.setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET);

    try {
        token = new TwitterFactory(cb.build()).getInstance().getOAuth2Token();
    } catch (Exception e) {
        System.out.println("Could not get OAuth2 token");
        e.printStackTrace();
        System.exit(0);
    }

    return token;
}

From source file:br.com.controller.TweetController.java

public static Twitter getTwitter() {
    OAuth2Token token;//from w ww  .j a va  2  s .c o m

    token = getOAuth2Token();
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setApplicationOnlyAuthEnabled(true);

    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);

    cb.setOAuth2TokenType(token.getTokenType());
    cb.setOAuth2AccessToken(token.getAccessToken());

    return new TwitterFactory(cb.build()).getInstance();
}

From source file:br.com.porcelli.hornetq.integration.twitter.outgoing.impl.OutgoingTwitterHandler.java

License:Apache License

public OutgoingTwitterHandler(final String connectorName, final Map<String, Object> configuration,
        final PostOffice postOffice) {

    this.connectorName = connectorName;

    this.mbean = new TwitterOutgoingManagement(this);

    try {//from   w w w . ja v  a  2  s .  co  m
        MBeanServer mbServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName mbeanName = new ObjectName("org.hornetq:module=ConnectorService,name=" + connectorName);
        mbServer.registerMBean(mbean, mbeanName);
    } catch (Exception e) {
        log.error("Error on registering JMX info.", e);
    }

    final Configuration conf = new ConfigurationBuilder()
            .setOAuthConsumerKey(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_CONSUMER_KEY, null, configuration))
            .setOAuthConsumerSecret(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_CONSUMER_SECRET, null, configuration))
            .setOAuthAccessToken(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_ACCESS_TOKEN, null, configuration))
            .setOAuthAccessTokenSecret(ConfigurationHelper
                    .getStringProperty(InternalTwitterConstants.PROP_ACCESS_TOKEN_SECRET, null, configuration))
            .build();

    this.postOffice = postOffice;
    this.twitter = new TwitterFactory(conf).getInstance();

    final String queueName = ConfigurationHelper.getStringProperty(InternalTwitterConstants.PROP_QUEUE_NAME,
            null, configuration);

    final String errorQueueName = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_ERROR_QUEUE_NAME, null, configuration);

    final String sentQueueName = ConfigurationHelper
            .getStringProperty(InternalTwitterConstants.PROP_SENT_QUEUE_NAME, null, configuration);

    final Binding queueBinding = postOffice.getBinding(new SimpleString(queueName));
    if (queueBinding == null) {
        throw new RuntimeException(connectorName + ": queue " + queueName + " not found");
    }
    queue = (Queue) queueBinding.getBindable();

    if (errorQueueName != null && errorQueueName.trim().length() > 0) {
        final Binding errorQueueBinding = postOffice.getBinding(new SimpleString(errorQueueName));
        if (errorQueueBinding == null) {
            throw new RuntimeException(connectorName + ": queue " + errorQueueName + " not found");
        }
        errorQueue = (Queue) errorQueueBinding.getBindable();
    } else {
        errorQueue = null;
    }

    if (sentQueueName != null && sentQueueName.trim().length() > 0) {
        final Binding sentQueueBinding = postOffice.getBinding(new SimpleString(sentQueueName));
        if (sentQueueBinding == null) {
            throw new RuntimeException(connectorName + ": queue " + sentQueueName + " not found");
        }
        sentQueue = (Queue) sentQueueBinding.getBindable();
    } else {
        sentQueue = null;
    }
}