Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

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

Prototype

public Configuration build() 

Source Link

Usage

From source file:adapter.TwitterKeywordsAdapter.java

License:Apache License

public void connectAndRead() throws Exception {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    Properties twitterProperties = new Properties();
    File twitter4jPropsFile = new File("../twitter4j.properties");
    if (!twitter4jPropsFile.exists()) {
        logger.error("Cannot find twitter4j.properties file in this location :[{}]",
                twitter4jPropsFile.getAbsolutePath());
        return;/*  w ww  . j  a v  a 2  s .co m*/
    }

    twitterProperties.load(new FileInputStream(twitter4jPropsFile));

    cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(twitterProperties.getProperty("oauth.consumerKey"));
    cb.setOAuthConsumerSecret(twitterProperties.getProperty("oauth.consumerSecret"));
    cb.setOAuthAccessToken(twitterProperties.getProperty("oauth.accessToken"));
    cb.setOAuthAccessTokenSecret(twitterProperties.getProperty("oauth.accessTokenSecret"));

    cb.setDebugEnabled(false);
    cb.setPrettyDebugEnabled(false);
    cb.setIncludeMyRetweetEnabled(false);

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

    StatusListener statusListener = new StatusListener() {
        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onStatus(Status status) {
            messageQueue.add(status);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    FilterQuery fq = new FilterQuery();

    //System.out.println(Arrays.toString(configuration.getTrack()));

    //Elige todos los tweets que posean esas palabras claves
    fq.track(new String[] { "palabra1,palabra2,palabra3" });
    //fq.track(keywords);
    twitterStream.addListener(statusListener);
    twitterStream.filter(fq);
}

From source file:adapter.TwitterLanguageAdapter.java

License:Apache License

public void connectAndRead() throws Exception {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    Properties twitterProperties = new Properties();
    File twitter4jPropsFile = new File("../twitter4j.properties");
    if (!twitter4jPropsFile.exists()) {
        logger.error("Cannot find twitter4j.properties file in this location :[{}]",
                twitter4jPropsFile.getAbsolutePath());
        return;//  w w w  . j  a va  2 s . c  o m
    }

    twitterProperties.load(new FileInputStream(twitter4jPropsFile));

    cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(twitterProperties.getProperty("oauth.consumerKey"));
    cb.setOAuthConsumerSecret(twitterProperties.getProperty("oauth.consumerSecret"));
    cb.setOAuthAccessToken(twitterProperties.getProperty("oauth.accessToken"));
    cb.setOAuthAccessTokenSecret(twitterProperties.getProperty("oauth.accessTokenSecret"));

    cb.setDebugEnabled(false);
    cb.setPrettyDebugEnabled(false);
    cb.setIncludeMyRetweetEnabled(false);

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

    StatusListener statusListener = new StatusListener() {
        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onStatus(Status status) {
            messageQueue.add(status);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    //Filter language and track
    FilterQuery tweetFilterQuery = new FilterQuery();
    tweetFilterQuery.track(new String[] { "palabra1,palabra2,palabra3" });
    tweetFilterQuery.language(new String[] { "es" });

    //TwitterStream
    twitterStream.addListener(statusListener);
    twitterStream.filter(tweetFilterQuery);
}

From source file:adapter.TwitterLocationAdapter.java

License:Apache License

public void connectAndRead() throws Exception {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    Properties twitterProperties = new Properties();
    File twitter4jPropsFile = new File("../twitter4j.properties");
    if (!twitter4jPropsFile.exists()) {
        logger.error("Cannot find twitter4j.properties file in this location :[{}]",
                twitter4jPropsFile.getAbsolutePath());
        return;//from  w  w w .  ja v a2 s . c  o  m
    }

    twitterProperties.load(new FileInputStream(twitter4jPropsFile));

    cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(twitterProperties.getProperty("oauth.consumerKey"));
    cb.setOAuthConsumerSecret(twitterProperties.getProperty("oauth.consumerSecret"));
    cb.setOAuthAccessToken(twitterProperties.getProperty("oauth.accessToken"));
    cb.setOAuthAccessTokenSecret(twitterProperties.getProperty("oauth.accessTokenSecret"));

    cb.setDebugEnabled(false);
    cb.setPrettyDebugEnabled(false);
    cb.setIncludeMyRetweetEnabled(false);

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

    StatusListener statusListener = new StatusListener() {
        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onStatus(Status status) {
            messageQueue.add(status);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    FilterQuery fq = new FilterQuery();
    // Posiciones geogrficas, esas dos coordenadas son el vrtice superior izquierda e inferior derecho
    // de un rectangulo, de tal manera de analizar solo una parte geografica
    double position[][] = { { 0.0, 0.0 }, { 0.0, 0.0 } };
    fq.locations(position);

    twitterStream.addListener(statusListener);
    twitterStream.filter(fq);
}

From source file:android.stickynotes.StickyNotesActivity.java

License:Apache License

private void getTweets(String twit) {
    wifi.setWifiEnabled(true);//from   w w w. j ava2s  .  co m
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("TvywVhWx7r7QQev2UGfA4g")
            .setOAuthConsumerSecret("Nv22zsyf1VS0vvi6hwAMyvJk9LUtSXwRUB4xwp2gRs");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    try {
        QueryResult result = twitter.search(new Query(twit));
        List<Tweet> tweets = result.getTweets();
        textStatus.setText("");
        textStatus.append("Recent tweets about '" + twit + "':\n");
        for (Tweet tweet : tweets) {
            textStatus.append("@" + tweet.getFromUser() + " - " + tweet.getText() + "\n\n");
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        textStatus.append("Failed to search tweets: " + te.getMessage() + " " + twit);
    }
}

From source file:apptwitter.Metodos.java

public Metodos() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("5yqwH2WcqZ3YlkE0W8BLYkeoW")
            .setOAuthConsumerSecret("s5s5QGigqzULDGbbQs4Rm0pKdqLEefbO4gCh53XgcnA0RoMA9n")
            .setOAuthAccessToken("3055143533-jeaPEtFscvDMVKwPVLubxkmHs9DzCjZ2eIoWdcQ")
            .setOAuthAccessTokenSecret("NzIM687NlVRe3VxKh0a0xRRYpsGytrSEKISaqpuQGtTZL");

    twitter = new TwitterFactory(cb.build()).getInstance();
}

From source file:au.com.infiniterecursion.hashqanda.MainActivity.java

public boolean loadTweets() {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Q2DfeCNOxprbDp66fWlw")
            .setOAuthConsumerSecret("TgyJ26CKXz1SxGiEJx4HG9rytFsqiMZlEPeCO7S9g");

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    // clear tweet list.
    MainActivity.this.runOnUiThread(new Runnable() {

        public void run() {
            // add to it , via the runOnUIThread
            app.getTweetList().clear();/*  w  ww  . j a  v a2s . c o m*/
        }

    });

    try {
        Log.d(TAG, " starting Tweets loading ");
        Query q = new Query("#qanda");

        q.setRpp(numberTweets);

        QueryResult result = twitter.search(q);
        List<Tweet> tweets = result.getTweets();
        for (Tweet tweet : tweets) {
            // Log.d(TAG, "@" + tweet.getFromUser() + " - " +
            // tweet.getText());
            // Log.d(TAG, " img url " + tweet.getProfileImageUrl());

            final CachedBitmapAndTweet cachedbmtwt = new CachedBitmapAndTweet();

            cachedbmtwt.twt = tweet;

            try {
                URL url = new URL(tweet.getProfileImageUrl());
                InputStream is = (InputStream) url.getContent();

                if (is != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    cachedbmtwt.bm = bitmap;
                } else {
                    cachedbmtwt.bm = null;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                cachedbmtwt.bm = null;
            } catch (IOException e) {
                e.printStackTrace();
                cachedbmtwt.bm = null;
            } catch (NullPointerException npe) {
                npe.printStackTrace();
                cachedbmtwt.bm = null;
            }

            MainActivity.this.runOnUiThread(new Runnable() {

                public void run() {
                    // add to it , via the runOnUIThread
                    app.getTweetList().add(cachedbmtwt);
                }

            });

        }

        Log.d(TAG, " finished Tweets loading ");

        return true;

    } catch (TwitterException te) {
        te.printStackTrace();
        Log.d(TAG, "Failed to search tweets: " + te.getMessage());
        return false;
    }
}

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

License:Open Source License

/**
 * @param streamConnection/*from   ww w. ja  v  a 2  s  . c  o  m*/
 *            <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 {/*w  ww.ja  va2 s.  co 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//from   ww w . ja  v a 2 s . c  om
 */
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  ww .  j  a  va2  s. c om
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();

}